commit 068ef188e751c23fc190b9a4cb21e485e74704b5 Author: wyc <1104749580@qq.com> Date: Tue Jun 16 11:18:22 2026 +0800 首次提交 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..153c761 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/sqlite/ +/data/ diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..ebe69f0 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,8 @@ +if(${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_CURRENT_LIST_DIR}) + include(${CMAKE_CURRENT_LIST_DIR}/main.cmake) +else() + +endif() + + + diff --git a/config/1221/config.json b/config/1221/config.json new file mode 100644 index 0000000..3678d35 --- /dev/null +++ b/config/1221/config.json @@ -0,0 +1,157 @@ +{ + "version": "v1.0.0", + "dsp": { + "library_path": "@/libdll_source.so", + "center_freq": 15000000, + "band_width": 10000, + "sample_rate": 60000, + "fft_point_number": 32768, + "fft_period_ms": 10, + "fft_win_type": "blkmc", + "url": "0.0.0.0", + "port": 6000, + "power_min": -200, + "power_max": 200, + "power_offset": -166, + "filename_prefix": "ECAP_", + "filename_suffix": ".dat", + "frame_rate": 30, + "debug": false + }, + "drogon": { + "app": { + "threads_num": 0 + } + }, + "mlat": { + "enable": false, + "merge": false, + "library_path": "@/mlat_source.dll", + "function_name": "read" + }, + "web_server": { + "webapp": "@/wwwroot", + "tiles": "@/../tiles" + }, + "device": { + "net": [ + { + "key": "device", + "ip": "192.168.1.75", + "netmask": "255.255.255.0", + "gateway": "192.168.1.1", + "port": 9081 + }, + { + "key": "wifi", + "ip": "192.168.10.193", + "netmask": "255.255.255.0", + "gateway": "192.168.10.1", + "port": 80 + } + ] + }, + "mode_acs": { + "timeout_seconds": 60, + "read_milliseconds": 100, + "monitor_msg_live": false, + "mode_s_max_num": 700000, + "mode_other_max_num": 10000, + "report_data_feed_msg_mum": 10000, + "data_feed": { + "empty_wait_milliseconds": 10, + "packet_byte_size": 1, + "list": [ + { + "key": "Port_10003", + "enable": true, + "type": "Data_Feed_TCP_Server", + "output_format": { + "type": "BIN", + "use_status": true, + "mode_s_output_type": "ALL_Mode_S", + "use_mode_ac": true + }, + "port": 10003 + }, + { + "key": "Port_10004", + "enable": false, + "type": "Data_Feed_TCP_Server", + "output_format": { + "type": "BIN", + "use_status": false, + "mode_s_output_type": "DF_11_17_18", + "use_mode_ac": false + }, + "port": 10004 + }, + { + "key": "Port_10005", + "enable": false, + "type": "Data_Feed_TCP_Client", + "output_format": { + "type": "BIN", + "use_status": true, + "mode_s_output_type": "NO_POS_Mode_S", + "use_mode_ac": false + }, + "url": "192.168.208.153", + "port": 10005 + }, + { + "key": "Port_30003", + "enable": false, + "type": "Data_Feed_TCP_Server", + "output_format": { + "type": "SBS", + "use_status": false, + "mode_s_output_type": "ALL_Mode_S", + "use_mode_ac": true + }, + "port": 30003 + } + ] + }, + "data_source": { + "list": [ + { + "key": "mode_acs_shared_memory", + "enable": true, + "base_station_show": true, + "aircraft_show": false, + "color": "#e4f40b", + "aircraft_pixel_size": 38, + "lat": 37.073685, + "lon": 120.870472, + "alt": 9479.280000, + "update_form_gps": false, + "type": "Shared_Memory_Data_Source", + "shared_memory_name": "mode_acs", + "shared_memory_size": 20000, + "data_type": "BIN_Blank" + } + ] + }, + "source_feed_relation": { + "list": [ + { + "key": "key_10003", + "enable": true, + "type": "First_Source_To_All_Feed_Relation" + } + ] + } + }, + "log": { + "open_mode": "Delete", + "piece_num": 10, + "size_MB": 10 + }, + "console": { + "record_playback": false, + "mode_s_console": false, + "post_request": false, + "mlat_server": true + } +} diff --git a/config/S79hostapd b/config/S79hostapd new file mode 100644 index 0000000..db78b80 --- /dev/null +++ b/config/S79hostapd @@ -0,0 +1,25 @@ +#!/bin/sh + +[ -f /etc/hostapd.conf ] || exit 0 + +case "$1" in + start) + printf "Starting hostapd: " + start-stop-daemon -S -x /usr/sbin/hostapd -- -B /etc/hostapd.conf + [ $? = 0 ] && echo "OK" || echo "FAIL" + ;; + stop) + printf "Stopping hostapd: " + start-stop-daemon -K -q -x /usr/sbin/hostapd + [ $? = 0 ] && echo "OK" || echo "FAIL" + ;; + restart|reload) + $0 stop + $0 start + ;; + *) + echo "Usage: $0 {start|stop|restart}" + exit 1 +esac + +exit 0 \ No newline at end of file diff --git a/config/S90E-CAP b/config/S90E-CAP new file mode 100644 index 0000000..938e691 --- /dev/null +++ b/config/S90E-CAP @@ -0,0 +1,26 @@ +#!/bin/sh + +case "$1" in + start|"") + while true + do + printf "Starting E-CAP: " + cd /root/ + ./Radarcape_Local_Server_aarch64-buildroot-linux-gnu-gxx_Linux_Debug > out.log 2>&1 +# ./Radarcape_Local_Server_aarch64-buildroot-linux-gnu-gxx_Linux_Debug + sleep 3 + done & + ;; + stop|status) + printf "Stopping E-CAP: " + pkill Radarcape_Local_Server_aarch64-buildroot-linux-gnu-gxx_Linux_Debug + ;; + restart|reload|force-reload) + echo "Error: argument '$1' not supported" >&2 + exit 3 + ;; + *) + echo "Usage: [start|stop]" >&2 + exit 3 + ;; +esac diff --git a/config/config.json b/config/config.json new file mode 100644 index 0000000..2f0232f --- /dev/null +++ b/config/config.json @@ -0,0 +1,302 @@ +{ + "version": "windows_v1.1.2", + "dsp": { + "library_path": "@/dll_source.dll", + "center_freq": 16000000, + "band_width": 6000, + "sample_rate": 60000, + "fft_point_number": 2048, + "fft_period_ms": 50, + "fft_win_type": "blkmc", + "url": "0.0.0.0", + "port": 6000, + "power_min": -380, + "power_max": 120, + "power_offset": -166, + "frame_rate": 60, + "debug": false, + "demod_mode": "LSB", + "audio_gain": 30, + "color_gain": 120 + }, + "drogon": { + "app": { + "threads_num": 0, + "client_max_body_size": "1000M", + "client_max_memory_body_size": "1000M" + } + }, + "http_monitor": { + "access_log": false, + "slow_request_threshold_ms": 3000, + "slow_scope_threshold_ms": 1000 + }, + "mlat": { + "enable": false, + "merge": false, + "library_path": "@/mlat_source.dll", + "function_name": "adsb_read" + }, + "web_server": { + "webapp": "D:/ae/proj/projects/ECAP_Server/ver/v1.0.4/wwwroot", + "tiles": "D:/tiles" + }, + "device": { + "net": [ + { + "key": "device", + "ip": "192.168.1.75", + "netmask": "255.255.255.0", + "gateway": "192.168.1.1", + "port": 80 + }, + { + "key": "wifi", + "ip": "192.168.10.193", + "netmask": "255.255.255.0", + "gateway": "192.168.10.1", + "port": 80 + } + ] + }, + "mode_acs": { + "timeout_seconds": 160, + "max_speed_m_s": 1000, + "air_pos_timeout": 8, + "surface_pos_timeout": 32, + "read_milliseconds": 100, + "max_track_point_size": 20000, + "mode_s_max_num": 700000, + "mode_other_max_num": 10000, + "report_data_feed_msg_mum": 10000, + "default_min_aircraft_list_num": 10, + "ignore_df_11": true, + "monitor_msg_live": false, + "data_feed": { + "empty_wait_milliseconds": 30, + "packet_byte_size": 0, + "tcp_server_default_connect_user_buffer_size": 409600, + "tcp_server_default_connect_system_buffer_size": 409600, + "list": [ + { + "key": "Port_10003", + "enable": true, + "type": "Data_Feed_TCP_Server", + "output_format": { + "type": "BIN", + "use_status": true, + "mode_s_output_type": "ALL_Mode_S", + "use_mode_ac": true, + "sbs_only_pos": true + }, + "port": 10003, + "connect_user_buffer_size": 409600, + "connect_system_buffer_size": 409600 + }, + { + "key": "22333", + "enable": false, + "type": "Data_Feed_UDP_Server", + "output_format": { + "type": "BIN", + "use_status": false, + "mode_s_output_type": "ALL_Mode_S", + "use_mode_ac": false, + "sbs_only_pos": false + }, + "port": 50001 + }, + { + "key": "Port_10004", + "enable": false, + "type": "Data_Feed_UDP_Client", + "output_format": { + "type": "AVR", + "use_status": false, + "mode_s_output_type": "DF_11_17_18", + "use_mode_ac": false, + "sbs_only_pos": true + }, + "url": "192.168.1.75", + "port": 30004 + }, + { + "key": "Port_10005", + "enable": true, + "type": "Data_Feed_TCP_Client", + "output_format": { + "type": "BIN", + "use_status": true, + "mode_s_output_type": "NO_POS_Mode_S", + "use_mode_ac": true, + "sbs_only_pos": true + }, + "url": "192.168.1.167", + "port": 10005 + }, + { + "key": "Port_30003", + "enable": false, + "type": "Data_Feed_TCP_Server", + "output_format": { + "type": "SBS", + "use_status": false, + "mode_s_output_type": "ALL_Mode_S", + "use_mode_ac": true, + "sbs_only_pos": true + }, + "port": 30003, + "connect_user_buffer_size": 0, + "connect_system_buffer_size": 0 + } + ] + }, + "data_source": { + "list": [ + { + "key": "lzy_dll", + "enable": true, + "base_station_show": true, + "aircraft_show": true, + "color": "#454641", + "aircraft_pixel_size": 28, + "type": "Dll_Data_Source", + "lat": 37.433547, + "lon": 121.408730, + "alt": 23.000000, + "update_form_gps": true, + "show_icao": true, + "show_call_sign": false, + "show_fly_status": false, + "keep_mode": true, + "library_path": "@/dll_source.dll", + "function_name": "adsb_read", + "data_type": "BIN_Blank_Text", + "buffer_size": 200000 + }, + { + "key": "aaaa", + "enable": false, + "base_station_show": true, + "aircraft_show": true, + "color": "#d1a54c", + "aircraft_pixel_size": 20, + "type": "File_Data_Source", + "lat": 37.000000, + "lon": 121.000000, + "alt": 0.000000, + "update_form_gps": false, + "show_icao": true, + "show_call_sign": true, + "show_fly_status": true, + "keep_mode": true, + "file_path": "D:\\ae\\proj\\projects\\ECAP_Server\\data\\BIN_Blank_Text\\ADS-B_195_0205.txt", + "data_type": "BIN_Blank_Text", + "play_mode": "loop" + } + ] + }, + "source_feed_relation": { + "list": [ + { + "key": "key_10003", + "enable": true, + "type": "First_Source_To_All_Feed_Relation" + } + ] + } + }, + "log": { + "open_mode": "Delete", + "piece_num": 10, + "size_MB": 10 + }, + "console": { + "record_playback": false, + "mode_s_console": false, + "post_request": false, + "mlat_server": true + }, + "external_database": { + "ecap_sqlite_path": "D:/ae/proj/projects/ECAP_Server/sqlite/ecap.sqlite", + "list": [ + { + "name": "tar1090_db_aircraft", + "download_url": "https://raw.githubusercontent.com/wiedehopf/tar1090-db/refs/heads/csv/aircraft.csv.gz", + "description": "wiedehopf/tar1090-db 发布的轻量 ICAO24 飞机静态库,提供注册号、机型、年份和运营方备注。", + "update_interval_seconds": 604800, + "last_updated_at": 1780388281 + }, + { + "name": "wiedehopf_tar1090_db_aircraft", + "download_url": "https://raw.githubusercontent.com/wiedehopf/tar1090-db/refs/heads/csv/aircraft.csv.gz", + "description": "wiedehopf/tar1090-db 项目发布的飞机静态数据库镜像,供 tar1090 本地识别飞机。", + "update_interval_seconds": 604800, + "last_updated_at": 1780381804 + }, + { + "name": "mictronics_aircraft_database", + "download_url": "https://raw.githubusercontent.com/wiedehopf/tar1090-db/refs/heads/csv/aircraft.csv.gz", + "description": "Mictronics 社区飞机数据库的 tar1090 汇总镜像,可按 ICAO24 查询注册号、机型和运营方。", + "update_interval_seconds": 604800, + "last_updated_at": 1780381804 + }, + { + "name": "opensky_aircraft_database", + "download_url": "https://opensky-network.org/datasets/metadata/aircraftDatabase.csv", + "description": "OpenSky Network 飞机元数据 CSV,包含制造商、型号、注册号和运营方等字段。", + "update_interval_seconds": 604800, + "last_updated_at": 1780381804 + }, + { + "name": "faa_aircraft_registry", + "download_url": "https://registry.faa.gov/database/ReleasableAircraft.zip", + "description": "FAA 官方可公开下载的美国飞机注册库,MASTER.txt 包含 Mode-S Hex 注册信息。", + "update_interval_seconds": 86400, + "last_updated_at": 1780381804 + }, + { + "name": "icao_doc_8643_aircraft_type_designators", + "download_url": "", + "description": "ICAO Doc 8643 机型代码表,用于将 A320、B738 等 designator 映射为制造商、型号和类别。", + "update_interval_seconds": 2419200, + "last_updated_at": 1780381804 + }, + { + "name": "vrs_routes", + "download_url": "https://vrs-standing-data.adsb.lol/routes.csv", + "description": "VRS 航线表,以 callsign 查询机场代码序列,用于推断起飞机场、经停机场和目的机场。", + "update_interval_seconds": 3600, + "last_updated_at": 1780381804 + }, + { + "name": "vrs_airports", + "download_url": "https://vrs-standing-data.adsb.lol/airports.csv", + "description": "VRS 机场字典,提供机场代码、名称、国家、经纬度和高度。", + "update_interval_seconds": 3600, + "last_updated_at": 1780381804 + }, + { + "name": "adsblol_vrs_standing_data_routes", + "download_url": "https://vrs-standing-data.adsb.lol/routes.csv", + "description": "ADSB.lol 发布的 VRS standing-data 航线镜像,以 callsign 查询机场代码序列。", + "update_interval_seconds": 3600, + "last_updated_at": 1780381804 + }, + { + "name": "vradarserver_standing_data_routes", + "download_url": "https://vrs-standing-data.adsb.lol/routes.csv", + "description": "Virtual Radar Server standing-data 的航线适配表;当前在线更新使用 ADSB.lol 公共镜像。", + "update_interval_seconds": 3600, + "last_updated_at": 1780381804 + }, + { + "name": "opensky_flightdata_api_cache", + "download_url": "", + "description": "OpenSky FlightData API 查询缓存,按 ICAO24 和时间范围保存历史航班起降机场结果。", + "update_interval_seconds": 0, + "last_updated_at": 1780381804 + } + ] + } +} diff --git a/config/config.json.back b/config/config.json.back new file mode 100644 index 0000000..fdc8eb2 --- /dev/null +++ b/config/config.json.back @@ -0,0 +1,302 @@ +{ + "version": "windows_v1.1.2", + "dsp": { + "library_path": "@/dll_source.dll", + "center_freq": 16000000, + "band_width": 6000, + "sample_rate": 60000, + "fft_point_number": 2048, + "fft_period_ms": 50, + "fft_win_type": "blkmc", + "url": "0.0.0.0", + "port": 6000, + "power_min": -380, + "power_max": 120, + "power_offset": -166, + "frame_rate": 60, + "debug": false, + "demod_mode": "LSB", + "audio_gain": 30, + "color_gain": 120 + }, + "drogon": { + "app": { + "threads_num": 0, + "client_max_body_size": "1000M", + "client_max_memory_body_size": "1000M" + } + }, + "http_monitor": { + "access_log": true, + "slow_request_threshold_ms": 1000, + "slow_scope_threshold_ms": 100 + }, + "mlat": { + "enable": false, + "merge": false, + "library_path": "@/mlat_source.dll", + "function_name": "adsb_read" + }, + "web_server": { + "webapp": "D:/ae/proj/projects/ECAP_Server/ver/v1.0.4/wwwroot", + "tiles": "D:/tiles" + }, + "device": { + "net": [ + { + "key": "device", + "ip": "192.168.1.75", + "netmask": "255.255.255.0", + "gateway": "192.168.1.1", + "port": 80 + }, + { + "key": "wifi", + "ip": "192.168.10.193", + "netmask": "255.255.255.0", + "gateway": "192.168.10.1", + "port": 80 + } + ] + }, + "mode_acs": { + "timeout_seconds": 160, + "max_speed_m_s": 1000, + "air_pos_timeout": 8, + "surface_pos_timeout": 32, + "read_milliseconds": 100, + "max_track_point_size": 20000, + "mode_s_max_num": 700000, + "mode_other_max_num": 10000, + "report_data_feed_msg_mum": 10000, + "default_min_aircraft_list_num": 10, + "ignore_df_11": true, + "monitor_msg_live": false, + "ecap_sqlite_path": "D:/ae/proj/projects/ECAP_Server/sqlite/ecap.sqlite", + "data_feed": { + "empty_wait_milliseconds": 30, + "packet_byte_size": 0, + "tcp_server_default_connect_user_buffer_size": 409600, + "tcp_server_default_connect_system_buffer_size": 409600, + "list": [ + { + "key": "Port_10003", + "enable": true, + "type": "Data_Feed_TCP_Server", + "output_format": { + "type": "BIN", + "use_status": true, + "mode_s_output_type": "ALL_Mode_S", + "use_mode_ac": true, + "sbs_only_pos": true + }, + "port": 10003, + "connect_user_buffer_size": 409600, + "connect_system_buffer_size": 409600 + }, + { + "key": "22333", + "enable": false, + "type": "Data_Feed_UDP_Server", + "output_format": { + "type": "BIN", + "use_status": false, + "mode_s_output_type": "ALL_Mode_S", + "use_mode_ac": false, + "sbs_only_pos": false + }, + "port": 50001 + }, + { + "key": "Port_10004", + "enable": false, + "type": "Data_Feed_UDP_Client", + "output_format": { + "type": "AVR", + "use_status": false, + "mode_s_output_type": "DF_11_17_18", + "use_mode_ac": false, + "sbs_only_pos": true + }, + "url": "192.168.1.75", + "port": 30004 + }, + { + "key": "Port_10005", + "enable": true, + "type": "Data_Feed_TCP_Client", + "output_format": { + "type": "BIN", + "use_status": true, + "mode_s_output_type": "NO_POS_Mode_S", + "use_mode_ac": true, + "sbs_only_pos": true + }, + "url": "192.168.1.167", + "port": 10005 + }, + { + "key": "Port_30003", + "enable": false, + "type": "Data_Feed_TCP_Server", + "output_format": { + "type": "SBS", + "use_status": false, + "mode_s_output_type": "ALL_Mode_S", + "use_mode_ac": true, + "sbs_only_pos": true + }, + "port": 30003, + "connect_user_buffer_size": 0, + "connect_system_buffer_size": 0 + } + ] + }, + "data_source": { + "list": [ + { + "key": "aaaa", + "enable": false, + "base_station_show": true, + "aircraft_show": true, + "color": "#d1a54c", + "aircraft_pixel_size": 20, + "type": "File_Data_Source", + "lat": 37.000000, + "lon": 121.000000, + "alt": 0.000000, + "update_form_gps": false, + "show_icao": true, + "show_call_sign": true, + "show_fly_status": true, + "keep_mode": true, + "file_path": "D:\\ae\\proj\\projects\\ECAP_Server\\data\\BIN_Blank_Text\\ADS-B_195_0205.txt", + "data_type": "BIN_Blank_Text", + "play_mode": "loop" + }, + { + "key": "lzy_dll", + "enable": true, + "base_station_show": true, + "aircraft_show": true, + "color": "#454641", + "aircraft_pixel_size": 28, + "type": "Dll_Data_Source", + "lat": 37.433547, + "lon": 121.408730, + "alt": 23.000000, + "update_form_gps": true, + "show_icao": true, + "show_call_sign": false, + "show_fly_status": false, + "keep_mode": true, + "library_path": "@/dll_source.dll", + "function_name": "adsb_read", + "data_type": "BIN_Blank_Text", + "buffer_size": 200000 + } + ] + }, + "source_feed_relation": { + "list": [ + { + "key": "key_10003", + "enable": true, + "type": "First_Source_To_All_Feed_Relation" + } + ] + } + }, + "log": { + "open_mode": "Delete", + "piece_num": 10, + "size_MB": 10 + }, + "console": { + "record_playback": false, + "mode_s_console": false, + "post_request": false, + "mlat_server": true + }, + "external_database": { + "list": [ + { + "name": "tar1090_db_aircraft", + "download_url": "https://raw.githubusercontent.com/wiedehopf/tar1090-db/refs/heads/csv/aircraft.csv.gz", + "description": "wiedehopf/tar1090-db 发布的轻量 ICAO24 飞机静态库,提供注册号、机型、年份和运营方备注。", + "update_interval_seconds": 604800, + "last_updated_at": 0 + }, + { + "name": "wiedehopf_tar1090_db_aircraft", + "download_url": "https://raw.githubusercontent.com/wiedehopf/tar1090-db/refs/heads/csv/aircraft.csv.gz", + "description": "wiedehopf/tar1090-db 项目发布的飞机静态数据库镜像,供 tar1090 本地识别飞机。", + "update_interval_seconds": 604800, + "last_updated_at": 0 + }, + { + "name": "mictronics_aircraft_database", + "download_url": "https://raw.githubusercontent.com/wiedehopf/tar1090-db/refs/heads/csv/aircraft.csv.gz", + "description": "Mictronics 社区飞机数据库的 tar1090 汇总镜像,可按 ICAO24 查询注册号、机型和运营方。", + "update_interval_seconds": 604800, + "last_updated_at": 0 + }, + { + "name": "opensky_aircraft_database", + "download_url": "https://opensky-network.org/datasets/metadata/aircraftDatabase.csv", + "description": "OpenSky Network 飞机元数据 CSV,包含制造商、型号、注册号和运营方等字段。", + "update_interval_seconds": 604800, + "last_updated_at": 0 + }, + { + "name": "faa_aircraft_registry", + "download_url": "https://registry.faa.gov/database/ReleasableAircraft.zip", + "description": "FAA 官方可公开下载的美国飞机注册库,MASTER.txt 包含 Mode-S Hex 注册信息。", + "update_interval_seconds": 86400, + "last_updated_at": 0 + }, + { + "name": "icao_doc_8643_aircraft_type_designators", + "download_url": "", + "description": "ICAO Doc 8643 机型代码表,用于将 A320、B738 等 designator 映射为制造商、型号和类别。", + "update_interval_seconds": 2419200, + "last_updated_at": 0 + }, + { + "name": "vrs_routes", + "download_url": "https://vrs-standing-data.adsb.lol/routes.csv", + "description": "VRS 航线表,以 callsign 查询机场代码序列,用于推断起飞机场、经停机场和目的机场。", + "update_interval_seconds": 3600, + "last_updated_at": 0 + }, + { + "name": "vrs_airports", + "download_url": "https://vrs-standing-data.adsb.lol/airports.csv", + "description": "VRS 机场字典,提供机场代码、名称、国家、经纬度和高度。", + "update_interval_seconds": 3600, + "last_updated_at": 0 + }, + { + "name": "adsblol_vrs_standing_data_routes", + "download_url": "https://vrs-standing-data.adsb.lol/routes.csv", + "description": "ADSB.lol 发布的 VRS standing-data 航线镜像,以 callsign 查询机场代码序列。", + "update_interval_seconds": 3600, + "last_updated_at": 0 + }, + { + "name": "vradarserver_standing_data_routes", + "download_url": "https://vrs-standing-data.adsb.lol/routes.csv", + "description": "Virtual Radar Server standing-data 的航线适配表;当前在线更新使用 ADSB.lol 公共镜像。", + "update_interval_seconds": 3600, + "last_updated_at": 0 + }, + { + "name": "opensky_flightdata_api_cache", + "download_url": "", + "description": "OpenSky FlightData API 查询缓存,按 ICAO24 和时间范围保存历史航班起降机场结果。", + "update_interval_seconds": 0, + "last_updated_at": 0 + } + ] + } +} diff --git a/config/config2.json b/config/config2.json new file mode 100644 index 0000000..0b2913e --- /dev/null +++ b/config/config2.json @@ -0,0 +1,251 @@ +{ + "version": "v1.0.4", + "dsp": { + "library_path": "@/dll_source.dll", + "center_freq": 16000000, + "band_width": 6000, + "sample_rate": 60000, + "fft_point_number": 2048, + "fft_period_ms": 50, + "fft_win_type": "blkmc", + "url": "0.0.0.0", + "port": 6000, + "power_min": -380, + "power_max": 120, + "power_offset": -166, + "frame_rate": 60, + "debug": false, + "demod_mode": "LSB", + "audio_gain": 30, + "color_gain": 120 + }, + "drogon": { + "app": { + "threads_num": 0, + "client_max_body_size": "1000M", + "client_max_memory_body_size": "1000M" + } + }, + "mlat": { + "enable": false, + "merge": false, + "library_path": "@/mlat_source.dll", + "function_name": "adsb_read" + }, + "web_server": { + "webapp": "@/wwwroot", + "tiles": "D:/tiles" + }, + "device": { + "net": [ + { + "key": "device", + "ip": "192.168.1.75", + "netmask": "255.255.255.0", + "gateway": "192.168.1.1", + "port": 80 + }, + { + "key": "wifi", + "ip": "192.168.10.193", + "netmask": "255.255.255.0", + "gateway": "192.168.10.1", + "port": 80 + } + ] + }, + "mode_acs": { + "timeout_seconds": 160, + "max_speed_m_s": 1000, + "air_pos_timeout": 8, + "surface_pos_timeout": 32, + "read_milliseconds": 100, + "max_track_point_size": 20000, + "mode_s_max_num": 700000, + "mode_other_max_num": 10000, + "report_data_feed_msg_mum": 10000, + "default_min_aircraft_list_num": 10, + "ignore_df_11": true, + "monitor_msg_live": false, + "ecap_sqlite_path": "D:/ae/proj/projects/ECAP_Server/sqlite/ecap.sqlite", + "data_feed": { + "empty_wait_milliseconds": 30, + "packet_byte_size": 0, + "tcp_server_default_connect_user_buffer_size": 0, + "tcp_server_default_connect_system_buffer_size": 0, + "list": [ + { + "key": "Port_10003", + "enable": true, + "type": "Data_Feed_TCP_Server", + "output_format": { + "type": "BIN", + "use_status": true, + "mode_s_output_type": "ALL_Mode_S", + "use_mode_ac": true, + "sbs_only_pos": true + }, + "port": 10003, + "connect_user_buffer_size": 409600, + "connect_system_buffer_size": 409600 + }, + { + "key": "22333", + "enable": false, + "type": "Data_Feed_UDP_Server", + "output_format": { + "type": "BIN", + "use_status": false, + "mode_s_output_type": "ALL_Mode_S", + "use_mode_ac": false, + "sbs_only_pos": false + }, + "port": 50001 + }, + { + "key": "Port_10004", + "enable": false, + "type": "Data_Feed_UDP_Client", + "output_format": { + "type": "AVR", + "use_status": false, + "mode_s_output_type": "DF_11_17_18", + "use_mode_ac": false, + "sbs_only_pos": true + }, + "url": "192.168.1.75", + "port": 30004 + }, + { + "key": "Port_10005", + "enable": true, + "type": "Data_Feed_TCP_Client", + "output_format": { + "type": "BIN", + "use_status": true, + "mode_s_output_type": "NO_POS_Mode_S", + "use_mode_ac": true, + "sbs_only_pos": true + }, + "url": "192.168.1.75", + "port": 10005 + }, + { + "key": "Port_30003", + "enable": false, + "type": "Data_Feed_TCP_Server", + "output_format": { + "type": "SBS", + "use_status": false, + "mode_s_output_type": "ALL_Mode_S", + "use_mode_ac": true, + "sbs_only_pos": true + }, + "port": 30003, + "connect_user_buffer_size": 0, + "connect_system_buffer_size": 0 + } + ] + }, + "data_source": { + "list": [ + { + "key": "aaaa", + "enable": true, + "base_station_show": true, + "aircraft_show": true, + "color": "#d1a54c", + "aircraft_pixel_size": 20, + "lat": 37.000000, + "lon": 121.000000, + "alt": 0.000000, + "update_form_gps": false, + "type": "File_Data_Source", + "file_path": "D:\\ae\\proj\\projects\\ECAP_Server\\data\\BIN_Blank_Text\\ADS-B_195_0205.txt", + "data_type": "BIN_Blank_Text", + "play_mode": "one" + }, + { + "key": "本地radarcape", + "enable": true, + "base_station_show": true, + "aircraft_show": true, + "color": "#cb3065", + "aircraft_pixel_size": 20, + "lat": 37.000000, + "lon": 121.000000, + "alt": 0.000000, + "update_form_gps": false, + "type": "TCP_Client_Data_Source", + "ip": "192.168.71.101", + "port": 10003 + }, + { + "key": "r205_113", + "enable": false, + "base_station_show": false, + "aircraft_show": true, + "color": "#661a30", + "aircraft_pixel_size": 30, + "lat": 37.000000, + "lon": 121.000000, + "alt": 0.000000, + "update_form_gps": false, + "type": "TCP_Client_Data_Source", + "ip": "192.168.205.113", + "port": 10003 + }, + { + "key": "102", + "enable": true, + "base_station_show": true, + "aircraft_show": true, + "color": "#186ce1", + "aircraft_pixel_size": 20, + "lat": 0.000000, + "lon": 0.000000, + "alt": 0.000000, + "update_form_gps": false, + "type": "TCP_Client_Data_Source", + "ip": "192.168.1.102", + "port": 10003 + }, + { + "key": "r205_116", + "enable": false, + "base_station_show": true, + "aircraft_show": true, + "color": "#d7c1b6a3", + "aircraft_pixel_size": 40, + "lat": 0.000000, + "lon": 0.000000, + "alt": 5394.960000, + "update_form_gps": true, + "type": "TCP_Client_Data_Source", + "ip": "192.168.205.116", + "port": 10003 + } + ] + }, + "source_feed_relation": { + "list": [ + { + "key": "key_10003", + "enable": true, + "type": "First_Source_To_All_Feed_Relation" + } + ] + } + }, + "log": { + "open_mode": "Delete", + "piece_num": 10, + "size_MB": 10 + }, + "console": { + "record_playback": false, + "mode_s_console": false, + "post_request": false, + "mlat_server": true + } +} diff --git a/config/data_progress_config.json b/config/data_progress_config.json new file mode 100644 index 0000000..e84b68b --- /dev/null +++ b/config/data_progress_config.json @@ -0,0 +1,9 @@ +{ + "library_path": "@/dll_source.dll", + "center_freq": 200000, + "band_width": 6000, + "sample_rate": 60000, + "fft_point_number": 2048, + "fft_period_ms": 50, + "fft_win_type": "blkmc" +} \ No newline at end of file diff --git a/config/deploy.sh b/config/deploy.sh new file mode 100644 index 0000000..9313523 --- /dev/null +++ b/config/deploy.sh @@ -0,0 +1,205 @@ +#!/bin/sh + +# 检查参数数量 +if [ "$#" -ne 1 ]; then + echo "Usage: $0 " + exit 1 +fi + +dir_path="/root/u" + +# 检查U盘目录是否存在 +if [ ! -d "$dir_path" ]; then + echo "U盘目录不存在,正在创建U盘目录..." + mkdir -p "$dir_path" # 创建目录 +else + echo "U盘目录已经存在." +fi + + +# 获取命令行参数 +sequence_number=$1 + +# 定义一个函数来执行复制操作并输出结果 +copy_file() { + local source_file="$1" + local target_dir="$2" + if [ -f "$source_file" ]; then + cp "$source_file" "$target_dir" + if [ $? -eq 0 ]; then + echo "文件 $source_file 已成功复制到 $target_dir 目录。" + else + echo "复制文件 $source_file 时出错。" + exit 1 + fi + else + echo "当前目录下未找到 $source_file 文件。" + fi +} +# 添加 启动脚本 到 /etc/init.d/ +copy_file "S79hostapd" "/etc/init.d/" +copy_file "S90E-CAP" "/etc/init.d/" +#copy_file "S99Check_reboot" "/etc/init.d/" + +# 移除 启动脚本 +rename_file() { + local original_name="$1" + local new_name="$2" + + if [ -f "$original_name" ]; then + mv "$original_name" "$new_name" + if [ $? -eq 0 ]; then + echo "已成功将 $original_name 重命名为 $new_name" + else + echo "重命名 $original_name 时出错。" + exit 1 + fi + else + echo "$original_name 文件不存在" + fi +} +rename_file "/etc/init.d/S49weston" "/etc/init.d/_S49weston" +rename_file "/etc/init.d/S41dhcpcd" "/etc/init.d/_S41dhcpcd" + +# 生成 /etc/hostapd.conf 文件 +hostapd_config="# 无线网络接口名称,可通过 ifconfig 或 ip addr 命令查看 +interface=wlan0 +# 使用的驱动程序,通常为 nl80211 +driver=nl80211 +# 热点的 SSID +ssid=E-CAP_${sequence_number} +# 通道号,可根据需要调整 +channel=6 +# 认证和加密模式 +hw_mode=g +ieee80211n=1 +wmm_enabled=1 +ht_capab=[HT40][SHORT-GI-20][DSSS_CCK-40] +macaddr_acl=0 +auth_algs=1 +ignore_broadcast_ssid=0 +wpa=2 +wpa_key_mgmt=WPA-PSK +wpa_pairwise=TKIP +rsn_pairwise=CCMP +# 热点的密码 +wpa_passphrase=12345678" + +echo "$hostapd_config" > /etc/hostapd.conf +if [ $? -eq 0 ]; then + echo "文件 /etc/hostapd.conf 已成功生成。" +else + echo "生成 /etc/hostapd.conf 文件时出错。" + exit 1 +fi + +# 生成 /etc/dnsmasq.conf 文件 +dnsmasq_config="# 监听的接口 +interface=wlan0 +# DHCP 服务的 IP 地址范围 +dhcp-range=192.168.10.10,192.168.10.100,255.255.255.0,12h +# 网关地址 +dhcp-option=3,192.168.10.1 +# DNS 服务器地址 +dhcp-option=6,8.8.8.8 +# 本地 DNS 服务器地址 +server=8.8.8.8 +# 禁用 DNS 缓存 +no-hosts +# 不读取 /etc/resolv.conf 文件 +no-resolv" + +echo "$dnsmasq_config" > /etc/dnsmasq.conf +if [ $? -eq 0 ]; then + echo "文件 /etc/dnsmasq.conf 已成功生成。" +else + echo "生成 /etc/dnsmasq.conf 文件时出错。" + exit 1 +fi + +# 生成 /etc/network/interfaces 文件 +network_config="# interface file auto-generated by buildroot + +auto lo +iface lo inet loopback + +auto eth0 +iface eth0 inet static + address 192.168.1.${sequence_number} + netmask 255.255.255.0 + gateway 192.168.1.1 + dns-nameservers 192.168.1.1 8.8.8.8 + post-up /usr/sbin/ethtool -s eth0 speed 100 duplex full autoneg off + pre-down /usr/sbin/ethtool -s eth0 autoneg on +# post-up 网络接口被激活之后应该执行的命令。 +# pre-down 在网络接口即将被关闭之前执行的命令。 +# 添加这两行命令是为了限制网速为100M,解决phy网络排线过长导致网卡不稳定的问题。 + +auto wlan0 +iface wlan0 inet static + address 192.168.10.${sequence_number} + netmask 255.255.255.0 + gateway 192.168.10.1 + dns-nameservers 192.168.10.1 8.8.8.8" + +# 生成 /etc/network/interfaces 文件 +echo "$network_config" > /etc/network/interfaces +if [ $? -eq 0 ]; then + echo "文件 /etc/network/interfaces 已成功生成。" +else + echo "生成 /etc/network/interfaces 文件时出错。" + exit 1 +fi + + +if [ ! -d "/root/tiles" ]; then + if [ -f "tiles.zip" ]; then # 检查 tiles.zip 文件是否存在 + unzip -q "tiles.zip" -d "/root/" # 解压 tiles.zip 到 /root/ 目录 + if [ $? -eq 0 ]; then + echo "tiles.zip 已成功解压到 /root/ 目录。" + else + echo "解压 tiles.zip 到 /root/ 目录时出错。" + exit 1 + fi + else + echo "当前目录下未找到 tiles.zip 文件。" + fi +else + echo "瓦片文件夹已存在。" +fi + + + +# 检查当前目录下的 Radarcape_Local_Server_aarch64-buildroot-linux-gnu-gxx_Linux_Debug 文件是否存在 +if [ -f "Radarcape_Local_Server_aarch64-buildroot-linux-gnu-gxx_Linux_Debug" ]; then + # 给文件添加执行权限 + chmod +x "Radarcape_Local_Server_aarch64-buildroot-linux-gnu-gxx_Linux_Debug" + if [ $? -eq 0 ]; then + echo "已成功给当前目录下的 Radarcape_Local_Server_aarch64-buildroot-linux-gnu-gxx_Linux_Debug 文件添加执行权限。" + else + echo "给当前目录下的 Radarcape_Local_Server_aarch64-buildroot-linux-gnu-gxx_Linux_Debug 文件添加执行权限时出错。" + exit 1 + fi +else + echo "当前目录下未找到 Radarcape_Local_Server_aarch64-buildroot-linux-gnu-gxx_Linux_Debug 文件。" +fi + +# 定义要设置的 root 密码 +ROOT_PASSWORD="123" + +# 使用 expect 来非交互式地修改 root 密码 +expect << EOF +spawn passwd root +expect "New password:" +send "$ROOT_PASSWORD\r" +expect "Retype new password:" +send "$ROOT_PASSWORD\r" +expect eof +EOF + +if [ $? -eq 0 ]; then + echo "root 用户密码已成功设置。" +else + echo "设置 root 用户密码时出错。" + exit 1 +fi \ No newline at end of file diff --git a/config/interface b/config/interface new file mode 100644 index 0000000..577f6b3 --- /dev/null +++ b/config/interface @@ -0,0 +1,36 @@ + + + +# interface file auto-generated by buildroot + +auto lo +iface lo inet loopback + +auto eth0 +iface eth0 inet static + address ${ip} + netmask ${netmask} + gateway ${gateway} + dns-nameservers ${gateway} 8.8.8.8 + post-up /usr/sbin/ethtool -s eth0 speed 100 duplex full autoneg off + pre-down /usr/sbin/ethtool -s eth0 autoneg on +# post-up 网络接口被激活之后应该执行的命令。 +# pre-down 在网络接口即将被关闭之前执行的命令。 +# 添加这两行命令是为了限制网速为100M,解决phy网络排线过长导致网卡不稳定的问题。 + +auto wlan0 +iface wlan0 inet static + address ${wifi_ip} + netmask ${wifi_netmask} + gateway ${wifi_gateway} + dns-nameservers ${wifi_gateway} 8.8.8.8 + + +auto eth75 +iface eth75 inet static + address 192.168.59.75 + netmask 255.255.255.0 + gateway 192.168.59.1 + dns-nameservers 192.168.59.1 8.8.8.8 + post-up /usr/sbin/ethtool -s eth75 speed 100 duplex full autoneg off + pre-down /usr/sbin/ethtool -s eth75 autoneg on \ No newline at end of file diff --git a/config/polkit 规则 b/config/polkit 规则 new file mode 100644 index 0000000..6e049c3 --- /dev/null +++ b/config/polkit 规则 @@ -0,0 +1,20 @@ +sudo nano /etc/polkit-1/rules.d/90-ecap.rules +polkit.addRule(function(action, subject) { + if ( + subject.user == "heco" && + action.id == "org.freedesktop.systemd1.manage-units" && + action.lookup("unit") == "ecap.service" + ) { + return polkit.Result.YES; + } +}); + +sudo mkdir /etc/polkit-1/rules.d +sudo chmod 777 /etc/polkit-1/rules.d +sudo touch /etc/polkit-1/rules.d/90-ecap.rules +sudo chmod 777 /etc/polkit-1/rules.d/90-ecap.rules + +sudo systemctl restart polkit +systemctl stop ecap +systemctl start ecap +systemctl restart ecap \ No newline at end of file diff --git a/config/pt b/config/pt new file mode 100644 index 0000000..528ff99 --- /dev/null +++ b/config/pt @@ -0,0 +1,226 @@ +#!/bin/bash + + +# 日志轮换函数 +rotate_log() { + local LOG_FILE="$1" # 日志文件路径 + local MAX_SIZE="$2" # 最大日志文件大小(如 50M) + local MAX_BACKUPS="$3" # 保留的最大备份数量 + + # 如果日志文件是 /dev/null,直接返回,不进行轮换 + if [ "$LOG_FILE" == "/dev/null" ]; then + echo "日志文件是 /dev/null,跳过日志轮换" + return + fi + + local LOG_DIR=$(dirname "$LOG_FILE") # 日志文件所在的目录 + local DATE_FORMAT=$(date +"%Y%m%d-%H%M%S") # 当前日期和时间格式 + + # 检查日志文件是否存在 + if [ ! -f "$LOG_FILE" ]; then + echo "日志文件不存在,创建新日志文件: $LOG_FILE" + touch "$LOG_FILE" + fi + + # 检查日志文件的大小 + log_size=$(stat -c %s "$LOG_FILE") # 获取日志文件的大小(字节) + max_size_bytes=$(numfmt --from=iec $MAX_SIZE) # 转换最大大小为字节 + + # 如果日志文件大小超过限制,进行轮换 + if [ "$log_size" -ge "$max_size_bytes" ]; then + echo "日志文件超过最大限制 $MAX_SIZE,开始轮换日志" + + # 创建备份目录(如果没有的话) + mkdir -p "$LOG_DIR/backups" + + # 获取备份文件名 + backup_file="${LOG_DIR}/backups/$(basename "$LOG_FILE").${DATE_FORMAT}" + +# # 备份当前日志文件 +# mv "$LOG_FILE" "$backup_file" +# echo "备份日志为: $backup_file" +# +# # 创建一个新的空日志文件 +# touch "$LOG_FILE" + + # 复制当前日志作为备份(不动 inode) + cp "$LOG_FILE" "$backup_file" + echo "备份日志为: $backup_file" + + # 截断原日志文件(FD 不变) + : > "$LOG_FILE" + + # 压缩备份日志文件 + gzip "$backup_file" + echo "压缩备份日志为: ${backup_file}.gz" + + # 删除多余的备份文件(如果超过最大保留数量) + backups_count=$(ls "$LOG_DIR/backups" | grep -E "^$(basename "$LOG_FILE")" | wc -l) + if [ "$backups_count" -gt "$MAX_BACKUPS" ]; then + # 删除最早的备份 + oldest_backup=$(ls -t "$LOG_DIR/backups" | grep -E "^$(basename "$LOG_FILE")" | tail -n 1) + rm "${LOG_DIR}/backups/$oldest_backup" + echo "删除最早的备份日志: ${LOG_DIR}/backups/$oldest_backup" + fi + fi +} + + +DIR="$(cd "$(dirname "$0")" && pwd)" +BOOT_TIME=$(uptime -s) # 使用 uptime 命令获取系统的开机时间 +MAX_SIZE="1M" # 最大日志文件大小 +MAX_BACKUPS=2 # 保留的最大备份数量 +# 自动崩溃收集服务 +#sudo systemctl stop apport.service +#sudo systemctl disable apport.service +#ulimit -c unlimited +#echo "/home/heco/ys_ecap_server/core/core_%e_${BOOT_TIME}_.%t.%p" | tee /proc/sys/kernel/core_pattern + +USE_VALGRIND=0 +USE_data_process=0 + +NAME1="data_process" +NAME2="ecap_server" +#LOG_PATH1="/dev/null" +#LOG_PATH2="/dev/null" +LOG_PATH1="$DIR/data_process.log" +LOG_PATH2="$DIR/ecap_server.log" + +if [ "$USE_data_process" == 1 ]; then + rotate_log "$LOG_PATH1" "$MAX_SIZE" "$MAX_BACKUPS" +fi + +rotate_log "$LOG_PATH2" "$MAX_SIZE" "$MAX_BACKUPS" + + + + + +# Ensure the log files exist and are writable +if [ "$USE_data_process" == 1 ]; then + echo "系统开机时间: $BOOT_TIME" >> "${LOG_PATH1}" + touch "${LOG_PATH1}" +fi + +echo "系统开机时间: $BOOT_TIME" >> "${LOG_PATH2}" +touch "${LOG_PATH2}" +echo "${DIR} 创建log文件成功" + + +if [ "$USE_VALGRIND" == 1 ]; then + echo "启用valgrind内存检查程序" + valgrind --leak-check=full --log-file=${DIR}/${NAME2}_valgrind.log --show-leak-kinds=all ${DIR}/${NAME2} >> "${LOG_PATH2}" 2>&1 & +fi + + +SLEEP_SEC="${1:-10}" +sleep "$SLEEP_SEC" +echo "等待 ${SLEEP_SEC}s 完成" + + + +if [ "$USE_data_process" == 1 ]; then + echo "第一次启动 ${NAME1}" + ${DIR}/${NAME1} >> "${LOG_PATH1}" 2>&1 & + if [ $? -ne 0 ]; then + echo "第一次启动 Failed to start ${NAME1} at $(date)" >> "${LOG_PATH1}" + fi +fi + + +restart_count_2=0 +echo "第一次启动 ${NAME2}" +${DIR}/${NAME2} >> "${LOG_PATH2}" 2>&1 & +if [ $? -ne 0 ]; then + echo "第一次启动 Failed to start ${NAME2} at $(date)" >> "${LOG_PATH2}" +fi + + +while true; do + # 监控 data_process + + if [ "$USE_data_process" == 1 ]; then + if ! pgrep -x "$NAME1" >/dev/null; then + restart_count_1=$((restart_count_1 + 1)) + echo "重启 ${NAME1} at $(date) - count: ${restart_count_1}" >> "${LOG_PATH1}" + echo "重启 ${NAME1} at $(date) - count: ${restart_count_1}" + + # 真正重启程序 + ${DIR}/${NAME1} >> "${LOG_PATH1}" 2>&1 & + if [ $? -ne 0 ]; then + echo "Failed to start ${NAME1} at $(date)" >> "${LOG_PATH1}" + fi + fi + fi + + sleep 60 + + # 监控 ecap_server + if [ "$USE_VALGRIND" == 0 ]; then + if ! pgrep -x "$NAME2" >/dev/null; then + + ss -ltnp >> "${LOG_PATH2}" + restart_count_2=$((restart_count_2 + 1)) + echo "重启 ${NAME2} at $(date) - count: ${restart_count_2}" >> "${LOG_PATH2}" + echo "重启 ${NAME2} at $(date) - count: ${restart_count_2}" + # 真正启动 + ${DIR}/${NAME2} >> "${LOG_PATH2}" 2>&1 & + if [ $? -ne 0 ]; then + echo "Failed to start ${NAME2} at $(date)" >> "${LOG_PATH2}" + fi + fi + fi + + + + + if [ "$USE_data_process" == 1 ]; then + rotate_log "$LOG_PATH1" "$MAX_SIZE" "$MAX_BACKUPS" + fi + + rotate_log "$LOG_PATH2" "$MAX_SIZE" "$MAX_BACKUPS" + +done + + + + +# tail -f /home/heco/ys_ecap_server/ecap_1201/data_process.log +# tail -f /home/heco/ys_ecap_server/ecap_1201/ecap_server.log +# multitail /home/heco/ys_ecap_server/ecap_1201/data_process.log /home/heco/ys_ecap_server/ecap_1201/ecap_server.log + + + +# kill -SIGINT +# pkill -SIGINT +# pkill -SIGINT 1125ecap_server +# pgrep -l 1125ecap_server +# [ubuntu创建守护进程,并设置开机自启动(rc.local,rc_local.sercive)] https://blog.csdn.net/weixin_46954054/article/details/134862013 +# [Ubuntu开机自启动脚本/命令的几种方案] https://blog.csdn.net/weixin_43455581/article/details/107815743 + +# sudo pkill protect.bash && sudo pkill -SIGINT ecap_server && pgrep -l protect.bash + + +# pgrep -l protect.bash +# sudo pkill protect.bash +# sudo pkill -SIGINT ecap_server + +# /home/heco/ys_ecap_server/protect.bash ecap_server + +# kill -SIGINT +# pkill -SIGINT +# pkill -SIGINT 1125ecap_server +# pgrep -l 1125ecap_server +# [ubuntu创建守护进程,并设置开机自启动(rc.local,rc_local.sercive)] https://blog.csdn.net/weixin_46954054/article/details/134862013 +# [Ubuntu开机自启动脚本/命令的几种方案] https://blog.csdn.net/weixin_43455581/article/details/107815743 + +# pgrep -l protect.bash +# pkill protect.bash + +# /home/heco/ys_ecap_server/protect.bash ecap_server + +# sudo systemctl daemon-reload +# sudo systemctl enable rc-local.service # 设置开机自启 +# sudo systemctl disable rc-local.service # 关闭开机自启 +# sudo systemctl start rc-local.service # 立即启动服务 +# sudo systemctl status rc-local.service diff --git a/config/restart_net_service.sh b/config/restart_net_service.sh new file mode 100644 index 0000000..e1186e7 --- /dev/null +++ b/config/restart_net_service.sh @@ -0,0 +1,12 @@ +#!/bin/sh + + +reboot + + +#cat etc/network/interfaces +# +#ip link set dev eth0 down +#ip link set dev eth0 up + +#sudo systemctl restart networking \ No newline at end of file diff --git a/config/server_config_win.json b/config/server_config_win.json new file mode 100644 index 0000000..b23b38f --- /dev/null +++ b/config/server_config_win.json @@ -0,0 +1,25 @@ +{ + "file_name": "./qingdao/data", + "http_server": { + "ip": "0.0.0.0", + "port": 40000 + }, + "tcp_server": { + "ip": "0.0.0.0", + "port": 40001, + "clients": [ + { + "id": 0, + "ip": "0.0.0.0", + "port": 10003, + "info": "仿制radarcape" + }, + { + "id": 0, + "ip": "0.0.0.0", + "port": 10003, + "info": "radarcape" + } + ] + } +} \ No newline at end of file diff --git a/config/update.sh b/config/update.sh new file mode 100644 index 0000000..4096b0a --- /dev/null +++ b/config/update.sh @@ -0,0 +1,55 @@ +#!/bin/sh + +export u_path="/media/udisk0" +export exe_name="Radarcape_Local_Server_aarch64-buildroot-linux-gnu-gxx_Linux_Debug" +export guard_exe_name="/bin/sh /etc/init.d/S90E-CAP start" + + +echo "pkill !" +pkill -f "${guard_exe_name}" +pkill -f "${exe_name}" + +echo "remove logs !" +rm -rf /root/logs* + +echo "update config.json!" +cp -r "$u_path"/config.json /root +echo "update restart_net_service.sh!" +cp -r "$u_path"/restart_net_service.sh /root +echo "update interface!" +cp -r "$u_path"/interface /root +echo "update wwwroot!" +rm -rf /root/wwwroot +cp -rp "$u_path"/wwwroot /root + + + +while pgrep -f "${guard_exe_name}" >/dev/null; do + echo "${guard_exe_name} Process is still running wait one second!" + sleep 1 +done +while pgrep -f "${exe_name}" >/dev/null; do + echo "${exe_name} Process is running still running wait one second!" + sleep 1 +done + + +echo "update ${exe_name}!" +cp -r "$u_path/${exe_name}" /root + +#/bin/sh /etc/init.d/S90E-CAP start + +echo "程序更新成功!" + +# 查看挂载: mount +# 卸载U盘: umount /media/udisk0 +# U盘默认地址:/media/udisk0 +# 单独更新 cp -r /media/udisk0/* /root +# mkdir /root/u && chmod 777 /root/u +# 自动部署: cp /media/udisk0/deploy.sh /root/u && chmod 777 /root/u/deploy.sh && /root/u/deploy.sh 190 +# 更新: cp /media/udisk0/update.sh /root/u && chmod 777 /root/u/update.sh && /root/u/update.sh + +# sudo fdisk -l + +# /etc/init.d/S90E-CAP stop +# pkill diff --git a/config/upgrade.bash b/config/upgrade.bash new file mode 100644 index 0000000..3a973da --- /dev/null +++ b/config/upgrade.bash @@ -0,0 +1,113 @@ +#!/bin/bash + +set -euo pipefail + + +if [[ "${UPGRADE_DAEMONIZED:-0}" != "1" ]]; then + export UPGRADE_DAEMONIZED=1 + nohup "$0" "$@" >/dev/null 2>&1 & + exit 0 +fi + +# ---------- 参数校验 ---------- +if [ "$#" -ne 2 ]; then + echo "用法: $0 " + exit 1 +fi + +old_version="$1" +new_version="$2" + +# ---------- 脚本目录 ---------- +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +# ---------- 日志 ---------- +LOG_DIR="${SCRIPT_DIR}/upgrade_logs" +LOG_FILE="${LOG_DIR}/upgrade_${old_version}_to_${new_version}.log" +mkdir -p "$LOG_DIR" + +# 覆盖写日志(重要) +: > "$LOG_FILE" + +# 所有输出写日志 + 控制台 +exec > >(tee -a "$LOG_FILE") 2>&1 + +echo "===== Upgrade start: $(date) =====" +echo "old_version=${old_version}" +echo "new_version=${new_version}" +echo "SCRIPT_DIR=${SCRIPT_DIR}" + +# ---------- 路径定义 ---------- +OLD_DIR="${SCRIPT_DIR}/${old_version}" +NEW_DIR="${SCRIPT_DIR}/${new_version}" +PKG="${NEW_DIR}/${new_version}.zip" +STOP_SCRIPT="${OLD_DIR}/stop.bash" +PT_BIN="${NEW_DIR}/pt" +PROTECT_SCRIPT="${SCRIPT_DIR}/protect.bash" + +# ---------- 基础校验 ---------- +for d in "$OLD_DIR" "$NEW_DIR"; do + [ -d "$d" ] || { echo "目录不存在: $d"; exit 1; } +done + +[ -f "$PKG" ] || { echo "升级包不存在: $PKG"; exit 1; } + +command -v unzip >/dev/null || { echo "unzip 未安装"; exit 1; } + +# ---------- 停止旧版本 ---------- +echo "[1/5] 停止旧版本" +if [ -x "$STOP_SCRIPT" ]; then + "$STOP_SCRIPT" +else + echo "stop.bash 不存在或不可执行: $STOP_SCRIPT" + exit 1 +fi + +# ---------- 解压新版本(覆盖) ---------- +echo "[2/5] 解压新版本" +unzip -o "$PKG" -d "$NEW_DIR" + +# ---------- 校验新程序 ---------- +echo "[3/5] 校验新程序" +[ -f "$PT_BIN" ] || { echo "pt 程序不存在: $PT_BIN"; exit 1; } +chmod +x "$PT_BIN" + +# ---------- 写 protect.bash(覆盖) ---------- +echo "[4/5] 写 protect.bash" + +cat > "$PROTECT_SCRIPT" < "\${DIR}/pt.log" 2>&1 +EOF + +chmod +x "$PROTECT_SCRIPT" + +# ---------- 启动新版本 ---------- +echo "[5/5] 启动新版本" + +LOG_FILE="${NEW_DIR}/pt.log" + +# 确保日志文件存在 +if [ ! -e "$LOG_FILE" ]; then + touch "$LOG_FILE" +fi + +# 设置日志权限 +chmod 777 "$LOG_FILE" + +# 后台启动新版本 +nohup "$PT_BIN" 0 >> "$LOG_FILE" 2>&1 & +disown + +echo "Upgrade finished, pt started in background" +exit 0 \ No newline at end of file diff --git a/config/x86_linux/config.json b/config/x86_linux/config.json new file mode 100644 index 0000000..3d564e3 --- /dev/null +++ b/config/x86_linux/config.json @@ -0,0 +1,174 @@ +{ + "version": "v1.0.0", + "dsp": { + "url": "0.0.0.0", + "port": 6000, + "center_freq": 800000, + "band_width": 6000, + "sample_rate": 7500, + "fft_point_number": 1024, + "fft_period_ms": 50, + "fft_win_type": "blkmc", + "library_path": "@/libdll_source.so", + "filename_prefix": "ECAP_", + "filename_suffix": ".dat", + "power_min": -200, + "power_max": 200, + "power_offset": -166, + "frame_rate": 30, + "debug": false + }, + "drogon": { + "app": { + "threads_num": 0 + } + }, + "mlat": { + "enable": false, + "merge": false, + "library_path": "@/mlat_source.dll", + "function_name": "read" + }, + "web_server": { + "webapp": "@/wwwroot", + "tiles": "@/tiles" + }, + "device": { + "net": [ + { + "key": "device", + "ip": "192.168.1.75", + "netmask": "255.255.255.0", + "gateway": "192.168.1.1", + "port": 9081 + }, + { + "key": "wifi", + "ip": "192.168.10.193", + "netmask": "255.255.255.0", + "gateway": "192.168.10.1", + "port": 80 + } + ] + }, + "mode_acs": { + "timeout_seconds": 60, + "read_milliseconds": 100, + "mode_s_max_num": 700000, + "mode_other_max_num": 10000, + "report_data_feed_msg_mum": 10000, + "monitor_msg_live": false, + "data_feed": { + "empty_wait_milliseconds": 10, + "packet_byte_size": 1, + "list": [ + { + "key": "Port_10003", + "enable": true, + "type": "Data_Feed_TCP_Server", + "output_format": { + "type": "BIN", + "use_status": true, + "mode_s_output_type": "ALL_Mode_S", + "use_mode_ac": true + }, + "port": 10003 + }, + { + "key": "Port_10004", + "enable": false, + "type": "Data_Feed_TCP_Server", + "output_format": { + "type": "BIN", + "use_status": false, + "mode_s_output_type": "DF_11_17_18", + "use_mode_ac": false + }, + "url": "0.0.0.0", + "port": 10004 + }, + { + "key": "Port_10005", + "enable": false, + "type": "Data_Feed_TCP_Client", + "output_format": { + "type": "BIN", + "use_status": true, + "mode_s_output_type": "NO_POS_Mode_S", + "use_mode_ac": false + }, + "url": "192.168.208.153", + "port": 10005 + }, + { + "key": "Port_30003", + "enable": false, + "type": "Data_Feed_TCP_Server", + "output_format": { + "type": "SBS", + "use_status": false, + "mode_s_output_type": "ALL_Mode_S", + "use_mode_ac": true + }, + "port": 30003 + } + ] + }, + "data_source": { + "list": [ + { + "key": "dll", + "enable": true, + "base_station_show": true, + "aircraft_show": true, + "color": "#6c5552fa", + "aircraft_pixel_size": 34, + "lat": 37.510269, + "lon": 121.439950, + "alt": 1000.000000, + "update_form_gps": false, + "type": "Dll_Data_Source", + "library_path": "@/libdll_source.so", + "function_name": "adsb_read", + "data_type": "BIN_Blank" + }, + { + "key": "binary_data48__2025-01-06.222333", + "enable": false, + "base_station_show": true, + "aircraft_show": true, + "color": "#4e545c", + "aircraft_pixel_size": 38, + "lat": 37.510269, + "lon": 121.439950, + "alt": 1000.000000, + "update_form_gps": false, + "type": "File_Data_Source", + "file_path": "C:\\wyc\\CLionProjects\\plantSunCat\\mainProjects\\Radarcape\\data\\BIN\\binary_data48__2025-01-06.2.log", + "data_type": "BIN", + "play_mode": "analysis" + } + ] + }, + "source_feed_relation": { + "list": [ + { + "key": "key_10003", + "enable": true, + "type": "First_Source_To_All_Feed_Relation" + } + ] + } + }, + "log": { + "open_mode": "Delete", + "piece_num": 10, + "size_MB": 10 + }, + "console": { + "record_playback": false, + "mode_s_console": false, + "post_request": false, + "mlat_server": true + } +} diff --git a/config/x86_linux/data_progress_config.json b/config/x86_linux/data_progress_config.json new file mode 100644 index 0000000..53fb584 --- /dev/null +++ b/config/x86_linux/data_progress_config.json @@ -0,0 +1,9 @@ +{ + "library_path": "@/libdll_source.so", + "center_freq": 200000, + "band_width": 6000, + "sample_rate": 60000, + "fft_point_number": 2048, + "fft_period_ms": 50, + "fft_win_type": "blkmc" +} \ No newline at end of file diff --git a/config/前端任务 b/config/前端任务 new file mode 100644 index 0000000..59d2806 --- /dev/null +++ b/config/前端任务 @@ -0,0 +1,7 @@ +前端构思 + + +那些接口写整体加上 一个数据源参数 +数据源可以设置颜色 默认随机色 + + diff --git a/doc/10003 b/doc/10003 new file mode 100644 index 0000000..bfad639 --- /dev/null +++ b/doc/10003 @@ -0,0 +1,74 @@ +9.3.1 Packetizing & Line Encoding +HULC Protocol uses the byte 0x1A as start-of-packet (SOP) marker. In order to avoid misinterpretation +of normal data bytes with value 0x1A as SOP, each occurrence of data byte 0x1A is doubled in the +data stream during transmission ('escaping'). It is thus necessary during reception to detect every +0x1A not followed by another 0x1A as an SOP marker and to reduce every occurrence of a double +0x1A to a single 0x1A data byte ('un-escaping'). +Example of a 4-byte long packet including SOP marker and 0x1A data bytes: +Before Escaping: 1A 32 27 1A E8 57 F0 1A 6C +During Transmission: 1A 32 27 1A 1A E8 57 F0 1A 1A 6C +After Un-Escaping: 1A 32 27 1A E8 57 F0 1A 6C + + + +Type Payload Size Description +0x31 4 bytes Mode-A/C raw data +0x32 7 bytes Mode-S Short Squitter raw data +0x33 14 bytes Mode-S Extended Squitter raw data + + +ll Data messages (Type 0x31 & 0x32 & 0x33) have the following structure: +0x1A TYPE Timestamp RSSI Data (Mode-S or Mode-A/C) + + +Fields: +TYPE 8-bit 0x31 or 0x32 or 0x33 for Mode-A/C or Mode-S short or extended squitter respectively +Timestamp 48-bit1 + Upper 18 bits are seconds since last midnight 00:00:00 UTC + Lower 30 bits are nanoseconds of current second +RSSI 8-bit Logarithmic field-strength indicator, uncalibrated +Data N * 8-bit raw data, N=4 for Type 0x31, N=7 for TYPE 0x32 and N=14 for TYPE 0x33 +1) MSB-first + + +Timestamps: +There are two distinct timestamp formats, absolute and relative timestamps depending on +whether a GPS receiver is attached or not. To find out which format is used check bit 15 +(Gps Detected) in the status flag field of the HULC Status Message. Both timestamp formats +are compatible with the respective timestamp formats used in the Beast Binary Protocol. +Relative Timestamp (No GPS): +Without a GPS receiver attached the timestamp is a 48-bit unsigned number counting 12 +MHz cycles. The timestamp will wrap approximately every 271 days. +Absolute Timestamp (With GPS): +If a suitable GPS receiver is attached the 48-bit timestamp field is divided into the upper +18 bits which count the seconds since last midnight 00:00:00 UTC and the lower 30 bits +which carry the nanoseconds of the current second. Timestamp nanoseconds are +guaranteed to be less than one complete second. +Example: 0x3746554be940 = (56601 sec + 357296448 nsec) = 15:43:21.357296448 +UTC + + +1A 31 +3A 52 56 53 02 E1 +8F +37 5A 1A A3 + +1A 31 +3A 52 56 53 02 E1 +8F +37 5A 1A 1A A3 + +1A 31 +4B 03 5B 02 E1 90 +10 +1E 89 50 + +1a31 +19 ea b6 3a 1f 91 +65 +01 47 + +1a31 +19 b4 18 c3 59 0c +6d +32 10 \ No newline at end of file diff --git a/doc/10003_zh b/doc/10003_zh new file mode 100644 index 0000000..0112b22 --- /dev/null +++ b/doc/10003_zh @@ -0,0 +1,39 @@ +数据包封装与行编码 +HULC协议使用字节0x1A作为数据包的起始标记(SOP)。为了避免误将正常数据字节0x1A解释为SOP标记,每次遇到数据字节0x1A时,会在数据流中对其进行转义(即“转义”操作), +即将0x1A替换为两个0x1A字节。接收端需要在接收时识别每个后续不是0x1A的0x1A字节作为SOP标记,并将每次出现的连续0x1A字节还原为一个0x1A的数据字节(即“解除转义”操作)。 +以下是一个包含SOP标记和数据字节0x1A的数据包示例: +转义前: 1A 32 27 1A E8 57 F0 1A 6C +传输中: 1A 32 27 1A 1A E8 57 F0 1A 1A 6C +解除转义后: 1A 32 27 1A E8 57 F0 1A 6C + + + + +所有类型的数据消息(0x31、0x32、0x33)具有以下结构: +0x1A TYPE 时间戳 RSSI数据 Mode-S或Mode-A/C + 1 1 6 1 2/7/14 +各字段说明: + TYPE(类型):8位,表示数据类型。0x31代表Mode-A/C,0x32代表Mode-S短报文,0x33代表Mode-S扩展报文。 + 时间戳(Timestamp):48位,包含两个部分: + 高18位:自当天00:00:00 UTC以来的秒数。 + 低30位:当前秒的纳秒部分。 + RSSI(信号强度指示):8位,表示信号强度的对数值(未校准)。 + 数据(Data):N * 8位的原始数据,具体长度取决于数据类型: + 对于Type 0x31,数据长度为2字节; + 对于Type 0x32,数据长度为7字节; + 对于Type 0x33,数据长度为14字节。 + 备注:数据采用MSB(最高位优先)格式。 + + + +时间戳格式 +时间戳有两种格式,分别是绝对时间戳和相对时间戳,取决于是否连接了GPS接收器。可以通过检查HULC状态消息中的状态标志字段的第15位(Gps Detected)来确定使用的是哪种格式。两种时间戳格式与Beast二进制协议中的相应时间戳格式兼容。 +1.相对时间戳(无GPS): +如果没有连接GPS接收器,则时间戳是一个48位的无符号整数,表示12 MHz的时钟周期数。该时间戳大约每271天会回绕一次。 +2.绝对时间戳(有GPS): +如果连接了适当的GPS接收器,则48位的时间戳字段分为两部分: +高18位:表示自当天00:00:00 UTC以来的秒数。 +低30位:表示当前秒的纳秒部分。纳秒数保证小于1秒。 + +示例: 时间戳0x3746554be940代表的时间为: +56601秒 + 357296448纳秒 = UTC时间:15:43:21.357296448 \ No newline at end of file diff --git a/doc/11.txt b/doc/11.txt new file mode 100644 index 0000000..b9136e6 --- /dev/null +++ b/doc/11.txt @@ -0,0 +1,78 @@ +AIVDM/AIVDO Sentence Layer +AIVDM/AIVDO is a two-layer protocol. The outer layer is a variant of NMEA 0183, the ancient standard for data interchange in marine navigation systems; NMEA 0183 is described at [NMEA]. +Here is a typical AIVDM data packet: +!AIVDM,1,1,,B,177KQJ5000G?tO`K>RA1wUbN0TKH,0*5C +And here is what the fields mean: +Field 1, !AIVDM, identifies this as an AIVDM packet. +Field 2 (1 in this example) is the count of fragments in the currently accumulating message. The payload size of each sentence is limited by NMEA 0183’s 82-character maximum, so it is sometimes required to split a payload over several fragment sentences. +Field 3 (1 in this example) is the fragment number of this sentence. It will be one-based. A sentence with a fragment count of 1 and a fragment number of 1 is complete in itself. +Field 4 (empty in this example) is a sequential message ID for multi-sentence messages. +Field 5 (B in this example) is a radio channel code. AIS uses the high side of the duplex from two VHF radio channels: AIS Channel A is 161.975Mhz (87B); AIS Channel B is 162.025Mhz (88B). In the wild, channel codes '1' and '2' may also be encountered; the standards do not prescribe an interpretation of these but it’s obvious enough. +Field 6 (177KQJ5000G?tO`K>RA1wUbN0TKH in this example) is the data payload. We’ll describe how to decode this in later sections. +Field 7 (0) is the number of fill bits requires to pad the data payload to a 6 bit boundary, ranging from 0 to 5. Equivalently, subtracting 5 from this tells how many least significant bits of the last 6-bit nibble in the data payload should be ignored. Note that this pad byte has a tricky interaction with the [ITU1371]requirement for byte alignment in over-the-air AIS messages; see the detailed discussion of message lengths and alignment in a later section. +The *-separated suffix (\*5C) is the NMEA 0183 data-integrity checksum for the sentence, preceded by "*". It is computed on the entire sentence including the AIVDM tag but excluding the leading "!". This checksum is the XOR of all bytes in the payload. +For comparison, here is an example of a multi fragment sentence with a nonempty message ID field: +!AIVDM,2,1,3,B,55P5TL01VIaAL@7WKO@mBplU@qc:0001R:t?tUFfnT03wj4h4Id,0*73 +!AIVDM,1,1,,A,E:hTsH1Pb7W@LHHqIHKqIHIJqpqDEpF8:eLFp1088;AP02,4*0E +// + +!AIVDM,1,1,,B,177KQJ5000G?tO`K>RA1wUbN0TKH,0*5C +下面是字段的含义: + +字段 1,!AIVDM,标识这是一个 AIVDM 数据包。 +字段 2(此示例中为 1)是当前正在累积的消息中的片段总数。由于每条 NMEA 0183 语句的最大有效负载大小为 82 字符,因此有时需要将有效负载拆分为多个片段语句。 +字段 3(此示例中为 1)是当前语句的片段编号,采用基于 1 的计数。如果片段总数为 1 且片段编号为 1,则该语句本身是完整的。 +字段 4(此示例为空)是多片段消息的序列消息 ID。 +字段 5(此示例中为 B)是无线电频道代码。AIS 使用两个 VHF 无线电频道的高端:AIS A频道是 161.975 MHz(87B),AIS B频道是 162.025 MHz(88B)。在实际应用中,也可能遇到频道代码 '1' 和 '2';标准并没有规定这些代码的含义,但显然它们也有明显的区分。 +字段 6(此示例中的 177KQJ5000G?tOK>RA1wUbN0TKH`)是数据有效载荷。稍后我们将描述如何解码它。 +字段 7(此示例中的 0)是填充位的数量,用于将数据有效载荷填充到 6 位的边界,范围为 0 到 5。相应地,从这个数字减去 5 就是告诉我们在数据有效载荷的最后一个 6 位字节中需要忽略的最低有效位数。需要注意的是,这个填充字节与 [ITU1371] 对于无线电 AIS 消息的字节对齐要求有一个复杂的相互作用,稍后会详细讨论消息长度和对齐问题。 +以 * 分隔的后缀(*5C)是该语句的 NMEA 0183 数据完整性校验和,计算方式是对整个语句进行异或运算,包括 AIVDM 标签,但不包括前导的 ! 字符。 +为了便于对比,这里是一个多片段语句的示例,其中消息 ID 字段不为空: + + + +!AIVDM,2,1,3,B,55P5TL01VIaAL@7WKO@mBplU@ 使用绝对时间戳 +x1xx xxxx xxxx xxxx - GPS 有效 (GGA, RMC 数据存在) +xx1x xxxx xxxx xxxx - GPS 当前有有效定位 +xxx1 xxxx xxxx xxxx - 高精度绝对时间通过 PPS 可用 +xxxx xxxx 1xxx xxxx - 启动以来的 TX-队列溢出(如果使用硬件握手通常会发生) +xxxx xxxx x1xx xxxx - 上一秒发生的 TX-队列溢出(可能由于硬件握手) +xxxx xxxx xx1x xxxx - 发现过多的 NMEA 数据(除 GGA/RMC 外) \ No newline at end of file diff --git a/doc/icao解码.txt b/doc/icao解码.txt new file mode 100644 index 0000000..f353bd8 --- /dev/null +++ b/doc/icao解码.txt @@ -0,0 +1,50 @@ +https://mode-s.org/1090mhz/content/mode-s/1-basics.html + + + +p(x):crc计算结果 + +符号解释 +A:是ICAO地址 +P:是后24位置零,crc的计算结果,任何消息都能算这个值 +AP=A^P + +异或可逆性性 +AP = A^P +A = AP^P +P = AP^A +DP = BDS^AAA^P //DP是数据奇偶校验,目前没看到那种24位,存这种东西 + + +df = 11 17 18 : 消息后24位存放P, A明文存放在消息中,直接获取 +df = 0 4 5 16 20 21 消息后24位存放AP, 先计算P,然后根据 A=AP^P 计算出A + + +// 上面这个df pyModeS-master 项目 源码py_common.py :119 +// pyModeS-master项目 作者也是 那个文档的作者 + +def icao(msg: str) -> Optional[str]: +"""Calculate the ICAO address from an Mode-S message. + + Applicable only with DF4, DF5, DF20, DF21 messages. + + Args: + msg (String): 28 bytes hexadecimal message string + + Returns: + String: ICAO address in 6 bytes hexadecimal string + + """ + addr: Optional[str] + DF = df(msg) + + if DF in (11, 17, 18): + addr = msg[2:8] + elif DF in (0, 4, 5, 16, 20, 21): + c0 = crc(msg, encode=True) + c1 = int(msg[-6:], 16) + addr = "%06X" % (c0 ^ c1) + else: + addr = None + + return addr diff --git a/doc/radarcape_状态消息.txt b/doc/radarcape_状态消息.txt new file mode 100644 index 0000000..216e413 --- /dev/null +++ b/doc/radarcape_状态消息.txt @@ -0,0 +1,65 @@ +当选择 GPS 时间戳时,状态帧由 1PPS 脉冲触发,在传统 12MHz 时间戳的情况下随机触发。 +状态帧包含有效的时间戳 +信号电平值为零 + + + +1. 消息内容 状态帧 +0x34 包含以下信息: + Byte 0:FPGA 开关设置状态 + Byte 1:1PPS 事件时的纳秒级时间偏移量 + Byte 2:GPS 相关状态信息 + + +2. Byte 0: +Byte 0 反映了 FPGA 的开关设置,FPGA 的这些设置会直接影响 原始数据端口 (10002-10006),以及高层功能的数据可用性。 +FPGA 开关设置: + Bit 位 '1'(启用) '0'(禁用) + Bit 0 数据输出模式 (端口 10002 适用):二进制格式 AVR Hexdump 格式 + Bit 1 原始数据帧类型:仅 DF11、DF17 和 DF18 无预过滤,输出所有帧类型 + Bit 2 AVR 格式中的时间戳:启用 禁用 + Bit 3 未使用 未使用 + Bit 4 时间戳模式:GPS 传统 12MHz + Bit 5 串行流控:禁用 启用 + Bit 6 1-bit 前向纠错 (FEC):禁用 启用 + Bit 7 Mode-A/C 解码:启用 禁用 + +3. Byte 1:1PPS 事件的纳秒偏移 + 当处于 GPS 时间戳模式 时: + Byte 1 记录 1PPS 事件时,纳秒定时器的偏移量。 + 该值的单位为 15.625ns,正常范围为 -3 至 +3。 + + +4. Byte 2:GPS 状态信息 + Byte 2 记录 GPS 相关的状态,具体比特位定义如下: + Bit 位 '1'(正常) '0'(异常) + Bit 0 天线状态:良好 失败 + Bit 1 至少跟踪 1 颗卫星:是 否 + Bit 2 至少跟踪 3 颗卫星:是 否 + Bit 3 时间基准:UTC 时间 GPS 时间(相差 8 秒) + Bit 4 未使用 未使用 + Bit 5 未使用 未使用 + Bit 6 未使用 未使用 + Bit 7 Daysec(一天的秒数范围):0 - 86399 1 - 86400 + + +5. 相关说明 +GPS 时间与 UTC 时间 + GPS 时间比 UTC 时间 早 8 秒。 + Bit 3 可以用于区分系统使用的时间基准。 + +FPGA 开关设置对数据的影响 + Bit 0 影响 数据端口 10002 的输出格式。 + Bit 1 影响 是否预过滤帧类型。 + Bit 4 选择 时间戳模式,影响所有时间同步相关功能。 + +总结 + 状态帧 0x34 提供了 FPGA 设置、1PPS 偏移量 和 GPS 状态,对于时间同步、数据格式选择和 GPS 信号监测至关重要。 + + +官网相关资料 +https://wiki.jetvision.de/wiki/Mode-S_Beast:Data_Output_Formats +https://wiki.jetvision.de/wiki/Radarcape:Version_History#Status_Frame_0x34_contents_were_extended_with_GPS_and_UTC_information + + +实际采集信息 和官网文档对不上 官网好多东西没说 \ No newline at end of file diff --git a/doc/模块数据格式分析 b/doc/模块数据格式分析 new file mode 100644 index 0000000..0fc04f7 --- /dev/null +++ b/doc/模块数据格式分析 @@ -0,0 +1,53 @@ + +@000217047C020143; +@0002170A69FE5D781F835AFF22; +@0002170759188D781F832320C1B8E31C200772A4; + + + +@000217047C02 0143; + +当启用MLAT格式时有下面三种格式 +@ + 6字节(48位)MLAT时间戳,1 字节信号电平,2 字节 Mode-AC + ; +@ + 6字节(48位)MLAT时间戳,1 字节信号电平,7 字节 Mode-S 短帧 + ; +@ + 6字节(48位)MLAT时间戳,1 字节信号电平,14 字节 Mode-S 长帧 + ; + +1字节信号电平 +功率大小 以 dBm 为单位 +时间戳格式 (18位 当天的秒数 + 30位 当天的纳秒数) +例: 时间戳 244bbb9ac9f0 +高18位 秒数 = 37166 +低30位 纳秒 = 999999984 +例如: +@016CE3671C74 7700; +@016CE3671C74 23FFE7AB7BFCAB; +@016CE3671AA8 A800199A8BB80030A8000628F400; + +参考链接 +https://wiki.jetvision.de/wiki/Mode-S_Beast:Data_Output_Formats +https://wiki.jetvision.de/wiki/Radarcape:Version_History#The_GPS_timestamp +https://wiki.jetvision.de/wiki/Radarcape:Version_History#Signal_level_in_dBm + + +1110 0000 0011 0000 + +2) https://en.wikipedia.org/wiki/Binary_scaling#Binary_angles + Status Flags: + 1xxx xxxx xxxx xxxx - GPS device detected -> Using absolute timestamp + x1xx xxxx xxxx xxxx - GPS valid (GGA, RMC present) + xx1x xxxx xxxx xxxx - GPS currently has a valid fix + xxx1 xxxx xxxx xxxx - High accuracy absolute time is available via PPS + xxxx xxxx 1xxx xxxx - TX-Queue overflow since start-up (normal if HW-handshaking is used) + xxxx xxxx x1xx xxxx - TX-Queue overflow during last second (probably due to HW-handshaking) + xxxx xxxx xx1x xxxx - Excessive NMEA found (other than GGA/RMC) + + +1a48 +0118 + +9607f81e +e030 + +000000000000000000000000000000000000 + +e030 diff --git a/doc/泰山派开发记录.md b/doc/泰山派开发记录.md new file mode 100644 index 0000000..8837ecc --- /dev/null +++ b/doc/泰山派开发记录.md @@ -0,0 +1,418 @@ +# ==应用开发== + +## APP + +CMakeLists.txt + +```cmake +cmake_minimum_required(VERSION 3.10) + +########################## 可单独生成 toolchain.cmake ################################################# +set(CMAKE_SYSTEM_NAME Linux) # 设置目标系统名字 +set(CMAKE_SYSTEM_PROCESSOR arm) # 设置目标处理器架构 + +# 该变量的值会传递给 gcc 编译器的--sysroot 选项,也就是--sysroot=${CMAKE_SYSROOT},--sysroot 选项指定了编译器的 sysroot 目录,也就是编译器的系统根目录,编译过程中需要链接的库、头文件等,就会去该目录下寻找,譬如标准 C 库、标准 C 头文件这些。 +set(CMAKE_SYSROOT /home/ml/sdk/buildroot/output/rockchip_rk3566/host/aarch64-buildroot-linux-gnu/sysroot/) # ⭐指定了目标系统的根目录 + +# 设置编译器路径 +set(CMAKE_C_COMPILER /home/ml/sdk/prebuilts/gcc/linux-x86/aarch64/gcc-linaro-6.3.1-2017.05-x86_64_aarch64-linux-gnu/bin/aarch64-linux-gnu-gcc) +set(CMAKE_CXX_COMPILER /home/ml/sdk/prebuilts/gcc/linux-x86/aarch64/gcc-linaro-6.3.1-2017.05-x86_64_aarch64-linux-gnu/bin/aarch64-linux-gnu-g++) +# 为编译器添加编译选项 +#set(CMAKE_C_FLAGS "-march=armv7ve -mfpu=neon -mfloat-abi=hard -mcpu=cortex-a7") +#set(CMAKE_CXX_FLAGS "-march=armv7ve -mfpu=neon -mfloat-abi=hard -mcpu=cortex-a7") + +# NEVER:仅搜索主机系统路径。 +# ONLY:只搜索 CMAKE_SYSROOT。 +# BOTH:将搜索主机系统路径和 CMAKE_SYSROOT 中的路径。 +set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) +set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) # 限制find_library()的搜索路径。 +set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) # 限制find_file()和 find_path()的搜索路径。 + +#set(ENV{LD_LIBRARY_PATH} "${CMAKE_SYSROOT}/lib:$ENV{LD_LIBRARY_PATH}") # 添加库路径到 LD_LIBRARY_PATH + +#set(CMAKE_LIBRARY_PATH "/opt/atk-dlrk356x-toolchain/lib/") # 添加依赖库find路径:用于指定库文件被find_library()时的目录列表。 +#set(CMAKE_INCLUDE_PATH "/opt/atk-dlrk356x-toolchain/include") # 添加依赖库头文件find路径:用于指定find_path()头文件时应考虑的额外目录列表。 + +set(CMAKE_INSTALL_PREFIX ${CMAKE_SOURCE_DIR}/myinstall) # 设置安装目录,当前CMakeLists.txt所在目录下的myinstall文件夹 +###################################################################################################### + +# 设置项目名称 +project(mongoose VERSION 1.0) + +# 包含工具链文件 +set(CMAKE_TOOLCHAIN_FILE ${CMAKE_CURRENT_SOURCE_DIR}/toolchain.cmake CACHE STRING "Toolchain file") + +# 查找所有源文件 +file(GLOB SOURCES "${CMAKE_SOURCE_DIR}/*.cpp" "${CMAKE_SOURCE_DIR}/*.c") + +# 添加可执行文件 +add_executable(${PROJECT_NAME} ${SOURCES}) + +# 指定头文件目录 +target_include_directories(${PROJECT_NAME} PRIVATE mongoose) +``` + + + +```sh +root@RK356X:/mnt# ./mongoose +terminate called after throwing an instance of 'std::runtime_error' + what(): locale::facet::_S_create_c_locale name not valid +Aborted +``` + +## WIFI&蓝牙 + +泰山派开发板板载了WIFI+蓝牙二合一模块,这里默认贴的是AP6212。 + +```sh +vi /data/cfg/wpa_supplicant.conf # 修改配置文件 +wpa_supplicant -B -i wlan0 -c /data/cfg/wpa_supplicant.conf # wpa_supplicant重新读取配置文件,启动,后面wpa_cli会和它进行通讯。 +wpa_cli -i wlan0 -p /var/run/wpa_supplicant scan # [可选]WIFI扫描,wpa_cli跟wpa_supplicant通信,确保wpa_supplicant运行。 +wpa_cli -i wlan0 -p /var/run/wpa_supplicant scan_results # [可选]显示扫描结果 +wpa_cli -i wlan0 -p /var/run/wpa_supplicant reconnect # 发起连接 +ping lckfb.com +``` + + + +## LED控制 + +RK3588的GPIO引脚号的计算方式,参考如下公式:( A、B、C、D 分别代表数值 0、1、2、3) + +GPIO3_A1 = 3x32 + 0x8 +1 = 97 + +| | 复用功能 | GPIO | 引脚编号 | 复用功能 | 复用功能 | | | +| -------- | ------------ | -------- | -------- | -------- | -------- | ----------- | ---- | +| | 3.3V | 3.3V | 1 | 2 | 5V | 5V | | +| | I2C2_SDA_M0 | GPIO0_B6 | 3 | 4 | 5V | 5V | | +| | I2C2_SCL_M0 | GPIO0_B5 | 5 | 6 | GND | GND | | +| | GPIO | GPIO1_A4 | 7 | 8 | GPIO3_B7 | UART3_TX_M1 | | +| | GND | GND | 9 | 10 | GPIO3_C0 | UART3_RX_M1 | | +| 97 | GPIO | GPIO3_A1 | 11 | 12 | GPIO3_C4 | PWM14_M0 | | +| 98 | GPIO | GPIO3_A2 | 13 | 14 | GND | GND | | +| 99 | GPIO | GPIO3_A3 | 15 | 16 | GPIO3_A4 | GPIO | 100 | +| | 3.3V | 3.3V | 17 | 18 | GPIO3_A5 | GPIO | 101 | +| | SPI3_MOSI_M1 | GPIO4_C3 | 19 | 20 | GND | GND | | +| | SPI3_MISO_M1 | GPIO4_C5 | 21 | 22 | GPIO3_A6 | GPIO | 102 | +| | SPI3_CLK_M1 | GPIO4_C2 | 23 | 24 | GPIO4_C6 | SPI3_CS0_M1 | | +| | GND | GND | 25 | 26 | GPIO3_A7 | | | +| | I2C3_SDA_M1 | GPIO3_B6 | 27 | 28 | GPIO3_B5 | I2C3_SCL_M1 | | +| | GPIO | GPIO3_B0 | 29 | 30 | GND | GND | | +| | GPIO | GPIO3_C2 | 31 | 32 | GPIO3_C5 | PWM15_IR_M0 | | +| 3 RK_PB1 | PWM8_M0 | GPIO3_B1 | 33 | 34 | GND | GND | | +| 3 RK_PB2 | PWM8_M0 | GPIO3_B2 | 35 | 36 | GPIO3_C3 | GPIO | | +| | GPIO | GPIO0_B7 | 37 | 38 | GPIO3_B3 | GPIO | | +| | GND | GND | 39 | 40 | GPIO3_B4 | GPIO | | + +```sh + +root@RK356X:/sys/class/gpio/gpio25# echo 97 > /sys/class/gpio/export +root@RK356X:/sys/class/gpio/gpio25# echo 98 > /sys/class/gpio/export +root@RK356X:/sys/class/gpio/gpio25# echo 99 > /sys/class/gpio/export +root@RK356X:/sys/class/gpio/gpio25# echo 100 > /sys/class/gpio/export +root@RK356X:/sys/class/gpio/gpio25# echo 101 > /sys/class/gpio/export +root@RK356X:/sys/class/gpio/gpio25# echo 102 > /sys/class/gpio/export + +echo out > /sys/class/gpio/gpio97/direction +echo out > /sys/class/gpio/gpio98/direction +echo out > /sys/class/gpio/gpio99/direction +echo out > /sys/class/gpio/gpio100/direction +echo out > /sys/class/gpio/gpio101/direction +echo out > /sys/class/gpio/gpio102/direction + +echo 1 > /sys/class/gpio/gpio97/value +echo 1 > /sys/class/gpio/gpio98/value +echo 1 > /sys/class/gpio/gpio99/value +echo 1 > /sys/class/gpio/gpio100/value +echo 1 > /sys/class/gpio/gpio101/value +echo 1 > /sys/class/gpio/gpio102/value //待验证?? +``` + + + +## ADS-B模块:GNS5894 + +**模块测试:** + +```sh +stty -F /dev/ttyS4 3000000 +cat /dev/ttyS4 +``` + +**控制命令:协议切换** + +11引脚:UART PS(低:HULC协议;高:Text协议),HULC协议的波特率921600、8N1、**RTS/CTS**,Text协议的波特率3000000、8N1、**RTS/CTS**。 + +Text协议在很大程度上与所谓的 AVR 协议兼容,而 HULC 协议的 Mode-S 消息与所谓的 Beast 二进制协议兼容,方便将 GNS 5894 TAC 与现有软件连接。 + +### 1.Text协议 + +**命令格式** + +每条消息都以 '#' (0x23) 开头,以 '' (0x0D, 0x0A) 结尾。中间是 1 到 16 个字节,采用 2 位十六进制表示,使用大写字母,用 '-' (0x2D) 分隔。 + +```sh +# command-message举例: +#00 # ASCII码发送,需要结尾发送回车换行 +23 30 30 0D 0A # HEX发送,0D 0A就是回车换行 +#43-12-00-00-00-00-00-00-00-00-00-00-00-00-00-00 # ASCII码接收 +23 34 33 2D 31 32 2D 30 30 2D 30 30 2D 30 30 2D 30 30 2D 30 30 2D 30 30 2D 30 30 2D 30 30 2D 30 30 2D 30 30 2D 30 30 2D 30 30 2D 30 30 2D 30 30 0D 0A # HEX接收 + +#43-02 # ASCII码发送 +23 34 33 2D 30 32 0D 0A # HEX发送 +``` + +**模块命令** + +1. 查看版本 + +```sh +#00 # 版本请求 +#00-00-80-04-81-yy-ww-bb-xx-xx-xx-xx-xx-xx-xx-xx +#00 +#00-00-80-04-81-15-0A-11-01-02-03-01-00-00-00-00 +``` + +2. 模式读取/设置 + +| 低四位 | 输出模式 | 高四位 | 模式标志 | +| ------ | --------------------------------- | ------ | ------------------------------- | +| 0x00 | Mode-S 数据关闭 | 0x10 | MLAT 模式(不与 0x80 结合使用) | +| 0x01 | 保留 | 0x80 | RSSI 模式(不与 0x10 结合使用) | +| 0x02 | 默认输出所有Mode-S & Mode-A/C数据 | | | +| 0x03 | 仅输出 ADS-B 数据 (DF17-19) | | | +| 0x04 | 仅输出具有有效 CRC 的 ADS-B 数据 | | | + +注:MLAT 模式就是**时间戳**加数据;RSSI 模式就是**信号强度**加数据。但是不能同时输出这两种模式。 + +```sh +# 设置模式 +# 通过 MLAT 模式(0x10)输出所有Mode-S & Mode-A/C数据(0x02) +#43-12 +#43-12-00-00-00-00-00-00-00-00-00-00-00-00-00-00 + +# 读取当前模式 +#43 # 模式命令/请求 +#43-02-00-00-00-00-00-00-00-00-00-00-00-00-00-00 # 返回模式02 +``` + +3. Mode-S & Mode-A/C 数据帧接收 + +在 0x02模式(接收所有 DF 数据)下,12位或56位或112位原始数据帧被输出为4字节或7字节或14字节ASCII帧,MSB优先。以 '*' 开头,以 ';' 结束。 + +![image-20240914144813244](泰山派开发记录/image-20240914144813244.png) + +| | | | | | | +| ---- | ---- | ---- | ---- | ---- | ---- | +| | | | | | | + + + +```sh +# 正常模式(默认): +*<7或14字节数据> ; # Mode-S 格式 +*5D4951B4192B49; # DF11 Mode-S 7 字节(短报文 Short Squitter) +*5D780AE871C60D; # DF11 All-call reply +*024101315B7DB6; # Short air-air surveillance (ACAS) +*20000210BE8DCE; # Long air-air surveillance (ACAS) + +*8D4951B49945B40CE8589F6181B6; # DF18 Mode-S 14 字节(扩展报文 Ext.Squitter) +*8D780AE899094D8CF0A02FA77CD2; # Extended squitter + +*<2字节2的2位八进制数据>; # Mode-A/C 格式 +*5734; # Mode-A/C 数据 + +# MLAT 模式(可选): +@<6字节时间戳><4/7/14字节的2位数据>;<6字节时间戳>:6字节MSB优先自由运行12MHz计数器值,十六进制为12位。 +@112233445566 5D4951B4192B49; # Short Squitter +@1122334455668D4951B49945B40CE8589F6181B6; # Ext. Squitter +@1122334455665734; # Mode-A/C + +# RSSI 模式(可选): ++<1字节RSSI> <4/7/14字节的2位数据>>; +<1字节RSSI>: 1字节未校准的对数RSSI值,以2位十六进制表示 ++AB5D4951B4192B49; ++AB8D4951B49945B40CE8589F6181B6; ++AB5734; +``` + +在 0x02+ RSSI 模式(所有模式-S & 模式-A/C数据的接收器,带有附加信号强度指示器)下,12 位或 56 位或 112 位原始数据帧输出为 3 字节、8 字节或 15 字节 ASCII 帧,MSB 优先。每个 ASCII 帧都以 '+' 开头,以 ';' 结束。 + +“+”后面的第一个字节是当前 ADS-B 帧的信号强度指示器。 + +重要提示: + +在数据之前的信号强度指示器(Signal Strength Indicator)仅仅是一个接收到的帧的场强(即信号强度)的指示器,而不是一个可以精确计算出与发射器之间距离的测量值。换句话说,这个信号强度指示器只告诉你信号的强弱,但它不能直接、确定地用来计算出你离信号发射器的确切距离。 + +该指示器所表示的值大约范围在0x20到0xd5之间。其中,0x20代表较远的距离(即信号较弱),而0xd5代表较近的距离(即信号较强)。这里的0x前缀表示这是一个十六进制数。在实际应用中,不同的设备或系统可能会对这个范围有不同的解释或处理方式,但基本原理相同:它提供的是一个信号强度的相对度量,而不是与发射器之间距离的直接度量。 + +### 2.HULC协议 + +参考`GNS5894TAC_ADSBModul_datasheet_V1.1.pdf`,待整理 + + + +## AIS模块:GNS5851 + +**模块测试:** + +```sh +stty -F /dev/ttyS3 115200 +cat /dev/ttyS3 +``` + + + + + + +# 术语 + +## Mode-S 和 Mode-A/C + +Mode-S (Mode Select) 和 Mode-A/C (Mode A and Mode C) 是航空监视系统中使用的不同类型的应答信号格式,它们分别用于不同的目的和提供不同的信息。 + +**Mode-A/C 帧** + +Mode-A/C 代表的是传统的二次监视雷达 (SSR, Secondary Surveillance Radar) 所使用的信号格式。Mode-A 和 Mode-C 是两个不同的信号模式,它们通常结合使用来提供飞机的身份识别和高度信息。 + +- **Mode-A (Mode Alpha)**:提供身份识别信息。飞机上的应答器会在收到询问信号后发送一个四位数的代码,这个代码由空中交通管制员分配给飞机,用于区分不同的飞行器。 +- **Mode-C (Mode Charlie)**:提供高度信息。与 Mode-A 类似,但 Mode-C 传输的是飞机的高度信息,通常以百英尺为单位。 + +**Mode-S 帧** + +Mode-S (Mode Select) 是一种更为现代的应答信号格式,它提供了比 Mode-A/C 更多的功能和更高的数据传输能力。Mode-S 被设计用于增强安全性和效率,尤其是在繁忙的空域中。 + +- **Mode-S 基本模式**:类似于 Mode-A/C,但也提供了飞机的身份识别信息。 +- **Mode-S 扩展消息 (ES)**:这是 Mode-S 的扩展版本,可以携带更多的信息,如飞机的位置、速度和其他相关数据。Mode-S ES 可以支持 ADS-B (Automatic Dependent Surveillance-Broadcast) 技术,这是一种自动广播监视技术,允许飞机自主广播其位置和其他飞行信息。 +- **Mode-S 增强型**:除了基本的身份识别和 ADS-B 信息外,还可以支持更多功能,如选择性呼叫、数据链通信等。 + +**区别** + +- **信息量**:Mode-S 能够携带更多的信息,而不仅仅是简单的识别和高度信息。 +- **安全性**:Mode-S 支持加密通信,增加了安全性。 +- **数据速率**:Mode-S 的数据速率更高,可以更快地传输更多的信息。 +- **兼容性**:Mode-A/C 是传统的格式,大多数旧的飞机仍然使用;而 Mode-S 是更新的技术标准,主要用于现代化的飞机和先进的空中交通管理系统。 + +总的来说,Mode-S 提供了更多的功能,增强了空中交通管理的能力,特别是在繁忙的空域中提高了安全性和效率。然而,由于 Mode-A/C 仍在广泛使用,因此许多雷达系统需要同时支持这两种模式。 + +## MLAT服务器 + +MLAT服务器,全称Multiple Lateral-sounding Radar(多点定位雷达)服务器,是一种利用多个地面站接收来自飞行器的广播式自动相关监视(ADS-B)信号,通过测量信号到达不同地面站的时间差,并结合地面站的精确位置信息,来计算飞行器位置的技术平台。以下是关于MLAT服务器的详细解释: + +一、技术原理 + +- **信号接收**:MLAT系统通过多个地面站接收飞行器发射的ADS-B信号。 +- **时间差测量**:由于信号传播速度有限,不同地面站接收到信号的时间会有所不同。系统通过测量这些时间差,构建出一组方程。 +- **位置计算**:结合地面站的精确位置信息,利用三角定位的原理,通过解这组方程来求解飞行器的位置。 + +二、系统特点 + +- **无需额外设备**:MLAT系统不需要在飞行器上安装额外的设备,仅利用现有的ADS-B设备即可实现精确的定位。 +- **广泛适用性**:由于依赖的是ADS-B信号,MLAT系统可以应用于大多数已加装ADS-B应答机的飞行器。 +- **高精度**:通过多个地面站的联合观测,MLAT系统能够提供高精度的飞行器位置信息。 + +三、应用领域 + +- **航空交通管制**:MLAT技术为航空交通管制提供了实时、精确的飞行器位置信息,有助于提升管制效率和安全性。 +- **飞行器追踪**:在飞行器追踪领域,MLAT系统能够实现对飞行器的持续、精确追踪,为飞行器的运行管理提供有力支持。 +- **空中交通管理**:MLAT技术的应用有助于优化空中交通流量,减少航班延误和冲突,提升整体航空运输效率。 + +四、系统构建 + +- **硬件要求**:MLAT系统需要安装多个地面接收机(如RadarCape),并在一台服务器上安装多点定位中央处理系统软件。 +- **网络连接**:通过以太网、移动网络或互联网将地面接收机与中央MLAT服务器连接,实现数据的实时传输和处理。 +- **数据处理**:中央MLAT服务器接收来自地面接收机的数据,进行位置解算,并将结果提供给用户或相关系统。 + +综上所述,MLAT服务器是一种基于多点定位技术的服务器平台,通过接收和处理来自多个地面站的ADS-B信号,实现对飞行器的精确定位。该技术在航空交通管制、飞行器追踪和空中交通管理等领域具有广泛的应用前景和重要的实用价值。 + +## GNSS数据格式RMC/GGA + +RMC(推荐最小数据)和GGA(全球定位信息)数据句(sentences) + +1. RMC(Recommended Minimum Specific GNSS Data) + - RMC是一种GNSS(全球导航卫星系统)数据格式,它提供了卫星导航系统的最小推荐数据集。 + - RMC数据句包含了时间、位置、速度等基本信息,但不包括所有可能的GNSS数据字段。 + - 它被设计为在数据传输带宽有限的情况下,仍能提供足够的导航信息。 +2. GGA(Global Positioning System Fix Data) + - GGA是GPS(全球定位系统)数据格式的一种,用于提供关于GPS定位的信息。 + - GGA数据句包含了定位的时间、质量指示、纬度、经度、高度等关键信息。 + - 它通常用于GPS接收机的标准输出,以提供关于当前位置的详细信息。 + +## Mode-S协议 + +AA:地址公布 ; + +AC:海拔代码 ; + +AF:应用领域 ; + +AP:地址/奇偶校验 ; + +AQ:收购 ; + +CA:能力 ; + +CC:交联能力 ; + +CF:控制场 ; + +CL:代码标签 ; + +DF:下行格式 ; + +DI:标号标识 ; + +DR:下行请求 ; + +DS:数据选择器 ; + +ELM:Extended length message 扩长消息 ; + +FS:航班状态 ; + +IC:询问器代码 ; + +ID:Identità ;KE:控制,ELM ; + +MA:消息,Comm-A ; + +MB:消息,Comm-B ; + +MC:消息,Comm-C ; + +MD:消息,Comm-D ; + +ME:消息,扩展 squitter ; + +MU:消息,ACAS ; + +MV:消息,ACAS ; + +NC:C 段数 ; + +ND:D 段数 ; + +PC:协议 ; + +PI:奇偶校验/询问器标识符 ; + +PR:回复概率 ; + +RC:回复控制 ; + +RI:回复信息 ; + +RL:回复长度 ; + +RR:回复请求 ; + +SD:特殊标号; + +UF:上行格式 ; + +UM:实用程序消息 ; + +VS:垂直状态 + diff --git a/doc/网页文档.md b/doc/网页文档.md new file mode 100644 index 0000000..8f9c513 --- /dev/null +++ b/doc/网页文档.md @@ -0,0 +1,36 @@ + +GNS5894TAC_ADSBModul_datasheet 模块在线文档 +https://www.gns-electronics.de/wp-content/uploads/2021/02/GNS5894TAC_ADSBModul_datasheet_V1.3.pdf + + + + +AIS DAC +https://en.wikipedia.org/w/index.php?title=Maritime_identification_digits + +解码AIS在线网站 +https://www.aggsoft.com/ais-decoder.htm +批量解码AIS在线网站 +https://www.maritec.co.za/aisvdmvdodecoding + + + + +GPSD 开源代码 ais C语言开源代码 +https://gitlab.com/gpsd/gpsd +https://gpsd.gitlab.io/gpsd/AIVDM.html + + + +jetvision +https://wiki.jetvision.de/wiki/Mode-S_Beast:Data_Output_Formats +https://wiki.jetvision.de/wiki/Radarcape:Version_History#The_GPS_timestamp +https://wiki.jetvision.de/wiki/Radarcape:Version_History#Signal_level_in_dBm +https://wiki.jetvision.de/wiki/Radarcape:Version_History#Status_Frame_0x34_contents_were_extended_with_GPS_and_UTC_information + +mode-s解码网站 +// crc算法 +https://mode-s.org/1090mhz/content/ads-b/8-error-control.html +// mode-s基础知识 +https://mode-s.org/1090mhz/content/mode-s/1-basics.html + diff --git a/logrotate b/logrotate new file mode 100644 index 0000000..1593436 --- /dev/null +++ b/logrotate @@ -0,0 +1,3 @@ +https://zhuanlan.zhihu.com/p/1899057198333670933 + + diff --git a/main.cmake b/main.cmake new file mode 100644 index 0000000..ba36148 --- /dev/null +++ b/main.cmake @@ -0,0 +1,153 @@ +get_filename_component(name ${CMAKE_CURRENT_LIST_DIR} NAME) + +set(rely libarchive SQLiteCpp) +rcl_load_dependency_environment(drogon ${rely}) + + +message(STATUS "before find SQLiteCpp CMAKE_PREFIX_PATH=${CMAKE_PREFIX_PATH}") + + + +message(STATUS "CMAKE_PREFIX_PATH=${CMAKE_PREFIX_PATH}") +message(STATUS "CMAKE_FIND_USE_CMAKE_PATH=${CMAKE_FIND_USE_CMAKE_PATH}") +message(STATUS "CMAKE_FIND_ROOT_PATH=${CMAKE_FIND_ROOT_PATH}") +message(STATUS "CMAKE_FIND_ROOT_PATH_MODE_PACKAGE=${CMAKE_FIND_ROOT_PATH_MODE_PACKAGE}") + + +find_package(Jsoncpp CONFIG) +find_package(Drogon) + + +set(Core Core_Static) + +if(1) + + + set(md "${CMAKE_CURRENT_LIST_DIR}/module") + + + if(WIN32) + set(cfg_dir ${CMAKE_CURRENT_LIST_DIR}/config) + + else() + set(cfg_dir ${CMAKE_CURRENT_LIST_DIR}/config/x86_linux) + endif() + + + + _create("dll" dll_source) + _create("exe" data_process) + _attach_include_dir(dll_source "${md}") + _attach_source_dir(dll_source "${md}/dll_source") + _attach_include_dir(data_process "${md}") + _attach_source_dir(data_process "${md}/dll_source") + + + + _depend(dll_source ${Core}) + _depend(data_process ${Core}) + _attach_post_build_file(dll_source ${cfg_dir}/data_progress_config.json + "${CMAKE_CURRENT_LIST_DIR}/data/BIN_Blank_Text/ADS-B_195_0205.txt") + + + _create("dll" mlat_source) + _attach_include_dir(mlat_source "${md}") + _attach_source_dir(mlat_source "${md}/mlat_source") + _depend(mlat_source ${Core}) + + _create("exe" mlat_source_exe) + _attach_include_dir(mlat_source_exe "${md}") + _attach_source_dir(mlat_source_exe "${md}/mlat_source") + _depend(mlat_source_exe ${Core}) + + + + + find_package(SQLiteCpp CONFIG REQUIRED) + + + + _create("exe" ecap_server) + _depend(ecap_server SSR) + _attach_include_dir(ecap_server "${md}") + _attach_source_dir(ecap_server "${md}/Local_Server") + target_link_libraries(ecap_server PRIVATE Drogon::Drogon) + target_link_libraries(ecap_server PRIVATE SQLiteCpp) + target_link_libraries(ecap_server PRIVATE ${ZLIB_LIBRARY}) + target_include_directories(ecap_server PRIVATE ${ZLIB_INCLUDE_DIR}) + + message("LibArchive_SUB_LIBRARIES ${LibArchive_SUB_LIBRARIES}") + target_link_libraries(ecap_server PRIVATE + LibArchive::LibArchive + ${LibArchive_SUB_LIBRARIES} + + ) + target_compile_definitions(ecap_server PRIVATE LIBARCHIVE_STATIC) + + + _attach_source_file(ecap_server "${md}/Local_Server_main.cpp") + _attach_post_build_file(ecap_server ${cfg_dir}/config.json) + + if(UNIX AND NOT APPLE) + # 添加进程间通信系统库 + target_compile_options(ecap_server PRIVATE -g -gstrict-dwarf -gdwarf-4 -fvar-tracking-assignments) + set(CMAKE_FOLDER "lzy") + add_subdirectory(${CMAKE_CURRENT_LIST_DIR}/lzy ${CMAKE_BINARY_DIR}/lzy) + unset(CMAKE_FOLDER) + set(ver v1.0.4) + set(WEB_DIR "${CMAKE_CURRENT_LIST_DIR}/webapp") + set(publish_root_dir "${CMAKE_CURRENT_LIST_DIR}/ver") + set(publish_dir "${publish_root_dir}/${ver}") + set(WEB_OUT_DIR "${publish_dir}/wwwroot") + set(PACKAGE_ZIP "${publish_dir}.zip") + set(NODE_DIR "C:/Users/wyc/AppData/Roaming/JetBrains/CLion2026.1/node/versions/24.15.0") + set(NPM_EXECUTABLE "${NODE_DIR}/npm.cmd") + if(NOT EXISTS "${NODE_DIR}/node.exe") + message(FATAL_ERROR "node.exe not found: ${NODE_DIR}/node.exe") + endif() + add_custom_target(ecap_server_package + COMMAND ${CMAKE_COMMAND} -E make_directory "${publish_dir}" + COMMAND ${CMAKE_COMMAND} -E copy_if_different $ ${publish_dir} + COMMAND ${CMAKE_COMMAND} -E remove_directory "${WEB_OUT_DIR}" + COMMAND ${CMAKE_COMMAND} -E env + "PATH=${NODE_DIR};$ENV{PATH}" + ${CMAKE_COMMAND} -E chdir "${WEB_DIR}" + "${NPM_EXECUTABLE}" run build -- --outDir "${WEB_OUT_DIR}" --emptyOutDir + COMMAND ${CMAKE_COMMAND} -E remove -f "${PACKAGE_ZIP}" + COMMAND ${CMAKE_COMMAND} -E chdir "${publish_dir}" + ${CMAKE_COMMAND} -E tar cf "${PACKAGE_ZIP}" --format=zip -- . + COMMENT "Build frontend" + USES_TERMINAL + + VERBATIM + ) + add_dependencies(ecap_server_package ecap_server) + endif() + if(MSVC) + target_compile_definitions(ecap_server PRIVATE + _CRTDBG_MAP_ALLOC + ) + endif() + add_dependencies(ecap_server dll_source) +if(WIN32) + +endif() + _create("exe" test_drogon) + _attach_include_dir(test_drogon "${md}") + _attach_source_dir(test_drogon "${md}/test_drogon") + target_link_libraries(test_drogon PRIVATE Drogon::Drogon) +endif() + +rcl_unload_dependency_environment(drogon ${rely}) + + +include("${CMAKE_SOURCE_DIR}/0_cmake_library/ninja_build_analyze/export.cmake") + +register_ninja_build_analyze_target( + ninja_build_analyze_ctx # 分析上下文 target 名,自己起名 + "Core_Static" # 要分析的构建目标;空字符串表示 all + "${CMAKE_BINARY_DIR}/analyze" # 分析输出目录;空字符串表示 build/build_analysis + "ON" # 是否先 clean:ON/OFF + "30" # top 数量;空字符串表示 30 +) + diff --git a/module/Local_Server.rar b/module/Local_Server.rar new file mode 100644 index 0000000..d913b6b Binary files /dev/null and b/module/Local_Server.rar differ diff --git a/module/Local_Server/Aircraft/Aircraft.cpp b/module/Local_Server/Aircraft/Aircraft.cpp new file mode 100644 index 0000000..721763a --- /dev/null +++ b/module/Local_Server/Aircraft/Aircraft.cpp @@ -0,0 +1 @@ +#include "../Aircraft/Aircraft.h" diff --git a/module/Local_Server/Aircraft/Aircraft.h b/module/Local_Server/Aircraft/Aircraft.h new file mode 100644 index 0000000..d16dcdf --- /dev/null +++ b/module/Local_Server/Aircraft/Aircraft.h @@ -0,0 +1,79 @@ +#pragma once + + +#include "../External_Database/export.h" + +#include +#include +#include +#include + +#include "SSR/Aircraft_Info.h" + +class Aircraft : public SSR::Aircraft_Info { +public: + explicit Aircraft(const std::string& icao); + + // 静态信息按 ICAO24 加载一次;航线信息仅在 callsign 变化时重新加载。 + // map 的键是外部数据源名称。 + std::map> external_database_info; + std::map> callsign_external_database_info; + bool external_database_info_loaded{}; + std::optional last_external_database_callsign; + + [[nodiscard]] std::shared_ptr external_database_row( + const std::string& resource_name) const { + const auto callsign_iter = callsign_external_database_info.find(resource_name); + if (callsign_iter != callsign_external_database_info.end()) { + return callsign_iter->second; + } + const auto iter = external_database_info.find(resource_name); + return iter == external_database_info.end() ? nullptr : iter->second; + } + + void refresh_external_database_info(); + + Psc::JSON toJson() { + refresh_external_database_info(); + Psc::JSON ret = Psc::JSON::object(); + Ret_J(icao) + ret.append({"每秒位置数", get_pest()}); + ret.append({"飞机位置轨迹点数", air_pos_track_list.size()}); + ret.append({"地面位置轨迹点数", surface_pos_track_list.size()}); + ret.append({"信号强度", signal_level}); + auto opt_pos = air_pos_track_list.last(); + ret.append({"当前位置消息", opt_pos.has_value() ? opt_pos->to_json() : ""}); + + auto cpr_state_opt = BDS05_airborne_position.value; + ret.append({"cpr解码器状态", + cpr_state_opt.has_value() + ? cpr_state_opt.value().current_state_json() + : ""}); + ret.append({"时间", Psc::utc_2_local_time(timestamp)}); + ret.append({"多点定位数据源", mlat}); + + auto external_info = Psc::JSON::object(); + for (const auto& [resource_key, row] : external_database_info) { + external_info.append({resource_key, row->to_json()}); + } + for (const auto& [resource_key, row] : callsign_external_database_info) { + external_info.append({resource_key, row->to_json()}); + } + ret.append({"external_database_info", external_info}); + + push_all_bds_info(ret); + return ret; + } + +#ifdef Cache_Some_Mode_S + std::list> cache; + size_t total_num = 0; + void add_msg_limit(const std::shared_ptr& msg) { + if (cache.size() > Cache_Some_Mode_S_Num) { + cache.pop_front(); + } + cache.emplace_back(msg); + total_num++; + } +#endif +}; diff --git a/module/Local_Server/Aircraft/Flight_VTO.cpp b/module/Local_Server/Aircraft/Flight_VTO.cpp new file mode 100644 index 0000000..e5c1cde --- /dev/null +++ b/module/Local_Server/Aircraft/Flight_VTO.cpp @@ -0,0 +1 @@ +#include "../Aircraft/Flight_VTO.h" diff --git a/module/Local_Server/Aircraft/Flight_VTO.h b/module/Local_Server/Aircraft/Flight_VTO.h new file mode 100644 index 0000000..d7f7021 --- /dev/null +++ b/module/Local_Server/Aircraft/Flight_VTO.h @@ -0,0 +1,67 @@ +#pragma once +#include "global.h" + + +struct Flight_VTO { + std::string icao; // 飞机身份标识(四字节十六进制代码) + time_t time_stamp{}; // 时间(原始时间数据,可能需要翻译显示) + bool mlat; + RET pos; // 纬度(飞机的当前位置纬度) + RET track; // 航迹(航迹方向,单位:度) + RET speed; // 航速(单位:米/秒) + RET vert_speed; // 航速(单位:米/秒) + RET altitude; // 米 + RET call_sign; + RET squawk; + + + Psc::JSON toJson() { + auto ret = Psc::JSON::object(); + ADD_Json(icao); + ADD_Json(mlat); + ret.children.emplace_back("time_stamp", timeToString(time_stamp)); + if (pos.has_value()) + { + ret.children.emplace_back("latitude", pos.value().lat); + ret.children.emplace_back("longitude", pos.value().lon); + } else + { + ret.children.emplace_back("latitude", nullptr); + ret.children.emplace_back("longitude", nullptr); + } + ADD_Json_RET(track); + ADD_Json_RET(speed); + ADD_Json_RET(altitude); + ADD_Json_RET(vert_speed); + ADD_Json_RET(call_sign); + ADD_Json_RET(squawk); + return ret; + } + + std::string timeToString(time_t time_stamp) { + struct tm* utc_time = std::gmtime(&time_stamp); // 转换为 UTC 时间 + char buffer[80]; + + // 使用 strftime 格式化时间为字符串 + std::strftime(buffer, sizeof(buffer), "%H:%M:%S", utc_time); + + return std::string(buffer); // 返回格式化后的时间字符串 + } + static Flight_VTO to_VTO(SSR::Aircraft_Info* info) { + Flight_VTO vto; + vto.icao = info->icao; + vto.mlat = info->mlat; + vto.time_stamp = info->timestamp; + vto.speed = info->speed(); + // 这个地 是相对于地的意思 + vto.track = info->surface_magnetic_heading(); + // vto.pos = info->pos(); + vto.pos = info->air_pos_track_list.last(); + vto.altitude = info->altitude_meter(); + vto.vert_speed = info->vertical_rate(); + vto.call_sign = info->bds20_call_sign(); + vto.squawk = info->squawk(); + return vto; + } +}; + diff --git a/module/Local_Server/Aircraft/aircraftlist_json.h b/module/Local_Server/Aircraft/aircraftlist_json.h new file mode 100644 index 0000000..79a187b --- /dev/null +++ b/module/Local_Server/Aircraft/aircraftlist_json.h @@ -0,0 +1,260 @@ +#pragma once + +#include "../Data_Source/Database.h" + +// https://wiki.jetvision.de/wiki/Radarcape:Software_Features#Aircraft_List_JSON_Service +struct Aircraft_List_JSON_Service_O { + size_t times; //自定义添加出现的次数 用于显示的优先级 + time_t uti{}; // Time of last message: Seconds since UNIX epoch + std::uint32_t ns{}; // Time of last message: Nanoseconds since Second epoch + std::uint32_t day_second{}; // Time of last message: Nanoseconds since Second epoch + std::string hex; // ICAO Mode-S or c, in Hex format + RET fli; // Flight Identification + RET ava; // Flight data: available flight data sources + std::string src; // Flight data: Source + std::string cla; // Subclass of ADS-B data + RET lat; // Flight data: Latitude (-90 to 90º) + RET lon; // Flight data: Longitude (-180 to 180º) + RET alt; // Flight data: Barometric uncalibrated altitude (ft) + RET spd; // Flight data: Ground Speed (kt) + RET trk; // Flight data: True track (0-360º) + RET vrt; // Flight data: Vertical Rate (ft/min) + std::string gda; // Airborne/Ground + std::string cat; // Aircraft category + RET org; // Origin DB 起点机场 + RET dst; // Destination DB 目标机场 + RET opr; // Operator DB + RET typ; // Type DB + RET reg; // Registration DB + RET squ; // Mode-A (Squawk) + RET cou; // Country + RET dis; // Distance (km or NM depending on configuration) + RET tru; // Trust count Number of Mode-S frames successfully decoded from this A/C. Statistically it's possible that for a very low count the A/C does not actually exist + int dbm{}; // Approximate signal level in dBm; + RET lla; // int Age of last Position (s) + RET tmp; // Temperature (ºC) + RET wsp ; // Wind Speed (kt) + RET wdi; // Wind from Direction (0-360º) + RET mop; // ADS-B MOPS version; + RET spi; // SPI (Squawk ident); + RET alr; // Alert status + RET ias; // IAS + RET tas; // TAS + RET hdgm; // Magnetic Heading + RET hdgt; // True Heading + RET qnhs; // Selected QNH + RET alts; // Selected QNH + RET hdgs; // Selected Heading + RET altg; // GNSS elipsoidal altitude (ft) + RET pic; // Asterix PIC + RET tcm; // ACAS/TCAS status + RET ape; // Autopilot engaged + RET sil; // ADS-B SIL + RET sda; // ADS-B SDA + RET nacp; // ADS-B SDA + RET pest; // Number of position estimations per second + RET nocl; // Number of sensors providing data aircraft + RET tq; // Time quality of this entry + + Psc::JSON toJson() { + auto ret = Psc::JSON::object(); + ADD_Json(times); + ADD_Json(uti); + ADD_Json(ns); + ADD_Json(day_second); + ADD_Json(hex); + ADD_Json_RET(fli); + ADD_Json_RET(ava); + ADD_Json(src); + ADD_Json(cla); + ADD_Json_RET(lat); + ADD_Json_RET(lon); + ADD_Json_RET(alt); + ADD_Json_RET(spd); + ADD_Json_RET(trk); + ADD_Json_RET(vrt); + ADD_Json(gda); + ADD_Json(cat); + ADD_Json_RET(org); + ADD_Json_RET(dst); + ADD_Json_RET(opr); + ADD_Json_RET(typ); + ADD_Json_RET(reg); + ADD_Json_RET(squ); + ADD_Json_RET(cou); + ADD_Json_RET(dis); + ADD_Json(tru); + ADD_Json(dbm); + ADD_Json_RET(lla); + ADD_Json_RET(tmp); + ADD_Json_RET(wsp); + ADD_Json_RET(wdi); + ADD_Json_RET(mop); + ADD_Json_RET(spi); + ADD_Json_RET(alr); + ADD_Json_RET(ias); + ADD_Json_RET(tas); + ADD_Json_RET(hdgm); + ADD_Json_RET(hdgt); + ADD_Json_RET(qnhs); + ADD_Json_RET(alts); + ADD_Json_RET(pic); + ADD_Json_RET(tcm); + ADD_Json_RET(ape); + ADD_Json_RET(sil); + ADD_Json_RET(sda); + ADD_Json_RET(nacp); + ADD_Json_RET(pest); + ADD_Json_RET(nocl); + ADD_Json_RET(tq); + return ret; + } + + + // https://wiki.jetvision.de/wiki/Radarcape:Software_Features#Aircraft_List_JSON_Service + static Aircraft_List_JSON_Service_O to_That(DataBase* db, Aircraft* info) { + Aircraft_List_JSON_Service_O ret; + // 航线查询结果保存在 Aircraft 中,仅在首次加载或 callsign 变化时重新读取数据库。 + ret.times = info->times; + ret.uti = info->timestamp; + ret.ns = info->mlat_timestamp.nanosec; + ret.day_second = info->mlat_timestamp.daysec; + ret.hex = info->icao; // TODO not c + // fli Flight Identification Mode-S From ADS-B or BDS2,0 as specified on ICAO Annex 10, Volume IV, Table 3-9; "?" when A/C reports loss of interface + ret.fli = info->bds20_call_sign(); + // ava ava Flight data: available flight data sources One letter per available flight data sources. A=ADSB, M=Jetvision MLAT, F=FlightAware MLAT, O=OGN, L=FLARM + // ret.ava + ret.ava = "暂不支持"; + // ret.src + ret.src = "暂不支持"; + // ret.cla + ret.cla = "暂不支持"; + RET pos = info->pos(); + if(pos.has_value()) { + ret.lat = pos.value().lat; + ret.lon = pos.value().lon; + } + ret.alt = info->altitude_meter(); + ret.spd = info->speed(); + ret.trk = info->air_magnetic_heading(); + ret.vrt = info->vertical_rate(); + // 飞机在地面还是空中 G for on ground, A for airborne (if TIS-B then lowercase g or a) + ret.gda = info->is_on_ground() ? "G" : "A"; + auto vt = info->vortex_type(); + if (vt.has_value()) { + ret.cat = Vortex_Type_to_radarcape_code(vt.value()); + } + // =============== 来自DB 航班数据库 ================ + auto route_info = info->external_database_row("vrs_routes"); + if (!route_info) { + route_info = info->external_database_row("adsblol_vrs_standing_data_routes"); + } + if (!route_info) { + route_info = info->external_database_row("vradarserver_standing_data_routes"); + } + if (route_info) { + const auto airport_codes = route_info->get("AirportCodes"); + if (airport_codes && !airport_codes->empty()) { + const auto first_separator = airport_codes->find('-'); + const auto last_separator = airport_codes->rfind('-'); + ret.org = airport_codes->substr(0, first_separator); + ret.dst = last_separator == std::string::npos + ? *airport_codes + : airport_codes->substr(last_separator + 1); + } + } + //ret.opr + const auto opensky_info = + info->external_database_row("opensky_aircraft_database"); + if (opensky_info) { + ret.opr = opensky_info->get("operator"); + } + //ret.typ + if (opensky_info) { + ret.typ = opensky_info->get("typecode"); + } + //ret.reg + if (opensky_info) { + ret.reg = opensky_info->get("registration"); + } + // =============================== + // squ Mode-A (Squawk) Mode-S While this is a Mode-A code, + // it can only be correlated in Mode-S targets. Mode-A or Mode-A/C targets are not + // displayed in decoded formats since they cannot be correlated with a value + ret.squ = info->squawk(); + // cou Country Country according to Mode-S allocation block if decodable, mostly unusable/invalid for FLARM A/C + //ret.cou + const auto faa_info = info->external_database_row("faa_aircraft_registry"); + if (faa_info) { + ret.cou = faa_info->get("country"); + } + // dis Distance (km or NM depending on configuration) To the Receiver GNSS location + auto p = db->base_station.get_pos(); + if (p.has_value() && pos.has_value()) { + ret.dis = SSR::CPR::haversine(pos.value(), p.value()); + } + ret.tru = info->times; + ret.dbm = info->signal_level; + //ret.lla + ret.lla = std::time(nullptr) - info->timestamp; + //ret.tmp + ret.tmp = info->temperature(); + //ret.wsp + ret.wsp = info->wind_speed(); + //ret.wdi + ret.wdi = info->wind_direction(); + ret.mop = info->ADS_B_Ver(); + //ret.spi + ret.spi = info->squawk(); + //ret.alr + ret.alr = info->alart(); + auto air_speed = info->get_airspeed(); + if (air_speed.has_value()) { + auto& t = air_speed.value(); + auto type = t.get_airspeed_type(); + if (type == SSR::Airspeed_type::Indicated_airspeed_IAS) { + ret.ias = air_speed.value().get_speed(); + } + if (type == SSR::Airspeed_type::True_airspeed_TAS) { + ret.tas= air_speed.value().get_speed(); + } + ret.hdgm = air_speed.value().get_magnetic_heading(); + ret.hdgt = "暂不支持"; + } + //ret.qnhs Selected QNH + ret.qnhs = "暂不支持"; + //ret.alts Selected Altitude + ret.alts = "暂不支持"; + //ret.hdgs Selected Heading + ret.hdgs = info->select_heading(); + auto it = info->get_speed_base(); + if (it.has_value()) { + auto i = it.value(); + i.get_GNSS_barometric_altitudes_difference(); + auto diff = i.get_GNSS_barometric_altitudes_difference(); + if (diff.has_value() && ret.alt.has_value()) { + ret.altg = diff.value() + ret.alt.value(); + } + } + //ret.pic + ret.pic = "暂不支持"; + //ret.tcm + ret.tcm = "暂不支持"; + // ape Autopilot engaged 2 Mode-S + //ret.ape + ret.ape = "暂不支持"; + ret.sil = info->SIL(); + //ret.sda + ret.sda = "暂不支持"; + ret.nacp = info->NACp(); + // pest Number of position estimations per second MLAT + ret.pest = info->get_pest(); + // nocl Number of sensors providing data aircraft MLAT + ret.nocl = 1; + // tq Time quality of this entry Sensor 0: GNSS 1: Sensor NTP 2: Server NTP + //ret.tq + ret.tq = "暂不支持"; + return ret; + } +}; + diff --git a/module/Local_Server/Aircraft/global.h b/module/Local_Server/Aircraft/global.h new file mode 100644 index 0000000..7517a08 --- /dev/null +++ b/module/Local_Server/Aircraft/global.h @@ -0,0 +1,38 @@ +#pragma once +#include "../../../../../core_library/Core/Core/Base/JSON.h" +#include "Core/socket/export.h" +#include "SSR/export.h" +#include +#include +#include +#include +#include +#include +#include + +// 用于debug 散乱的飞机从何而来 +// #define Cache_Some_Mode_S +#ifdef Cache_Some_Mode_S + #define Cache_Some_Mode_S_Num 20 +#endif + + + +#define Parse(t, Field) \ +auto& _##t = info.Field.value; \ +info.Field.time = info.timestamp; \ +if (!_##t.has_value()) _##t = std::remove_reference_t::ValueType(); \ +_##t.value().parse(msg); \ +auto& t = _##t.value(); +// ret.append(NAME.value.has_value()? Psc::Json(STRINGIFY(NAME##_time), NAME.time) : Psc::Json(STRINGIFY(NAME##_time), nullptr)); +#define STRINGIFY(x) #x +#define ADD_Json(NAME) ret.children.emplace_back(STRINGIFY(NAME), NAME); +#define ADD_Json_RET(NAME) \ +if (NAME.has_value()) \ +{ \ +ret.children.emplace_back(STRINGIFY(NAME), NAME.value()); \ +} else \ +{ \ +ret.children.emplace_back(STRINGIFY(NAME), nullptr); \ +} + diff --git a/module/Local_Server/Crawler/Crawler.cpp b/module/Local_Server/Crawler/Crawler.cpp new file mode 100644 index 0000000..c8ccda9 --- /dev/null +++ b/module/Local_Server/Crawler/Crawler.cpp @@ -0,0 +1,96 @@ +#include "Crawler.h" + +#include "Local_Server/server/Global.h" + +void Crawler::handle(Call_back call_back) { + using namespace drogon; + int idx = 0; + + SQLite::Statement aircraft_rows( + db_, "SELECT icao24, type_code FROM mictronics_aircraft_database"); + while (aircraft_rows.executeStep()) { + idx++; + + if (idx > 10) break; + if (idx % 1 == 0) { + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); + } + { + static Frequency_Limit fl; + if (fl.test()) { + std::cout << idx++ << "/618325 条数据已发出! " << std::endl; + } + } + const auto hex = aircraft_rows.getColumn(0).getString(); + const auto icaoType = aircraft_rows.isColumnNull(1) + ? std::string{} + : aircraft_rows.getColumn(1).getString(); + + bool ok = check_aircraft_exists(db_, hex); + if (!ok) { + static Frequency_Limit fl; + if (fl.test()) { + std::cout << idx << "/618325 数据存在跳过! " << std::endl; + } + } + auto client = HttpClient::newHttpClient("https://planespotters.live"); + + std::string path = "/api/aircraft/hex/" + hex; + + // GET https://planespotters.live/api/aircraft/hex/780F0E + // User-Agent: IntelliJ HTTP Client/CLion 2025.2.6 + // Accept-Encoding: br, deflate, gzip, x-gzip + // Accept: */* + + auto req = HttpRequest::newHttpRequest(); + req->setMethod(Get); + req->setPath(path); + + // query 参数:?icaoType=B763 + req->setParameter("icaoType", icaoType); + + req->addHeader("Accept-Language", "en-US,en;q=0.9"); + req->addHeader("User-Agent", "IntelliJ HTTP Client/CLion 2025.2.6"); + req->addHeader("Accept", "*/*"); + req->addHeader("Accept-Encoding", "br, deflate, gzip, x-gzip"); + + + + + + client->sendRequest(req, [hex, icaoType, call_back]( + ReqResult r, const HttpResponsePtr &resp) { + if (r != ReqResult::Ok || !resp) { + LOG_ERROR << "request failed, ReqResult=" << (int)r; + return; + } + + if (resp->getStatusCode() != k200OK) { + static Frequency_Limit_Multi fl; + auto tt = to_string(resp->getStatusCode()); + if (fl.test(tt)) { + std::cout << tt << std::endl; + + } + + return; + } + + // 解析 JSON(如果响应是 JSON) + auto json = resp->getJsonObject(); + if (!json) { + LOG_ERROR << "not json, body=" << resp->getBody(); + return; + } + + auto t = try_parse_json(json->toStyledString()); + + if (!t) { + std::cout << "解析失败???" << t->to_json_string() << std::endl; + Psc::fail_fast_core_dump(); + return; + } + call_back(hex, icaoType, t.value()); + }); + } +} diff --git a/module/Local_Server/Crawler/Crawler.h b/module/Local_Server/Crawler/Crawler.h new file mode 100644 index 0000000..8a9705d --- /dev/null +++ b/module/Local_Server/Crawler/Crawler.h @@ -0,0 +1,96 @@ +#pragma once + +#include "../../../../../core_library/Core/Core/Base/JSON.h" +#include "Core/Statistics/Frequency_Limit.h" + +#include +#include +#include +#include +#include +#include + + +class Crawler { +public: + using Call_back = std::function; + + explicit Crawler(const std::string &db_path) + : db_(db_path, SQLite::OPEN_READWRITE | SQLite::OPEN_CREATE) { + aircraft_json_table_create_if_not_exists(); + // 可选:性能更好(仍然是同步) + db_.exec("PRAGMA journal_mode=WAL;"); + db_.exec("PRAGMA synchronous=NORMAL;"); + } + + void aircraft_json_table_create_if_not_exists() { + db_.exec(R"sql( + CREATE TABLE IF NOT EXISTS aircraft_json ( + icao TEXT PRIMARY KEY, + json TEXT + ); + )sql"); + } + + bool check_aircraft_exists(SQLite::Database& db, const std::string& icao) { + // 查询是否存在该icao + static auto stmt_check_ = SQLite::Statement(db, R"sql( + SELECT COUNT(*) FROM aircraft_json WHERE icao = ?; + )sql"); + + stmt_check_.reset(); + stmt_check_.clearBindings(); + stmt_check_.bind(1, icao); + + int count = 0; + if (stmt_check_.executeStep()) { + count = stmt_check_.getColumn(0).getInt(); + } + + // 如果存在记录,返回 true + return count > 0; + } + + void insert_aircraft_json(const std::string &icao, const Psc::JSON &j) { + static auto stmt_upsert_ = SQLite::Statement(db_, R"sql( + INSERT INTO aircraft_json(icao, json) + VALUES(?, ?) + ON CONFLICT(icao) DO UPDATE SET + json = excluded.json; + )sql"); + const std::string json_str = j.to_json_string(); + std::lock_guard g(mtx); + SQLite::Transaction tx(db_); // BEGIN + stmt_upsert_.reset(); + stmt_upsert_.clearBindings(); + stmt_upsert_.bind(1, icao); + stmt_upsert_.bind(2, json_str); + stmt_upsert_.exec(); + tx.commit(); + } + + void req_all_insert_aircraft_json() { + std::atomic idx = 0; + handle( + [this, &idx](std::string hex, std::string icaoType, Psc::JSON &json) { + // 直接同步写库(最简单) + try { + static Frequency_Limit fl; + idx++; + if (fl.test()) { + std::cout << idx << "/618325 条数据处理成功! " << std::endl; + } + insert_aircraft_json(hex, json); + } catch (const std::exception &e) { + // 用你自己的 LOG_ERROR + std::cerr << "sqlite insert failed: " << e.what() << "\n"; + } + }); + } + +private: + SQLite::Database db_; + std::mutex mtx; + void handle(Call_back cb); // 你自己实现/已有 +}; diff --git a/module/Local_Server/DSP/DSP_Config.cpp b/module/Local_Server/DSP/DSP_Config.cpp new file mode 100644 index 0000000..c53996a --- /dev/null +++ b/module/Local_Server/DSP/DSP_Config.cpp @@ -0,0 +1,382 @@ + + +#include "Local_Server/DSP/DSP_Config.h" +#include "../server/Global.h" +#include "Core/socket/ByteOrder.h" + +#include +#include +#include + +#if!USE_PROCESS + +// adsb_set_less_30Mhz_ddc_param_t set_less_30Mhz_ddc_param; +// adsb_set_less_30Mhz_fft_param_t set_less_30Mhz_fft_param; + + +decltype(&adsb_set_less_30Mhz_ddc_param) psc_set_less_30Mhz_ddc_param; +decltype(&adsb_set_less_30Mhz_fft_param) psc_set_less_30Mhz_fft_param; + +#endif + + +using namespace drogon; +// ws://127.0.0.1:8848/chat + + + + + + + + + + + +BaseLogger* dsp_logger = nullptr; +DSP_Config::~DSP_Config() = default; + +void DSP_Config::close_dsp_device() const { + + auto r = Psc::try_load_function(lib, "adsb_close"); + if (!r) { + Psc::fail_fast(); + } + auto tmp_adsb_close = (decltype(&adsb_close)) r.value(); + std::ostringstream oss; + oss << "stop_program ===== " << VAR_STR_1(stop_program) << std::endl; + oss << "DSP_Config adsb_close 开始关闭子库!" << std::endl; + tmp_adsb_close(); + oss << "DSP_Config adsb_close 关闭子库结束!" << std::endl; + dsp_logger->c_debug("dsp", {}, oss.str()); +} + + +void DSP_Config::server(Global *g) { + + auto &svr = g->svr; + auto &api = g->api; + std::string name = "dsp"; + + drogon::app().registerWebSocketControllerRegex(R"(^/websocket/.*$)", "DSP_Ws_Mgr", {Get}); + + ws_iq = Ws_Mgr::instance()->register_ws("/download_iq"); + ws_fft = Ws_Mgr::instance()->register_ws("/get_fft"); + + + svr.Post(api + svr.update + name, [this, g](HTTP_Param) { + CHECK_JSON_PARAM + init_update(¶ms); + + +#if USE_PROCESS + adsb_set_less_30Mhz_ddc_param(this->center_freq, this->sample_rate, this->band_width, 1); + adsb_set_less_30Mhz_fft_param(fft_win_type, fft_point_number, fft_period_ms, 1); +#else + psc_set_less_30Mhz_ddc_param(this->center_freq, this->sample_rate, this->band_width, 1); + psc_set_less_30Mhz_fft_param(fft_win_type, fft_point_number, fft_period_ms, 1); +#endif + set_fft_point_number(this->fft_point_number); + g->save(); + res->setBody(warp(to_json()).to_json_string()); + }); + svr.Post(api + "get_dsp_config", [this](HTTP_Param) { res->setBody(warp(to_json()).to_json_string()); }); + + + drogon::app().registerHandler(api + "start_record_iq_stream", + [this](const drogon::HttpRequestPtr &request, + std::function &&callback) { + this->record_iq_stream_ing = true; + auto res = drogon::HttpResponse::newHttpResponse(); + res->setBody("{}"); + callback(res); + }, + {drogon::Post}); + + + svr.Post(api + "end_record_iq_stream", [this](HTTP_Param) { + this->record_iq_stream_ing = false; + res->setBody("{}"); + }); + + svr.Post(api + "restart_device", [this](HTTP_Param) { +#if USE_PROCESS + restart_device(); +#endif + }); +} + + +void DSP_Config::set_fft_point_number(uint64_t new_fft_point_number, bool force) { + fft_point_number = new_fft_point_number; +#if !USE_PROCESS + std::lock_guard lock(fft_mtx); + if (!force && fft_data.size() == (new_fft_point_number * sizeof(short))) { + return; + } + fft_data.resize(new_fft_point_number * sizeof(short)); +#endif + +} + + +#if USE_PROCESS +void DSP_Config::adsb_set_less_30Mhz_ddc_param(double center_freq, double sample_rate, double band_width, int sw) { + JSON ret = JSON::object(); + ret.append(JSON("method", "adsb_set_less_30Mhz_ddc_param")); + ret.append(JSON("center_freq", center_freq)); + ret.append(JSON("sample_rate", sample_rate)); + ret.append(JSON("band_width", band_width)); + ret.append(JSON("sw", sw)); + auto d = ret.to_json_string(); + json_func_call.write((uint8_t *) d.data(), d.size()); +} + +void DSP_Config::adsb_set_less_30Mhz_fft_param(UHD_FFTWin fft_win_type, size_t fft_point_number, size_t fft_period_ms, + int sw) { + JSON ret = JSON::object(); + ret.append(JSON("method", "adsb_set_less_30Mhz_fft_param")); + ret.append(JSON("fft_win_type", fft_win_type)); + ret.append(JSON("fft_point_number", fft_point_number)); + ret.append(JSON("fft_period_ms", fft_period_ms)); + ret.append(JSON("sw", sw)); + auto d = ret.to_json_string(); + json_func_call.write((uint8_t *) d.data(), d.size()); +} + +void DSP_Config::restart_device() { + JSON ret = JSON::object(); + ret.append(JSON("method", "restart_device")); + auto d = ret.to_json_string(); + json_func_call.write((uint8_t *) d.data(), d.size()); +} +#endif + + +#define USE_ERROR_CBK + +void DSP_Config::init_env() { + + set_fft_point_number(fft_point_number, true); + auto g = Global::instance(); + Detach_Thread_Manager &manager = g->thread_manager; + + auto handle_iq= [this](void* data) { + uint8_t* pdata = (uint8_t*) data; + auto wi = Ws_Mgr::instance(); + if (!wi) return; + auto d = (UHD_Struct_KFFT *) (pdata); + if (debug) { + std::ostringstream oss; + oss << "UHD_Struct_KFFT{" << mem2hex(std::string((char *) pdata, 64), true, " ") << std::endl; + oss << "DataType{" << (int) d->DataType << "} 接收到数据:[" + << "] == " << mem2hex(std::string((char *) pdata + 64, 20), true, " ") << std::endl; + server_logger->c_debug({}, {}, oss.str()); + } + if (d->DataType == zd_ddc || d->DataType == kd_ddc) { + auto len = d->UsefullLen; + bool cross_the_boundary = len > 2048; + if (cross_the_boundary || debug) { + auto show_len = (size_t) std::min((decltype(len)) 20, len); + + std::ostringstream oss; + oss << "iq 有效数据长度 【" << len << "】 有效数据: 【" + << std::string((char *) pdata + 64, show_len) << "】" << std::endl; + server_logger->c_debug({}, {}, oss.str()); + } + if (cross_the_boundary) { + std::ostringstream oss; + oss << LOG_POS << "ERROR: ddc iq 回调返回的有效长度越界!" << std::endl; + server_logger->c_debug({}, {}, oss.str()); + return; + } + if (record_iq_stream_ing) { + ws_iq->push_data((const char *) pdata , 2112); + } + } else if (d->DataType == kd_fft) { +#if !USE_PROCESS + auto idx = d->Param.FFT.SubFrame; + auto max = fft_point_number/1024; + if (idx >= max) { + std::ostringstream oss; + oss << "收到了不合法kd_fft Param.FFT.SubFrame " << idx << std::endl; + server_logger->c_debug({}, {}, oss.str()); + return; + } + + + std::lock_guard lock(fft_mtx); + auto pos = fft_data.data() + idx * 2048; + memcpy(pos, pdata + 64, 2048); +#endif + } + }; + +#if USE_PROCESS + manager.test_and_start_thread("读取iq进程数据线程", [this, handle_iq](std::atomic &running) { + while (running) { + uint8_t buf[3000]; + size_t length = 3000; + + while (rb.read(buf, length)) { + Frequency_Limit lm(0.1); + if (lm.test()) { + std::cout << "读取到iq数据" << std::endl; + } + handle_iq(buf); + //auto data = std::string((char *) buf, length); + // if (length != 0) { + // std::cout << "read:【" << length << "】 【" << mem2hex(data.substr(64, 20)) << "】" << std::endl; + // } + if (!running) { + break; + } + } + + std::this_thread::sleep_for(std::chrono::microseconds(1)); + } + }); +#else + manager.test_and_start_thread("iq回调处理线程", [this, handle_iq](std::atomic &running) { + Frequency_Limit_ST limit(frame_rate); + while (running) { + auto list = iq_memory_buffer.get_all(); + if (debug && list.size() > 1000) { + std::ostringstream oss; + oss << "警告: 数据过多 当前数据队列长度:" << list.size() << std::endl; + server_logger->c_debug({}, {}, oss.str()); + } + if (list.empty()) { + std::this_thread::sleep_for(std::chrono::microseconds(1)); + continue; + } + auto wi = Ws_Mgr::instance(); + if (!wi) continue; + auto frame_number = list.size(); + for (int i = 0; i < frame_number; i++) { + auto pdata = list[i].data(); + handle_iq(pdata); + } + } + }); +#endif + + + + + auto interval = 1.0 / (double) frame_rate; + app().getLoop()->runEvery(interval, [this] { + +#if USE_PROCESS + wi->ws_get_fft->push_data((const char *) psm.shm.data(), fft_point_number * 2); +#else + std::lock_guard lock(fft_mtx); + ws_fft->push_data((const char *) fft_data.data(), fft_data.size()); +#endif + + }); + + + + +#if !USE_PROCESS + + { + auto r = try_load_library(Psc::get_abs_path(library_path)); + if (!r) { + Psc::fail_fast(); + } + lib = r.value(); + } + { + auto r = Psc::try_load_function(lib, "adsb_set_less_30Mhz_ddc_param"); + if (!r) { + Psc::fail_fast(); + } + psc_set_less_30Mhz_ddc_param = (adsb_set_less_30Mhz_ddc_param_t)r.value(); + } + { + auto r = Psc::try_load_function(lib, "adsb_set_less_30Mhz_fft_param"); + if (!r) { + Psc::fail_fast(); + } + psc_set_less_30Mhz_fft_param = (adsb_set_less_30Mhz_fft_param_t)r.value(); + } + using set_iq_cbk_t = decltype(&adsb_set_iq_cbk); + set_iq_cbk_t set_iq_cbk; + { + auto r = Psc::try_load_function(lib, "adsb_set_iq_cbk"); + if (!r) { + Psc::fail_fast(); + } + set_iq_cbk = (set_iq_cbk_t)r.value(); + } + + using adsb_set_error_cbk_t = decltype(&set_error_cbk); + adsb_set_error_cbk_t adsb_set_error_cbk; + { + auto r = Psc::try_load_function(lib, "set_error_cbk"); + if (!r) { + Psc::fail_fast(); + } + adsb_set_error_cbk = (adsb_set_error_cbk_t)r.value(); + } + + + psc_set_less_30Mhz_ddc_param(center_freq, sample_rate, band_width, 1); + psc_set_less_30Mhz_fft_param(fft_win_type, fft_point_number, fft_period_ms, 1); + + + set_iq_cbk( + [](void *phandle, void *pdata, uint64_t length) { + if (stop_program != 0) { + static Frequency_Limit fl; + if (fl.test()) { + std::ostringstream oss; + oss << "set_iq_cbk 回调退出:" << signal_to_string(stop_program) << " " << VAR_STR_1(stop_program) << LOG_POS << std::endl; + dsp_logger->c_debug({}, {}, oss.str()); + } + } + if (length != 2112) { + std::ostringstream oss; + oss << LOG_POS << " IQ回调传入的长度不对!" << std::endl; + dsp_logger->c_debug({}, {}, oss.str()); + return; + } + auto that = (DSP_Config *) phandle; + that->iq_memory_buffer.push(pdata, length); // length 永远等于2112 + }, + (void*)&Global::instance()->dsp_config); + + +#ifdef USE_ERROR_CBK + + adsb_set_error_cbk([](const char *file_name ,const char *func_name,const char *err_msg) { + if (stop_program != 0) { + static Frequency_Limit fl; + if (fl.test()) { + std::ostringstream oss; + oss << "adsb_set_error_cbk 回调退出:" << signal_to_string(stop_program) << " " << VAR_STR_1(stop_program) << LOG_POS << std::endl; + dsp_logger->c_debug({}, {}, oss.str()); + } + return; + } + Log_Type lt{ + {}, + { + {"file_name", std::string(file_name)}, + {"func_name", std::string(func_name)}, + } + }; + dsp_logger->debug({}, lt, std::string(err_msg)); + }); +#endif + + + +#else + adsb_set_less_30Mhz_ddc_param(center_freq, sample_rate, band_width, 1); + adsb_set_less_30Mhz_fft_param(fft_win_type, fft_point_number, fft_period_ms, 1); +#endif + +} diff --git a/module/Local_Server/DSP/DSP_Config.h b/module/Local_Server/DSP/DSP_Config.h new file mode 100644 index 0000000..33c34e4 --- /dev/null +++ b/module/Local_Server/DSP/DSP_Config.h @@ -0,0 +1,132 @@ +#ifndef PLANTSUNCAT_DSP2_H +#define PLANTSUNCAT_DSP2_H + +#include "../server/WebSocket_Manager.h" +#include "global.h" + +class Global; + + +#define USE_PROCESS 0 +#ifdef USE_PROCESS +#include "../../../../../core_library/Core/Core/Shared_Memory/Shared_Memory.h" +#endif +// #ifdef WIN32 +// #define USE_PROCESS 1 +// #endif +// #define USE_PROCESS 1 + +enum Demod_Mode { + LSB, + USB, + AM, + FM +}; + + +extern BaseLogger* dsp_logger; +struct DSP_Config : Base_DSP { + std::string url; + std::uint16_t port{}; + std::int64_t power_min; + std::int64_t power_max; + std::int64_t power_offset; + std::uint64_t frame_rate; + bool debug; + Demod_Mode demod_mode; + std::int64_t audio_gain; + std::int64_t color_gain; + ~DSP_Config(); + + void close_dsp_device() const; + + void init_update(const Psc::JSON *that_json) { + Get_J(port); + Get_J(center_freq); + Get_J(band_width); + Get_J(sample_rate); + Get_J(fft_point_number); + Get_J(power_min); + Get_J(power_max); + Get_J(power_offset); + Get_J(demod_mode); + Get_J(audio_gain); + Get_J(color_gain); + } + void init(const Psc::JSON *that_json) { + init_update(that_json); + Get_J(url); + Get_J(fft_period_ms); + Get_J(fft_win_type); + Get_J(debug); + Get_J(frame_rate); + Get_J(library_path); + } + Psc::JSON to_json() const { + Psc::JSON ret = Base_DSP::to_json(); + Ret_J(url); + Ret_J(port); + Ret_J(power_min); + Ret_J(power_max); + Ret_J(power_offset); + Ret_J(frame_rate); + Ret_J(debug); + Ret_J(demod_mode); + Ret_J(audio_gain); + Ret_J(color_gain); + return ret; + } + + + void init_env(); + + + void set_fft_point_number(uint64_t fft_point_number, bool force = false); + + + + std::atomic record_iq_stream_ing = false; + + struct Memory_Buffer { + std::vector get_all() { + std::vector empty; + std::lock_guard lock(m); + std::swap(empty, data); + return empty; + } + void push(void *pdata, uint64_t length) { + std::lock_guard lock(m); + data.emplace_back((char *) pdata, length); + } + + protected: + std::vector data; + Psc::Spin_Lock m; + }; + +#if USE_PROCESS + + + void adsb_set_less_30Mhz_ddc_param(double center_freq, double sample_rate, double band_width, int sw); + void adsb_set_less_30Mhz_fft_param(UHD_FFTWin fft_win_type, size_t fft_point_number, size_t fft_period_ms, int sw); + + Psc::SM_Block_RingBuffer json_func_call = Psc::SM_Block_RingBuffer("json_func_call2", 1000); + Psc::SM_Block_RingBuffer rb = Psc::SM_Block_RingBuffer("rb", 2112 * 1000); + Psc::Pure_Share_Memory psm = Psc::Pure_Share_Memory("fft_data", 65536); + void restart_device(); +#else + + + void server(Global *g); + std::shared_ptr ws_fft; + std::shared_ptr ws_iq; + Memory_Buffer iq_memory_buffer; + std::vector fft_data; + std::mutex fft_mtx; + void* lib{}; +#endif + +}; + + +#endif diff --git a/module/Local_Server/DSP/export.h b/module/Local_Server/DSP/export.h new file mode 100644 index 0000000..a5d1203 --- /dev/null +++ b/module/Local_Server/DSP/export.h @@ -0,0 +1,3 @@ +#pragma once + +#include "DSP_Config.h" \ No newline at end of file diff --git a/module/Local_Server/DSP/global.h b/module/Local_Server/DSP/global.h new file mode 100644 index 0000000..a987d3f --- /dev/null +++ b/module/Local_Server/DSP/global.h @@ -0,0 +1,34 @@ +#pragma once +#include "../../dll_source/main.h" +#include "Core/spdlog/export.h" +#include "Core/Base/JSON.h" + +struct Base_DSP { + std::string library_path; + std::uint64_t center_freq{}; + std::uint64_t band_width{}; + std::uint64_t sample_rate{}; + std::atomic fft_point_number = 1024; + int fft_period_ms; + UHD_FFTWin fft_win_type; + [[nodiscard]] Psc::JSON to_json() const { + Psc::JSON ret = Psc::JSON::object(); + Ret_J(library_path); + Ret_J(center_freq); + Ret_J(band_width); + Ret_J(sample_rate); + Ret_J(fft_point_number); + Ret_J(fft_period_ms); + Ret_J(fft_win_type); + return ret; + } + void load(Psc::JSON* that_json) { + Get_J(library_path); + Get_J(center_freq); + Get_J(band_width); + Get_J(sample_rate); + Get_J(fft_point_number); + Get_J(fft_period_ms); + Get_J(fft_win_type); + } +}; diff --git a/module/Local_Server/Data_Feed/Data_Feed.cpp b/module/Local_Server/Data_Feed/Data_Feed.cpp new file mode 100644 index 0000000..a5d0402 --- /dev/null +++ b/module/Local_Server/Data_Feed/Data_Feed.cpp @@ -0,0 +1,177 @@ +#include "Local_Server/Data_Feed/Data_Feed.h" +#include "../server/Global.h" +void Data_Feed_UDP_Server::handle_in_loop() { + svr.tick(); +} +bool Data_Feed_UDP_Server::_open() { + svr.set_bind_address("0.0.0.0", port); + svr.create(); + + server_logger->c_debug({}, {}, to_string() + "开启!"); + return true; +} +JSON Data_feed_Config::get_feed(const std::string& key) { + auto ret = map.get(key); + if (ret.has_value()) { + auto r = ret.value().get(); + return r->to_json(); + } + return {nullptr}; +} + +void Data_feed_Config::server(Global* g) { + auto& svr = g->svr; + auto& api = g->api; + std::string name = "data_feed"; + + + svr.Post(api + "get_data_feed_state", [this](HTTP_Param) { + CHECK_JSON_PARAM + HTTP_REQUIRE_VALUE(key, params.try_get_string("key")) + auto t = map.get(key); + JSON ret{nullptr}; + if (t.has_value()) { + ret = t.value()->get_state_json(); + } + res->setBody(warp(ret).to_json_string()); + }); + + + + svr.Post(api + "update_data_feed_config", [this](HTTP_Param) { + CHECK_JSON_PARAM + Get_J(packet_byte_size) + Get_J(empty_wait_milliseconds) + res->setBody(warp(to_json()).to_json_string()); + Global::save(); + }); + + svr.Post(api + "get_data_feed_config", [this](HTTP_Param) { + res->setBody(warp(to_json()).to_json_string()); + }); + + svr.Post(api + "get_data_feed_server_connect", [this](HTTP_Param) { + CHECK_JSON_PARAM + HTTP_REQUIRE_VALUE(key, params.try_get_string("key")) + auto t = map.get(key); + JSON ret{nullptr}; + if (t.has_value()) { + auto dfs = dynamic_cast(t.value().get()); + if (dfs) { + ret = dfs->get_clients_json(); + } + auto dfs2 = dynamic_cast(t.value().get()); + if (dfs2) { + ret = dfs2->get_clients_json(); + } + } + res->setBody(warp(ret).to_json_string()); + }); + + svr.Post(api + svr.search + name, [this](HTTP_Param) { + CHECK_JSON_PARAM + HTTP_REQUIRE_VALUE(type, params.try_get_string("key")) + res->setBody(warp(get_feed(type)).to_json_string()); + }); + + + + svr.Post(api + svr.update + name, [g, this](HTTP_Param) { + CHECK_JSON_PARAM + HTTP_REQUIRE_VALUE(key, params.try_get_string("key")) + HTTP_REQUIRE_VALUE(t, map.get(key)) + // 直接关闭 + t->close(); + t->from_json(¶ms); + if (t->enable) { + t->check_and_open(); + } + Global::save(); + g->mode_acs.source_feed_relation_config.set_need_refresh(); + }); + + svr.Post(api + svr.insert + name, [g, this](HTTP_Param) { + CHECK_JSON_PARAM + HTTP_REQUIRE_VALUE(index, params.try_get_number("index")) + HTTP_REQUIRE_PTR(data, params.get("data")) + HTTP_REQUIRE_VALUE(t, data->try_get_string("type")) + auto df = create_data_feed_from_type(t); + df->from_json(data); + HTTP_REQUIRE_VALUE(enable, data->try_get_bool("enable")) + if (enable) + { + df->check_and_open(); + } + HTTP_REQUIRE_TRUE(map.insert(index, df), "index") + res->setBody(warp(to_json()).to_json_string()); + Global::save(); + g->mode_acs.source_feed_relation_config.set_need_refresh(); + }); + + svr.Post(api + svr.remove + name, [g, this](HTTP_Param) { + CHECK_JSON_PARAM + HTTP_REQUIRE_VALUE(index, params.try_get_number("index")) + HTTP_REQUIRE_VALUE(df, map.try_get(index)) + df->close(); + HTTP_REQUIRE_TRUE(map.remove(index), "index") + g->save(); + res->setBody(warp(to_json()).to_json_string()); + g->mode_acs.source_feed_relation_config.set_need_refresh(); + }); + + svr.Post(api + svr.rise + name, [g, this](HTTP_Param) { + CHECK_JSON_PARAM + HTTP_REQUIRE_VALUE(index, params.try_get_number("index")) + HTTP_REQUIRE_TRUE(map.swap(index, index - 1), "index") + g->save(); + res->setBody(warp(to_json()).to_json_string()); + g->mode_acs.source_feed_relation_config.set_need_refresh(); + }); + svr.Post(api + svr.fall + name, [g, this](HTTP_Param) { + CHECK_JSON_PARAM + HTTP_REQUIRE_VALUE(index, params.try_get_number("index")) + HTTP_REQUIRE_TRUE(map.swap(index, index + 1), "index") + g->save(); + res->setBody(warp(to_json()).to_json_string()); + g->mode_acs.source_feed_relation_config.set_need_refresh(); + }); +} + +void BIN_Msg_Buffer::push(const std::string& msg) { + auto output_packet_size = Global::instance()->mode_acs.data_feed_config.packet_byte_size.load(); + std::lock_guard g(mtx); + auto& pool = Global::instance()->mode_acs.data_feed_config.pool_; + if (msg_list_cache.empty() || msg_list_cache.back()->size() > output_packet_size) { + auto t = pool.get(); + t->append(msg); + msg_list_cache.push_back(t); + } else { + msg_list_cache.back()->append(msg); + } +} +const std::vector &BIN_Msg_Buffer::get_all() { + std::lock_guard g(mtx); + std::swap(msg_list_cache, msg_list); + msg_list_cache.clear(); + mode_s_msg_num = 0; + mode_other_msg_num = 0; + return msg_list; +} +BIN_Msg_Buffer::BIN_Msg_Buffer() { + msg_list_cache.reserve(8 * 1024); + msg_list.reserve(8* 1024); +} +Psc::JSON BIN_Msg_Buffer::state_json() { + + auto output_packet_size = Global::instance()->mode_acs.data_feed_config.packet_byte_size.load(); + size_t size, cache_size, pool_capacity, pool_free_count; + { + std::lock_guard g(mtx); + auto& pool = Global::instance()->mode_acs.data_feed_config.pool_; + size = msg_list.size(); + cache_size = msg_list_cache.size(); + pool_capacity = pool.capacity(); + pool_free_count = pool.free_count(); + } + return VAR_JSON_7(mode_s_msg_num, mode_other_msg_num, output_packet_size, cache_size, size, pool_capacity, pool_free_count); +} diff --git a/module/Local_Server/Data_Feed/Data_Feed.h b/module/Local_Server/Data_Feed/Data_Feed.h new file mode 100644 index 0000000..b54ff23 --- /dev/null +++ b/module/Local_Server/Data_Feed/Data_Feed.h @@ -0,0 +1,356 @@ +#pragma once + +#include "global.h" + +enum class Output_Data_Format { + AVR, + AVR_MLAT, + BIN, + SBS, + BIN_ID +}; + +enum class Mode_S_Output_Type { + DF_11_17_18, + NO_POS_Mode_S, + ALL_Mode_S +}; + +struct Output_Format { + Output_Data_Format type = Output_Data_Format::BIN; + std::atomic use_status = false; + Mode_S_Output_Type mode_s_output_type = Mode_S_Output_Type::DF_11_17_18; + std::atomic use_mode_ac = false; + std::atomic sbs_only_pos = false; + std::atomic use_crc = false; + + [[nodiscard]] Psc::JSON to_Json() const { + Psc::JSON ret = Psc::JSON::object(); + Ret_J(type) + Ret_J(use_status) + Ret_J(mode_s_output_type) + Ret_J(use_mode_ac) + Ret_J(sbs_only_pos) + return ret; + } + + void from_json(const Psc::JSON *that_json) { + Get_J(type) + Get_J(use_status) + Get_J(mode_s_output_type) + Get_J(use_mode_ac) + Get_J(sbs_only_pos) + } +}; + + +class Data_Feed { +public: + virtual ~Data_Feed() = default; + BIN_Msg_Buffer msg_buffer{}; + std::string key; + bool enable = false; + std::string type; + Output_Format output_format; + Frequency_Limit_Multi sbs_flm{}; + virtual void handle_in_loop() { + + } + virtual Psc::JSON to_json() { + Psc::JSON ret = Psc::JSON::object(); + Ret_J(key); + Ret_J(enable); + Ret_J(type); + ret.append({"output_format", output_format.to_Json()}); + return ret; + } + virtual void from_json(const Psc::JSON *that_json) { + Get_J(key) + Get_J(enable) + Get_J(type) + output_format.from_json(that_json->get("output_format")); + } + virtual Psc::JSON get_custom_state_json() { + return Psc::JSON::object(); + } + virtual Psc::JSON get_state_json() { + Psc::JSON ret = msg_buffer.state_json(); + ret.append_list(get_custom_state_json().children); + return ret; + } + bool check_and_open() { + if (_open_) return true; + bool ret = _open(); + _open_ = true; + return ret; + } + + void close() { + _open_ = false; + _close(); + } + + std::string to_string() { + return "Data_Feed【" + VAR_STR_3(key, enable, type) + "】"; + } +protected: + Data_Feed() = default; + bool _open_ = false; + virtual bool _open() { + return true; + } + + virtual void _close() { + + } +}; + + +class Data_Feed_TCP_Server : public Data_Feed { +public: + std::uint16_t port{}; + size_t connect_user_buffer_size{}; + size_t connect_system_buffer_size{}; + Psc::asio_socket::TCP_Server svr; + Psc::JSON get_custom_state_json() override { + auto& state = svr.state; + Psc::JSON ret = Psc::JSON::object(); + Ret_J(connect_system_buffer_size) + Ret_J(connect_user_buffer_size) + ret.key = "fixed"; + auto t = VAR_JSON_1(state); + t.append(ret); + return t; + } + + ~Data_Feed_TCP_Server() override {} + void handle_in_loop() override { + //std::cout << socket.to_string() << "flush_clients" << std::endl; + svr.flush_clients(); + svr.tick(); + } + void from_json(const Psc::JSON* that_json) override { + Data_Feed::from_json(that_json); + Get_J(port); + Get_J(connect_user_buffer_size) + Get_J(connect_system_buffer_size) + } + Psc::JSON to_json() override { + Psc::JSON ret = Data_Feed::to_json(); + Ret_J(port); + Ret_J(connect_user_buffer_size) + Ret_J(connect_system_buffer_size) + return ret; + } + void _close() override { svr.close(); } + bool _open() override { + svr.set_connect_user_buffer_size(connect_user_buffer_size); + svr.set_connect_system_buffer_size(connect_system_buffer_size); + svr.set_tcp_no_delay(false); + svr.create(); + bool ok = svr.listen("0.0.0.0", port); + return true; + } + Psc::JSON get_clients_json() { + Psc::JSON ret = Psc::JSON::array(); + for (const auto& conn : svr.get_all_clients()) { + auto& info = conn->info; + Psc::JSON cur = Psc::JSON::object(); + auto& fd = info.fd; + auto& cur_ip = info.sockaddr.ip; + auto& cur_port = info.sockaddr.port; + cur.append({"base", VAR_STR_3(cur_ip, cur_port, fd)}); + cur.append({"state", conn->send_buffer.state_str()}); + { + auto& ins = conn->push_speed.instant_speed; + auto& avr = conn->push_speed.average_speed; + cur.append({"send_speed(KB/s)", VAR_STR_2(ins, avr)}); + } + { + auto& ins = conn->lose_speed.instant_speed; + auto& avr = conn->lose_speed.average_speed; + cur.append({"lose_speed(KB/s)", VAR_STR_2(ins, avr)}); + } + { + auto& ins = conn->send_num.instant; + auto& avr =conn->send_num.average; + cur.append({"send_num(byte/次)", VAR_STR_2(ins, avr)}); + } + ret.append(cur); + } + return ret; + } +}; + + +class Data_Feed_TCP_Client : public Data_Feed { +public: + void handle_in_loop() override { + cli.tick(); + } + std::string url; + Psc::JSON get_custom_state_json() override { + auto& state = cli.state; + return VAR_JSON_1(state); + } + std::uint16_t port{}; + Psc::asio_socket::TCP_Client cli; + ~Data_Feed_TCP_Client() override = default; + void _close() override { cli.close(); } + bool _open() override { + Psc::asio_socket::Sockaddr_In sockaddr_in; + sockaddr_in.ip = url; + sockaddr_in.port = port; + cli.set_dest_address(sockaddr_in); + cli.create(); + return true; + } + void from_json(const Psc::JSON* that_json) override { + Data_Feed::from_json(that_json); + Get_J(url) + Get_J(port); + } + Psc::JSON to_json() override { + Psc::JSON ret = Data_Feed::to_json(); + Ret_J(url); + Ret_J(port); + return ret; + } +}; + + + +class Data_Feed_UDP_Server : public Data_Feed { +public: + Psc::JSON get_custom_state_json() override { + auto& state = svr.state; + return VAR_JSON_1(state); + } + + + + Data_Feed_UDP_Server()= default; + ~Data_Feed_UDP_Server() override = default; + void handle_in_loop() override; + [[nodiscard]] Psc::JSON get_clients_json() const { + Psc::JSON ret = Psc::JSON::array(); + for (const auto& i : svr.clients) { + Psc::JSON cur = Psc::JSON::object(); + cur.append({"ip", i.ip}); + cur.append({"port", i.port}); + ret.append(cur); + } + return ret; + } + + void from_json(const Psc::JSON* that_json) override { + Data_Feed::from_json(that_json); + Get_J(port); + } + Psc::JSON to_json() override { + Psc::JSON ret = Data_Feed::to_json(); + Ret_J(port); + return ret; + } + void _close() override { svr.close(); } + bool _open() override; + std::uint16_t port{}; + Psc::asio_socket::UDP_Server svr; +}; + + +class Data_Feed_UDP_Client : public Data_Feed { +public: + Data_Feed_UDP_Client() {} + ~Data_Feed_UDP_Client() override {} + Psc::JSON get_custom_state_json() override { + auto& state = cli.state; + return VAR_JSON_1(state); + } + void handle_in_loop() override { + cli.tick(); + } + Psc::asio_socket::UDP_Client cli; + std::string url; + std::uint16_t port{}; + void from_json(const Psc::JSON* that_json) override { + Data_Feed::from_json(that_json); + Get_J(url) + Get_J(port); + } + Psc::JSON to_json() override { + Psc::JSON ret = Data_Feed::to_json(); + Ret_J(url); + Ret_J(port); + return ret; + } + void _close() override { + std::cout << "udp客户端 目标地址:" << cli.dest_address.to_string() << "关闭!" << std::endl; + cli.close(); + } + bool _open() override { + cli.create(); + cli.set_dest_address(url, port); + cli.connect(); + return true; + } +}; + + + +inline std::shared_ptr create_data_feed_from_type(const std::string& t) { + std::shared_ptr ret{}; + if (t == "Data_Feed_TCP_Server") ret = std::make_shared(); else + if (t == "Data_Feed_UDP_Server") ret = std::make_shared(); else + if (t == "Data_Feed_TCP_Client") ret = std::make_shared(); else + if (t == "Data_Feed_UDP_Client") ret = std::make_shared(); else { + std::cout << "未知的 Data_Feed type类型! t:[" << t << "]"<< std::endl; + throw std::invalid_argument("unknown Data_Feed type: " + t); + } + return ret; +} + +struct Data_feed_Config { + Psc::String_Pool pool_ = Psc::String_Pool(1600, 8* 1024); // 8192 * 1600 12.5 MB + Ordered_Map> map; + std::atomic empty_wait_milliseconds{}; + std::atomic packet_byte_size{}; + size_t tcp_server_default_connect_user_buffer_size{}; + size_t tcp_server_default_connect_system_buffer_size{}; + Data_feed_Config() = default; + void init(const Psc::JSON* that_json) { + auto connect = that_json->get("list"); + for (auto& it : connect->children) { + auto type = it.get_string("type"); + std::shared_ptr t = create_data_feed_from_type(type); + t->from_json(&it); + map.push_back(t); + } + Get_J(empty_wait_milliseconds) + Get_J(tcp_server_default_connect_user_buffer_size) + Get_J(tcp_server_default_connect_system_buffer_size) + } + + Psc::JSON list() { + auto connect_json = Psc::JSON::array(); + for (auto& it : map.list()) { + connect_json.children.emplace_back(it->to_json()); + } + return connect_json; + } + + Psc::JSON to_json() { + Psc::JSON ret = Psc::JSON::object(); + Ret_J(empty_wait_milliseconds) + Ret_J(packet_byte_size) + Ret_J(tcp_server_default_connect_user_buffer_size) + Ret_J(tcp_server_default_connect_system_buffer_size) + ret.append({"list", list()}); + return ret; + } + Psc::JSON get_feed(const std::string& key); + void server(Global* g); +}; +class Data_Source; +std::optional convert_to_send_format(Data_Source* ds, const std::shared_ptr& feed, const std::shared_ptr& msg); + diff --git a/module/Local_Server/Data_Feed/data_feed_thread.cpp b/module/Local_Server/Data_Feed/data_feed_thread.cpp new file mode 100644 index 0000000..667c485 --- /dev/null +++ b/module/Local_Server/Data_Feed/data_feed_thread.cpp @@ -0,0 +1,230 @@ +#include "../server/Global.h" +#include "../server/Mode_Msg_Buffer.h" +#include +#include +long long get_current_milliseconds() { + auto now = std::chrono::system_clock::now(); + auto duration = std::chrono::duration_cast(now.time_since_epoch()); + return duration.count(); +} +Frequency_Limit too_many_msg_limit; +Frequency_Limit flush_limit; + + +std::optional convert_to_send_format(Data_Source* ds, const std::shared_ptr& feed, const std::shared_ptr& msg) +{ + auto& type = msg->type; + auto fs = dynamic_cast(msg->source.get()); + if (fs) { + if (fs->play_mode == Play_Mode::analysis) { + //std::cout << fs->key << " analysis i ==" << i << std::endl; + } + } + // 出口输出的条件 + auto& output_format = feed->output_format.type; + auto& use_mode_ac = feed->output_format.use_mode_ac; + auto& use_status = feed->output_format.use_status; + auto& mode_s_output_type = feed->output_format.mode_s_output_type; + // 计算出是否输出消息 + std::optional send_msg = std::nullopt; + if (type == SSR::Msg::HULC_Status) { + if (!use_status) return std::nullopt; + auto data = static_cast(msg.get()); + if (output_format == Output_Data_Format::BIN || output_format == Output_Data_Format::BIN_ID) { + send_msg = SSR::packet_to_escape_format(data->packet); + } + } else if (type == SSR::Msg::Radarcape_status) { + auto data = static_cast(msg.get()); + if (output_format == Output_Data_Format::BIN || output_format == Output_Data_Format::BIN_ID) { + send_msg = SSR::packet_to_escape_format(data->packet); + } + } else if (type == SSR::Msg::AC) { + if (!use_mode_ac) return std::nullopt; + auto data = static_cast(msg.get()); + std::string& msg_hex = data->msg_hex; + char signal_level = data->signal_level; + SSR::MLAT_timestamp& mlat_timestamp = data->mlat_timestamp; + if (output_format == Output_Data_Format::BIN) { + //send_msg = create_Binary_Format_memory(msg_hex, signal_level, &mlat_timestamp); + send_msg = SSR::packet_to_escape_format(msg->packet); + } else if (output_format == Output_Data_Format::BIN_ID) { + // std::uint32_t id; + // { + // id = Global::instance()->mlat_server.id; + // } + // auto bin_id_packet = mode_s_msg_packet_to_server_packet(id, data->packet); + // send_msg = packet_to_escape_format(bin_id_packet); + } else if (output_format == Output_Data_Format::AVR) { + send_msg = SSR::create_AVR_format(msg_hex); + } else if (output_format == Output_Data_Format::AVR_MLAT) { + send_msg = create_MLAT_AVR_format(msg_hex, &mlat_timestamp); + } + } else if (type == SSR::Msg::S7 || type == SSR::Msg::S14) { + auto s_msg = static_cast(msg.get()); + std::string& icao = s_msg->icao; + SSR::Downlink_Format& df = s_msg->df; + std::string& msg_hex = s_msg->msg_hex; + auto& signal_level = s_msg->signal_level; + SSR::MLAT_timestamp& mlat_timestamp = s_msg->mlat_timestamp; + auto aircraft = ds->get_aircraft(s_msg->icao); + + if (output_format == Output_Data_Format::SBS) { + bool sbs_out_put = false; + if (feed->output_format.sbs_only_pos) { + auto s = ds->get_aircraft(s_msg->icao); + if (s) { + auto pos = s->pos(); + if (pos.has_value()) { + if (feed->sbs_flm.test(s_msg->icao)) { + sbs_out_put = true; + } + } + } + } else { + if (feed->sbs_flm.test(s_msg->icao)) { + sbs_out_put = true; + } + } + if (!sbs_out_put) return std::nullopt; + + send_msg = ""; + SSR::SBS_MSG msg_base; + if (!aircraft) return std::nullopt; + msg_base.set(aircraft.get()); + for (int msg_t = 1; msg_t <= 8; ++msg_t) { + send_msg->append(msg_base.to_msg(msg_t) + "\n"); + } + send_msg->append(msg_base.to_ID() + "\n"); + send_msg->append(msg_base.to_AIR() + "\n"); + send_msg->append(msg_base.to_CLK() + "\n"); + send_msg->append(msg_base.to_SEL() + "\n"); + send_msg->append(msg_base.to_STA() + "\n"); + return send_msg; + } + + bool DF_11_17_18 = df == SSR::Downlink_Format::All_Call_Reply_11 || df == SSR::Downlink_Format::Extended_Squitter_17 || df == + SSR::Downlink_Format::Extended_Squitter_Non_Transponder_18; + if (mode_s_output_type == Mode_S_Output_Type::DF_11_17_18 && !DF_11_17_18) return std::nullopt; + if (mode_s_output_type == Mode_S_Output_Type::NO_POS_Mode_S) { + if (aircraft && aircraft->pos().has_value()) { + return std::nullopt; + } + } + + if (output_format == Output_Data_Format::BIN) { + send_msg = SSR::packet_to_escape_format(s_msg->packet); + //send_msg = create_Binary_Format_memory(msg_hex, signal_level, &mlat_timestamp); + } else if (output_format == Output_Data_Format::BIN_ID) { + // std::uint32_t id; + // { + // id = Global::instance()->mlat_server.id; + // } + // auto bin_id_packet = mode_s_msg_packet_to_server_packet(id, data->packet); + // send_msg = packet_to_escape_format(bin_id_packet); + } else if (output_format == Output_Data_Format::AVR) { + send_msg = SSR::create_AVR_format(msg_hex); + } else if (output_format == Output_Data_Format::AVR_MLAT) { + send_msg = create_MLAT_AVR_format(msg_hex, &mlat_timestamp); + } else { + std::cerr << "Unknown output format " << VAR_STR_1(output_format) << std::endl; + return std::nullopt; + } + } + return send_msg; +} + +void data_feed_thread(std::atomic& running) { + auto g = Global::instance(); + for (auto& t : g->mode_acs.data_feed_config.map.list()) { + if (t->enable) { + auto ret = t->check_and_open(); + if (!ret) { + std::cout << "[Data_feed_Config] [" << t->key << "] 第一次打开失败! 程序退出! " << std::endl; + } + } + } + auto& mode_acs = Global::instance()->mode_acs; + auto& cfg = mode_acs.data_feed_config; + auto& pool = cfg.pool_; + auto t = cfg.empty_wait_milliseconds.load(); + auto& report_data_feed_msg_mum = mode_acs.report_data_feed_msg_mum; + std::vector> enable_feeds; // all_feed 保证声明周期仍然存在 + auto monitor_msg_live = mode_acs.monitor_msg_live.load(); + bool all_empty = true; + while (running.load(std::memory_order_acquire) == true) { + // 这两个每次循环都要重新计算 保证实时性 + // if (flush_limit.test()) { + auto all_feed = cfg.map.list(); + enable_feeds.clear(); + for (auto& feed : all_feed) { + if (!feed->enable) continue; + enable_feeds.push_back(feed); + // 执行特定的刷新逻辑 比如 tcp_server 检查自身的连接 + feed->handle_in_loop(); + } + + + int m = static_cast(enable_feeds.size()); + for (int j = 0; j < m; j++) { + auto& feed = enable_feeds[j]; + auto s_num = feed->msg_buffer.mode_s_msg_num.load(); + auto other_num = feed->msg_buffer.mode_other_msg_num.load(); + //const std::vector>& all = feed->msg_buffer.get_all(); + const std::vector& all = feed->msg_buffer.get_all(); + // 释放内存池 + + + Pool_Guard pg(&pool, all); + + auto num = report_data_feed_msg_mum.load(); + if (monitor_msg_live) { + if (num != 0 && all.size() > num) { + if (too_many_msg_limit.test()) { + std::ostringstream oss; + oss << "feed_key:" << feed->key << " "; + oss << "recv_s:" << s_num << " "; + oss << "recv_other:" << other_num << " "; + std::cout << oss.str() << std::endl; + } + } + } + if (all.empty()) continue; + all_empty = false; + auto n = all.size(); + + + + for (auto i = 0; i < n; i++) { + const auto& str = all[i]; + if (str->empty()) { + std::cout << "警告:未知原因:" << feed->key << "内有空的消息体" << std::endl; + continue; + } + if (feed->type == "Data_Feed_TCP_Server") { + auto it = dynamic_cast(feed.get()); + it->svr.write_to_all_clients(*str); + } + else if (feed->type == "Data_Feed_UDP_Server") { + auto it = dynamic_cast(feed.get()); + it->svr.write_to_all_clients(*str); + } + else if (feed->type == "Data_Feed_TCP_Client") { + auto it = dynamic_cast(feed.get()); + it->cli.send(*str); + } + else if (feed->type == "Data_Feed_UDP_Client") { + auto it = dynamic_cast(feed.get()); + it->cli.send(*str); + } + } + } + if (t != 0) { + if (all_empty) { + std::this_thread::sleep_for(std::chrono::milliseconds(t * 2)); + } else { + std::this_thread::sleep_for(std::chrono::milliseconds(t)); + } + } + } +} + diff --git a/module/Local_Server/Data_Feed/export.h b/module/Local_Server/Data_Feed/export.h new file mode 100644 index 0000000..3eaa8da --- /dev/null +++ b/module/Local_Server/Data_Feed/export.h @@ -0,0 +1,2 @@ +#pragma once +#include "Data_Feed.h" diff --git a/module/Local_Server/Data_Feed/global.h b/module/Local_Server/Data_Feed/global.h new file mode 100644 index 0000000..a5ea2c8 --- /dev/null +++ b/module/Local_Server/Data_Feed/global.h @@ -0,0 +1,6 @@ +#pragma once +#include "../server/Mode_Msg_Buffer.h" +#include "Core/Serial/Serial.h" +#include "Core/Statistics/Frequency_Limit.h" +#include "Core/socket/TCP_Server.h" +#include "Core/socket/export.h" diff --git a/module/Local_Server/Data_Source/BaseStation.cpp b/module/Local_Server/Data_Source/BaseStation.cpp new file mode 100644 index 0000000..f25df77 --- /dev/null +++ b/module/Local_Server/Data_Source/BaseStation.cpp @@ -0,0 +1,43 @@ +#include "BaseStation.h" + + + +namespace SSR { +struct HULC_Status_Message; +} + + +std::optional BaseStation::get_pos() { + std::lock_guard g(mtx); + return SSR::CPR::Position{hulc.get_latitude(), hulc.get_longitude()}; +} +void BaseStation::set_msg(const SSR::HULC_Status_Message& msg) { + std::lock_guard g(mtx); + hulc = msg; + if (handle_when_updated) handle_when_updated(msg); +} +std::string BaseStation::to_string() { + std::lock_guard g(mtx); + return "BaseStation:[" + std::to_string(hulc.get_latitude()) + ", " + std::to_string(hulc.get_longitude()) + "]"; +} +Psc::JSON BaseStation::to_Json() { + std::lock_guard g(mtx); + auto ret = Psc::JSON::object(); + ret.append({"序列号", hulc.SerNum}); + ret.append({"状态标志", hulc.Flags}); + ret.append({"内部使用", hulc.I_U_}); + ret.append({"时间", Psc::utc_2_local_time(hulc.xTime)}); + ret.append({"latitude", hulc.get_latitude()}); + ret.append({"longitude", hulc.get_longitude()}); + ret.append({"height", hulc.Alt}); + ret.append({"卫星数量", hulc.Sat}); + ret.append({"HDOP", hulc.get_HDOP()}); + ret.append({"GPS设备检测到", hulc.GPS_device_detected()}); + ret.append({"GPS有效", hulc.GPS_valid()}); + ret.append({"GPS有效定位", hulc.GPS_has_valid_fix()}); + ret.append({"GPS高精度时间", hulc.GPS_high_accuracy_time()}); + ret.append({"启动以来TX队列溢出", hulc.TX_queue_overflow_since_startup()}); + ret.append({"过去一秒TX队列溢出", hulc.TX_queue_overflow_last_second()}); + ret.append({"发现过多NMEA数据", hulc.excessive_NMEA_found()}); + return ret; +} \ No newline at end of file diff --git a/module/Local_Server/Data_Source/BaseStation.h b/module/Local_Server/Data_Source/BaseStation.h new file mode 100644 index 0000000..432f649 --- /dev/null +++ b/module/Local_Server/Data_Source/BaseStation.h @@ -0,0 +1,20 @@ +#pragma once +#include "global.h" + + + +class BaseStation { +public: + std::string to_string(); + Psc::JSON to_Json(); + std::optional get_pos(); + void set_msg(const SSR::HULC_Status_Message& msg); + std::function handle_when_updated = nullptr; +protected: + std::mutex mtx; + SSR::HULC_Status_Message hulc{}; +}; +class Global; + + + diff --git a/module/Local_Server/Data_Source/Data_Source.cpp b/module/Local_Server/Data_Source/Data_Source.cpp new file mode 100644 index 0000000..525c32c --- /dev/null +++ b/module/Local_Server/Data_Source/Data_Source.cpp @@ -0,0 +1,1078 @@ +#include "Data_Source.h" + +#include + +#include "../server/Global.h" +#include "Database.h" + +Psc::serial::Serial* create_serial(const std::string& serial_name, Baud_Rate_Type baud_rate) { + auto serial = new Psc::serial::Serial; + serial->set_serial_name(serial_name); + serial->set_baud_rate(baud_rate); + serial->set_parity(Psc::serial::Parity::NoParity); + serial->set_data_bits(Psc::serial::DataBits::Data8); + serial->set_stop_bits(Psc::serial::StopBits::OneStop); + serial->set_flow_control(Psc::serial::FlowControl::HardwareControl); + serial->set_buffer_byte_size(10 * 1024); + if (!serial->open()) + { + std::cerr << "createSerial " + serial_name + ":" + std::to_string(baud_rate) + " 打开串口失败!\n"; + Psc::fail_fast(); + return nullptr; + } else + { + // std::cerr << "createSerial " + serial_name + ":" + std::to_string(baud_rate) + " 打开串口成功!\n"; + } + return serial; +} + +std::shared_ptr create_from_json(const JSON* that_json) { + std::string type = that_json->get_string("type"); + std::shared_ptr ret = create_data_source_from_type(type); + ret->from_json(that_json); + // if (ret->enable) + // { + // ret->open(); + // } + return ret; +} + + +std::shared_ptr Data_Source::that() { + return shared_from_this(); +} +Psc::JSON Data_Source::get_state() { + Psc::JSON ret = Psc::JSON::object(); + ret.append_list(get_custom_state_json().children); + ret.append({"ds: read_speed(byte)", read_speed}); + ret.append({"ds: value_statistics(byte)", value_statistics}); + return ret; +} + +std::string Data_Source::thread_key() const { + //return "Data_Source_Handle_Thread:[" + key + "]"; + return key + "_DS_HT"; +} + +void Data_Source::test_and_attach_thread() { + //static int t = Global::instance()->mode_acs.read_milliseconds; + Global::instance()->thread_manager.test_and_start_thread(thread_key(), [this](std::atomic& running) { + if (enable) { + open(); + } + while (running.load(std::memory_order_acquire) == true) + { + handle_in_loop(); + handle_mode_acs_source(); + } + }); +} + + +std::shared_ptr Data_Source::create_msg(const std::shared_ptr &source, + const std::string &packet) { + if (packet[0] != 0x1a) + { + std::cout << "first:" << mem2hex(packet) << std::endl; + return nullptr; + } + std::string error_len = key + " " + LOG_POS_SIMPLE + std::string(" ") + "mode_s_error_length"; + if (packet.size() < 2) return nullptr; + auto mt = packet[1]; + if (mt == SSR::Msg::AC) + { + if (packet.size() != SSR::Msg::AC_len) + { + SSR::mode_s_logger->c_debug(error_len, {}, + std::to_string(mt) + " size:" + std::to_string(packet.size()) + + " hex:" + mem2hex(packet) + " should:" + std::to_string(SSR::Msg::AC_len)); + mode_ac_statistic.add_length_error(); + return nullptr; + } + mode_ac_statistic.add(); + return std::make_shared(that(), packet); + } + if (mt == SSR::Msg::S7) + { + if (packet.size() != SSR::Mode_S_Msg::S7_len) + { + SSR::mode_s_logger->c_debug(error_len, {}, + std::to_string(mt) + " size:" + std::to_string(packet.size()) + + " hex:" + mem2hex(packet) + " should:" + std::to_string(SSR::Msg::S7_len)); + mode_s_statistic.add_length_error("[length error] Msg::S7 handle_mode_s_source"); + return nullptr; + } + return std::make_shared(that(), packet); + } + + if (mt == SSR::Msg::S14) + { + if (packet.size() != SSR::Msg::S14_len) + { + SSR::mode_s_logger->c_debug(error_len, {}, + std::to_string(mt) + " size:" + std::to_string(packet.size()) + + " hex:" + mem2hex(packet) + " should:" + std::to_string(SSR::Msg::S14_len)); + mode_s_statistic.add_length_error("[length error] Msg::S14 handle_mode_s_source"); + return nullptr; + } + return std::make_shared(that(), packet); + } + + if (mt == SSR::Msg::Radarcape_status) { + return nullptr; // 不知道如何解析跳过 + if (packet.size() != SSR::Msg::Radarcape_status_len) + { + SSR::mode_s_logger->c_debug(error_len, {}, + std::to_string(mt) + " size:" + std::to_string(packet.size()) + + " hex:" + mem2hex(packet) + " should:" + std::to_string(SSR::Msg::Radarcape_status_len)); + mode_s_statistic.add_length_error("[length error] Msg::Radarcape_status_len handle_mode_s_source"); + return nullptr; + } + return std::make_shared(that(), packet); + } + + if (mt == SSR::Msg::HULC_Status) + { + if (packet.size() != SSR::Msg::HULC_len) + { + + // 找不到协议 size:23 hex:1A34195F0000001500B502FF06F423CE50000090000000 should:5 + SSR::mode_s_logger->c_debug(error_len, {}, + Psc::to_string(type) + " HULC size:" + + std::to_string(packet.size()) + " hex:" + mem2hex(packet)); + return nullptr; + } + return std::make_shared(that(), packet); + } + // std::cout << "unknown_type:" << memory2hex(packet); + rotating_log("unknown_type", mem2hex(packet)); + return nullptr; +} + + +void Data_Source::update_msg_day_time(std::shared_ptr msg) { + auto cur = std::dynamic_pointer_cast(msg); + if (cur != nullptr) { + auto& pre = last_prase_msg; + if (!pre) { + pre = cur; + return; + } + cur->day_num = pre->day_num; + if (cur->time() < pre->time()) { + ++cur->day_num; + } + } +} + +void Data_Source::handle_mode_acs_source() { + std::string mode_data = read(); + + if (mode_data.empty()) { + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + //std::cout << key + "数据为空,没有消息积压" << std::endl; + return; + } + + + auto size = mode_data.size(); + read_speed.update(size); + value_statistics.update(size); + + pre_handle(mode_data); + + SSR::Binary_Format_handle_buffer(buffer, mode_data, [this](std::string& packet) { + auto msg = create_msg(that(), packet); + if (!msg) return; + update_msg_day_time(msg); + push_to_feed(msg); + auto mt = msg->type; + bool mode_s = mt == SSR::Msg::S7 || mt == SSR::Msg::S14; + if (mt == SSR::Msg::HULC_Status) { + handle_HULC(packet); + } + else if (mt == SSR::Msg::Radarcape_status) { + auto radarcape_msg = SSR::create_Radarcape_STATUS_Message(packet); + std::cout << radarcape_msg.toJson().to_json_string() << std::endl; + SSR::mode_s_logger->debug("Radarcape_status/radarcape", {}, radarcape_msg.toJson().to_json_string()); + } + else if (mode_s) + { + // 拓展点 + handle_mode_s(std::dynamic_pointer_cast(msg)); + } + }); +} + + +void Data_Source::test_and_stop_thread() const { + Global::instance()->thread_manager.test_and_stop_thread(thread_key()); +} + +Psc::JSON Data_Source::get_all_connect_feed_status() { + Psc::JSON ret = Psc::JSON::object(); + std::vector list; + { + std::lock_guard g(cdf_mtx); + list = cached_data_feed_key_list; + } + for (auto& i : list) { + Psc::JSON cur = Psc::JSON::object(); + auto odf = Global::instance()->mode_acs.data_feed_config.map.get(i.key); + if (odf.has_value()) { + const auto& df = odf.value(); + i.mode_s_cache_num.update(df->msg_buffer.mode_s_msg_num); + i.mode_other_cache_num.update(df->msg_buffer.mode_other_msg_num); + cur.append({"mode_s_msg_num", i.mode_s_cache_num.to_json()}); + cur.append({"mode_other_msg_num", i.mode_other_cache_num.to_json()}); + } + ret.append({i.key, cur}); + } + return ret; +} +Psc::JSON Data_Source::get_all_connect_feed() { + Psc::JSON ret = Psc::JSON::array(); + std::vector list; + { + std::lock_guard g(cdf_mtx); + list = cached_data_feed_key_list; + } + for (auto& i : list) { + Psc::JSON cur = Psc::JSON::object(); + cur.append({"key", i.key}); + ret.append(cur); + } + return ret; +} + + +std::vector readLines(const std::string& path) { + std::vector lines; + + std::filesystem::path p = std::filesystem::path((const char8_t*)path.c_str()); + + //std::filesystem::path p = std::filesystem::u8path(path); + std::ifstream istream(p); + if (!istream) { + std::cerr << "读取模拟数据源 readLines 无法打开文件:" << path << std::endl; + Psc::fail_fast(); + } + + // 将整个文件读入一个字符串 + std::stringstream stream; + stream << istream.rdbuf(); + // 使用 stringstream 按行分割内容 + std::string line; + char ch; + while (stream.get(ch)) { + if (ch == ' ') { + continue; + } + if (ch == '\r' || ch == '\n') { + if (!line.empty()) { + lines.push_back(line); + line.clear(); + } + + // if (ch == '\r') { + // stream.get(); // 吃掉 \n + // } + // if (ch == '\n') { + // stream.get(); // 吃掉 \n + // } + // 处理 \r\n 组合:如果当前是 \r,下一个是 \n,跳过它 + // if (ch == '\r' && stream.peek() == '\n') { + // stream.get(); // 吃掉 \n + // } + + } else { + line += ch; + } + if (line.size() == 1000) { + lines.push_back(line); + line.clear(); + } + } + // 最后一行如果没有换行符也处理一下 + if (!line.empty()) { + lines.push_back(line); + } + std::ostringstream oss; + oss << path + " 总行数:" + std::to_string(lines.size()) + " 有效行数:" + std::to_string(lines.size()) + "\n" << std::flush; + std::cout << oss.str() << std::flush; + return lines; +} + + + +std::string extractID(const std::string& logLine) { + size_t lastSpacePos = logLine.rfind(" "); // 查找最后一个空格 + if (lastSpacePos != std::string::npos) { + return logLine.substr(lastSpacePos + 1); // 从最后一个空格之后提取字符串 + } + return logLine; +} + +time_t convert_to_timestamp(const std::string& str) { + // 创建一个结构体 tm 来存储解析后的时间 + std::tm timeStruct = {}; + + std::istringstream ss(str); + ss >> std::get_time(&timeStruct, "%Y-%m-%d %H:%M:%S"); + if (ss.fail()) { + std::cerr << "Failed to parse time" << std::endl; + return -1; // 如果解析失败,返回 -1 + } + + // 将 tm 转换为 time_t(时间戳) + time_t timestamp = std::mktime(&timeStruct); + + if (timestamp == -1) { + std::cerr << "Failed to convert to time_t" << std::endl; + return -1; // 如果转换失败,返回 -1 + } + return timestamp; +} + +std::tuple extractID2(const std::string& logLine) { + size_t lastSpacePos = logLine.rfind(" "); // 查找最后一个空格 + time_t t = convert_to_timestamp(logLine.substr(0, 19)); + if (lastSpacePos != std::string::npos) { + return {logLine.substr(lastSpacePos + 1), t}; // 从最后一个空格之后提取字符串 + } + return {logLine, t}; +} + + +std::string bin_format(const std::string& hex, time_t t){ + std::tm* currentTime = std::localtime(&t); + auto sec = currentTime->tm_hour * 3600 + currentTime->tm_min * 60 + currentTime->tm_sec; + SSR::MLAT_timestamp a(sec, 0); + return create_Binary_Format_memory(hex, 0, &a); +} + +std::optional File_Data_Source::get_raw_line(int& ret_index) { + if (index == 0 && part_infos.empty()) + { + ret_index = -1; + return std::nullopt; + } + std::optional log_info = std::nullopt; + if (index == part_infos.size()) + { + if (play_mode == Play_Mode::loop) + { + index = 0; + } else + { + if (!have_report_play_back_all_success) + { + std::ostringstream oss; + oss << SSR::get_current_date() << " " << SSR::get_current_time() << " [进程:" << std::this_thread::get_id() << "] " << file_path + " 全部加载成功!\n" << std::flush; + std::cout << oss.str() << std::flush; + have_report_play_back_all_success = true; + } + ret_index = -1; + return std::nullopt; + } + } + ret_index = index + 1; + return part_infos[index++]; +} + + +// 1A 33 1A 1A F1 FB 87 73 7E 7F a8001d81a87543b0a80000 + +std::string get_true_from_raw_line(Data_Source* ds, File_Data_Type data_type, int index, const std::string& log_info) { + std::string ret; + + // 2025-01-06 07:20:17 [info] dc2541e65001401a3119b2dd1c7af67132201 + if (data_type == File_Data_Type::BIN) { + return log_info; + } + else if (data_type == File_Data_Type::BIN_Text) + { + auto info = extractID(log_info); + ret = hex2mem(info); + } + else if (data_type == File_Data_Type::AVR) + { + auto [info, time] = extractID2(log_info); + ret = bin_format(info, time); + } + // 1A 33 10 01 A5 31 FB 9A 5D 8D 78 0E 47 99 08 8E 32 B0 08 BE E9 8A E6 1A 32 10 01 AA 14 61 7E 5E 02 E6 0F 38 7D 87 08 + // 1A 32 10 01 AD B5 64 F7 63 5D 78 0F 9D BA 93 BA + else if (data_type == File_Data_Type::BIN_Blank_Text) + { + std::string info = log_info; + std::string result = ds->last_char; + ds->last_char = ""; + + + + for (char c : info) + { + if (std::isxdigit(c)) { // 会判断字符 c 是否是十六进制数字字符 + result += c; + } else if (std::isspace(c)) { + // + } else { + std::ostringstream oss; + oss << "存在非法字符[" << c << "]: value:" << (int)c << " in:" << log_info << LOG_POS; + server_logger->c_debug("非法字符:", {}, oss.str()); + return ""; + } + } + auto size = result.size(); + if (size % 2 != 0) { + // 保存最后一个字符 + ds->last_char = result.empty() ? "" : std::string(1, result.back()); + result.pop_back(); + } + ret = hex2mem(result); + + // if (size % 2 != 0) + // { + // std::ostringstream oss; + // size_t prefix_num = 20; + // size_t suffix_num = 20; + // auto origin_size = log_info.size(); + // prefix_num = std::min(origin_size, prefix_num); + // suffix_num = std::min(origin_size, suffix_num); + // std::string prefix_data = log_info.substr(0, prefix_num); + // std::string suffix_data = log_info.substr(log_info.size() - suffix_num, suffix_num); + // oss << "index:" << index << " 长度不为偶数 不能转换成内存:" << "[内容]" << "result_size" << result.size() << " origin_size:[" << origin_size << "]" << std::endl << + // " prefix[" << prefix_num << "]:" << prefix_data << std::endl << + // " suffix[" << suffix_num << "]:" << suffix_data << std::endl << + // std::endl; + // server_logger->c_debug("长度不为偶数", {}, oss.str()); + // //std::cout << "result:" << log_info << std::endl << std::endl; + // return ""; + // } + + } + else if (data_type == File_Data_Type::BIN_Blank_One_Line_With_Escape) { + auto size = log_info.size(); + if (size % 2 != 0) + { + return hex2mem(log_info.substr(0, size - 1)); + } + return hex2mem(log_info); + } + else if (data_type == File_Data_Type::BIN_Blank_One_Line_No_Escape) { + auto size = log_info.size(); + std::string data; + if (size % 2 != 0) + { + data = log_info.substr(0, size - 1); + } else { + data = log_info; + } + return SSR::packet_to_escape_format(hex2mem(data)); + } + else if (data_type == File_Data_Type::SIMPLE_BIN_Blank) + { + std::string info = log_info; + std::string result; + for (char c : info) + { + if (c != ' ') + { + result += c; + } + } + // 1 + 1 + 6 + 1 + 2/7/14 + // 1a + type time_stamp signal_level data + int size = result.size(); + if (size != 2*2 && size != 7*2 && size != 14*2) + { + std::cout << "line_offset:[" << index << "] " << "大小" << size << " 不为偶数,或不为2,7,14 不能转换成二进制格式:" << result << std::endl; + return ""; + } + std::string head("\x1a"); + std::string type; + std::string time_stamp = "\x11\x22\x33\x44\x55\x66"; + std::string signal_level("\xFF"); + if (size == 2 * 2) + { + type = R"(1)"; + } else if (size == 7 * 2) + { + type = R"(2)"; + } else if (size == 14 * 2) + { + type = R"(3)"; + } + ret = SSR::packet_to_escape_format(head + type + time_stamp + signal_level + hex2mem(result)); + + //std::cout << ret.size() << std::endl; + } + else + { + std::cout << "未知的回放类型 " << static_cast(data_type) << std::endl; + Psc::fail_fast(); + } + return ret; +} + + + + +void File_Data_Source::_close() { + std::lock_guard g(mtx); + index = 0; + part_infos.clear(); +} + +bool File_Data_Source::_open() { + std::lock_guard g(mtx); + auto path = get_true_file_path(); + + namespace fs = std::filesystem; + if (!fs::exists(path)) { + state = "文件不存在"; + return false; + } + + if (data_type == File_Data_Type::BIN) { + part_infos = readBinaryFileAsString(path, 1000); + } + else { + part_infos = readLines(path); + } + state = "已加载" + to_string(part_infos.size()) + "长度数据!"; + return true; +} + + +std::vector File_Data_Source::readBinaryFileAsString(const std::string& filepath, size_t part_size) { + // 打开文件(以二进制模式) + std::ifstream file(filepath, std::ios::binary); + + if (!file) { + std::cerr << "无法打开文件: " << filepath << std::endl; + return {}; // 文件打开失败,返回空vector + } + + // 获取文件大小 + file.seekg(0, std::ios::end); + size_t fileSize = file.tellg(); + file.seekg(0, std::ios::beg); + + // 存储读取的部分 + std::vector parts; + + // 读取文件的每一部分 + size_t bytesRead = 0; + while (bytesRead < fileSize) { + // 计算每个部分的长度(最后一部分可能小于part_size) + size_t remaining = fileSize - bytesRead; + size_t currentPartSize = (remaining < part_size) ? remaining : part_size; + + // 创建buffer来存储当前部分 + std::string buffer(currentPartSize, '\0'); + + // 读取当前部分 + file.read(&buffer[0], currentPartSize); + + // 将读取的部分添加到vector + parts.push_back(std::move(buffer)); + + // 更新已读取字节数 + bytesRead += currentPartSize; + } + + // 关闭文件 + file.close(); + + return parts; +} + + +std::string File_Data_Source::read() { + std::lock_guard g(mtx); + int ret_index = 0; + if (play_mode != Play_Mode::analysis) + { + std::optional log_info = get_raw_line(ret_index); + return log_info.has_value() ? get_true_from_raw_line(this, data_type, ret_index, log_info.value()) : ""; + } else + { + int num = 0; + std::string ret; + std::optional log_info = get_raw_line(ret_index); + while (log_info.has_value()) + { + num++; + auto data = log_info.value(); + auto cur = get_true_from_raw_line(this, data_type, ret_index, data); + ret += cur; + // 一定要在这个位置,否则会导致遗漏报文 + if (num == 1000) { + break; + } + log_info = get_raw_line(ret_index); + } + // std::cout << "size == " << t.size() << std::endl; + return ret; + } +} + + +void File_Data_Source::handle_mode_acs_source() { + std::string mode_data = read(); + if (mode_data.empty()) { + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + return; + } + pre_handle(mode_data); + + SSR::Binary_Format_handle_buffer(buffer, mode_data, [this](std::string& packet) { + auto msg = create_msg(that(), packet); + if (msg == nullptr) return; + update_msg_day_time(msg); + push_to_feed(msg); + auto mt = msg->type; + bool mode_s = mt == SSR::Msg::S7 || mt == SSR::Msg::S14; + // 文件回放只处理mode_s + if (mode_s) + { + // 拓展点 + cache_list.push_back(std::make_shared(std::dynamic_pointer_cast(msg))); + } + }); + + + if (cache_list.empty()) return; + // 初始化流程 + if (pre_cache == nullptr) { + pre_cache = cache_list.front(); + cache_list.pop_front(); + + // 初始化当前开始时间点 + SSR::Play_Back_Time_Point& start = player_clock.start_time; + start.day_num = pre_cache->day_num; + start.day_sec = pre_cache->msg->mlat_timestamp.daysec; + } + + + auto sys_time = player_clock.get_cur_time_point(); + while (true) { + if (cache_list.empty()) break; + auto pre = pre_cache; + auto cur = cache_list.front(); + cur->day_num = pre->day_num; + if (cur->time() < pre->time()) { + cur->day_num++; + } + cache_list.pop_front(); + pre_cache = cur; + // 时间到了 回放这个文件 + handle_mode_s(cur->msg); + if (cur->time() > sys_time) { + break; + } + } +} + +std::string Dll_Data_Source::read() { + + auto start = std::chrono::steady_clock::now(); + + if (read_func_ptr == nullptr) return ""; + + auto buf = reinterpret_cast(buffer.data()); + auto len = read_func_ptr(buf, buffer_size); + vs.update(len); + + std::string data(buf, len); + + if (data.empty()) { + auto end = std::chrono::steady_clock::now(); + auto cost = std::chrono::duration_cast(end - start).count(); + //std::cout << "Dll_Data_Source::read cost: " << cost << " us\n"; + return ""; + } + + auto ret = get_true_from_raw_line(this, data_type, -1, data); + + auto end = std::chrono::steady_clock::now(); + auto cost = std::chrono::duration_cast(end - start).count(); + + // std::cout << "Dll_Data_Source::read cost: " << cost << " us\n"; + + return ret; +} + + +// std::string Dll_Data_Source::read() { +// if (read_func_ptr == nullptr) return ""; +// auto buf = reinterpret_cast(buffer.data()); +// auto len = read_func_ptr(buf, buffer_size); +// vs.update(len); +// std::string data(buf, len); +// // std::ostringstream oss; +// // oss << "Dll_Data_Source::read == (" << data.size() << ")\n"; +// // std::cout << oss.str() << std::flush; +// if (data.empty()) return ""; +// auto ret = get_true_from_raw_line(this, data_type, -1, data); +// return ret; +// } +bool Shared_Memory_Data_Source::_open() { + sm = std::make_unique(); + sm->init(shared_memory_name, shared_memory_size); + return true; +} +void Shared_Memory_Data_Source::_close() { + sm.reset(); +} + + +std::string Shared_Memory_Data_Source::read() { + auto size = sm->shm.size(); + size_t length = size; + std::string data; + data.resize(size); + + bool ok = sm->read((uint8_t *)data.data(), length); + if (!ok) { + return ""; + } + + if (length != size) { + data.resize(length); + } + if (Global::instance()->console_config.mode_s_console) { + std::cout << "read:" << data << std::endl; + } + auto ret = get_true_from_raw_line(this, data_type, -1, data); + return ret; +} + +void Data_Source_Config::server(Global* g) { + auto& svr = g->svr; + auto& api = g->api; + std::string name = "data_source"; + // 返回所有 JSON 数据的 API + svr.Post(api + "get_data_source_connect", [this](HTTP_Param) { + CHECK_JSON_PARAM + HTTP_REQUIRE_VALUE(key, params.try_get_string("key")) + auto t = map.get(key); + JSON ret{nullptr}; + if (t.has_value()) { + ret = t.value()->get_all_connect_feed(); + } + res->setBody(warp(ret).to_json_string()); + }); + + + + svr.Post(api + "get_data_source_state", [this](HTTP_Param) { + CHECK_JSON_PARAM + HTTP_REQUIRE_VALUE(key, params.try_get_string("key")) + auto t = map.get(key); + JSON ret{nullptr}; + if (t.has_value()) { + ret = t.value()->get_state(); + } + res->setBody(warp(ret).to_json_string()); + }); + + + svr.Post(api + "get_mode_s_data_source_config", [this](HTTP_Param) { + res->setBody(warp(to_json()).to_json_string()); + }); + + svr.Post(api + svr.update + name, [this, g](HTTP_Param) { + CHECK_JSON_PARAM + HTTP_REQUIRE_VALUE(key, params.try_get_string("key")) + HTTP_REQUIRE_VALUE(ds, map.get(key)) + // 直接关闭 + ds->close(); + ds->from_json(¶ms); + if (ds->enable) { + ds->open(); + ds->test_and_attach_thread(); + } else + { + ds->test_and_stop_thread(); + } + g->save(); + g->mode_acs.source_feed_relation_config.set_need_refresh(); + }); + svr.Post(api + svr.insert + name, [g, this](HTTP_Param) { + CHECK_JSON_PARAM + + HTTP_REQUIRE_VALUE(index, params.try_get_number("index")) + HTTP_REQUIRE_PTR(data, params.get("data")) + HTTP_REQUIRE_VALUE(t, data->try_get_string("type")) + std::cout << params.to_json_string() << std::endl; + std::shared_ptr ds = create_data_source_from_type(t); + ds->from_json(data); + HTTP_REQUIRE_VALUE(enable, data->try_get_bool("enable")) + if (enable) + { + ds->open(); + ds->test_and_attach_thread(); + } + + HTTP_REQUIRE_TRUE(map.insert(index, ds), "index") + //std::cout << params.to_json_string() << std::endl; + g->mode_acs.source_feed_relation_config.set_need_refresh(); + Config::save(); + res->setBody(warp(to_json()).to_json_string()); + }); + + svr.Post(api + svr.remove + name, [g, this](HTTP_Param) { + CHECK_JSON_PARAM + HTTP_REQUIRE_VALUE(index, params.try_get_number("index")) + HTTP_REQUIRE_VALUE(ds, map.try_get(index)) + ds->close(); + ds->test_and_stop_thread(); + + HTTP_REQUIRE_TRUE(map.remove(index), "index") + g->save(); + res->setBody(warp(to_json()).to_json_string()); + g->mode_acs.source_feed_relation_config.set_need_refresh(); + }); + + svr.Post(api + svr.rise + name, [g, this](HTTP_Param) { + CHECK_JSON_PARAM + HTTP_REQUIRE_VALUE(index, params.try_get_number("index")) + HTTP_REQUIRE_TRUE(map.swap(index, index - 1), "index") + g->save(); + res->setBody(warp(to_json()).to_json_string()); + g->mode_acs.source_feed_relation_config.set_need_refresh(); + }); + svr.Post(api + svr.fall + name, [g, this](HTTP_Param) { + CHECK_JSON_PARAM + HTTP_REQUIRE_VALUE(index, params.try_get_number("index")) + HTTP_REQUIRE_TRUE(map.swap(index, index + 1), "index") + g->save(); + res->setBody(warp(to_json()).to_json_string()); + g->mode_acs.source_feed_relation_config.set_need_refresh(); + }); +} +void Data_Source::refresh_data_feed_key_list() { + //std::cout << key << " refresh_data_feed_key_list" << std::endl; + std::vector tmp; + for (auto& relation : Global::instance()->mode_acs.source_feed_relation_config.map.list()) { + if (!relation->enable) continue; + if (relation->type == "One_to_One_Relation") { + auto t = dynamic_cast(relation.get()); + + //std::cout << VAR_STR_2(t->source_key, this->key) << " refresh_data_feed_key_list" << std::endl; + if (t->source_key == this->key) { + tmp.push_back(t->feed_key); + } + } else if (relation->type == "First_Source_To_All_Feed_Relation") { + auto t = dynamic_cast(relation.get()); + std::shared_ptr first = nullptr; + for (const auto& ds : Global::instance()->mode_acs.data_source_config.map.list()) { + if (ds->enable) { + first = ds; + break; + } + } + if (first->key == key) { + for (const auto& df : Global::instance()->mode_acs.data_feed_config.map.list()) { + if (df->enable) { + tmp.push_back(df->key); + } + } + } + } + + std::sort(tmp.begin(), tmp.end()); + // 去重 + auto last = std::unique(tmp.begin(), tmp.end()); + tmp.erase(last, tmp.end()); + + + + { + std::vector tmp_info; + + // 创建 tmp_info 向量,将 tmp 的内容转化为 Cached_Source_Info 对象 + for (const auto& key : tmp) { + tmp_info.push_back({key}); + } + + { + // 进入临界区,锁住 mutex,确保线程安全 + std::lock_guard lock(cdf_mtx); + + // 1. 删除 tmp 中没有的 cached_data_feed_key_list 元素 + auto it = cached_data_feed_key_list.begin(); + while (it != cached_data_feed_key_list.end()) { + if (std::find_if(tmp_info.begin(), tmp_info.end(), + [&](const Cached_Source_Info& info) { + return info.key == it->key; + }) == tmp_info.end()) { + // 如果当前元素在 tmp 中找不到,删除它 + it = cached_data_feed_key_list.erase(it); + } else { + ++it; + } + } + + // 2. 创建 tmp 中有但 cached_data_feed_key_list 没有的元素 + for (const auto& tmp_item : tmp_info) { + auto found = std::find_if(cached_data_feed_key_list.begin(), cached_data_feed_key_list.end(), + [&](const Cached_Source_Info& cached_item) { + return cached_item.key == tmp_item.key; + }); + if (found == cached_data_feed_key_list.end()) { + // 如果 tmp_item 不在 cached_data_feed_key_list 中,添加它 + cached_data_feed_key_list.push_back(tmp_item); + } + } + } + } + } +} + +void Data_Source::push_to_feed(const std::shared_ptr& msg) { + if (need_refresh_data_feed_key_list) { + refresh_data_feed_key_list(); + need_refresh_data_feed_key_list = false; + } + auto& other_size = Global::instance()->mode_acs.mode_other_max_num; + auto& s_size = Global::instance()->mode_acs.mode_other_max_num; + std::vector list; + + + + for (const auto& item : cached_data_feed_key_list) { + auto& key = item.key; + auto opt_feed = Global::instance()->mode_acs.data_feed_config.map.get(key); + if (!opt_feed.has_value()) { + std::cout << "wrong data feed: " << key << std::endl; + break; + } + std::shared_ptr& feed = opt_feed.value(); + if (!feed->enable) continue; + + + if (msg->type == SSR::Mode_Msg::T::S7 || msg->type == SSR::Mode_Msg::T::S14) { + if (feed->msg_buffer.mode_s_msg_num > s_size) { + continue; + } else { + ++feed->msg_buffer.mode_s_msg_num; + } + } else { + if (feed->msg_buffer.mode_other_msg_num > other_size) { + continue; + } else { + ++feed->msg_buffer.mode_other_msg_num; + } + } + std::optional binary = convert_to_send_format(this, feed, msg); + if (binary.has_value()) { + feed->msg_buffer.push(binary.value()); + } + } +} + +void Data_Source::handle_mode_s(std::shared_ptr mode_s_msg) { + std::string t = mode_s_msg->mlat_timestamp.to_memory() + mode_s_msg->signal_level + Psc::hex2mem(mode_s_msg->msg_hex); + auto p = mode_s_msg->packet.substr(2); + if (t != p) { + std::cout << mem2hex(t, true, " ") << std::endl; + std::cout << mem2hex(mode_s_msg->packet, true, " ") << std::endl; + std::cout << VAR_STR_2(t, mode_s_msg->packet) << std::endl; + } + push_to_feed(mode_s_msg); + auto& cfg = Global::instance()->mode_acs; + SSR::parse_mode_s_bin(this, mode_s_msg, base_station.get_pos(),cfg.max_speed_m_s, cfg.air_pos_timeout, cfg.surface_pos_timeout); + + + + + + + auto base = get_aircraft(mode_s_msg->icao); + + if (base) + { + auto derived = std::dynamic_pointer_cast(base); + derived->refresh_external_database_info(); + } + + + + + + if (Global::instance()->mlat.merge) { + auto& mh = Global::instance()->mlat_handler; + mh.push(mode_s_msg); + auto tt = mh.get_all(); + if (!tt.empty()) { + pure_log("@/logs/mlat.log", "receive[" + std::to_string(tt.size()) + "]:\n"); + for (Mlat_MSG& t : tt) { + std::ostringstream oss; + oss << std::fixed << std::setprecision(10); + oss << "===================================================\n"; + int n = static_cast(t.size()); + auto icao = t.icao().value_or("null"); + oss << "\tmlat_msg:" << n; + oss << "\ticao:" << icao; + oss << "\thex:" << t.msg_hex() << std::endl; + + bool have_pos = false; + if (icao != "null") { + auto air = get_aircraft(icao); + if (air != nullptr) { + auto callsign = air->bds20_call_sign(); + oss << "\tcall_sign:" << callsign.value_or("null") << std::endl; + auto o_pos = air->pos(); + auto o_alt = air->altitude_meter(); + if (o_pos.has_value() && o_alt.has_value()) { + have_pos = true; + auto pos = o_pos.value(); + alt = o_alt.value(); + double x, y, z; + SSR::CPR::WGS84_LBH_to_XYZ(pos.lon, pos.lat, alt, x, y, z); + oss << "\tpos:[" << pos.lon << "," << pos.lat << "," << alt << "]" << std::endl; + oss << "\tXYZ:[" << x << "," << y << "," << z << "]" << std::endl; + } + } + } + for (int i = 0; i < t.size(); i++) { + auto& msg = t.list[i]; + oss << "\t\tds:" << msg->source->get_key(); + oss << "\ttime:" << msg->mlat_timestamp.to_string() << std::endl; + } + // if (have_pos) { + //std::cout << oss.str() << std::endl; + pure_log("@/logs/mlat.log", oss.str()); + // } + // if (t.size() > 3 && have_pos && icao == "78139F") { + // size_t i = 1; + // auto range = hex_mlat_map.equal_range(t.msg_hex()); + // // 遍历与key_to_find对应的所有元素 + // for (auto it = range.first; it != range.second; ++it) { + // oss << "\t" << i++ << " " << it->second.msg << std::endl; + // } + // oss << "===================================================\n"; + // std::cout << oss.str() << std::endl; + // pure_log("@/logs/icao/" + icao + "_mlat.log", oss.str(), true); + // } + } + } + } + +} +void Data_Source::pre_handle(const std::string& mode_data) { + static bool mode_s_console = Global::instance()->console_config.mode_s_console; + static bool record_playback = Global::instance()->console_config.record_playback; + //std::cout << source->key + " read " << mode_s_data.size() << std::endl; + if (mode_data.empty()) return; + if (record_playback) { + pure_log(get_exe_dir() + "/playback/" + key + "_playback.dat", mem2hex(mode_data, true, " ") + "\n"); + } + if (mode_s_console) { + std::cout << key + " read:[mode_s_serial]:" << mem2hex(mode_data) << std::endl; + } +} + diff --git a/module/Local_Server/Data_Source/Data_Source.h b/module/Local_Server/Data_Source/Data_Source.h new file mode 100644 index 0000000..dc8439c --- /dev/null +++ b/module/Local_Server/Data_Source/Data_Source.h @@ -0,0 +1,527 @@ +#pragma once + +#include + +#include "Core/Base/SM_RingBuffer.h" +#include "Core/Serial/Serial.h" + +#include "Core/Statistics/Frequency_Limit.h" +#include "Core/Statistics/Statistics.h" +#include "Core/transmit_protocol/core/statistics.h" +#include "Database.h" + +#include "Local_Server/global_include.h" +#include "global.h" +#include "PlayBack.h" + +namespace Psc { +class SM_RingBuffer; +} +// 统一封装数据输出的模式 +class Data_Source; +std::shared_ptr create_from_json(const Psc::JSON *that_json); + + +class Input_Format { +public: + Input_Format() { + test_v.resize(static_cast(SSR::Downlink_Format::Unknown)); + } + + Psc::JSON to_json() { + std::lock_guard g(mtx); + Psc::JSON ret = Psc::JSON::object(); + for (auto e : magic_enum::enum_values()) { + std::string_view value_view = magic_enum::enum_name(e); + std::string value(value_view.begin(), value_view.end()); + if (value == Psc::to_string(SSR::Downlink_Format::Unknown)) continue; + auto ev = static_cast(e); + bool it = test_v[ev]; + ret.append({value, it}); + } + return ret; + } + + void from_json(const Psc::JSON* json) { + std::lock_guard g(mtx); + for (auto e : magic_enum::enum_values()) { + std::string_view value_view = magic_enum::enum_name(e); + std::string value(value_view.begin(), value_view.end()); + if (value == Psc::to_string(SSR::Downlink_Format::Unknown)) continue; + auto use = json->get_bool(value); + auto ev = static_cast(e); + test_v[ev] = use; + } + } + + + bool test(SSR::Downlink_Format df) { + std::lock_guard g(mtx); + auto dfv = static_cast(df); + if (dfv >= static_cast(SSR::Downlink_Format::Unknown)) return false; + return test_v[dfv]; + } + + bool test(std::uint8_t dfv) { + std::lock_guard g(mtx); + if (dfv >= static_cast(SSR::Downlink_Format::Unknown)) return false; + return test_v[dfv]; + } +protected: + std::mutex mtx; + std::vector test_v; +}; + +class Data_Source : public DataBase, public std::enable_shared_from_this { +public: + ~Data_Source() override = default; + virtual std::string read() { return ""; } + std::shared_ptr that(); + virtual Psc::JSON get_custom_state_json() = 0; + Psc::JSON get_state(); + + + std::string last_char; // 用于处理奇数字节的情况 + + // std::shared_ptr parse_format; + Psc::Speed_Statistics read_speed; + Psc::Value_Statistics value_statistics; + Data_Source() { + // parse_format = std::make_shared(); + // 写入到配置文件是懒加载 其他保存时他跟着保存 + base_station.handle_when_updated = [this](SSR::HULC_Status_Message msg) { + if (this->update_form_gps) { + lat = msg.get_latitude(); + lon = msg.get_longitude(); + alt = msg.Alt; + } + }; + } + std::shared_ptr last_prase_msg = nullptr; + + + + + virtual void handle_mode_s(std::shared_ptr msg); + virtual void pre_handle(const std::string &data); + virtual std::shared_ptr create_msg(const std::shared_ptr& source, const std::string& packet); + virtual void update_msg_day_time(std::shared_ptr msg); + virtual void handle_mode_acs_source(); + + + void refresh_data_feed_key_list(); + void push_to_feed(const std::shared_ptr &msg); + std::atomic enable{}; + std::string type; + std::atomic base_station_show{}; + std::atomic aircraft_show{}; + + + std::atomic show_icao = true; + std::atomic show_call_sign = false; + std::atomic show_fly_status = false; + std::atomic keep_mode = true; + + + + double lat{}; + double lon{}; + double alt{}; + std::atomic update_form_gps{}; + std::string color = "#1677ff"; + int aircraft_pixel_size{}; + Mode_AC_Statistic_Data mode_ac_statistic; + Mode_S_Statistic_Data mode_s_statistic; + Frequency_Limit statistic_fl; + + virtual void handle_in_loop() {}; + std::string thread_key() const; + void test_and_attach_thread(); + void test_and_stop_thread() const; + Psc::JSON statistic_json() { + Psc::JSON ret = Psc::JSON::object(); + Ret_J(enable); + Ret_J(type); + ret.append({"飞机总数", get_aircraft_num()}); + ret.append({"解出位置的数量", have_pos_aircraft_num}); + ret.append({"mode_ac_statistic", mode_ac_statistic.to_json()}); + ret.append({"mode_s_statistic", mode_s_statistic.to_json()}); + ret.append({"all_connect_feed", get_all_connect_feed_status()}); + + + return ret; + } + virtual Psc::JSON to_json() { + Psc::JSON ret = Psc::JSON::object(); + Ret_J(key); + Ret_J(enable); + Ret_J(base_station_show); + Ret_J(aircraft_show); + Ret_J(color); + Ret_J(aircraft_pixel_size); + Ret_J(type); + Ret_J(lat); + Ret_J(lon); + Ret_J(alt); + Ret_J(update_form_gps); + Ret_J(show_icao); + Ret_J(show_call_sign); + Ret_J(show_fly_status); + Ret_J(keep_mode); + // ret.append({"parse_format", parse_format->to_json()}); + return ret; + } + virtual void from_json(const Psc::JSON *that_json) { + Get_J(key); + Get_J(enable); + Get_J(base_station_show); + Get_J(aircraft_show); + Get_J(color); + Get_J(aircraft_pixel_size); + Get_J(type); + Get_J(lat); + Get_J(lon); + Get_J(alt); + Get_J(update_form_gps); + Get_J(show_icao); + Get_J(show_call_sign); + Get_J(show_fly_status); + Get_J(keep_mode); + // parse_format->from_json(that_json->get("parse_format")); + } + bool open() { + if (!_open_) { + _open_ = _open(); + return _open_; + } + return true; + } + void close() { + if (_open_) { + _open_ = false; + _close(); + } + } + + struct Cached_Source_Info { + std::string key; + Psc::Value_Statistics mode_s_cache_num; + Psc::Value_Statistics mode_other_cache_num; + }; + + std::string buffer; + std::atomic need_refresh_data_feed_key_list = true; + Psc::JSON get_all_connect_feed_status(); + Psc::JSON get_all_connect_feed(); +protected: + std::mutex cdf_mtx; + std::vector cached_data_feed_key_list{}; + bool _open_ = false; + virtual bool _open() = 0; + virtual void _close() = 0; +}; + + +struct TCP_Client_Data_Source : Data_Source { + void handle_in_loop() override { + cli.tick(); + } + Psc::JSON get_custom_state_json() override { + auto& state = cli.state; + return VAR_JSON_1(state); + } + Psc::asio_socket::TCP_Client cli; + std::string ip; + std::uint16_t port{}; + + ~TCP_Client_Data_Source() override = default; + TCP_Client_Data_Source() { + type = "TCP_Client_Data_Source"; + } + bool _open() override { + Psc::asio_socket::Sockaddr_In addr; + addr.ip = ip; + addr.port = port; + + cli.set_dest_address(addr); + cli.create(); + return true; + } + void _close() override { cli.close(); } + + Psc::JSON to_json() override { + Psc::JSON ret = Data_Source::to_json(); + Ret_J(ip); + Ret_J(port); + return ret; + } + void from_json(const Psc::JSON *that_json) override { + Data_Source::from_json(that_json); + Get_J(ip); + Get_J(port); + } + + std::string read() override { + return cli.read(); + } +}; +struct Serial_Data_Source : Data_Source { + std::string port_name; + Baud_Rate_Type baud_rate{}; + Psc::JSON get_custom_state_json() override { + return Psc::JSON::object(); + } + Serial_Data_Source() { this->type = "Serial_Data_Source"; } + bool _open() override { + serial = new Psc::serial::Serial; + serial->set_serial_name(port_name); + serial->set_baud_rate(baud_rate); + serial->set_parity(Psc::serial::Parity::NoParity); + serial->set_data_bits(Psc::serial::DataBits::Data8); + serial->set_stop_bits(Psc::serial::StopBits::OneStop); + serial->set_flow_control(Psc::serial::FlowControl::HardwareControl); + serial->set_buffer_byte_size(10 * 1024); + bool ok = serial->open(); + if (!ok) { + std::cerr << "createSerial " + port_name + ":" + std::to_string(baud_rate) + " 打开串口失败!\n"; + } else { + // std::cerr << "createSerial " + serial_name + ":" + std::to_string(baud_rate) + " 打开串口成功!\n"; + } + return ok; + } + void _close() override { serial->close(); } + std::string read() override { return serial->read(); } + Psc::JSON to_json() override { + Psc::JSON ret = Data_Source::to_json(); + Ret_J(port_name); + Ret_J(baud_rate); + return ret; + } + void from_json(const Psc::JSON *that_json) override { + Data_Source::from_json(that_json); + Get_J(port_name) Get_J(baud_rate); + } + Psc::serial::Serial *serial{}; + ~Serial_Data_Source() override { + if (serial) { + serial->close(); + delete serial; + } + } +}; + + +enum class File_Data_Type { + SIMPLE_BIN_Blank, // 没有1a转义的 + BIN_Blank_Text, + AVR, + BIN_Text, + BIN_Blank_One_Line_With_Escape, + BIN_Blank_One_Line_No_Escape, + BIN, + Unknown + // 纯粹的二进制 +}; +enum Play_Mode { one, loop, analysis, time_batch }; + + +struct File_Data_Source : public Data_Source { + std::string file_path; + File_Data_Type data_type = File_Data_Type::BIN_Blank_Text; + Play_Mode play_mode = Play_Mode::one; + bool have_report_play_back_all_success = false; + std::string state = "null"; + Psc::JSON get_custom_state_json() override { + auto cur_virtual_time = player_clock.get_cur_time_point(); + auto playback_speed_rate = player_clock.playback_speed_rate; + return VAR_JSON_5(cur_virtual_time, playback_speed_rate, state, index, part_infos.size()); + } + File_Data_Source() { this->type = "File_Data_Source"; } + ~File_Data_Source() override = default; + + + + + struct Cache_Msg { + explicit Cache_Msg(std::shared_ptr msg) : msg(std::move(msg)) {} + SSR::Play_Back_Time_Point time() const { + return SSR::Play_Back_Time_Point{day_num, msg->mlat_timestamp.daysec}; + } + std::uint64_t day_num = 0; + std::shared_ptr msg; + }; + Player_Clock player_clock; + std::shared_ptr pre_cache = nullptr; + std::deque> cache_list; + + + + std::string get_true_file_path() const { return Psc::get_abs_path(file_path); } + void _close() override; + bool _open() override; + std::vector readBinaryFileAsString(const std::string& filepath, size_t part_size); + void from_json(const Psc::JSON *that_json) override { + Data_Source::from_json(that_json); + Get_J(file_path); + Get_J(data_type); + Get_J(play_mode); + } + + Psc::JSON to_json() override { + Psc::JSON ret = Data_Source::to_json(); + Ret_J(file_path); + Ret_J(data_type); + Ret_J(play_mode); + return ret; + } + std::string read() override; + void handle_mode_acs_source() override; + + protected: + std::optional get_raw_line(int &ret_index); + long long index = 0; + std::vector part_infos; + std::mutex mtx; +}; +struct Dll_Data_Source : Data_Source { + Psc::JSON get_custom_state_json() override { + auto ret = VAR_JSON_1(state); + ret.append({"read_vaild_len", vs.to_string()}); + return ret; + } + Psc::Value_Statistics vs; + std::string library_path; + std::string function_name; + File_Data_Type data_type = File_Data_Type::BIN_Blank_Text; + Dll_Data_Source() { this->type = "Dll_Data_Source"; } + ~Dll_Data_Source() override = default; + std::size_t buffer_size{}; + std::vector buffer; + void from_json(const Psc::JSON *that_json) override { + Data_Source::from_json(that_json); + Get_J(library_path); + Get_J(function_name); + Get_J(data_type); + Get_J(buffer_size); + buffer.resize(buffer_size); + } + Psc::JSON to_json() override { + Psc::JSON ret = Data_Source::to_json(); + Ret_J(library_path); + Ret_J(function_name); + Ret_J(data_type); + Ret_J(buffer_size); + return ret; + } + void *lib{}; + + using Func_Type = size_t (*)(char *buf, std::size_t max_len); + // using Func_Type = std::uint16_t (*)(char *buf, std::uint16_t max_len); + Func_Type read_func_ptr{}; + + + using Call_Back = void (*)(char *buf, std::size_t len); + using set_Call_back = void (*)(Call_Back); + + std::string state; + void _close() override { Psc::free_library(lib); } + bool _open() override { + { + auto r = Psc::try_load_library(Psc::get_abs_path(library_path)); + if (!r) { + state = r.error().message(); + return false; + } + lib = r.value(); + } + { + auto r = Psc::try_load_function(lib, function_name); + if (!r) { + state = r.error().message(); + std::cout << LOG_POS << " [" << function_name << "] 函数指针加载失败!" << std::endl; + return false; + } + read_func_ptr = (Func_Type) r.value(); + } + state = "加载成功"; + return true; + } + std::string read() override; +}; + + +struct Shared_Memory_Data_Source : Data_Source { + Psc::JSON get_custom_state_json() override { + return Psc::JSON::object(); + } + void from_json(const Psc::JSON *that_json) override { + Data_Source::from_json(that_json); + Get_J(shared_memory_name); + Get_J(shared_memory_size); + Get_J(data_type); + } + Psc::JSON to_json() override { + Psc::JSON ret = Data_Source::to_json(); + Ret_J(shared_memory_name); + Ret_J(shared_memory_size); + Ret_J(data_type); + return ret; + } + bool _open() override; + void _close() override; + std::string read() override; + +protected: + std::unique_ptr sm; + std::string shared_memory_name; + std::uint64_t shared_memory_size{}; + File_Data_Type data_type = File_Data_Type::BIN_Blank_Text; +}; + + +inline std::shared_ptr create_data_source_from_type(const std::string &t) { + std::shared_ptr ret{}; + if (t == "Serial_Data_Source") + ret = std::make_shared(); + else if (t == "TCP_Client_Data_Source") + ret = std::make_shared(); + else if (t == "File_Data_Source") + ret = std::make_shared(); + else if (t == "Dll_Data_Source") + ret = std::make_shared(); + else if (t == "Shared_Memory_Data_Source") + ret = std::make_shared(); + else { + std::cout << "未知的 Data_Source type类型!" << std::endl; + throw std::invalid_argument("unknown Data_Source type: " + t); + } + return ret; +} + + +struct Data_Source_Config { + Ordered_Map> map; + Data_Source_Config() = default; + void init(const Psc::JSON *that_json) { + auto list = that_json->get("list"); + for (auto &it: list->children) { + auto ds = create_from_json(&it); + map.push_back(ds); + } + } + Psc::JSON list() { + auto connect_json = Psc::JSON::array(); + for (auto &it: map.list()) { + connect_json.children.emplace_back(it->to_json()); + } + return connect_json; + } + Psc::JSON to_json() { + Psc::JSON ret = Psc::JSON::object(); + ret.append({"list", list()}); + return ret; + } + void server(Global *g); +}; + + diff --git a/module/Local_Server/Data_Source/Database.cpp b/module/Local_Server/Data_Source/Database.cpp new file mode 100644 index 0000000..23c39fd --- /dev/null +++ b/module/Local_Server/Data_Source/Database.cpp @@ -0,0 +1,339 @@ +#include "Database.h" +#include "../server/Global.h" +#include "../server/Performance_Monitor.h" + +#include +#include +#include + +Aircraft::Aircraft(const std::string &icao) : Aircraft_Info(icao) { + auto size = Global::instance()->mode_acs.max_track_point_size.load(); + air_pos_track_list.init(size); + surface_pos_track_list.init(size); +} + +void Aircraft::refresh_external_database_info() { + auto& manager = Global::instance()->external_resources_manager; + if (!external_database_info_loaded) { + external_database_info = manager.query_aircraft_external_databases(icao); + external_database_info_loaded = true; + } + + auto callsign = flight(); + if (!callsign) callsign = bds20_call_sign(); + if (last_external_database_callsign == callsign) { + return; + } + + callsign_external_database_info = + manager.query_callsign_external_databases(callsign); + last_external_database_callsign = std::move(callsign); +} + +std::shared_ptr DataBase::get_aircraft(const std::string& icao) { + return aircraft_map.get(icao); +} + + + + +std::shared_ptr DataBase::create_aircraft(const std::string& icao) { + auto ret = aircraft_map.create(icao); + ret->refresh_external_database_info(); + return ret; +} + +void DataBase::delete_timeout_aircraft() { + aircraft_map.remove_cond([](const std::shared_ptr& item) { + if (item->timestamp == 0) { + std::cout << "未初始化的 timestamp " << LOG_POS << std::endl; + } + long long time = std::time(nullptr) - item->timestamp; + return time > Global::instance()->mode_acs.timeout_seconds; + }); +} + + +JSON DataBase::get_aircraftlist() { + JSON json = JSON::array(); + for (auto& it : aircraft_map.values()) { + auto o = Aircraft_List_JSON_Service_O::to_That(this, it.get()); + json.children.push_back(o.toJson()); + } + return json; +} + +Psc::JSON DataBase::get_aircraftlist(int limit_msg_num) { + JSON json = JSON::array(); + for (auto& it : aircraft_map.values()) { + if (it->times < limit_msg_num) continue; + auto o = Aircraft_List_JSON_Service_O::to_That(this, it.get()); + json.children.push_back(o.toJson()); + } + return json; +} + +JSON DataBase::get_all_aircraft_json() { + JSON json = JSON::array(); + auto g = Global::instance(); + size_t num = 0; + for (auto& it : aircraft_map.values()) { + auto vto = Flight_VTO::to_VTO(it.get()); + bool have_pos = !it.get()->air_pos_track_list.empty(); + if (have_pos) { + json.children.push_back(vto.toJson()); + num++; + } + } + have_pos_aircraft_num = num; + return json; +} + + + + + +JSON DataBase::get_aircraft_list_after(time_t timestamp) { + JSON json = JSON::array(); + auto g = Global::instance(); + for (auto& it : aircraft_map.values()) { + auto vto = Flight_VTO::to_VTO(it.get()); + bool have_pos = !it.get()->air_pos_track_list.empty(); + if (have_pos && vto.time_stamp > timestamp) { + json.children.push_back(vto.toJson()); + } + } + return json; +} + +#ifdef Cache_Some_Mode_S +Psc::JSON DataBase::get_limit_mode_s_msg_info() { + + JSON ret = JSON::object(); + JSON list = JSON::array(); + std::map map; + std::map num_test; + for (auto& air : aircraft_map.values()) { + if (air->total_num > Cache_Some_Mode_S_Num) continue; + Psc::JSON air_json = Psc::JSON::object(); + { + Psc::JSON ms = Psc::JSON::array(); + int n = air->cache.size(); + for (auto msg : air->cache) { + Psc::JSON cur = Psc::JSON::object({ + {"hex", msg->msg_hex}, + {"df", to_string(msg->df)} + }); + if (msg->df == Downlink_Format::Extended_Squitter_17) { + + auto tc = type_code(msg->msg_bin); + cur.children.push_back({"tc", tc}); + map[tc]++; + num_test[air->total_num] = n; + } + ms.append(cur); + } + air_json.children.push_back({"icao", air->icao}); + air_json.children.push_back({"total_num", air->total_num}); + air_json.children.push_back({"ms", ms}); + } + list.children.push_back(air_json); + } + ret.children.push_back({"key", key}); + for (auto pair : map) { + ret.children.push_back({std::to_string(pair.first), pair.second}); + } + Psc::JSON t = Psc::JSON::object(); + for (auto pair : num_test) { + t.children.push_back({std::to_string(pair.first), pair.second}); + } + ret.children.push_back({"数量统计", t}); + ret.children.push_back({"list", list}); + return ret; +} +#endif + +size_t DataBase::get_aircraft_num() { return aircraft_map.size(); } + +#define _init_db \ +HTTP_REQUIRE_VALUE(data_source_key, params.try_get_string("data_source_key")) \ +auto db = Global::instance()->source(data_source_key); \ +if (db == nullptr) { \ + res->setStatusCode(drogon::k503ServiceUnavailable); \ + JSON ret; \ + res->setBody(ret.to_json_string()); \ + return; \ +} + + + +void database_server(Global* g) { + auto& svr = g->svr; + auto& api = g->api; + // g->load_aircraft_csv(g->mode_acs.aircraft_csv_path); + g->external_resources_manager.load_sqlite_db( + Psc::get_abs_path(g->external_resources_manager.ecap_sqlite_path)); + + +#ifdef Cache_Some_Mode_S + svr.Post(api + "get_cache_some_mode_s_info", [](HTTP_Param) { + CHECK_JSON_PARAM + _init_db + auto g = Global::instance(); + auto ret = JSON::object(); + if (db) { + ret = db->get_limit_mode_s_msg_info(); + } + res->setBody(warp(ret).to_json_string()); + }); +#endif + + svr.Post(api + "get_base_station_location", [](HTTP_Param) { + CHECK_JSON_PARAM + _init_db + auto g = Global::instance(); + auto ret = JSON::object(); + if (db) { + ret = db->base_station.to_Json(); + } + res->setBody(warp(ret).to_json_string()); + }); + svr.Post(api + "get_aircraft_base_info", [](HTTP_Param) { + CHECK_JSON_PARAM + _init_db + HTTP_REQUIRE_VALUE(icao, params.try_get_string("icao")) + auto aircraft = db->get_aircraft(icao); + JSON ret; + if (aircraft != nullptr) { + auto vto = Flight_VTO::to_VTO(aircraft.get()); + ret = vto.toJson(); + } + res->setBody(ret.to_json_string()); + }); + svr.Post(api + "get_aircraft_detail_info", [](HTTP_Param) { + CHECK_JSON_PARAM + _init_db + HTTP_REQUIRE_VALUE(icao, params.try_get_string("icao")) + auto aircraft = db->get_aircraft(icao); + JSON ret; + if (aircraft != nullptr) { + ret = aircraft->toJson(); + } + res->setBody(ret.to_json_string()); + }); + svr.Post(api + "get_aircraft_track_list", [](HTTP_Param) { + CHECK_JSON_PARAM + _init_db + HTTP_REQUIRE_VALUE(icao, params.try_get_string("icao")) + HTTP_REQUIRE_VALUE(last_size, params.try_get_number("last_size")) + auto aircraft = db->get_aircraft(icao); + JSON ret; + if (aircraft != nullptr) + { + ret = aircraft->air_pos_track_list.get_last_array_json(last_size); + ret.children.insert(ret.children.begin(), JSON("ds", data_source_key)); + ret.children.insert(ret.children.begin(), JSON("icao", icao)); + } + res->setBody(ret.to_json_string()); + }); + svr.Post(api + "get_aircraft_list_after", [](HTTP_Param) { + CHECK_JSON_PARAM + _init_db + HTTP_REQUIRE_VALUE(timestamp, params.try_get_number("timestamp")) + auto ret = db->get_aircraft_list_after(timestamp); + res->setBody(ret.to_json_string()); + }); + + svr.Post(api + "aircraft_change_list", [](HTTP_Param) { + CHECK_JSON_PARAM + _init_db + JSON ret = JSON::array(); + if (db) { + ret = db->get_all_aircraft_json(); + } else + { + + } + res->setBody(warp(ret).to_json_string()); + }); + + + svr.Get(R"(/aircraftlist.json)", [](HTTP_Param) { + auto list = Global::instance()->mode_acs.data_source_config.map.list(); + std::shared_ptr ts = nullptr; + auto ret = JSON::array(); + for (const auto& li : list) { + if (li->enable) { + ret = li->get_aircraftlist(); + break; + } + } + res->setBody(ret.to_json_string("", "\n", "")); + }); + + // aircraftlist.json 的带数据源版本 + svr.Post(api + "aircraft_list", [](HTTP_Param) { + CHECK_JSON_PARAM + auto g = Global::instance(); + HTTP_REQUIRE_VALUE(data_source_key, params.try_get_string("data_source_key")) + std::shared_ptr db; + { + db = g->source(data_source_key); + } + if (db == nullptr) { + res->setStatusCode(drogon::k503ServiceUnavailable); + JSON ret; + res->setBody(ret.to_json_string()); + return; + } + + + auto limit_msg_num = g->mode_acs.default_min_aircraft_list_num.load(); + auto t = params.get("limit_msg_num"); + if (t) { + HTTP_REQUIRE_VALUE(requested_limit_msg_num, t->try_number_val()) + limit_msg_num = requested_limit_msg_num; + } + JSON ret = JSON::array(); + { + Scope_Timer timer( + "aircraft_list.db_query", + g->http_monitor_config.slow_scope_threshold_ms); + ret = db->get_aircraftlist(limit_msg_num); + } + std::string body; + { + Scope_Timer timer( + "aircraft_list.json_serialization", + g->http_monitor_config.slow_scope_threshold_ms); + body = warp(ret).to_json_string(); + } + res->setBody(body); + }); + +} + + + + +static std::string output; + +static void log_i(const std::string& label, const std::string& value, + const std::string& unit = "") { + std::ostringstream oss; + // Format the label and value + oss << std::left << std::setw(30) << label << ": " << value; + // Add unit if not empty + if (!unit.empty()) { + oss << " " << unit << "\n"; + } else { + oss << "\n"; + } + // Append formatted string to output + output += oss.str(); +} + +static void log_i(const std::string& label, double value, + const std::string& unit = "") { + log_i(label, std::to_string(value), unit); +} diff --git a/module/Local_Server/Data_Source/Database.h b/module/Local_Server/Data_Source/Database.h new file mode 100644 index 0000000..4e8f39f --- /dev/null +++ b/module/Local_Server/Data_Source/Database.h @@ -0,0 +1,228 @@ +#pragma once +#include "BaseStation.h" +#include "../Aircraft/Aircraft.h" +#include "../Aircraft/Flight_VTO.h" +#include "../External_Database/export.h" +#include +#include +#include +#include +#include + + +template < + typename Key_Type, + typename Value_Type, + size_t Shard_Count = 64 +> +struct Data_Map { + using Ptr = std::shared_ptr; + + size_t size() const { + size_t ret = 0; + + for (const auto& shard : shards) { + std::shared_lock g(shard.mtx); + ret += shard.map.size(); + } + + return ret; + } + + Ptr get(const Key_Type& key) const { + const auto& shard = get_shard(key); + + std::shared_lock g(shard.mtx); + + auto iter = shard.map.find(key); + if (iter == shard.map.end()) { + return nullptr; + } + + return iter->second; + } + + Ptr create(const Key_Type& key) { + auto& shard = get_shard(key); + + { + std::shared_lock g(shard.mtx); + + auto iter = shard.map.find(key); + if (iter != shard.map.end()) { + return iter->second; + } + } + + // 构造对象放锁外,避免构造期间占锁 + auto new_value = std::make_shared(key); + + { + std::unique_lock g(shard.mtx); + + auto [iter, inserted] = shard.map.emplace(key, new_value); + + // 如果别的线程已经创建了,返回已有对象 + return iter->second; + } + } + + void remove(const Key_Type& key) { + auto& shard = get_shard(key); + + std::unique_lock g(shard.mtx); + shard.map.erase(key); + } + + std::vector values() const { + std::vector ret; + + for (const auto& shard : shards) { + std::shared_lock g(shard.mtx); + + for (const auto& [key, val] : shard.map) { + ret.push_back(val); + } + } + + return ret; + } + + template + std::vector get_cond(Cond&& cond) const { + std::vector ret; + + for (const auto& shard : shards) { + std::vector snapshot; + + { + std::shared_lock g(shard.mtx); + + snapshot.reserve(shard.map.size()); + + for (const auto& [key, val] : shard.map) { + snapshot.push_back(val); + } + } + + // cond 放锁外执行 + for (const auto& val : snapshot) { + if (cond(val)) { + ret.push_back(val); + } + } + } + + return ret; + } + + template + void remove_cond(Cond&& cond) { + for (auto& shard : shards) { + std::vector> snapshot; + + { + std::shared_lock g(shard.mtx); + + snapshot.reserve(shard.map.size()); + + for (const auto& [key, val] : shard.map) { + snapshot.emplace_back(key, val); + } + } + + std::vector> need_remove; + + // cond 放锁外执行 + for (const auto& [key, val] : snapshot) { + if (cond(val)) { + need_remove.emplace_back(key, val); + } + } + + if (need_remove.empty()) { + continue; + } + + { + std::unique_lock g(shard.mtx); + + for (const auto& [key, old_val] : need_remove) { + auto iter = shard.map.find(key); + if (iter == shard.map.end()) { + continue; + } + + // 防止同 key 已经被换成新对象,误删 + if (iter->second == old_val) { + shard.map.erase(iter); + } + } + } + } + } + + void delete_all() { + for (auto& shard : shards) { + std::unique_lock g(shard.mtx); + shard.map.clear(); + } + } + +protected: + struct Shard { + mutable std::shared_mutex mtx; + std::unordered_map map; + }; + + Shard& get_shard(const Key_Type& key) { + const size_t index = hasher(key) % Shard_Count; + return shards[index]; + } + + const Shard& get_shard(const Key_Type& key) const { + const size_t index = hasher(key) % Shard_Count; + return shards[index]; + } + +protected: + std::hash hasher; + Shard shards[Shard_Count]; +}; + + +class DataBase : public SSR::Data_Source_Interface { +public: + std::shared_ptr get_aircraft(const std::string& icao) override; + std::shared_ptr create_aircraft(const std::string& icao) override; + Psc::JSON get_aircraftlist(); + Psc::JSON get_aircraftlist(int limit_msg_num); + BaseStation base_station; + void delete_timeout_aircraft(); + std::string get_key() override { + return key; + } + std::string key; + std::atomic have_pos_aircraft_num{}; + Psc::JSON get_all_aircraft_json(); + Psc::JSON get_aircraft_list_after(time_t timestamp); +#ifdef Cache_Some_Mode_S + Psc::JSON get_limit_mode_s_msg_info(); +#endif + size_t get_aircraft_num(); + void clear_aircraft() { aircraft_map.delete_all(); } + void handle_HULC(const std::string& packet); + ~DataBase() override { + aircraft_map.delete_all(); + } + +protected: + + + Data_Map aircraft_map; +}; + + +struct Mode_S_Msg; +void database_server(Global* g); + diff --git a/module/Local_Server/Data_Source/PlayBack.cpp b/module/Local_Server/Data_Source/PlayBack.cpp new file mode 100644 index 0000000..60593e9 --- /dev/null +++ b/module/Local_Server/Data_Source/PlayBack.cpp @@ -0,0 +1 @@ +#include "PlayBack.h" diff --git a/module/Local_Server/Data_Source/PlayBack.h b/module/Local_Server/Data_Source/PlayBack.h new file mode 100644 index 0000000..230de4d --- /dev/null +++ b/module/Local_Server/Data_Source/PlayBack.h @@ -0,0 +1,33 @@ +#pragma once + +#include "SSR/Msg.h" + +#include + + +struct Player_Clock { + using clock = std::chrono::system_clock; + SSR::Play_Back_Time_Point start_time; // 抽象时间起点 + std::chrono::time_point true_start_time; // 真正开始回放的墙钟起点 + double playback_speed_rate = 20.0; + Player_Clock() { + true_start_time = clock::now(); + } + SSR::Play_Back_Time_Point get_cur_time_point() const noexcept { + + const auto now = clock::now(); + + // 防御:系统时间回拨或还没初始化导致 now < true_start_time + const double real_elapsed_sec = + std::max(0.0, std::chrono::duration(now - true_start_time).count()); + + const double sim_elapsed_sec = real_elapsed_sec * playback_speed_rate; + + // Time_Point 只有秒精度:向下取整 + const auto add = static_cast(sim_elapsed_sec); + + SSR::Play_Back_Time_Point tp = start_time; + tp.add_sec(add); + return tp; + } +}; diff --git a/module/Local_Server/Data_Source/export.h b/module/Local_Server/Data_Source/export.h new file mode 100644 index 0000000..a2939c1 --- /dev/null +++ b/module/Local_Server/Data_Source/export.h @@ -0,0 +1,5 @@ +#pragma once +#include "../Aircraft/aircraftlist_json.h" +#include "Data_Source.h" +#include "PlayBack.h" +#include "Database.h" \ No newline at end of file diff --git a/module/Local_Server/Data_Source/global.h b/module/Local_Server/Data_Source/global.h new file mode 100644 index 0000000..7517a08 --- /dev/null +++ b/module/Local_Server/Data_Source/global.h @@ -0,0 +1,38 @@ +#pragma once +#include "../../../../../core_library/Core/Core/Base/JSON.h" +#include "Core/socket/export.h" +#include "SSR/export.h" +#include +#include +#include +#include +#include +#include +#include + +// 用于debug 散乱的飞机从何而来 +// #define Cache_Some_Mode_S +#ifdef Cache_Some_Mode_S + #define Cache_Some_Mode_S_Num 20 +#endif + + + +#define Parse(t, Field) \ +auto& _##t = info.Field.value; \ +info.Field.time = info.timestamp; \ +if (!_##t.has_value()) _##t = std::remove_reference_t::ValueType(); \ +_##t.value().parse(msg); \ +auto& t = _##t.value(); +// ret.append(NAME.value.has_value()? Psc::Json(STRINGIFY(NAME##_time), NAME.time) : Psc::Json(STRINGIFY(NAME##_time), nullptr)); +#define STRINGIFY(x) #x +#define ADD_Json(NAME) ret.children.emplace_back(STRINGIFY(NAME), NAME); +#define ADD_Json_RET(NAME) \ +if (NAME.has_value()) \ +{ \ +ret.children.emplace_back(STRINGIFY(NAME), NAME.value()); \ +} else \ +{ \ +ret.children.emplace_back(STRINGIFY(NAME), nullptr); \ +} + diff --git a/module/Local_Server/External_Database/Adsblol_Vrs_Standing_Data.cpp b/module/Local_Server/External_Database/Adsblol_Vrs_Standing_Data.cpp new file mode 100644 index 0000000..01e402b --- /dev/null +++ b/module/Local_Server/External_Database/Adsblol_Vrs_Standing_Data.cpp @@ -0,0 +1,18 @@ +// 数据来源:adsblol/vrs-standing-data。VRS standing-data 的镜像和转换项目。 +// 链接:https://github.com/adsblol/vrs-standing-data +// 在线表使用该项目发布的 routes.csv,以 callsign 为业务主键。 +// 官方更新要求:ADSB.lol 镜像说明导出文件每小时更新。本地告警策略:超过 1 小时提示更新。 + +#include "Resource_Utils.h" + +std::unique_ptr make_adsblol_vrs_standing_data_resource() { + return External_Database_Utils::make_header_csv_resource({ + "adsblol_vrs_standing_data_routes", + "adsblol_routes.csv", + "https://vrs-standing-data.adsb.lol/routes.csv", + "ADSB.lol 发布的 VRS standing-data 航线镜像,以 callsign 查询机场代码序列。", + 3600, + {"Callsign", "Code", "Number", "AirlineCode", "AirportCodes"}, + {"Callsign"} + }); +} diff --git a/module/Local_Server/External_Database/External_Database.cpp b/module/Local_Server/External_Database/External_Database.cpp new file mode 100644 index 0000000..151c8fa --- /dev/null +++ b/module/Local_Server/External_Database/External_Database.cpp @@ -0,0 +1,581 @@ +#include "global.h" + +#include "Resource_Utils.h" +#include "Resources.h" +#include "../server/Global.h" +#include "../server/Performance_Monitor.h" + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace { + +Psc::JSON external_resource_status_to_json(const External_Resource_Status& status) { + return Psc::JSON::object({ + {"name", status.name}, + {"row_count", status.row_count}, + {"downloaded", status.downloaded}, + {"imported", status.imported}, + {"message", status.message}, + }); +} + +Psc::JSON external_resource_status_list_to_json( + const std::vector& status_list) { + auto result = Psc::JSON::array(); + for (const auto& status : status_list) { + result.append(external_resource_status_to_json(status)); + } + return result; +} + +} // 命名空间 + +std::optional External_Database_Row::get(const std::string& column) const { + const auto iter = columns.find(column); + return iter == columns.end() ? std::nullopt : iter->second; +} + +Psc::JSON External_Database_Row::to_json() const { + auto result = Psc::JSON::object(); + for (const auto& [column, value] : columns) { + result.append({column, value ? Psc::JSON(*value) : Psc::JSON(nullptr)}); + } + return result; +} + +External_Resources::External_Resources(std::string name, + std::string cache_file_name, + std::string download_url, + std::string description, + const std::uint64_t update_interval_seconds) + : name(std::move(name)), + cache_file_name(std::move(cache_file_name)), + download_url(std::move(download_url)), + description(std::move(description)), + update_interval_seconds(update_interval_seconds) {} + + + + + + +void External_Resources::mark_updated() { + last_updated_at = std::time(nullptr); +} + +void External_Resources::clear_last_updated_at() { + last_updated_at = 0; +} + +std::size_t External_Resources::row_count(SQLite::Database& db) const { + return static_cast( + db.execAndGet("SELECT COUNT(*) FROM " + + External_Database_Utils::quote_identifier(name)).getInt64()); +} + +std::filesystem::path External_Resources::source_file( + const std::filesystem::path& cache_pos) const { + return cache_pos / cache_file_name; +} + +bool External_Resources::fetch(const std::filesystem::path& cache_pos, + const bool force_download) const { + const auto target_file = source_file(cache_pos); + if (!force_download) return false; + if (download_url.empty()) return false; + External_Database_Utils::download_to_file(download_url, target_file); + return true; +} + +External_Resource_Status External_Resources::update( + SQLite::Database& db, + const std::filesystem::path& cache_pos, + const bool force_download, + const bool only_when_empty) { + create_table(db); + External_Resource_Status result{name, row_count(db), false, false, ""}; + if (only_when_empty && result.row_count != 0) { + result.message = "table already populated"; + return result; + } + + std::filesystem::create_directories(cache_pos); + result.downloaded = fetch(cache_pos, force_download); + if (cache_file_name.empty()) { + result.message = "dynamic query required"; + return result; + } + const auto local_file = source_file(cache_pos); + if (!std::filesystem::exists(local_file)) { + result.message = download_url.empty() ? "offline import or dynamic query required" + : "cache file unavailable"; + return result; + } + + result.row_count = import_file(db, local_file); + result.imported = true; + result.message = "ok"; + mark_updated(); + return result; +} + +External_Resource_Status External_Resources::import_offline( + SQLite::Database& db, + const std::filesystem::path& source_file) { + create_table(db); + External_Resource_Status result{name, 0, false, false, ""}; + result.row_count = import_file(db, source_file); + result.imported = true; + result.message = "ok"; + mark_updated(); + return result; +} + +External_Resource_Status External_Resources::clear_table( + SQLite::Database& db, + const std::filesystem::path& cache_pos) { + SQLite::Transaction transaction(db); + db.exec("DROP TABLE IF EXISTS " + + External_Database_Utils::quote_identifier(name)); + create_table(db); + transaction.commit(); + + if (!cache_file_name.empty()) { + std::error_code error; + std::filesystem::remove(source_file(cache_pos), error); + if (error) { + throw std::runtime_error("Cannot remove cache file for resource " + name + + ": " + error.message()); + } + } + + clear_last_updated_at(); + return {name, 0, false, false, "table cleared"}; +} + +std::optional External_Resources::query_one( + SQLite::Database& db, + const std::vector& primary_key_values) const { + const auto& columns = primary_key_columns(); + if (columns.size() != primary_key_values.size()) { + throw std::invalid_argument("primary key value count mismatch for resource: " + name); + } + + std::string sql = "SELECT * FROM " + + External_Database_Utils::quote_identifier(name) + " WHERE "; + for (std::size_t index = 0; index < columns.size(); ++index) { + if (index != 0) sql += " AND "; + sql += External_Database_Utils::quote_identifier(columns[index]) + + " = ? COLLATE NOCASE"; + } + sql += " LIMIT 1"; + + SQLite::Statement statement(db, sql); + for (std::size_t index = 0; index < primary_key_values.size(); ++index) { + statement.bind(static_cast(index + 1), + External_Database_Utils::normalize_key(primary_key_values[index])); + } + if (!statement.executeStep()) return std::nullopt; + + External_Database_Row row; + for (int index = 0; index < statement.getColumnCount(); ++index) { + const auto name = statement.getColumnName(index); + if (statement.isColumnNull(index)) { + row.columns.emplace(name, std::nullopt); + } else { + row.columns.emplace(name, statement.getColumn(index).getString()); + } + } + return row; +} + +External_Resources_Manager::External_Resources_Manager() { + register_external_resource(make_tar1090_db_aircraft_csv_gz_resource()); + register_external_resource(make_wiedehopf_tar1090_db_resource()); + register_external_resource(make_mictronics_aircraft_database_resource()); + register_external_resource(make_opensky_aircraft_database_resource()); + register_external_resource(make_faa_aircraft_registry_resource()); + register_external_resource(make_icao_doc_8643_resource()); + register_external_resource(make_vrs_routes_resource()); + register_external_resource(make_vrs_airports_resource()); + register_external_resource(make_adsblol_vrs_standing_data_resource()); + register_external_resource(make_vradarserver_standing_data_resource()); + register_external_resource(make_opensky_flightdata_api_resource()); +} + +void External_Resources_Manager::init(const Psc::JSON* that_json) { + if (!that_json) return; + const auto list = that_json->get("list"); + if (!list) return; + std::lock_guard lock(mtx_); + for (const auto& config : list->children) { + const auto name = config.try_get_string("name"); + if (!name) continue; + for (const auto& resource : resources_) { + if (resource->name != *name) continue; + resource->init(&config); + break; + } + } + Get_J(ecap_sqlite_path) +} + +Psc::JSON External_Resources_Manager::to_json() const { + std::lock_guard lock(mtx_); + auto ret = Psc::JSON::object(); + Ret_J(ecap_sqlite_path) + auto list = Psc::JSON::array(); + for (const std::unique_ptr& resource : resources_) { + list.children.emplace_back(resource->to_json()); + } + ret.children.emplace_back(Psc::JSON{"list", list}); + return ret; +} + +void External_Resources_Manager::load_sqlite_db(std::string path) { + try { + db_ = std::make_unique( + path, SQLite::OPEN_READWRITE | SQLite::OPEN_CREATE); + } catch (SQLite::Exception& error) { + Psc::fail_fast(std::string("load_sqlite_db error: ") + error.what()); + } + + db_->exec("PRAGMA journal_mode=WAL;"); + db_->exec("PRAGMA synchronous=NORMAL;"); + initialize(*db_, std::filesystem::path(path).parent_path()); + sync_missing(*db_); +} + +std::vector +External_Resources_Manager::refresh_external_databases(const bool force_download) { + return refresh_all(require_db(), force_download); +} + +External_Resource_Status External_Resources_Manager::refresh_external_database( + const std::string& resource_name, + const bool force_download) { + return refresh_one(require_db(), resource_name, force_download); +} + +External_Resource_Status External_Resources_Manager::import_external_database( + const std::string& resource_name, + const std::filesystem::path& source_file) { + return import_offline(require_db(), resource_name, source_file); +} + +External_Resource_Status External_Resources_Manager::clear_external_database_table( + const std::string& resource_name) { + return clear_table(require_db(), resource_name); +} + +std::optional +External_Resources_Manager::query_external_database( + const std::string& resource_name, + const std::vector& primary_key_values) const { + return query_one(require_db(), resource_name, primary_key_values); +} + +std::map> +External_Resources_Manager::query_aircraft_external_databases( + const std::string& icao24) const { + return query_aircraft(require_db(), icao24); +} + +std::map> +External_Resources_Manager::query_callsign_external_databases( + const std::optional& callsign) const { + return query_callsign(require_db(), callsign); +} + +std::vector +External_Resources_Manager::external_database_status() const { + return status(require_db()); +} + +void External_Resources_Manager::server(Global* g) { + auto& svr = g->svr; + const auto& api = g->api; + + svr.Post(api + "get_external_database_config", [this](HTTP_Param) { + + + auto t = warp(to_json()).to_json_string(); + + res->setBody(t); + }); + svr.Post(api + "get_external_database_status", [this](HTTP_Param) { + res->setBody( + warp(external_resource_status_list_to_json(external_database_status())) + .to_json_string()); + }); + svr.Post(api + "refresh_external_database", [this, g](HTTP_Param) { + CHECK_JSON_PARAM + HTTP_REQUIRE_VALUE(name, params.try_get_string("name")) + const auto result = refresh_external_database(name, true); + g->save(); + res->setBody(warp(external_resource_status_to_json(result)).to_json_string()); + }); + svr.Post(api + "refresh_external_databases", [this, g](HTTP_Param) { + const auto result = refresh_external_databases(true); + g->save(); + res->setBody(warp(external_resource_status_list_to_json(result)).to_json_string()); + }); + svr.Post(api + "import_external_database", [this, g](HTTP_Param) { + CHECK_JSON_PARAM + HTTP_REQUIRE_VALUE(name, params.try_get_string("name")) + HTTP_REQUIRE_VALUE(source_file, params.try_get_string("source_file")) + const auto result = import_external_database(name, source_file); + g->save(); + res->setBody(warp(external_resource_status_to_json(result)).to_json_string()); + }); + svr.Post(api + "upload_external_database", [this, g](HTTP_Param) { + drogon::MultiPartParser parser; + if (parser.parse(req) != 0) { + throw_invalid_http_param("multipart"); + } + const auto name = parser.getOptionalParameter("name"); + if (!name || parser.getFiles().size() != 1) { + throw_invalid_http_param("name or file"); + } + + const auto& upload = parser.getFiles().front(); + const auto serial = std::chrono::steady_clock::now().time_since_epoch().count(); + auto extension = std::string(upload.getFileExtension()); + if (!extension.empty() && extension.front() != '.') { + extension.insert(extension.begin(), '.'); + } + const auto saved_name = + "external_database_" + std::to_string(serial) + extension; + if (upload.saveAs(saved_name) != 0) { + throw std::runtime_error("Cannot save uploaded external database file"); + } + + const auto source_file = + std::filesystem::path(drogon::app().getUploadPath()) / saved_name; + const auto result = import_external_database(*name, source_file); + g->save(); + res->setBody(warp(external_resource_status_to_json(result)).to_json_string()); + }); + svr.Post(api + "clear_external_database_table", [this, g](HTTP_Param) { + CHECK_JSON_PARAM + HTTP_REQUIRE_VALUE(name, params.try_get_string("name")) + const auto result = clear_external_database_table(name); + g->save(); + res->setBody(warp(external_resource_status_to_json(result)).to_json_string()); + }); + svr.Post(api + "query_external_database", [this](HTTP_Param) { + CHECK_JSON_PARAM + HTTP_REQUIRE_VALUE(name, params.try_get_string("name")) + HTTP_REQUIRE_PTR(primary_key_values_json, params.get("primary_key_values")) + std::vector primary_key_values; + for (const auto& value : primary_key_values_json->children) { + if (value.valueType != Psc::JsonType::String) { + throw_invalid_http_param("primary_key_values"); + } + primary_key_values.push_back(value.val); + } + const auto row = query_external_database(name, primary_key_values); + res->setBody(row ? warp(row->to_json()).to_json_string() + : Psc::JSON(nullptr).to_json_string()); + }); +} + +void External_Resources_Manager::register_external_resource( + std::unique_ptr external_res) { + if (!external_res) throw std::invalid_argument("external resource is null"); + resources_.push_back(std::move(external_res)); +} + +void External_Resources_Manager::initialize(SQLite::Database& db, + std::filesystem::path cache_pos) { + std::lock_guard lock(mtx_); + cache_pos_ = std::move(cache_pos); + for (const auto& resource : resources_) resource->create_table(db); +} + +std::vector External_Resources_Manager::sync_missing( + SQLite::Database& db) { + return update_all(db, false, true); +} + +std::vector External_Resources_Manager::refresh_all( + SQLite::Database& db, + const bool force_download) { + return update_all(db, force_download, false); +} + +External_Resource_Status External_Resources_Manager::refresh_one( + SQLite::Database& db, + const std::string& resource_name, + const bool force_download) { + std::lock_guard lock(mtx_); + return get_resource(resource_name).update(db, cache_pos_, force_download, false); +} + +External_Resource_Status External_Resources_Manager::import_offline( + SQLite::Database& db, + const std::string& resource_name, + const std::filesystem::path& source_file) { + std::lock_guard lock(mtx_); + return get_resource(resource_name).import_offline(db, source_file); +} + +External_Resource_Status External_Resources_Manager::clear_table( + SQLite::Database& db, + const std::string& resource_name) { + std::lock_guard lock(mtx_); + return get_resource(resource_name).clear_table(db, cache_pos_); +} + +std::optional External_Resources_Manager::query_one( + SQLite::Database& db, + const std::string& resource_name, + const std::vector& primary_key_values) const { + std::lock_guard lock(mtx_); + return get_resource(resource_name).query_one(db, primary_key_values); +} + +std::map> +External_Resources_Manager::query_aircraft(SQLite::Database& db, + const std::string& icao24) const { + Scope_Timer timer( + "external_database.query_aircraft", + Global::instance()->http_monitor_config.slow_scope_threshold_ms); + static const std::vector kAircraftResourceKeys = { + "tar1090_db_aircraft", + "wiedehopf_tar1090_db_aircraft", + "mictronics_aircraft_database", + "opensky_aircraft_database", + "faa_aircraft_registry", + }; + std::lock_guard lock(mtx_); + std::map> result; + const auto add_row = [&](const std::string& resource_name, + const std::vector& primary_key_values, + const std::string& result_name = std::string{}) { + auto& resource = get_resource(resource_name); + auto row = resource.query_one(db, primary_key_values); + if (!row) return std::shared_ptr{}; + auto shared_row = std::make_shared(std::move(*row)); + result.emplace(result_name.empty() ? resource_name : result_name, shared_row); + return shared_row; + }; + + std::optional type_code; + for (const auto& resource_name : kAircraftResourceKeys) { + const auto row = add_row(resource_name, {icao24}); + if (row && !type_code) { + type_code = row->get("type_code"); + if (!type_code) type_code = row->get("typecode"); + } + } + + if (type_code) add_row("icao_doc_8643_aircraft_type_designators", {*type_code}); + return result; +} + +std::map> +External_Resources_Manager::query_callsign( + SQLite::Database& db, + const std::optional& callsign) const { + Scope_Timer timer( + "external_database.query_callsign", + Global::instance()->http_monitor_config.slow_scope_threshold_ms); + static const std::vector kRouteResourceKeys = { + "vrs_routes", + "adsblol_vrs_standing_data_routes", + "vradarserver_standing_data_routes", + }; + + std::lock_guard lock(mtx_); + std::map> result; + const auto add_row = [&](const std::string& resource_name, + const std::vector& primary_key_values, + const std::string& result_name = std::string{}) { + auto& resource = get_resource(resource_name); + auto row = resource.query_one(db, primary_key_values); + if (!row) return std::shared_ptr{}; + auto shared_row = std::make_shared(std::move(*row)); + result.emplace(result_name.empty() ? resource_name : result_name, shared_row); + return shared_row; + }; + + std::set airport_codes; + if (callsign && !callsign->empty()) { + for (const auto& resource_name : kRouteResourceKeys) { + const auto row = add_row(resource_name, {*callsign}); + if (!row) continue; + const auto airports = row->get("AirportCodes"); + if (!airports) continue; + + std::size_t start = 0; + while (start < airports->size()) { + const auto end = airports->find('-', start); + airport_codes.emplace(airports->substr(start, end - start)); + if (end == std::string::npos) break; + start = end + 1; + } + } + } + + for (const auto& airport_code : airport_codes) { + if (airport_code.empty()) continue; + add_row("vrs_airports", {airport_code}, "vrs_airports:" + airport_code); + } + return result; +} + +std::vector External_Resources_Manager::status( + SQLite::Database& db) const { + std::lock_guard lock(mtx_); + std::vector result; + for (const auto& resource : resources_) { + result.push_back({resource->name, resource->row_count(db), false, false, ""}); + } + return result; +} + +SQLite::Database& External_Resources_Manager::require_db() const { + if (!db_) { + throw std::runtime_error("DB not loaded. Call load_sqlite_db() first."); + } + return *db_; +} + +External_Resources& External_Resources_Manager::get_resource( + const std::string& resource_name) const { + for (const auto& resource : resources_) { + if (resource->name == resource_name) return *resource; + } + throw std::invalid_argument("unknown external resource: " + resource_name); +} + +std::vector External_Resources_Manager::update_all( + SQLite::Database& db, + const bool force_download, + const bool only_when_empty) { + std::lock_guard lock(mtx_); + std::vector result; + for (const auto& resource : resources_) { + try { + auto status = resource->update(db, cache_pos_, force_download, only_when_empty); + std::cout << "External database [" << status.name << "] " + << status.message << ", rows=" << status.row_count << std::endl; + result.push_back(std::move(status)); + } catch (const std::exception& error) { + std::cerr << "External database [" << resource->name + << "] update failed: " << error.what() << std::endl; + result.push_back( + {resource->name, resource->row_count(db), false, false, error.what()}); + } + } + return result; +} diff --git a/module/Local_Server/External_Database/Faa_Aircraft_Registry.cpp b/module/Local_Server/External_Database/Faa_Aircraft_Registry.cpp new file mode 100644 index 0000000..a5a342c --- /dev/null +++ b/module/Local_Server/External_Database/Faa_Aircraft_Registry.cpp @@ -0,0 +1,115 @@ +// 数据来源:FAA Aircraft Registry。美国 FAA 官方注册库,每日更新,MASTER.txt 包含 Mode-S Hex。 +// 链接:https://www.faa.gov/licenses_certificates/aircraft_certification/aircraft_registry/releasable_aircraft_download +// 下载:https://registry.faa.gov/database/ReleasableAircraft.zip +// 官方更新要求:FAA 下载页说明文件每日刷新。本地告警策略:超过 24 小时提示更新。 + +#include "../server/libarchive.h" +#include "Resource_Utils.h" + +#include + +#include +#include + +namespace { + +const std::vector kFaaColumns = { + "n_number", "serial_number", "aircraft_mfr_model_code", "engine_mfr_model_code", + "year_mfr", "registrant_type", "name", "street", "street2", "city", "state", + "zip_code", "region", "county", "country", "last_action_date", "cert_issue_date", + "certification", "type_aircraft", "type_engine", "status_code", "mode_s_code", + "fractional_ownership", "airworthiness_date", "other_names_1", "other_names_2", + "other_names_3", "other_names_4", "other_names_5", "expiration_date", + "unique_id", "kit_mfr", "kit_model", "icao24" +}; +const std::vector kFaaPrimaryKey = {"icao24"}; + +class Faa_Aircraft_Registry_Resource final : public External_Resources { +public: + Faa_Aircraft_Registry_Resource() + : External_Resources("faa_aircraft_registry", + "faa_registry/MASTER.txt", + "https://registry.faa.gov/database/ReleasableAircraft.zip", + "FAA 官方可公开下载的美国飞机注册库,MASTER.txt 包含 Mode-S Hex 注册信息。", + 86400) {} + + void create_table(SQLite::Database& db) const override { + db.exec(R"sql( + CREATE TABLE IF NOT EXISTS faa_aircraft_registry ( + n_number TEXT, serial_number TEXT, aircraft_mfr_model_code TEXT, + engine_mfr_model_code TEXT, year_mfr TEXT, registrant_type TEXT, + name TEXT, street TEXT, street2 TEXT, city TEXT, state TEXT, + zip_code TEXT, region TEXT, county TEXT, country TEXT, + last_action_date TEXT, cert_issue_date TEXT, certification TEXT, + type_aircraft TEXT, type_engine TEXT, status_code TEXT, + mode_s_code TEXT, fractional_ownership TEXT, airworthiness_date TEXT, + other_names_1 TEXT, other_names_2 TEXT, other_names_3 TEXT, + other_names_4 TEXT, other_names_5 TEXT, expiration_date TEXT, + unique_id TEXT, kit_mfr TEXT, kit_model TEXT, + icao24 TEXT NOT NULL PRIMARY KEY + ); + )sql"); + } + +protected: + bool fetch(const std::filesystem::path& cache_pos, + const bool force_download) const override { + const auto master_file = source_file(cache_pos); + if (!force_download) return false; + const auto zip_file = cache_pos / "ReleasableAircraft.zip"; + External_Database_Utils::download_to_file(download_url, zip_file); + unarchive_file(zip_file, cache_pos / "faa_registry"); + return true; + } + + std::size_t import_file(SQLite::Database& db, + const std::filesystem::path& source_file) const override { + auto master_file = source_file; + if (source_file.extension() == ".zip") { + const auto output_dir = source_file.parent_path() / "faa_registry"; + unarchive_file(source_file, output_dir); + master_file = output_dir / "MASTER.txt"; + } + + std::ifstream input(master_file, std::ios::binary); + if (!input) throw std::runtime_error("Cannot open FAA MASTER.txt: " + + master_file.string()); + + SQLite::Transaction transaction(db); + db.exec("DELETE FROM faa_aircraft_registry"); + SQLite::Statement statement( + db, External_Database_Utils::make_upsert_sql( + name, kFaaColumns, kFaaPrimaryKey)); + std::vector fields; + External_Database_Utils::read_csv_row(input, fields, ','); // 跳过表头。 + std::size_t row_count = 0; + while (External_Database_Utils::read_csv_row(input, fields, ',')) { + if (fields.size() < kFaaColumns.size()) fields.resize(kFaaColumns.size()); + const auto icao24 = External_Database_Utils::normalize_key(fields[33]); + if (icao24.empty()) continue; + + statement.reset(); + statement.clearBindings(); + for (std::size_t index = 0; index < kFaaColumns.size(); ++index) { + auto value = External_Database_Utils::normalize_field(fields[index]); + if (index == 33) value = icao24; + External_Database_Utils::bind_optional( + statement, static_cast(index + 1), value); + } + statement.exec(); + ++row_count; + } + transaction.commit(); + return row_count; + } + + [[nodiscard]] const std::vector& primary_key_columns() const override { + return kFaaPrimaryKey; + } +}; + +} // 命名空间 + +std::unique_ptr make_faa_aircraft_registry_resource() { + return std::make_unique(); +} diff --git a/module/Local_Server/External_Database/Icao_Doc_8643.cpp b/module/Local_Server/External_Database/Icao_Doc_8643.cpp new file mode 100644 index 0000000..b610b40 --- /dev/null +++ b/module/Local_Server/External_Database/Icao_Doc_8643.cpp @@ -0,0 +1,18 @@ +// 数据来源:ICAO Doc 8643 Aircraft Type Designators。用于把机型 designator 映射为制造商、型号和类别。 +// 链接:https://www.icao.int/operational-safety/doc-8643-aircraft-type-designators +// ICAO 页面没有稳定公开 CSV 地址;模块支持把人工下载的 CSV 离线导入。 +// 官方更新要求:ICAO 在每个 AIRAC 周期按月更新。本地告警策略:超过 28 天提示更新。 + +#include "Resource_Utils.h" + +std::unique_ptr make_icao_doc_8643_resource() { + return External_Database_Utils::make_header_csv_resource({ + "icao_doc_8643_aircraft_type_designators", + "icao_doc_8643.csv", + "", + "ICAO Doc 8643 机型代码表,用于将 A320、B738 等 designator 映射为制造商、型号和类别。", + 2419200, + {"type_designator", "manufacturer", "model", "description", "wtc"}, + {"type_designator"} + }); +} diff --git a/module/Local_Server/External_Database/Mictronics_Aircraft_Database.cpp b/module/Local_Server/External_Database/Mictronics_Aircraft_Database.cpp new file mode 100644 index 0000000..37d0fc4 --- /dev/null +++ b/module/Local_Server/External_Database/Mictronics_Aircraft_Database.cpp @@ -0,0 +1,13 @@ +// 数据来源:Mictronics Aircraft Database。社区维护的飞机静态信息库。 +// 链接:https://www.mictronics.de/aircraft-database/ +// 在线更新使用 tar1090-db 发布的 Mictronics 汇总镜像。 +// 官方更新要求:官网未声明固定更新频率。本地告警策略:超过 7 天提示检查。 + +#include "Resource_Utils.h" + +std::unique_ptr make_mictronics_aircraft_database_resource() { + return External_Database_Utils::make_tar1090_aircraft_resource( + "mictronics_aircraft_database", + "Mictronics 社区飞机数据库的 tar1090 汇总镜像,可按 ICAO24 查询注册号、机型和运营方。", + 604800); +} diff --git a/module/Local_Server/External_Database/OpenSky_Aircraft_Database.cpp b/module/Local_Server/External_Database/OpenSky_Aircraft_Database.cpp new file mode 100644 index 0000000..1863d4d --- /dev/null +++ b/module/Local_Server/External_Database/OpenSky_Aircraft_Database.cpp @@ -0,0 +1,24 @@ +// 数据来源:OpenSky Aircraft Database。字段较完整的 ICAO24 飞机静态库。 +// 链接:https://opensky-network.org/datasets/metadata/aircraftDatabase.csv +// 官方更新要求:下载页未声明固定更新频率。本地告警策略:超过 7 天提示检查。 + +#include "Resource_Utils.h" + +std::unique_ptr make_opensky_aircraft_database_resource() { + return External_Database_Utils::make_header_csv_resource({ + "opensky_aircraft_database", + "aircraftDatabase.csv", + "https://opensky-network.org/datasets/metadata/aircraftDatabase.csv", + "OpenSky Network 飞机元数据 CSV,包含制造商、型号、注册号和运营方等字段。", + 604800, + { + "icao24", "registration", "manufacturericao", "manufacturername", "model", + "typecode", "serialnumber", "linenumber", "icaoaircrafttype", "operator", + "operatorcallsign", "operatoricao", "operatoriata", "owner", "testreg", + "registered", "reguntil", "status", "built", "firstflightdate", + "seatconfiguration", "engines", "modes", "adsb", "acars", "notes", + "categoryDescription" + }, + {"icao24"} + }); +} diff --git a/module/Local_Server/External_Database/OpenSky_FlightData_Api.cpp b/module/Local_Server/External_Database/OpenSky_FlightData_Api.cpp new file mode 100644 index 0000000..e983933 --- /dev/null +++ b/module/Local_Server/External_Database/OpenSky_FlightData_Api.cpp @@ -0,0 +1,30 @@ +// 数据来源:OpenSky FlightData API。按 ICAO24 和时间范围查询历史航班与起降机场。 +// 链接:https://openskynetwork.github.io/opensky-api/rest.html +// 该来源不是全量 CSV;表作为 API 查询结果缓存,主键为 ICAO24 与时间范围。 +// 官方更新要求:API 按请求提供数据并有调用限额,不执行全量定时下载。 +// 本地告警策略:动态缓存不显示周期性过期告警。 + +#include "Resource_Utils.h" + +std::unique_ptr make_opensky_flightdata_api_resource() { + return External_Database_Utils::make_schema_only_resource({ + "opensky_flightdata_api_cache", + "OpenSky FlightData API 查询缓存,按 ICAO24 和时间范围保存历史航班起降机场结果。", + 0, + R"sql( + CREATE TABLE IF NOT EXISTS opensky_flightdata_api_cache ( + icao24 TEXT NOT NULL, + begin_time TEXT NOT NULL, + end_time TEXT NOT NULL, + callsign TEXT, + est_departure_airport TEXT, + est_arrival_airport TEXT, + first_seen TEXT, + last_seen TEXT, + raw_json TEXT, + PRIMARY KEY (icao24, begin_time, end_time) + ); + )sql", + {"icao24", "begin_time", "end_time"} + }); +} diff --git a/module/Local_Server/External_Database/Resource_Utils.cpp b/module/Local_Server/External_Database/Resource_Utils.cpp new file mode 100644 index 0000000..1beeb29 --- /dev/null +++ b/module/Local_Server/External_Database/Resource_Utils.cpp @@ -0,0 +1,458 @@ +#include "Resource_Utils.h" + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace External_Database_Utils { +namespace { + +constexpr const char* kTar1090Url = + "https://raw.githubusercontent.com/wiedehopf/tar1090-db/refs/heads/csv/aircraft.csv.gz"; + +const std::vector kTar1090Columns = { + "icao24", "registration", "type_code", "subtype", + "type_name", "year", "operator_info" +}; +const std::vector kTar1090PrimaryKey = {"icao24"}; + +std::pair split_url(const std::string& url) { + const auto scheme_end = url.find("://"); + if (scheme_end == std::string::npos) { + throw std::runtime_error("Invalid download URL: " + url); + } + const auto path_begin = url.find('/', scheme_end + 3); + if (path_begin == std::string::npos) return {url, "/"}; + return {url.substr(0, path_begin), url.substr(path_begin)}; +} + +void replace_file(const std::filesystem::path& temp_file, + const std::filesystem::path& target_file) { + std::error_code error; + std::filesystem::remove(target_file, error); + error.clear(); + std::filesystem::rename(temp_file, target_file, error); + if (error) { + throw std::runtime_error("Cannot replace cache file " + target_file.string() + + ": " + error.message()); + } +} + +std::string create_csv_table_sql(const std::string& table_name, + const std::vector& columns, + const std::vector& primary_key_columns) { + std::ostringstream sql; + sql << "CREATE TABLE IF NOT EXISTS " << quote_identifier(table_name) << " ("; + for (std::size_t index = 0; index < columns.size(); ++index) { + if (index != 0) sql << ','; + sql << quote_identifier(columns[index]) << " TEXT"; + } + if (!primary_key_columns.empty()) { + sql << ", PRIMARY KEY ("; + for (std::size_t index = 0; index < primary_key_columns.size(); ++index) { + if (index != 0) sql << ','; + sql << quote_identifier(primary_key_columns[index]); + } + sql << ')'; + } + sql << ");"; + return sql.str(); +} + +class Header_Csv_Resource final : public External_Resources { +public: + explicit Header_Csv_Resource(Header_Csv_Resource_Config config) + : External_Resources(config.name, + config.cache_file_name, + config.download_url, + config.description, + config.update_interval_seconds), + config_(std::move(config)) {} + + void create_table(SQLite::Database& db) const override { + db.exec(create_csv_table_sql(name, config_.columns, + config_.primary_key_columns)); + } + +protected: + std::size_t import_file(SQLite::Database& db, + const std::filesystem::path& source_file) const override { + return import_header_csv(db, source_file, name, config_.columns, + config_.primary_key_columns, config_.delimiter); + } + + [[nodiscard]] const std::vector& primary_key_columns() const override { + return config_.primary_key_columns; + } + +private: + Header_Csv_Resource_Config config_; +}; + +class Schema_Only_Resource final : public External_Resources { +public: + explicit Schema_Only_Resource(Schema_Only_Resource_Config config) + : External_Resources(config.name, + "", + "", + config.description, + config.update_interval_seconds), + config_(std::move(config)) {} + + void create_table(SQLite::Database& db) const override { + db.exec(config_.create_table_sql); + } + +protected: + std::size_t import_file(SQLite::Database&, + const std::filesystem::path&) const override { + throw std::runtime_error("This resource is updated by its API-specific adapter"); + } + + [[nodiscard]] const std::vector& primary_key_columns() const override { + return config_.primary_key_columns; + } + +private: + Schema_Only_Resource_Config config_; +}; + +class Tar1090_Aircraft_Resource final : public External_Resources { +public: + Tar1090_Aircraft_Resource(std::string name, + std::string description, + const std::uint64_t update_interval_seconds) + : External_Resources(std::move(name), + "aircraft.csv", + kTar1090Url, + std::move(description), + update_interval_seconds) {} + + void create_table(SQLite::Database& db) const override { + db.exec(create_csv_table_sql(name, kTar1090Columns, kTar1090PrimaryKey)); + } + +protected: + bool fetch(const std::filesystem::path& cache_pos, + const bool force_download) const override { + const auto csv_file = source_file(cache_pos); + if (!force_download) return false; + const auto gzip_file = cache_pos / "aircraft.csv.gz"; + download_to_file(download_url, gzip_file); + decompress_gzip(gzip_file, csv_file); + return true; + } + + std::size_t import_file(SQLite::Database& db, + const std::filesystem::path& source_file) const override { + if (source_file.extension() == ".gz") { + auto csv_file = source_file; + csv_file.replace_extension(".csv"); + decompress_gzip(source_file, csv_file); + return import_file(db, csv_file); + } + + std::ifstream input(source_file, std::ios::binary); + if (!input) throw std::runtime_error("Cannot open CSV file: " + source_file.string()); + + SQLite::Transaction transaction(db); + db.exec("DELETE FROM " + quote_identifier(name)); + SQLite::Statement statement( + db, make_upsert_sql(name, kTar1090Columns, kTar1090PrimaryKey)); + std::vector fields; + std::size_t row_count = 0; + while (read_csv_row(input, fields, ';')) { + if (fields.empty()) continue; + const auto icao = normalize_key(fields[0]); + if (icao.empty()) continue; + + statement.reset(); + statement.clearBindings(); + statement.bind(1, icao); + for (std::size_t index = 1; index < kTar1090Columns.size(); ++index) { + std::optional value; + if (index < fields.size()) value = normalize_field(fields[index]); + bind_optional(statement, static_cast(index + 1), value); + } + statement.exec(); + ++row_count; + } + transaction.commit(); + return row_count; + } + + [[nodiscard]] const std::vector& primary_key_columns() const override { + return kTar1090PrimaryKey; + } +}; + +} // 命名空间 + +std::string quote_identifier(const std::string& value) { + std::string result = "\""; + for (const char ch : value) { + result += ch; + if (ch == '"') result += '"'; + } + result += '"'; + return result; +} + +std::string normalize_key(std::string value) { + const auto is_space = [](unsigned char ch) { return std::isspace(ch) != 0; }; + value.erase(value.begin(), std::find_if(value.begin(), value.end(), + [&](char ch) { return !is_space(ch); })); + value.erase(std::find_if(value.rbegin(), value.rend(), + [&](char ch) { return !is_space(ch); }).base(), + value.end()); + std::transform(value.begin(), value.end(), value.begin(), + [](unsigned char ch) { return static_cast(std::toupper(ch)); }); + return value; +} + +std::optional normalize_field(std::string value) { + const auto is_space = [](unsigned char ch) { return std::isspace(ch) != 0; }; + value.erase(value.begin(), std::find_if(value.begin(), value.end(), + [&](char ch) { return !is_space(ch); })); + value.erase(std::find_if(value.rbegin(), value.rend(), + [&](char ch) { return !is_space(ch); }).base(), + value.end()); + if (value.empty()) return std::nullopt; + return value; +} + +void bind_optional(SQLite::Statement& statement, + const int index, + const std::optional& value) { + if (value) statement.bind(index, *value); + else statement.bind(index); +} + +bool read_csv_row(std::istream& input, + std::vector& fields, + const char delimiter) { + fields.clear(); + std::string field; + char quote = '\0'; + bool have_data = false; + while (true) { + const int next = input.get(); + if (next == EOF) { + if (!have_data && field.empty() && fields.empty()) return false; + fields.push_back(std::move(field)); + return true; + } + have_data = true; + const char ch = static_cast(next); + if (quote != '\0') { + if (ch == quote) { + if (input.peek() == quote) { + input.get(); + field += quote; + } else { + quote = '\0'; + } + } else { + field += ch; + } + } else if ((ch == '"' || ch == '\'') && field.empty()) { + quote = ch; + } else if (ch == delimiter) { + fields.push_back(std::move(field)); + field.clear(); + } else if (ch == '\n') { + fields.push_back(std::move(field)); + return true; + } else if (ch != '\r') { + field += ch; + } + } +} + +std::string make_upsert_sql(const std::string& table_name, + const std::vector& columns, + const std::vector& primary_key_columns) { + std::ostringstream sql; + sql << "INSERT INTO " << quote_identifier(table_name) << " ("; + for (std::size_t index = 0; index < columns.size(); ++index) { + if (index != 0) sql << ','; + sql << quote_identifier(columns[index]); + } + sql << ") VALUES ("; + for (std::size_t index = 0; index < columns.size(); ++index) { + if (index != 0) sql << ','; + sql << '?'; + } + sql << ')'; + if (!primary_key_columns.empty()) { + sql << " ON CONFLICT ("; + for (std::size_t index = 0; index < primary_key_columns.size(); ++index) { + if (index != 0) sql << ','; + sql << quote_identifier(primary_key_columns[index]); + } + sql << ") DO UPDATE SET "; + bool first = true; + for (const auto& column : columns) { + if (std::find(primary_key_columns.begin(), primary_key_columns.end(), column) != + primary_key_columns.end()) continue; + if (!first) sql << ','; + first = false; + sql << quote_identifier(column) << "=excluded." << quote_identifier(column); + } + } + return sql.str(); +} + +void download_to_file(std::string url, const std::filesystem::path& target_file) { + std::filesystem::create_directories(target_file.parent_path()); + constexpr int kMaxRedirects = 5; + for (int redirect = 0; redirect <= kMaxRedirects; ++redirect) { + const auto [origin, path] = split_url(url); + auto client = drogon::HttpClient::newHttpClient(origin); + auto request = drogon::HttpRequest::newHttpRequest(); + request->setMethod(drogon::Get); + request->setPath(path); + request->addHeader("User-Agent", "ECAP_Server external database updater"); + const auto [result, response] = client->sendRequest(request, 600.0); + if (result != drogon::ReqResult::Ok || !response) { + throw std::runtime_error("Download failed: " + url); + } + const int status = static_cast(response->getStatusCode()); + if (status >= 300 && status < 400) { + const auto location = response->getHeader("location"); + if (location.empty()) throw std::runtime_error("Redirect has no location: " + url); + url = location.front() == '/' ? origin + location : location; + continue; + } + if (status != 200) { + throw std::runtime_error("Download returned HTTP " + std::to_string(status) + + ": " + url); + } + const auto temp_file = target_file.string() + ".tmp"; + std::ofstream output(temp_file, std::ios::binary | std::ios::trunc); + if (!output) throw std::runtime_error("Cannot write cache file: " + temp_file); + const auto body = response->getBody(); + output.write(body.data(), static_cast(body.size())); + output.close(); + if (!output) throw std::runtime_error("Cannot finish cache file: " + temp_file); + replace_file(temp_file, target_file); + return; + } + throw std::runtime_error("Too many redirects while downloading: " + url); +} + +void decompress_gzip(const std::filesystem::path& gzip_file, + const std::filesystem::path& target_file) { + const auto temp_file = target_file.string() + ".tmp"; + gzFile input = gzopen(gzip_file.string().c_str(), "rb"); + if (!input) throw std::runtime_error("Cannot open gzip file: " + gzip_file.string()); + std::ofstream output(temp_file, std::ios::binary | std::ios::trunc); + if (!output) { + gzclose(input); + throw std::runtime_error("Cannot write decompressed file: " + temp_file); + } + char buffer[64 * 1024]; + int size = 0; + while ((size = gzread(input, buffer, sizeof(buffer))) > 0) output.write(buffer, size); + const int close_result = gzclose(input); + output.close(); + if (size < 0 || close_result != Z_OK || !output) { + std::filesystem::remove(temp_file); + throw std::runtime_error("Cannot decompress gzip file: " + gzip_file.string()); + } + replace_file(temp_file, target_file); +} + +std::size_t import_header_csv(SQLite::Database& db, + const std::filesystem::path& source_file, + const std::string& table_name, + const std::vector& columns, + const std::vector& primary_key_columns, + const char delimiter) { + std::ifstream input(source_file, std::ios::binary); + if (!input) throw std::runtime_error("Cannot open CSV file: " + source_file.string()); + std::vector header; + if (!read_csv_row(input, header, delimiter)) { + throw std::runtime_error("CSV file is empty: " + source_file.string()); + } + if (!header.empty() && header.front().size() >= 3 && + static_cast(header.front()[0]) == 0xef && + static_cast(header.front()[1]) == 0xbb && + static_cast(header.front()[2]) == 0xbf) { + header.front().erase(0, 3); + } + std::map header_index; + for (std::size_t index = 0; index < header.size(); ++index) { + header_index.emplace(header[index], index); + } + for (const auto& column : columns) { + if (header_index.count(column) == 0) { + throw std::runtime_error("CSV header is missing column '" + column + "'"); + } + } + + SQLite::Transaction transaction(db); + db.exec("DELETE FROM " + quote_identifier(table_name)); + SQLite::Statement statement(db, make_upsert_sql(table_name, columns, primary_key_columns)); + std::vector fields; + std::size_t row_count = 0; + while (read_csv_row(input, fields, delimiter)) { + bool primary_key_ok = true; + for (const auto& column : primary_key_columns) { + const auto index = header_index.at(column); + if (index >= fields.size() || normalize_key(fields[index]).empty()) { + primary_key_ok = false; + break; + } + } + if (!primary_key_ok) continue; + statement.reset(); + statement.clearBindings(); + for (std::size_t index = 0; index < columns.size(); ++index) { + std::optional value; + const auto source_index = header_index.at(columns[index]); + if (source_index < fields.size()) value = normalize_field(fields[source_index]); + if (value && + std::find(primary_key_columns.begin(), primary_key_columns.end(), + columns[index]) != primary_key_columns.end()) { + value = normalize_key(*value); + } + bind_optional(statement, static_cast(index + 1), value); + } + statement.exec(); + ++row_count; + } + transaction.commit(); + return row_count; +} + +std::unique_ptr make_header_csv_resource( + Header_Csv_Resource_Config config) { + return std::make_unique(std::move(config)); +} + +std::unique_ptr make_schema_only_resource( + Schema_Only_Resource_Config config) { + return std::make_unique(std::move(config)); +} + +std::unique_ptr make_tar1090_aircraft_resource( + std::string name, + std::string description, + const std::uint64_t update_interval_seconds) { + return std::make_unique( + std::move(name), std::move(description), update_interval_seconds); +} + +} // 命名空间 External_Database_Utils diff --git a/module/Local_Server/External_Database/Resource_Utils.h b/module/Local_Server/External_Database/Resource_Utils.h new file mode 100644 index 0000000..928e62a --- /dev/null +++ b/module/Local_Server/External_Database/Resource_Utils.h @@ -0,0 +1,67 @@ +#pragma once + +#include "global.h" + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace External_Database_Utils { + +struct Header_Csv_Resource_Config { + std::string name; + std::string cache_file_name; + std::string download_url; + std::string description; + std::uint64_t update_interval_seconds{}; + std::vector columns; + std::vector primary_key_columns; + char delimiter = ','; +}; + +struct Schema_Only_Resource_Config { + std::string name; + std::string description; + std::uint64_t update_interval_seconds{}; + std::string create_table_sql; + std::vector primary_key_columns; +}; + +std::string quote_identifier(const std::string& value); +std::string normalize_key(std::string value); +std::optional normalize_field(std::string value); +void bind_optional(SQLite::Statement& statement, + int index, + const std::optional& value); +bool read_csv_row(std::istream& input, + std::vector& fields, + char delimiter); +std::string make_upsert_sql(const std::string& table_name, + const std::vector& columns, + const std::vector& primary_key_columns); +void download_to_file(std::string url, const std::filesystem::path& target_file); +void decompress_gzip(const std::filesystem::path& gzip_file, + const std::filesystem::path& target_file); +std::size_t import_header_csv(SQLite::Database& db, + const std::filesystem::path& source_file, + const std::string& table_name, + const std::vector& columns, + const std::vector& primary_key_columns, + char delimiter = ','); + +std::unique_ptr make_header_csv_resource( + Header_Csv_Resource_Config config); +std::unique_ptr make_schema_only_resource( + Schema_Only_Resource_Config config); +std::unique_ptr make_tar1090_aircraft_resource( + std::string name, + std::string description, + std::uint64_t update_interval_seconds); + +} // 命名空间 External_Database_Utils diff --git a/module/Local_Server/External_Database/Resources.h b/module/Local_Server/External_Database/Resources.h new file mode 100644 index 0000000..ae3cfc9 --- /dev/null +++ b/module/Local_Server/External_Database/Resources.h @@ -0,0 +1,17 @@ +#pragma once + +#include + +class External_Resources; + +std::unique_ptr make_tar1090_db_aircraft_csv_gz_resource(); +std::unique_ptr make_wiedehopf_tar1090_db_resource(); +std::unique_ptr make_mictronics_aircraft_database_resource(); +std::unique_ptr make_opensky_aircraft_database_resource(); +std::unique_ptr make_faa_aircraft_registry_resource(); +std::unique_ptr make_icao_doc_8643_resource(); +std::unique_ptr make_vrs_routes_resource(); +std::unique_ptr make_vrs_airports_resource(); +std::unique_ptr make_adsblol_vrs_standing_data_resource(); +std::unique_ptr make_vradarserver_standing_data_resource(); +std::unique_ptr make_opensky_flightdata_api_resource(); diff --git a/module/Local_Server/External_Database/Tar1090_Db_Aircraft_Csv_Gz.cpp b/module/Local_Server/External_Database/Tar1090_Db_Aircraft_Csv_Gz.cpp new file mode 100644 index 0000000..a42c38e --- /dev/null +++ b/module/Local_Server/External_Database/Tar1090_Db_Aircraft_Csv_Gz.cpp @@ -0,0 +1,12 @@ +// 数据来源:tar1090-db aircraft.csv.gz。轻量飞机静态库,提供 ICAO24 到注册号、机型、年份和备注的映射。 +// 链接:https://github.com/wiedehopf/tar1090-db/raw/refs/heads/csv/aircraft.csv.gz +// 官方更新要求:项目未声明固定发布频率。本地告警策略:超过 7 天提示检查。 + +#include "Resource_Utils.h" + +std::unique_ptr make_tar1090_db_aircraft_csv_gz_resource() { + return External_Database_Utils::make_tar1090_aircraft_resource( + "tar1090_db_aircraft", + "wiedehopf/tar1090-db 发布的轻量 ICAO24 飞机静态库,提供注册号、机型、年份和运营方备注。", + 604800); +} diff --git a/module/Local_Server/External_Database/Vradarserver_Standing_Data.cpp b/module/Local_Server/External_Database/Vradarserver_Standing_Data.cpp new file mode 100644 index 0000000..3dd6fa2 --- /dev/null +++ b/module/Local_Server/External_Database/Vradarserver_Standing_Data.cpp @@ -0,0 +1,19 @@ +// 数据来源:vradarserver/standing-data。Virtual Radar Server 的上游 standing-data 项目。 +// 链接:https://github.com/vradarserver/standing-data +// 在线表使用公开镜像 routes.csv,以 callsign 为业务主键。 +// 官方更新要求:上游未声明固定频率;当前使用的 ADSB.lol 镜像每小时更新。 +// 本地告警策略:超过 1 小时提示更新。 + +#include "Resource_Utils.h" + +std::unique_ptr make_vradarserver_standing_data_resource() { + return External_Database_Utils::make_header_csv_resource({ + "vradarserver_standing_data_routes", + "vradarserver_routes.csv", + "https://vrs-standing-data.adsb.lol/routes.csv", + "Virtual Radar Server standing-data 的航线适配表;当前在线更新使用 ADSB.lol 公共镜像。", + 3600, + {"Callsign", "Code", "Number", "AirlineCode", "AirportCodes"}, + {"Callsign"} + }); +} diff --git a/module/Local_Server/External_Database/Vrs_Airports.cpp b/module/Local_Server/External_Database/Vrs_Airports.cpp new file mode 100644 index 0000000..d7a94d4 --- /dev/null +++ b/module/Local_Server/External_Database/Vrs_Airports.cpp @@ -0,0 +1,18 @@ +// 数据来源:VRS airports.csv。以机场 ICAO/Code 为主键,保存机场名称、国家、经纬度和高度。 +// 链接:https://vrs-standing-data.adsb.lol/airports.csv +// 官方更新要求:ADSB.lol 镜像说明导出文件每小时更新。本地告警策略:超过 1 小时提示更新。 + +#include "Resource_Utils.h" + +std::unique_ptr make_vrs_airports_resource() { + return External_Database_Utils::make_header_csv_resource({ + "vrs_airports", + "airports.csv", + "https://vrs-standing-data.adsb.lol/airports.csv", + "VRS 机场字典,提供机场代码、名称、国家、经纬度和高度。", + 3600, + {"Code", "Name", "ICAO", "IATA", "Location", "CountryISO2", + "Latitude", "Longitude", "AltitudeFeet"}, + {"Code"} + }); +} diff --git a/module/Local_Server/External_Database/Vrs_Routes.cpp b/module/Local_Server/External_Database/Vrs_Routes.cpp new file mode 100644 index 0000000..0202587 --- /dev/null +++ b/module/Local_Server/External_Database/Vrs_Routes.cpp @@ -0,0 +1,17 @@ +// 数据来源:VRS routes.csv。以 callsign 为主键,保存航空公司代码和机场代码序列。 +// 链接:https://vrs-standing-data.adsb.lol/routes.csv +// 官方更新要求:ADSB.lol 镜像说明导出文件每小时更新。本地告警策略:超过 1 小时提示更新。 + +#include "Resource_Utils.h" + +std::unique_ptr make_vrs_routes_resource() { + return External_Database_Utils::make_header_csv_resource({ + "vrs_routes", + "routes.csv", + "https://vrs-standing-data.adsb.lol/routes.csv", + "VRS 航线表,以 callsign 查询机场代码序列,用于推断起飞机场、经停机场和目的机场。", + 3600, + {"Callsign", "Code", "Number", "AirlineCode", "AirportCodes"}, + {"Callsign"} + }); +} diff --git a/module/Local_Server/External_Database/Wiedehopf_Tar1090_Db.cpp b/module/Local_Server/External_Database/Wiedehopf_Tar1090_Db.cpp new file mode 100644 index 0000000..5de4d08 --- /dev/null +++ b/module/Local_Server/External_Database/Wiedehopf_Tar1090_Db.cpp @@ -0,0 +1,12 @@ +// 数据来源:wiedehopf/tar1090-db 项目。该项目发布 aircraft.csv.gz,并汇总 Mictronics 飞机数据库。 +// 链接:https://github.com/wiedehopf/tar1090-db?tab=readme-ov-file +// 官方更新要求:项目未声明固定发布频率。本地告警策略:超过 7 天提示检查。 + +#include "Resource_Utils.h" + +std::unique_ptr make_wiedehopf_tar1090_db_resource() { + return External_Database_Utils::make_tar1090_aircraft_resource( + "wiedehopf_tar1090_db_aircraft", + "wiedehopf/tar1090-db 项目发布的飞机静态数据库镜像,供 tar1090 本地识别飞机。", + 604800); +} diff --git a/module/Local_Server/External_Database/export.h b/module/Local_Server/External_Database/export.h new file mode 100644 index 0000000..e31b58c --- /dev/null +++ b/module/Local_Server/External_Database/export.h @@ -0,0 +1,2 @@ +#pragma once +#include "global.h" diff --git a/module/Local_Server/External_Database/global.h b/module/Local_Server/External_Database/global.h new file mode 100644 index 0000000..03965ce --- /dev/null +++ b/module/Local_Server/External_Database/global.h @@ -0,0 +1,159 @@ +#pragma once + +#include "../../../../../core_library/Core/Core/Base/JSON.h" +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class Global; + +struct External_Database_Row { + std::map> columns; + + [[nodiscard]] std::optional get(const std::string& column) const; + [[nodiscard]] Psc::JSON to_json() const; +}; + +struct External_Resource_Status { + std::string name; + std::size_t row_count{}; + bool downloaded{}; + bool imported{}; + std::string message; +}; + +// 每个数据源模块只管理一张 SQLite 表。主键由数据源按业务含义选择: +// ICAO24、航班呼号、机场 ICAO 代码、机型代码或其他业务键。 +class External_Resources { +public: + External_Resources(std::string name, + std::string cache_file_name, + std::string download_url, + std::string description, + std::uint64_t update_interval_seconds); + virtual ~External_Resources() = default; + + + + [[nodiscard]] std::size_t row_count(SQLite::Database& db) const; + + virtual void create_table(SQLite::Database& db) const = 0; + External_Resource_Status update(SQLite::Database& db, + const std::filesystem::path& cache_pos, + bool force_download, + bool only_when_empty); + External_Resource_Status import_offline(SQLite::Database& db, + const std::filesystem::path& source_file); + External_Resource_Status clear_table(SQLite::Database& db, + const std::filesystem::path& cache_pos); + [[nodiscard]] std::optional query_one( + SQLite::Database& db, + const std::vector& primary_key_values) const; + void init(const Psc::JSON* that_json) + { + Get_J(name) + Get_J(download_url) + Get_J(description) + Get_J(update_interval_seconds) + Get_J(last_updated_at) + } + [[nodiscard]] Psc::JSON to_json() const + { + Psc::JSON ret = Psc::JSON::object(); + Ret_J(name) + Ret_J(download_url) + Ret_J(description) + Ret_J(update_interval_seconds) + Ret_J(last_updated_at) + return ret; + } + std::string name; + std::string cache_file_name; + std::string download_url; + std::string description; + std::uint64_t update_interval_seconds{}; + std::time_t last_updated_at{}; +protected: + [[nodiscard]] virtual std::filesystem::path source_file( + const std::filesystem::path& cache_pos) const; + virtual bool fetch(const std::filesystem::path& cache_pos, + bool force_download) const; + virtual std::size_t import_file(SQLite::Database& db, + const std::filesystem::path& source_file) const = 0; + [[nodiscard]] virtual const std::vector& primary_key_columns() const = 0; + void mark_updated(); + void clear_last_updated_at(); + + +}; + +class External_Resources_Manager { +public: + External_Resources_Manager(); + + void init(const Psc::JSON* that_json); + [[nodiscard]] Psc::JSON to_json() const; + void server(Global* g); + void load_sqlite_db(std::string path); + std::vector refresh_external_databases(bool force_download = true); + External_Resource_Status refresh_external_database(const std::string& resource_name, + bool force_download = true); + External_Resource_Status import_external_database( + const std::string& resource_name, + const std::filesystem::path& source_file); + External_Resource_Status clear_external_database_table(const std::string& resource_name); + [[nodiscard]] std::optional query_external_database( + const std::string& resource_name, + const std::vector& primary_key_values) const; + [[nodiscard]] std::map> + query_aircraft_external_databases(const std::string& icao24) const; + [[nodiscard]] std::map> + query_callsign_external_databases( + const std::optional& callsign) const; + [[nodiscard]] std::vector external_database_status() const; + + void register_external_resource(std::unique_ptr external_res); + void initialize(SQLite::Database& db, std::filesystem::path cache_pos); + std::vector sync_missing(SQLite::Database& db); + std::vector refresh_all(SQLite::Database& db, + bool force_download = true); + External_Resource_Status refresh_one(SQLite::Database& db, + const std::string& resource_name, + bool force_download = true); + External_Resource_Status import_offline(SQLite::Database& db, + const std::string& resource_name, + const std::filesystem::path& source_file); + External_Resource_Status clear_table(SQLite::Database& db, + const std::string& resource_name); + [[nodiscard]] std::optional query_one( + SQLite::Database& db, + const std::string& resource_name, + const std::vector& primary_key_values) const; + [[nodiscard]] std::map> + query_aircraft(SQLite::Database& db, const std::string& icao24) const; + [[nodiscard]] std::map> + query_callsign(SQLite::Database& db, + const std::optional& callsign) const; + [[nodiscard]] std::vector status(SQLite::Database& db) const; + std::string ecap_sqlite_path; + + std::filesystem::path cache_pos_; +private: + [[nodiscard]] SQLite::Database& require_db() const; + External_Resources& get_resource(const std::string& resource_name) const; + std::vector update_all(SQLite::Database& db, + bool force_download, + bool only_when_empty); + std::unique_ptr db_; + std::vector> resources_; + mutable std::mutex mtx_; +}; diff --git a/module/Local_Server/State_Report/State_Report.cpp b/module/Local_Server/State_Report/State_Report.cpp new file mode 100644 index 0000000..3dd14a1 --- /dev/null +++ b/module/Local_Server/State_Report/State_Report.cpp @@ -0,0 +1,13 @@ +#include "State_Report.h" + +using namespace drogon; + +State_Report::State_Report() { + wm = Ws_Mgr::instance()->register_ws("/state_report"); +} + +void State_Report::push_state(Psc::JSON json) { + auto data = json.to_json_string(); + wm->push_data(data.data(), data.length()); +} + diff --git a/module/Local_Server/State_Report/State_Report.h b/module/Local_Server/State_Report/State_Report.h new file mode 100644 index 0000000..924beb4 --- /dev/null +++ b/module/Local_Server/State_Report/State_Report.h @@ -0,0 +1,22 @@ +#pragma once +#include "../global_include.h" +#include "../server/WebSocket_Manager.h" + +class State_Report : public Psc::Singleton { +public: + std::shared_ptr wm; + State_Report(); + void push_state(Psc::JSON json); +}; + + + +class With_State_Report { +public: + Psc::JSON state_json() { + return Psc::JSON::object(); + } + void report() { + State_Report::instance()->push_state(state_json()); + } +}; \ No newline at end of file diff --git a/module/Local_Server/global_include.h b/module/Local_Server/global_include.h new file mode 100644 index 0000000..d41fe26 --- /dev/null +++ b/module/Local_Server/global_include.h @@ -0,0 +1,419 @@ +#ifndef PSC_GLOBAL_INCLUDE_H +#define PSC_GLOBAL_INCLUDE_H +#include "Core/Statistics/Statistics.h" +#include "Core/socket/ByteOrder.h" +#include "SSR/export.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class Global; + +class Invalid_Http_Param final : public std::runtime_error { +public: + using std::runtime_error::runtime_error; +}; + +[[noreturn]] inline void throw_invalid_http_param(const char* detail) { + throw Invalid_Http_Param(detail); +} + + + +#define CHECK_JSON_PARAM \ +auto o_params = Psc::try_parse_json(req->body().data()); \ +if (!o_params.has_value()) { \ +throw_invalid_http_param("request body is not valid JSON"); \ +} \ +auto& params = o_params.value(); \ +auto that_json = ¶ms; + +#define HTTP_REQUIRE_VALUE(NAME, EXPRESSION) \ +auto o_http_##NAME = (EXPRESSION); \ +if (!o_http_##NAME.has_value()) { \ +throw_invalid_http_param(#NAME); \ +} \ +auto NAME = std::move(o_http_##NAME).value(); + +#define HTTP_REQUIRE_PTR(NAME, EXPRESSION) \ +auto NAME = (EXPRESSION); \ +if ((NAME) == nullptr) { \ +throw_invalid_http_param(#NAME); \ +} + +#define HTTP_REQUIRE_TRUE(EXPRESSION, DETAIL) \ +if (!(EXPRESSION)) { \ +throw_invalid_http_param(DETAIL); \ +} + + + + + +template +class Ordered_List { +public: + void swap(size_t i, size_t j) { + std::lock_guard g(mtx); + if (i >= _list.size() || j >= _list.size()) return; + + std::swap(_list[i], _list[j]); + } + + + + void push_back(Value_Type value) { + std::lock_guard g(mtx); + _list.push_back(value); // 添加默认值 + } + + void insert(int i, Value_Type value) { + std::lock_guard g(mtx); + _list.insert(_list.begin() + i, value); + } + + Value_Type get(size_t i) { + return _list[i]; + } + + void remove(size_t i) { + std::lock_guard g(mtx); + if (i >= _list.size()) return; + _list.erase(_list.begin() + i); + } + std::vector list(){ + std::lock_guard g(mtx); + return this->_list; + } + + void clear() { + list().clear(); + } +protected: + std::mutex mtx; + std::vector _list; +}; + + + +template +class Ordered_Map { +public: + + std::optional get(Key_Type key) { + std::lock_guard g(mtx); + auto it = _map.find(key); + if (it != _map.end()) { + return it->second; + } + return std::nullopt; + } + bool swap(size_t i, size_t j) { + std::lock_guard g(mtx); + if (i >= _list.size() || j >= _list.size()) return false; + + std::swap(_list[i], _list[j]); + + // 更新 map 中的 value,假设你可以从 Value 中获取 key + Key_Type key_i = _list[i]->key; + Key_Type key_j = _list[j]->key; + + _map[key_i] = _list[i]; + _map[key_j] = _list[j]; + return true; + } + + + + void push_back(Value_Type value) { + std::lock_guard g(mtx); + _list.push_back(value); // 添加默认值 + _map[value->key] = value; // 插入到 map + } + + bool insert(int i, Value_Type value) { + std::lock_guard g(mtx); + if (i < 0 || static_cast(i) > _list.size()) return false; + _list.insert(_list.begin() + i, value); + _map[value->key] = value; + return true; + } + + Value_Type get(size_t i) { + return _list[i]; + } + + std::optional try_get(size_t i) { + std::lock_guard g(mtx); + if (i >= _list.size()) return std::nullopt; + return _list[i]; + } + + bool remove(size_t i) { + std::lock_guard g(mtx); + if (i >= _list.size()) return false; + Key_Type& key = _list[i]->key; + _map.erase(key); + _list.erase(_list.begin() + i); + return true; + } + std::vector list(){ + std::lock_guard g(mtx); + return this->_list; + } + // std::map map(){ + // std::lock_guard g(mtx); + // return this->_map; + // } + void clear() { + list().clear(); + _map.clear(); + } +protected: + std::mutex mtx; + std::vector _list; + std::map _map; +}; + +class Mode_AC_Statistic_Data { +public: + Psc::JSON to_json() { + std::lock_guard g(mtx); + Psc::JSON ret = Psc::JSON::object(); + Ret_J(pre_second_num); + Ret_J(total_num); + Ret_J(length_error_num); + // Ret_J(speed); + return ret; + } + void add() { + std::lock_guard g(mtx); + add_inter(); + // speed.update(1); + } + void add_length_error() { + std::lock_guard g(mtx); + add_inter(); + length_error_num++; + } + +protected: + std::atomic length_error_num{}; + void add_inter() { + total_num++; + auto cur_time = std::time(nullptr); + if (cur_time != utc) + { + utc = cur_time; + pre_second_num = 0; + } + pre_second_num++; + } + std::mutex mtx; + size_t pre_second_num{}; + size_t total_num{}; + time_t utc{}; + // Psc::Speed_Statistics speed; +}; + + +class Statistic_Data { +public: + time_t utc{}; + size_t pre_second_num{}; + size_t total_num{}; + [[nodiscard]] Psc::JSON to_json() const { + Psc::JSON ret = Psc::JSON::object(); + Ret_J(pre_second_num); + Ret_J(total_num); + return ret; + } + Statistic_Data() = default; +}; + +class DF_Statistic_Data { +public: + time_t utc{}; + size_t pre_second_num{}; + size_t total_num{}; + size_t crc_error_num{}; + Psc::JSON to_json() { + Psc::JSON ret = Psc::JSON::object(); + Ret_J(pre_second_num); + Ret_J(total_num); + Ret_J(crc_error_num); + // Ret_J(speed); + + std::string t = "null"; + if (total_num != 0) { + t = std::to_string(static_cast(crc_error_num)/static_cast(total_num)) + "%"; + } + ret.append({"crc误码率", t}); + for (auto& cur : statistic_map) + { + ret.append({cur.first, cur.second.to_json()}); + } + return ret; + } + void add() { + add_inter(); + } + void add_crc_error() { + crc_error_num++; + } + void add_sub_part(const std::string& key) { + add_sub_part_inter(key); + } + + // Psc::Speed_Statistics speed; +protected: + void add_inter() { + total_num++; + auto cur_time = std::time(nullptr); + if (cur_time != utc) + { + utc = cur_time; + pre_second_num = 0; + } + pre_second_num++; + // speed.update(1); + } + + void add_sub_part_inter(const std::string& key) { + auto t = get_create_statistic_data(key); + t->total_num++; + auto cur_time = std::time(nullptr); + if (cur_time != t->utc) + { + t->utc = cur_time; + t->pre_second_num = 0; + } + t->pre_second_num++; + } + Statistic_Data* get_create_statistic_data(const std::string& key) { + Statistic_Data* t; + auto iter = statistic_map.find(key); + if (iter == statistic_map.end()) + { + Statistic_Data cur{}; + statistic_map.insert(std::make_pair(key, cur)); + } + t = &statistic_map[key]; + return t; + } + + std::map statistic_map; +}; + +class Mode_S_Statistic_Data { +public: + // Psc::Speed_Statistics speed; + + // Psc::Speed_Statistics total_speed() const { + // Psc::Speed_Statistics total_speed{}; + // for (auto& cur : DF_Statistic_Data_map) { + // total_speed += cur.second.speed; + // } + // return total_speed; + // } + Psc::JSON to_json() { + size_t total_num = get_total_num(); + size_t crc_error_num = get_crc_error_num(); + Psc::JSON ret = Psc::JSON::object(); + + + ret.append({"每秒数量", get_total_pre_second_num()}); + + Ret_J(length_error_num); + Ret_J(total_num); + + std::string t = "null"; + if (total_num != 0) { + t = std::to_string(static_cast(crc_error_num)/static_cast(total_num)) + "%"; + } + Ret_J(crc_error_num); + ret.append({"crc_error_rate", t}); + + + + + Psc::JSON df_sub_type = Psc::JSON::object(); + for (auto& cur : DF_Statistic_Data_map) + { + df_sub_type.append({Psc::to_string(cur.first) + " [" + std::to_string(static_cast(cur.first)) + "]", cur.second.to_json()}); + } + Psc::JSON cpr_error_o = Psc::JSON::object(); + for (auto& cur : cpr_error) + { + cpr_error_o.append({Psc::to_string(cur.first) + " [" + std::to_string(static_cast(cur.first)) + "]", Psc::to_string(cur.second)}); + } + ret.append({"DF子类型", df_sub_type}); + ret.append({"CPR统计信息", cpr_error_o}); + return ret; + } + + void add_length_error(const std::string& key) { + length_error_num++; + } + + void add_cpr_error(SSR::CPR_Error_Type cet) { + ++cpr_error[cet]; + } + + DF_Statistic_Data* get_create_df_statistic_data(const SSR::Downlink_Format& key) { + DF_Statistic_Data* t; + auto iter = DF_Statistic_Data_map.find(key); + if (iter == DF_Statistic_Data_map.end()) + { + DF_Statistic_Data cur{}; + DF_Statistic_Data_map.insert(std::make_pair(key, cur)); + } + t = &DF_Statistic_Data_map[key]; + return t; + } + + size_t get_total_pre_second_num() { + size_t ret = 0; + for (auto& cur : DF_Statistic_Data_map) { + ret += cur.second.pre_second_num; + } + return ret; + } + + size_t get_total_num() { + size_t ret = 0; + for (auto& cur : DF_Statistic_Data_map) { + ret += cur.second.total_num; + } + return ret; + } + size_t get_crc_error_num() { + size_t ret = 0; + for (auto& cur : DF_Statistic_Data_map) { + ret += cur.second.crc_error_num; + } + return ret; + } + + +protected: + std::atomic length_error_num{}; + std::map DF_Statistic_Data_map; + std::map cpr_error; +}; + + +template +class Immutable : public T { + +}; + +#endif diff --git a/module/Local_Server/lib9002/DDCSampTable.h b/module/Local_Server/lib9002/DDCSampTable.h new file mode 100644 index 0000000..93b554b --- /dev/null +++ b/module/Local_Server/lib9002/DDCSampTable.h @@ -0,0 +1,28 @@ +#ifndef DDCSAMPTABLE_H +#define DDCSAMPTABLE_H +#include + +// adsb +const double KDDCSampTab0[11][2] = {{24000000, 1}, {12000000, 2}, {6000000, 4}, {3000000, 8}, {1500000, 16}, {750000, 32}, {375000, 64}, {187500, 128}, {93750, 256}, {46875, 512}, {23437, 1024}}; +const std::string KDDCSampTabStr0[11] = {"24000000 ", "12000000 ", "6000000 ", "3000000 ", "1500000 ", "750000 ", "375000 ", "187500 ", "93750 ", "46875 ", "23437 "}; +const int KDDCSampIndxMin0 = 0; +const int KDDCSampIndxMax0 = 10; +const double define_KDDCSampleMax0 = 24000000; +const double X0 = 0.8; +const int ZDDCSampIndxMin0 = 0; +const int ZDDCSampIndxMax0 = 12; +const double ZDDCSampTab0[13] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; +const double TXSFTab0[11] = {24000000, 12000000, 6000000, 3000000, 1500000, 750000, 375000, 187500, 93750, 46875, 23437}; + +// less 30 mhz +const double KDDCSampTab1[11][2] = {{61440000, 1}, {30720000, 2}, {15360000, 4}, {7680000, 8}, {3840000, 16}, {1920000, 32}, {960000, 64}, {480000, 128}, {240000, 256}, {120000, 512}, {60000, 1024}}; +const std::string KDDCSampTabStr1[11] = {"61440000", "30720000", "15360000", "7680000", "3840000", "1920000", "960000", "480000", "240000", "120000", "60000"}; +const int KDDCSampIndxMin1 = 0; +const int KDDCSampIndxMax1 = 10; +const double define_KDDCSampleMax1 = 61440000; +const double X1 = 0.8; +const int ZDDCSampIndxMin1 = 0; +const int ZDDCSampIndxMax1 = 12; +const double ZDDCSampTab1[13] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; +const double TXSFTab1[11] = {61440000, 30720000, 15360000, 7680000, 3840000, 1920000, 960000, 480000, 240000, 120000, 60000}; +#endif // DDCSAMPTABLE_H diff --git a/module/Local_Server/server/Config.cpp b/module/Local_Server/server/Config.cpp new file mode 100644 index 0000000..29720ea --- /dev/null +++ b/module/Local_Server/server/Config.cpp @@ -0,0 +1,192 @@ +#include "Config.h" +#include "../../../../../core_library/Core/Core/Base/Check.h" +#include "Core/Net_Adapter/Net_Adapter.h" +#include "Global.h" +#include +#undef interface + +std::string default_config_path; + + +std::string get_config_path() { +#ifdef WIN32 + return "D:/ae/proj/projects/ECAP_Server/config/config.json"; +#endif + static bool first = true; + if (!default_config_path.empty()) return default_config_path; + std::string ret; + std::ostringstream oss; + std::string file_name = "config.json"; + ret = get_exe_dir() + "/" + file_name; + if (first) + { + std::cout << oss.str() << std::endl; + first = false; + } + return ret; +} + + + + +void Mode_ACS_Config::server(Global* g) { + auto& svr = g->svr; + auto& api = g->api; + data_source_config.server(g); + data_feed_config.server(g); + source_feed_relation_config.server(g); + + svr.Post(api + "get_mode_s_basic_config", [this](HTTP_Param) { + CHECK_JSON_PARAM + res->setBody(warp(to_base_json()).to_json_string()); + }); + svr.Post(api + "set_mode_s_basic_config", [this](HTTP_Param) { + CHECK_JSON_PARAM + auto& j = o_params.value(); + init_base_json(&j); + res->setBody(warp(to_base_json()).to_json_string()); + }); +} + + +void Device_Config::server(Global* g) { + auto& svr = g->svr; + auto& api = g->api; + svr.Post(api + "get_device_config", [this](HTTP_Param) { + res->setBody(warp(to_json()).to_json_string()); + }); + + svr.Post(api + "get_net_adapter_list", [this](HTTP_Param) { + JSON ret = JSON::object(); + auto arr = JSON::array(); + for (auto& it : Psc::get_net_adapter_info_map()) + { + arr.append(it.second.to_Json()); + } + ret.append({"list", arr}); + res->setBody(warp(ret).to_json_string()); + }); + + + svr.Post(api + "set_device_config", [this](HTTP_Param) { + CHECK_JSON_PARAM + JSON old_device_config; + { + + old_device_config = to_json(); + } + HTTP_REQUIRE_PTR(net, params.get("net")) + Net_Config device, wifi; + bool has_device = false; + bool has_wifi = false; + for (const auto& it : net->children) + { + HTTP_REQUIRE_VALUE(net_key, it.try_get_string("key")) + if (net_key == "device") + { + device.init_from_json(&it); + has_device = true; + } + if (net_key == "wifi") + { + wifi.init_from_json(&it); + has_wifi = true; + } + } + HTTP_REQUIRE_TRUE(has_device && has_wifi, "net") + + + bool it1 = check_ip_netmask_gateway(device.ip, device.netmask, device.gateway); + bool it2 = check_ip_netmask_gateway(wifi.ip, wifi.netmask, wifi.gateway); + bool p1 = check_port(device.port); + bool p2 = check_port(wifi.port); + if (!it1 || !it2 || !p1 || !p2) + { + server_logger->error("", {}, LOG_POS + " ip port! " + device.ip + ":" + std::to_string(device.port)); + res->setBody(warp(old_device_config).to_json_string()); + return; + } + + +#if WIN32 + bool use = false; +#else + bool use = true; +#endif + { + + auto& w = *this; + *w.list.get("device").value() = device; + *w.list.get("wifi").value() = wifi; + } + Global::save(); + if (use) + { + std::string interface; + { + std::string path = get_exe_dir() + "/interface"; + std::ifstream ifs(path); + if (!ifs.is_open()) + { + server_logger->error("", {}, LOG_POS + " 无法打开文件! " + path); + res->setBody(warp(old_device_config).to_json_string()); + return; + } + std::stringstream buffer; + buffer << ifs.rdbuf(); + interface = buffer.str(); + } + static auto set = [](std::string& interface, const std::string& token, const std::string& value) { + std::string var_name = "${" + token + "}"; + auto size = var_name.size(); + size_t pos = interface.find(var_name); + while (pos != std::string::npos) + { + interface.replace(pos, size, value); + pos = interface.find(var_name); + } + }; + set(interface, "ip", device.ip); + set(interface, "gateway", device.gateway); + set(interface, "netmask", device.netmask); + set(interface, "wifi_ip", wifi.ip); + set(interface, "wifi_gateway", wifi.gateway); + set(interface, "wifi_netmask", wifi.netmask); + std::cout << interface << std::endl; + std::string path = "/etc/network/interfaces"; + std::ofstream outfile(path); + if (!outfile.is_open()) + { + server_logger->error("", {}, LOG_POS + " 无法打开文件!" + path); + res->setBody(warp(old_device_config).to_json_string()); + return; + } + outfile << interface; + outfile.close(); + std::string bash_path = get_exe_dir() + "/restart_net_service.sh"; + if (!std::filesystem::exists(bash_path)) + { + server_logger->error("", {}, LOG_POS + " !" + bash_path); + res->setBody(warp(old_device_config).to_json_string()); + return; + } + int result = system(bash_path.c_str()); + if (result != 0) + { + server_logger->error("", {}, LOG_POS + " 脚本执行失败!" + bash_path); + res->setBody(warp(old_device_config).to_json_string()); + return; + } + } + res->setBody(warp(params).to_json_string()); + }); +} + + +void Config::save() { + std::ofstream config_file; + config_file.open(get_config_path()); + std::string json = Global::instance()->toJson().to_json_string(); + config_file.write(json.c_str(), static_cast(json.size())); + config_file.close(); +} diff --git a/module/Local_Server/server/Config.h b/module/Local_Server/server/Config.h new file mode 100644 index 0000000..e872878 --- /dev/null +++ b/module/Local_Server/server/Config.h @@ -0,0 +1,357 @@ +#ifndef CONFIG_H_H +#define CONFIG_H_H +#include "../DSP/export.h" +#include "../Data_Feed/export.h" +#include "Core/spdlog/export.h" +#include "../Data_Source/export.h" +#include "MLAT.h" +#include "Source_Feed_Relation.h" + +#include +inline bool delete_log = false; + +extern std::string default_config_path; +std::string get_config_path(); + +struct Log_Config { + DELETE_COPY(Log_Config) + Log_Config() = default; + ~Log_Config() { + if (delete_log) std::cout << "~Log_Config()" << std::endl; + } + enum class Open_Mode { + Append, + Delete, + Rename + }; + Open_Mode open_mode = Open_Mode::Rename; + std::uint16_t piece_num{}; + std::uint16_t size_MB{}; + void init(const Psc::JSON* that_json) { + open_mode = Psc::to_enum(that_json->get_string("open_mode")); + Get_J(piece_num) + Get_J(size_MB) + } + [[nodiscard]] Psc::JSON to_json() const { + Psc::JSON ret = Psc::JSON::object(); + Ret_J(open_mode); + Ret_J(piece_num); + Ret_J(size_MB); + return ret; + } +}; + +struct Console_Config { + DELETE_COPY(Console_Config) + Console_Config() = default; + ~Console_Config() { + if (delete_log) std::cout << "~Console_Config()" << std::endl; + } + bool record_playback; + bool mode_s_console; + bool post_request; + bool mlat_server; + void init(const Psc::JSON* that_json) { + Get_J(record_playback) + Get_J(mode_s_console) + Get_J(post_request) + Get_J(mlat_server) + } + [[nodiscard]] Psc::JSON to_json() const { + Psc::JSON ret = Psc::JSON::object(); + Ret_J(record_playback) + Ret_J(mode_s_console) + Ret_J(post_request) + Ret_J(mlat_server) + return ret; + } +}; + +struct Http_Monitor_Config { + bool access_log = true; + std::size_t slow_request_threshold_ms = 1000; + std::size_t slow_scope_threshold_ms = 100; + + void init(const Psc::JSON* that_json) { + if (!that_json) return; + Get_J(access_log) + Get_J(slow_request_threshold_ms) + Get_J(slow_scope_threshold_ms) + } + + [[nodiscard]] Psc::JSON to_json() const { + Psc::JSON ret = Psc::JSON::object(); + Ret_J(access_log) + Ret_J(slow_request_threshold_ms) + Ret_J(slow_scope_threshold_ms) + return ret; + } +}; + + + + + +struct Mode_ACS_Config { + DELETE_COPY(Mode_ACS_Config) + std::atomic timeout_seconds{}; + std::atomic max_track_point_size{}; + std::atomic max_speed_m_s{}; + std::atomic air_pos_timeout = 8; + std::atomic surface_pos_timeout = 32; + // static I air_time = 8; + // static I surface_time = 8 * 4; + std::atomic read_milliseconds{}; + std::atomic mode_s_max_num{}; + std::atomic mode_other_max_num{}; + std::atomic report_data_feed_msg_mum{}; + std::atomic Report_Data_Feed_Message_Num{}; + std::atomic default_min_aircraft_list_num{}; + + std::atomic ignore_df_11{}; + std::atomic monitor_msg_live{}; + + + + Data_feed_Config data_feed_config; + Data_Source_Config data_source_config; + Source_Feed_Relation_Config source_feed_relation_config; + Mode_ACS_Config() = default; + + ~Mode_ACS_Config() { + if(delete_log) std::cout << " ~Mode_S_Config()" << std::endl; + } + + + Psc::JSON to_base_json() const { + Psc::JSON ret = Psc::JSON::object(); + Ret_J(timeout_seconds) + Ret_J(max_speed_m_s) + Ret_J(air_pos_timeout) + Ret_J(surface_pos_timeout) + Ret_J(read_milliseconds) + return ret; + } + + void init_base_json(const Psc::JSON* that_json) { + Get_J(timeout_seconds) + Get_J(max_speed_m_s) + Get_J(air_pos_timeout) + Get_J(surface_pos_timeout) + Get_J(read_milliseconds) + } + + + + + + + + void init(const Psc::JSON* that_json) { + init_base_json(that_json); + Get_J(max_track_point_size) + Get_J(mode_s_max_num) + Get_J(mode_other_max_num) + Get_J(report_data_feed_msg_mum) + Get_J(default_min_aircraft_list_num) + Get_J(ignore_df_11) + Get_J(monitor_msg_live) + + data_feed_config.init(that_json->get("data_feed")); + data_source_config.init(that_json->get("data_source")); + source_feed_relation_config.from_json(that_json->get("source_feed_relation")); + if (monitor_msg_live) { + SSR::Monitor_Mode_ACS_Message_Num = this->monitor_msg_live; + } + } + + Psc::JSON to_json() { + Psc::JSON ret = to_base_json(); + Ret_J(max_track_point_size) + Ret_J(mode_s_max_num) + Ret_J(mode_other_max_num) + Ret_J(report_data_feed_msg_mum) + Ret_J(default_min_aircraft_list_num) + Ret_J(ignore_df_11) + Ret_J(monitor_msg_live) + // Ret_J(aircraft_csv_path) + + ret.append(Psc::JSON("data_feed", data_feed_config.to_json())); + ret.append(Psc::JSON("data_source", data_source_config.to_json())); + ret.append(Psc::JSON("source_feed_relation", source_feed_relation_config.to_json())); + return ret; + } + void server(Global* g); +}; + + + +struct Web_Server_Config { + Web_Server_Config() = default; + [[nodiscard]] std::string get_true_webapp() const { + return Psc::get_abs_path(webapp); + } + [[nodiscard]] std::string get_true_tiles() const { + return Psc::get_abs_path(tiles); + } + Psc::JSON to_json() { + Psc::JSON ret = Psc::JSON::object(); + Ret_J(webapp) + Ret_J(tiles) + return ret; + } + void init(const Psc::JSON* that_json) { + Get_J(webapp) + Get_J(tiles) + } +protected: + std::string webapp; + std::string tiles; +}; + +struct Net_Config { + std::string key; + std::string ip; + std::uint16_t port{}; + std::string netmask; + std::string gateway; + Net_Config() = default; + [[nodiscard]] Psc::JSON to_json() const { + Psc::JSON ret = Psc::JSON::object(); + Ret_J(key) + Ret_J(ip) + Ret_J(netmask) + Ret_J(gateway) + Ret_J(port) + return ret; + } + void init_from_json(const Psc::JSON* that_json) { + Get_J(key) + Get_J(ip) + Get_J(netmask) + Get_J(gateway) + Get_J(port) + } +}; + +struct Device_Config { + Ordered_Map list; + + ~Device_Config() { + if (delete_log) std::cout << "~Device_Config()" << std::endl; + for (auto it : list.list()) { + delete it; + } + list.clear(); + } + + + Psc::JSON to_json() { + Psc::JSON ret = Psc::JSON::object(); + Psc::JSON net = Psc::JSON::array(); + for (auto& li : list.list()) { + net.append(li->to_json()); + } + ret.append({"net", net}); + return ret; + } + + Device_Config() = default; + void init(const Psc::JSON* that_json) { + for (auto& li : that_json->get("net")->children) + { + auto cur = new Net_Config(); + cur->init_from_json(&li); + list.push_back(cur); + } + } + + Psc::JSON to_net_json() { + Psc::JSON ret = Psc::JSON::object(); + Psc::JSON net = Psc::JSON::array(); + for (auto& li : list.list()) { + net.append(li->to_json()); + } + ret.append({"net", net}); + return ret; + } + void server(Global* g); +}; + + + + +class Config { +public: + Config() = default; + DELETE_COPY(Config) + MLAT_Config mlat; + Device_Config device_config; + Web_Server_Config web_server_config; + Mode_ACS_Config mode_acs; + Log_Config log_config; + Console_Config console_config{}; + DSP_Config dsp_config; + Psc::JSON drogon_config; + Http_Monitor_Config http_monitor_config; + std::string version; + External_Resources_Manager external_resources_manager; + static Psc::JSON load() { + std::string config_path = get_config_path(); + + std::ifstream iso(config_path); + if (!iso.is_open()) + { + std::cerr << config_path << " can not open!" << std::endl; + Psc::fail_fast(); + } else { + std::cout << get_current_date_string() << " 启动加载配置文件: 【" << config_path << "】" << std::endl; + } + std::stringstream ss; + std::stringstream buffer; + buffer << iso.rdbuf(); + std::string fileContents = buffer.str(); + return Psc::parse_json(fileContents); + } + + void fromJson(Psc::JSON* that_json) { + Get_J(version) + mlat.init(that_json->get("mlat")); + web_server_config.init(that_json->get("web_server")); + device_config.init(that_json->get("device")); + mode_acs.init(that_json->get("mode_acs")); + console_config.init(that_json->get("console")); + dsp_config.init(that_json->get("dsp")); + drogon_config = *that_json->get("drogon"); + http_monitor_config.init(that_json->get("http_monitor")); + external_resources_manager.init(that_json->get("external_database")); + } + + Psc::JSON toJson() { + auto ret = Psc::JSON::object({ + {"version", version}, + {"dsp", dsp_config.to_json()}, + {"drogon", drogon_config}, + {"http_monitor", http_monitor_config.to_json()}, + {"mlat", mlat.to_json()}, + {"web_server", web_server_config.to_json()}, + {"device", device_config.to_json()}, + {"mode_acs", mode_acs.to_json()}, + //{"ais", ais.to_json()}, + {"log", log_config.to_json()}, + {"console", console_config.to_json()}, + {"external_database", external_resources_manager.to_json()}, + }); + + return ret; + } + static void save(); +}; + + + + + + + +#endif diff --git a/module/Local_Server/server/Global.cpp b/module/Local_Server/server/Global.cpp new file mode 100644 index 0000000..7c9a94a --- /dev/null +++ b/module/Local_Server/server/Global.cpp @@ -0,0 +1,385 @@ +#include "Global.h" +#include +#include +#include +#include +#include + + + + + +BaseLogger* server_logger = nullptr; +Debug_Logger_Info_Manager debug_logger_info_manager; + +void Global::handle_old_logs() { + auto mode = log_config.open_mode; + std::string dirPath = get_exe_dir() + "/" + "logs"; + namespace fs = std::filesystem; + try { + switch (mode) { + case Log_Config::Open_Mode::Rename: { + auto now = std::chrono::system_clock::now(); + auto in_time_t = std::chrono::system_clock::to_time_t(now); + std::ostringstream oss; + oss << std::put_time(std::localtime(&in_time_t), "%Y-%m-%d_%H-%M-%S"); + fs::path newDirPath = dirPath + "_" + oss.str(); + if (fs::exists(newDirPath)) { + std::cout << "New directory name already exists!" << std::endl; + return; + } + fs::rename(dirPath, newDirPath); + std::cout << "Directory renamed to: " << newDirPath << std::endl; + break; + } + case Log_Config::Open_Mode::Delete: { + if (fs::exists(dirPath)) { + fs::remove_all(dirPath); // 删除目录及其所有内容 + std::cout << "Directory and its contents deleted: " << dirPath << std::endl; + } + if (fs::create_directories(dirPath)) { + std::cout << "Directory created: " << dirPath << std::endl; + } else { + std::cout << "创建目录失败: " << dirPath << std::endl; + Psc::fail_fast(); + } + fs::permissions(dirPath, fs::perms::owner_all | fs::perms::group_all | fs::perms::others_all); + break; + } + case Log_Config::Open_Mode::Append: break; + default: std::cerr << "未知的打开模式!" << std::endl; + break; + } + } catch (const std::exception& ex) { + std::cerr << "Error: " + Psc::platform_2_utf8(ex.what()) + "\n"; + } +} + + +Global::Global() { + + + auto j = load(); + log_config.init(j.get("log")); + handle_old_logs(); + Base_Logger_Manager::instance()->set_thread_num(1).set_flush_seconds(3).init(); + int piece_num = log_config.piece_num; + int size_MB = log_config.size_MB; + int MB = 1024 * 1024; + asio_socket::socket_logger = new BaseLogger("@/logs/socket", MB * size_MB, piece_num); + serial::serial_logger = new BaseLogger("@/logs/serial", MB * size_MB, piece_num); + SSR::mode_s_logger = new BaseLogger("@/logs/mode_s", MB * size_MB * 10, piece_num); + dsp_logger = new BaseLogger("@/logs/dsp", MB * size_MB, piece_num); + //libais::libais_logger = new BaseLogger("@/logs/libais", MB * size_MB, piece_num); + server_logger = new BaseLogger("@/logs/server", MB * size_MB, piece_num); + asio_socket::socket_logger->set_redirect([](const BaseLogger::Log_Info& log_info) { + auto msg = "[" + std::string("func") + "~" + log_info.func_pattern + "] " + log_info.log_type.to_string() + + log_info.content; + debug_logger_info_manager.push_info(msg); + }); + serial::serial_logger->set_redirect([](const BaseLogger::Log_Info& log_info) { + auto msg = "[" + std::string("func") + "~" + log_info.func_pattern + "] " + log_info.log_type.to_string() + + log_info.content; + debug_logger_info_manager.push_info(msg); + }); + fromJson(&j); + +#ifdef Cache_Some_Mode_S + auto old_parse_ok_json = SSR::parse_ok_json; + SSR::parse_ok_json = [old_parse_ok_json](Aircraft_Info* aircraft_info, SSR::P_S mode_s_msg, Psc::JSON json) { + old_parse_ok_json(aircraft_info, mode_s_msg, json); + auto f = static_cast(aircraft_info); + f->add_msg_limit(mode_s_msg); + }; +#endif + + + SSR::cpr_cb = [](SSR::CPR_Error_Type t, const std::string& log, SSR::P_S msg) { + auto src = std::dynamic_pointer_cast(msg->source); + Mode_S_Statistic_Data* ss = &src->mode_s_statistic; + if (t != SSR::CPR_Error_Type::Normal) { + ss->add_cpr_error(t); + } + SSR::mode_s_logger->debug("CPR/"+ to_string(t), {}, log); + }; + // 处理错误 + SSR::parse_call_back = [this](SSR::Parse_Call_Back_Type type, SSR::Aircraft_Info* info, + const std::string& field_name, std::vector bds_list, void*, SSR::P_S msg) { + auto src = std::dynamic_pointer_cast(msg->source); + Mode_S_Statistic_Data* ss = &src->mode_s_statistic; + if (type == SSR::Parse_Call_Back_Type::Unknown_DF) { + //std::cout << "Unknown DF type!" << (int)(msg->df) << std::endl; + return; + } + DF_Statistic_Data* dfs = ss->get_create_df_statistic_data(msg->df); + dfs->add(); + if (type == SSR::Parse_Call_Back_Type::Normal_Block) { + dfs->add_sub_part(field_name); + info->update(msg); + } else if (type == SSR::Parse_Call_Back_Type::CRC_Error) { + dfs->add_crc_error(); + //std::cout << field_name << " :crc_error msg:" << msg->msg_hex << " df:" << (int)msg->df << std::endl; + } else if (type == SSR::Parse_Call_Back_Type::Length_Error) { + ss->add_length_error(field_name); + //std::cout << field_name << " :length_error msg:" << msg->msg_hex << " df:" << (int)msg->df << std::endl; + } + + //else if (type == Mode_S::Parse_Call_Back_Type::UNKNOWN_ERROR) {} else {} + }; + auto str = toJson().to_json_string(); + server_logger->debug("启动", {}, str); + SSR::mode_s_logger->debug("启动", {}, str); + //libais::libais_logger->debug("启动", {}, str); + std::cout << str << std::endl; + // libais::log = normal_log; + // libais::log = ais_log; + // mode_s_log_info = mode_s_log; + init_web_server(); +} +Global::~Global() { + std::cout << "Global::~Global()" << std::endl; +} + +void replace(std::string& originalStr, const std::string& findStr, const std::string& replaceStr) { + size_t pos = originalStr.find(findStr); + while (pos != std::string::npos) { + originalStr.replace(pos, findStr.length(), replaceStr); + pos = originalStr.find(findStr, pos + replaceStr.length()); + } +} +std::string oneLine(std::string str) { + replace(str, "\n", "[n]"); + return str; +} +bool isHexadecimal(const std::string& str) { + return std::all_of(str.begin(), str.end(), [](unsigned char c) { + return std::isdigit(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); + }); +} +void handle_buffer_muti_start(std::string& buffer, const std::string& data, const std::set& prefix_list, + const std::function& callback) { + if (!data.empty()) { + buffer += data; + // std::cout << "[data]:" + data + "\n"; + // std::cout << "[buffer]:" + buffer + "\n"; + while (!buffer.empty() && buffer.back() == '\n') { + buffer.pop_back(); + } + while (true) { + std::string c; + size_t pos = 0, n = buffer.size(); + for (; pos < n; pos++) { + bool find = false; + for (const std::string& prefix : prefix_list) { + if (pos + prefix.size() <= n) { + if (buffer.substr(pos, prefix.size()) == prefix) { + c = prefix; + find = true; + break; + } + } + } + if (find) break; + } + if (pos == n) break; + std::string line = c + buffer.substr(0, pos); // 截取从开头到!之前的数据 + buffer = buffer.substr(pos + 1); // 更新buffer为剩余数据 + // std::cout << "[line]:" + line + "\n"; + if (pos != 0) callback(line); + } + } +} +void handle_buffer_head_tail(std::string& buffer, const std::string& data, const std::string& prefix, + const std::string& suffix, const std::function& callback) { + // 只在数据可用时进行读取 + if (!data.empty()) { + buffer += data; + size_t pos; + while ((pos = buffer.find_first_of(suffix)) != std::string::npos) { + size_t start = buffer.find_first_of(prefix); + if (start == std::string::npos) break; + std::string packet = buffer.substr(start + 1, pos - start - 1); + buffer.erase(0, pos + 1); + // 处理尾部空格 + while (!buffer.empty() && buffer.back() == '\n') { + buffer.pop_back(); + } + if (!packet.empty()) { + callback(packet); + } + } + } +} +void DataBase::handle_HULC(const std::string& packet) { + std::uint8_t len = SSR::get_len(packet); + std::uint8_t id = SSR::get_id(packet); + auto msg = mem2hex(packet); + + if (len != packet.size() - 4) { + SSR::mode_s_logger->debug("HULC/error_length", {}, + "需要: " + std::to_string(len) + " 当前: " + std::to_string(packet.size()) + " hex: " + + mem2hex(packet)); + return; + } + if (id == 1) { + // 状态消息 + auto status_msg = SSR::create_HULC_Status_Message(packet); + bool gps_ok = status_msg.GPS_device_detected() && status_msg.GPS_valid() && status_msg.GPS_has_valid_fix(); + if (gps_ok) { + + } + auto g = Global::instance(); + base_station.set_msg(status_msg); + Log_Type type({}, {{"msg", msg}}); + SSR::mode_s_logger->debug("HULC/status", type, status_msg.toJson().to_json_string()); + if (gps_ok) { + + } + } else if (id == 24) { + SSR::mode_s_logger->debug("HULC/reply", {}, msg); + } else { + SSR::mode_s_logger->debug("HULC/unknown_id", {}, msg); + } +} + +void read_ais_serial_data(std::atomic& running) { + // static int t = config.ais.read_serial_milliseconds; + // static bool ais_log = config.console_config.ais_serial; + // static bool use_ais_serial = !config.ais_mock.enable || config.ais_mock.use_real_serial; + // static auto lm = Light_Manager::instance(); + // serial::Serial* ais_serial{}; + // if (use_ais_serial) ais_serial = create_serial(config.ais.port_name, config.ais.baud_rate); + // libais::VdmStream stream; + // std::string ais_buffer; + // while (running.load(std::memory_order_acquire) == true) + // { + // std::string ais_data = use_ais_serial ? ais_serial->read() : mock_ais_serial.read(); + // if (!ais_data.empty()) + // { + // if (ais_log && !ais_data.empty()) + // { + // std::cout << "read:[ais_serial]:" << ais_data << std::endl; + // } + // libais::libais_logger->debug("ais_serial_read/ais_serial_read", {}, ais_data + "\n"); + // handle_buffer_muti_start(ais_buffer, ais_data, {"!", "$"}, [&](std::string& line) { + // lm->light_control(Light_Type::AIS, true); + // stream.AddLine(line); + // while (auto msg = stream.PopOldestMessage()) + // { + // parse_ais(msg.get()); + // } + // lm->light_control(Light_Type::AIS, false); + // }); + // } + // std::this_thread::sleep_for(std::chrono::milliseconds(t)); + // } + // delete ais_serial; +} +bool is_10004(SSR::Mode_S_Msg& msg) { + bool DF_11_17_18 = msg.df == SSR::Downlink_Format::All_Call_Reply_11 || msg.df == SSR::Downlink_Format::Extended_Squitter_17 || msg.df + == SSR::Downlink_Format::Extended_Squitter_Non_Transponder_18; + return DF_11_17_18; +} + +std::string to_file_name(std::string str) { + // 定义允许的合法字符 + auto is_valid_char = [](char c) { + return std::isalnum(c) || c == '_' || c == '-' || c == '.'; // 允许字母、数字、下划线、连字符、点 + }; + // 替换非法字符为下划线 '_' + std::transform(str.begin(), str.end(), str.begin(), [&](char c) { return is_valid_char(c) ? c : '_'; }); + // 检查结果字符串是否全是替换字符,防止生成全是下划线的文件名 + if (str.find_first_not_of('_') == std::string::npos) { + return "default_file_name"; // 返回一个默认文件名 + } + return str; +} +void Debug_Logger_Info_Manager::push_info(const std::string& c) { + std::lock_guard g(mtx); + std::string content = std::to_string(cur_serial_number) + ": " + c; + size_t content_length = content.size(); + info_list.push_back({cur_serial_number, content}); + current_total_length += content_length; + while (current_total_length > max_length && !info_list.empty()) { + current_total_length -= info_list.front().content.size(); + info_list.pop_front(); // 删除最早的记录 + } + cur_serial_number++; +} +Serial_Number_Type Debug_Logger_Info_Manager::get_cur_serial_number() { + std::lock_guard g(mtx); + return cur_serial_number; +} +JSON Debug_Logger_Info_Manager::to_json() { + JSON ret = JSON::object(); + ret.append({"cur_serial_number", cur_serial_number}); + return ret; +} +bool Web_Server::listen(const std::string &host, int port) { + drogon::HttpAppFramework* app = &drogon::app(); + auto g = Global::instance(); + Json::Value drogon_config; + { + auto jsonStr = g->drogon_config.to_json_string(); + std::cout << "drogon::app().run(); " << jsonStr << std::endl; + Json::CharReaderBuilder builder; + std::string errs; + auto reader = builder.newCharReader(); + if (!reader->parse(jsonStr.c_str(), jsonStr.c_str() + jsonStr.size(), &drogon_config, &errs)) { + // 解析失败 + std::cout << "drogon 配置文件加载失败!json格式解析失败!" << jsonStr << std::endl; + Psc::fail_fast(); + } + delete reader; + } + app->loadConfigJson(drogon_config); + app->disableSigtermHandling(); //关闭服务器信号处理 + app->addListener(host, port); + auto base_dir = get_exe_dir(); + // app->setLogPath(base_dir + "/logs/drogon.log"); + app->setUploadPath(base_dir + "/drogon_uploads"); + app->run(); + return true; +} + +std::string Debug_Logger_Info_Manager::get_info(Serial_Number_Type serial_number) { + std::lock_guard g(mtx); + std::string result; + if (serial_number == cur_serial_number) { + return ""; + } + // 从后向前遍历 data 列表 + for (auto it = info_list.rbegin(); it != info_list.rend(); ++it) { + // std::cout << "max_length: " << max_length << " size: " << info_list.size() << " serial_number " << + // serial_number << "cur_sequence" << it->sequence << " content.size" << it->content.size() << std::endl; + if (it->sequence >= serial_number) { + result = it->content + result; // 叠加 content + } else { + break; + } + } + return result; +} + + +std::string inet_address_to_string(const trantor::InetAddress &addr) +{ + char buf[INET6_ADDRSTRLEN] = {0}; + + if (!addr.isIpV6()) + { + // IPv4 + auto sa = reinterpret_cast(addr.getSockAddr()); + inet_ntop(AF_INET, &(sa->sin_addr), buf, sizeof(buf)); + uint16_t port = ntohs(sa->sin_port); + return std::string(buf) + ":" + std::to_string(port); + } + else + { + // IPv6 + auto sa6 = reinterpret_cast(addr.getSockAddr()); + inet_ntop(AF_INET6, &(sa6->sin6_addr), buf, sizeof(buf)); + uint16_t port = ntohs(sa6->sin6_port); + return "[" + std::string(buf) + "]:" + std::to_string(port); + } +} diff --git a/module/Local_Server/server/Global.h b/module/Local_Server/server/Global.h new file mode 100644 index 0000000..21e52be --- /dev/null +++ b/module/Local_Server/server/Global.h @@ -0,0 +1,239 @@ +#pragma once + + + +#include "Core/Base/ThreadManager.h" +#include "../Data_Source/export.h" +#include "../State_Report/State_Report.h" +#include "../global_include.h" +#include "Config.h" +#include + +#include "Config.h" + +#include "../../Radarcape_Core/cpp-httplib/httplib.h" +#include "../Data_Source/export.h" +#include "Core/Net_Adapter/Net_Adapter.h" +#include "libarchive.h" +#include +#include +#include + +// 集中 管理日志 +using namespace Psc; +extern BaseLogger* server_logger; +std::string to_file_name(std::string str); +std::string inet_address_to_string(const trantor::InetAddress &addr); + +using Serial_Number_Type = unsigned int; +struct Debug_Logger_Info_Manager { + void push_info(const std::string& content); + std::string get_info(Serial_Number_Type serial_number); + Serial_Number_Type get_cur_serial_number(); + struct Info { + Serial_Number_Type sequence; + std::string content; + }; + std::list info_list; + JSON to_json(); +private: + // 最大总长度 + static constexpr size_t max_length = 1000 * 300; + // 当前总长度 + size_t current_total_length = 0; + Serial_Number_Type cur_serial_number = 0; + std::mutex mtx; +}; +extern Debug_Logger_Info_Manager debug_logger_info_manager; + + + +#define RET_OK \ + res.status = StatusCode::OK_200; \ + res.set_content("{\"status\": 200}", "application/json"); + inline JSON warp(const JSON& data) { + // Json ret = Json::object(); + // ret.append({"status", 200}); + // ret.append({"data", data}); + // return ret; + return data; +} + + + +#define HTTP_Param const drogon::HttpRequestPtr& req, const drogon::HttpResponsePtr& res + +class Web_Server { +public: + std::string update = "update_"; + std::string insert = "insert_"; + std::string remove = "remove_"; + std::string search = "search_"; + std::string rise = "rise_"; + std::string fall = "fall_"; + using Handler = std::function; + bool listen(const std::string& host, int port); + + ~Web_Server() = default; + + + + + + static void stop() { + std::cout << "开始停止web服务" << std::endl; + drogon::app().quit(); + } + + Web_Server& Post(const std::string& pattern, Handler handler) { + drogon::app().registerHandler( + pattern, + [handler](const drogon::HttpRequestPtr& request, + std::function&& callback) { + auto resp = drogon::HttpResponse::newHttpResponse(); + resp->setContentTypeCode(drogon::CT_APPLICATION_JSON); + + handler(request, resp); + + callback(resp); + }, + {drogon::Post} + ); + + return *this; + } + + Web_Server& Get(const std::string& pattern, Handler handler) { + drogon::app().registerHandlerViaRegex( + pattern, + [handler](const drogon::HttpRequestPtr& request, + std::function&& callback) { + auto resp = drogon::HttpResponse::newHttpResponse(); + resp->setContentTypeCode(drogon::CT_APPLICATION_JSON); + + handler(request, resp); + + callback(resp); + }, + {drogon::Get} + ); + + return *this; + } +}; + + +// 这个对象不释放 + + + + + +class Mlat_MSG { +public: + explicit Mlat_MSG(const std::shared_ptr& first) { list.push_back(first);} + [[nodiscard]] std::optional icao() const { + auto a = list[0]; + auto t = a->type; + if (t == SSR::Mode_Msg::T::S7 || t == SSR::Mode_Msg::T::S14) { + return dynamic_cast(a.get())->icao; + } + return std::nullopt; + } + [[nodiscard]] std::string msg_hex() const { return list[0]->msg_hex;} + [[nodiscard]] SSR::Mode_Msg::T type() const { return static_cast(list[0]->type);} + [[nodiscard]] SSR::MLAT_timestamp& timestamp() const { return list[0]->mlat_timestamp;} + [[nodiscard]] std::shared_ptr data_source() const { return list[0]->source;} + void add(const std::shared_ptr& t) { + list.push_back(t); + } + [[nodiscard]] size_t size() const { return list.size(); } + std::vector> list; +}; + + + + + +class Mlat_Handler { +public: + std::list get_all() { + std::lock_guard gg(ok_mtx); + if (ok_list.empty()) return {}; + std::list ret; + std::swap(ok_list, ret); + return ret; + } + + void push(const std::shared_ptr& msg) { + std::lock_guard g(mtx); + + if (list.empty()) { + list.emplace_back(msg); + return; + } + + auto time = msg->mlat_timestamp; + auto p = list.rbegin(); + + while (p != list.rend()) { + auto cur_time = p->timestamp(); + // 往前最多找3秒 + if (cur_time.daysec + 3 < time.daysec) { + std::lock_guard gg(ok_mtx); + ok_list.splice(ok_list.end(), list, list.begin(), p.base()); + return; + } + if (p->msg_hex() == msg->msg_hex) { + p->add(msg); + return; + } + ++p; + } + list.insert(p.base(), Mlat_MSG(msg)); + } +protected: + std::list ok_list; + std::list list; + std::mutex ok_mtx; + std::mutex mtx; +}; + + + + + +class Global : public Config, public Singleton{ +public: + // asio::io_context ctx; + std::atomic init_ok{false}; + Global(); + ~Global(); + Detach_Thread_Manager thread_manager; + std::shared_ptr source(const std::string& data_source_key) { + return mode_acs.data_source_config.map.get(data_source_key).value_or(nullptr); + } + std::shared_ptr total_source() { + for (auto i : mode_acs.data_source_config.map.list()) + { + if (i->enable) return i; + } + return mode_acs.data_source_config.map.list().at(0); + } + Web_Server svr; + std::string api = "/api/"; + Mlat_Handler mlat_handler; + void init_web_server(); + void handle_old_logs(); + std::time_t start_server_time; + DELETE_COPY(Global) +}; + +void data_feed_thread(std::atomic& running); + + +void handle_buffer_muti_start(std::string& buffer, const std::string& data, const std::set& prefix_list, + const std::function& callback); +void handle_buffer_head_tail(std::string& buffer, const std::string& data, const std::string& prefix, + const std::string& suffix, const std::function& callback); + diff --git a/module/Local_Server/server/MLAT.cpp b/module/Local_Server/server/MLAT.cpp new file mode 100644 index 0000000..0e57948 --- /dev/null +++ b/module/Local_Server/server/MLAT.cpp @@ -0,0 +1,194 @@ +#include "MLAT.h" + +#include "Global.h" + +#include + +time_t datetime_to_timestamp(const std::string& datetime) { + std::tm tm = {}; + std::istringstream ss(datetime); + ss >> std::get_time(&tm, "%Y-%m-%d %H:%M:%S"); + if (ss.fail()) { + throw std::runtime_error("时间格式错误"); + } + // std::mktime按本地时区转换 + return std::mktime(&tm); +} + +std::multimap hex_mlat_map; +std::vector read_lines() { + Base_Logger_Manager::instance()->init(); + + std::multimap ordered_multimap; + std::ifstream fin("C:/wyc/CLionProjects/plantSunCat/mainProjects/Radarcape/data/0701/info.txt"); + if (!fin) { + std::cerr << "无法打开文件!" << std::endl; + return {}; + } + std::string line; + while (std::getline(fin, line)) { + if (line.empty()) continue; + + std::vector fields; + std::stringstream ss(line); + std::string item; + while (std::getline(ss, item, ';')) { + fields.push_back(item); + } + // 检查字段数 + if (fields.size() < 9) continue; + // 2025-07-03 10:16:21;VG_MSDW;28069B;2025-06-27 08:00:14;A800103FFF9CCB27FFFCA89DE0D3;121.691398;37.344925;8000;;0000;2_1_3 + // 按 1-base 提取 + std::string icao = fields[2]; + icao.resize(6, '_'); + std::string msg = fields[4]; + std::string lon = fields[5]; + std::string lat = fields[6]; + + + + std::string time = fields[3]; + std::string hex = fields[4]; + // 输出(或者你可以存到 vector 里) + // std::cout << icao << " " << lat << " " << lon << " " << alt << std::endl; + + Base_MLAT_Data b; + //cur.icao = icao; + b.mlat_data.lon = stod(lon); + b.mlat_data.lat = stod(lat); + b.msg = line; + b.hex = hex; + b.icao = icao; + strncpy(b.mlat_data.icao, icao.c_str(), 6); + //std::cout << cur.lat << " " << cur.lon << std::endl; + // if (35 < cur.lat && cur.lat < 37 + // && + // 120 < cur.lon && cur.lon < 122 + // ) { + // + // pure_log("@/logs/mlat_.log", line + "\n"); + // } + ordered_multimap.insert({datetime_to_timestamp(time), b}); + + } + std::vector list; + for (auto it : ordered_multimap) { + Base_MLAT_Data& b = it.second; + list.push_back(b.mlat_data); + auto icao = std::string(b.mlat_data.icao, 6); + // if (icao == "78139F") { + // pure_log("@/logs/icao/" + icao + "_mlat_result.log", b.msg + "\n"); + // } + hex_mlat_map.insert({b.hex, b}); + } + return list; +} +std::vector all; + +void read(MLAT_Data* buf, std::uint16_t* len) { + if (all.empty()) { + all = read_lines(); + } + static size_t pos = 0; // 上一次拷贝结束后的位置 + const size_t BATCH = 100; + size_t total = all.size(); + size_t n = std::min(BATCH, total - pos); // 本次实际要拷贝多少 + + for (size_t i = 0; i < n; ++i) { + buf[i] = all[pos + i]; + } + *len = static_cast(n); + + pos += n; + if (pos >= total) { + pos = 0; // 如果需要循环一轮后归零,否则你可以不归零 + } +} + + +MLAT_Config::MLAT_Config() {} +void MLAT_Config::init(const Psc::JSON * that_json) { + enable = that_json->get_bool("enable"); + merge = that_json->get_bool("merge"); + library_path = that_json->get_string("library_path"); + function_name = that_json->get_string("function_name"); + if (enable) { + { + auto r = Psc::try_load_library(Psc::get_abs_path(library_path)); + if (!r) { + Psc::fail_fast(); + } + lib = r.value(); + } + { + auto r = Psc::try_load_function(lib, function_name); + if (!r) { + Psc::fail_fast(); + } + read_func_ptr = (Func_Type)r.value(); + } + + + all = read_lines(); + read_func_ptr = read; + } +} + + +void MLAT_Config::refresh() { + std::lock_guard guard(mtx); + std::uint16_t len{}; + if (read_func_ptr) read_func_ptr(buf, &len); + auto list = Global::instance()->mode_acs.data_source_config.map.list(); + for (std::uint16_t i = 0; i < len; i++) { + MLAT_Data& cur = buf[i]; + std::string icao = std::string(cur.icao, 6); + + for (const auto& li : list) { + //auto air = li->get_aircraft(icao); + auto air = li->get_aircraft(icao); + if (air) { + // air->mlat = true; + // air->air_pos_track_list.push(CPR::Position{cur.lat, cur.lon}); + } + } + + auto& t = update_map[icao]; + if (t.d.lat != cur.lat || t.d.lon != cur.lon) { + t.d = cur; + } + } +} + + +void MLAT_Config::server(Global* g) { + auto& svr = g->svr; + auto& api = g->api; + svr.Post(api + "get_mlat_list", [this](HTTP_Param) { + res->setBody(warp(get_reset()).to_json_string()); + }); + + // svr.Post(api + "get_mlat_server_config", [this](HTTP_Param) { + // res->setBody(warp(to_json()).to_json_string()); + // }); + // svr.Post(api + "/set_mlat_server_config", [this, g](HTTP_Param) { + // CHECK_JSON_PARAM + // MLAT_Server_Config t; + // t.init(&o_params.value()); + // bool ok = check_ipv4(t.ip) && check_port(t.port); + // if (!ok) + // { + // server_logger->error("", {}, LOG_POS + " ip port! " + t.ip + ":" + std::to_string(t.port)); + // res->setBody(warp(to_json()).to_json_string()); + // return; + // } + // + // auto& s = g->mlat_server; + // s.id = t.id; + // s.port = t.port; + // s.ip = t.ip; + // + // Global::save(); + // res->setBody(warp(to_json()).to_json_string()); + // }); +} diff --git a/module/Local_Server/server/MLAT.h b/module/Local_Server/server/MLAT.h new file mode 100644 index 0000000..6607d62 --- /dev/null +++ b/module/Local_Server/server/MLAT.h @@ -0,0 +1,80 @@ +#ifndef MLAT_H +#define MLAT_H +#include "../../../../../core_library/Core/Core/Base/JSON.h" +#include "../../../../../core_library/Core/Core/system/export.h" +#include "../global_include.h" +#include +#include + +class Global; +#pragma pack(push, 8) +extern "C" { + struct MLAT_Data { + char icao[6]; + double lon; + double lat; + }; +} +#pragma pack(pop) + + +struct MLAT_Store { + MLAT_Data d{}; + [[nodiscard]] Psc::JSON to_json() const { + Psc::JSON ret = Psc::JSON::object(); + ret.append({"icao", std::string(d.icao, 6)}); + ret.append({"lon", d.lon}); + ret.append({"lat", d.lat}); + return ret; + } + [[nodiscard]] std::string icao() const { + return {d.icao, 6}; + } +}; + +struct Base_MLAT_Data { + MLAT_Data mlat_data; + std::string msg; + std::string hex; + std::string icao; +}; + +extern std::multimap hex_mlat_map; + +struct MLAT_Config { + std::atomic enable{}; + std::atomic merge{}; + std::string library_path; + std::string function_name; + ~MLAT_Config() = default; + MLAT_Config(); + [[nodiscard]] Psc::JSON to_json() const { + Psc::JSON ret = Psc::JSON::object(); + ret.append(Psc::JSON("enable", this->enable)); + ret.append(Psc::JSON("merge", this->merge)); + Ret_J(library_path) + Ret_J(function_name) + return ret; + } + void* lib{}; + using Func_Type = void(*)(MLAT_Data* buf, std::uint16_t* len); + Func_Type read_func_ptr{}; + void init(const Psc::JSON* that_json); + MLAT_Data buf[std::numeric_limits::max()]{}; + void refresh(); + + Psc::JSON get_reset() { + std::lock_guard guard(mtx); + Psc::JSON ret = Psc::JSON::array(); + for (auto & t : update_map) { + ret.append(t.second.to_json()); + } + update_map.clear(); + return ret; + } + void server(Global* g); +protected: + std::mutex mtx; + std::map update_map; +}; +#endif diff --git a/module/Local_Server/server/Mode_Msg_Buffer.h b/module/Local_Server/server/Mode_Msg_Buffer.h new file mode 100644 index 0000000..fed97f7 --- /dev/null +++ b/module/Local_Server/server/Mode_Msg_Buffer.h @@ -0,0 +1,58 @@ +#ifndef BIN_Msg_Buffer_H +#define BIN_Msg_Buffer_H + +#include "../global_include.h" +#include + +struct Mode_Msg_Buffer { + void push(const std::shared_ptr& msg) { + std::lock_guard g(mtx); + msg_list_cache.push_back(msg); + } + + const std::vector>& get_all() { + std::lock_guard g(mtx); + std::swap(msg_list_cache, msg_list); + msg_list_cache.clear(); + mode_s_msg_num = 0; + mode_other_msg_num = 0; + return msg_list; + } + + size_t size() { + std::lock_guard g(mtx); + return msg_list_cache.size(); + } + std::atomic mode_s_msg_num{}; + std::atomic mode_other_msg_num{}; + Mode_Msg_Buffer() { + msg_list_cache.reserve(8 * 10240); + msg_list.reserve(8* 10240); + } +protected: + std::mutex mtx; + std::vector> msg_list_cache; + std::vector> msg_list; +}; + + + + +struct BIN_Msg_Buffer { + void push(const std::string& msg); + const std::vector& get_all(); + + + std::atomic mode_s_msg_num{}; + std::atomic mode_other_msg_num{}; + BIN_Msg_Buffer(); + + Psc::JSON state_json(); +protected: + std::mutex mtx; + std::vector msg_list_cache; + std::vector msg_list; +}; + + +#endif diff --git a/module/Local_Server/server/Performance_Monitor.h b/module/Local_Server/server/Performance_Monitor.h new file mode 100644 index 0000000..49e2ee1 --- /dev/null +++ b/module/Local_Server/server/Performance_Monitor.h @@ -0,0 +1,85 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include + +class Access_Logger { +public: + static void log(const drogon::HttpRequestPtr& request, + const drogon::HttpResponsePtr& response, + const double elapsed_ms) { + std::cout << "[http access] method=" << request->methodString() + << ", path=" << request->path() + << ", status=" << static_cast(response->statusCode()) + << ", cost_ms=" << elapsed_ms << std::endl; + } +}; + +class Slow_Request_Monitor { +public: + static void log_if_slow(const drogon::HttpRequestPtr& request, + const drogon::HttpResponsePtr& response, + const double elapsed_ms, + const std::size_t threshold_ms) { + if (elapsed_ms < static_cast(threshold_ms)) return; + std::cout << "[slow http request] method=" << request->methodString() + << ", path=" << request->path() + << ", status=" << static_cast(response->statusCode()) + << ", cost_ms=" << elapsed_ms + << ", threshold_ms=" << threshold_ms << std::endl; + } +}; + +class Scope_Timer { +public: + Scope_Timer(std::string name, const std::size_t threshold_ms) + : name_(std::move(name)), + threshold_ms_(threshold_ms), + start_(std::chrono::steady_clock::now()) {} + + ~Scope_Timer() { + const auto elapsed_ms = + std::chrono::duration( + std::chrono::steady_clock::now() - start_).count(); + if (elapsed_ms < static_cast(threshold_ms_)) return; + std::cout << "[slow scope] name=" << name_ + << ", cost_ms=" << elapsed_ms + << ", threshold_ms=" << threshold_ms_ << std::endl; + } + +private: + std::string name_; + std::size_t threshold_ms_; + std::chrono::steady_clock::time_point start_; +}; + +inline constexpr const char* kHttpRequestStart = "ecap.http_request_start"; + +inline void register_http_performance_monitor(const bool access_log, + const std::size_t slow_request_threshold_ms) { + drogon::app().registerSyncAdvice( + [](const drogon::HttpRequestPtr& request) -> drogon::HttpResponsePtr { + request->attributes()->insert(kHttpRequestStart, std::chrono::steady_clock::now()); + return {}; + }); + drogon::app().registerPreSendingAdvice( + [access_log, slow_request_threshold_ms]( + const drogon::HttpRequestPtr& request, + const drogon::HttpResponsePtr& response) { + const auto& start = + request->attributes()->get( + kHttpRequestStart); + if (start == std::chrono::steady_clock::time_point{}) return; + const auto elapsed_ms = + std::chrono::duration( + std::chrono::steady_clock::now() - start).count(); + if (access_log) Access_Logger::log(request, response, elapsed_ms); + Slow_Request_Monitor::log_if_slow( + request, response, elapsed_ms, slow_request_threshold_ms); + }); +} diff --git a/module/Local_Server/server/Source_Feed_Relation.cpp b/module/Local_Server/server/Source_Feed_Relation.cpp new file mode 100644 index 0000000..413aeeb --- /dev/null +++ b/module/Local_Server/server/Source_Feed_Relation.cpp @@ -0,0 +1,80 @@ +#include "Source_Feed_Relation.h" +#include "Config.h" +#include "Global.h" +void Source_Feed_Relation_Config::set_need_refresh() { + for (const auto& li : Global::instance()->mode_acs.data_source_config.map.list()) { + li->need_refresh_data_feed_key_list = true; + } +} + +void Source_Feed_Relation_Config::server(Global* g) { + auto& svr = g->svr; + auto& api = g->api; + std::string name = "source_feed_relation"; + + + + svr.Post(api + "get_" + name + "_config", [this](HTTP_Param) { + res->setBody(warp(to_json()).to_json_string()); + }); + + svr.Post(api + svr.search + name, [this, g](HTTP_Param) { + CHECK_JSON_PARAM + HTTP_REQUIRE_VALUE(key, params.try_get_string("key")) + HTTP_REQUIRE_VALUE(relation, map.get(key)) + res->setBody(warp(relation->to_json()).to_json_string()); + }); + + + + svr.Post(api + svr.update + name, [this, g](HTTP_Param) { + CHECK_JSON_PARAM + HTTP_REQUIRE_VALUE(key, params.try_get_string("key")) + HTTP_REQUIRE_VALUE(ds, map.get(key)) + ds->from_json(¶ms); + + // 直接关闭 + g->save(); + set_need_refresh(); + }); + + svr.Post(api + svr.insert + name, [g, this](HTTP_Param) { + CHECK_JSON_PARAM + HTTP_REQUIRE_VALUE(index, params.try_get_number("index")) + HTTP_REQUIRE_PTR(data, params.get("data")) + HTTP_REQUIRE_VALUE(t, data->try_get_string("type")) + std::cout << params.to_json_string() << std::endl; + auto ds = create_source_feed_relation_from_type(t); + ds->from_json(data); + HTTP_REQUIRE_TRUE(map.insert(index, ds), "index") + //std::cout << params.to_json_string() << std::endl; + res->setBody(warp(to_json()).to_json_string()); + g->save(); + set_need_refresh(); + }); + + svr.Post(api + svr.remove + name, [g, this](HTTP_Param) { + CHECK_JSON_PARAM + HTTP_REQUIRE_VALUE(index, params.try_get_number("index")) + HTTP_REQUIRE_TRUE(map.remove(index), "index") + g->save(); + res->setBody(warp(to_json()).to_json_string()); + set_need_refresh(); + }); + svr.Post(api + svr.rise + name, [g, this](HTTP_Param) { + CHECK_JSON_PARAM + HTTP_REQUIRE_VALUE(index, params.try_get_number("index")) + HTTP_REQUIRE_TRUE(map.swap(index, index - 1), "index") + g->save(); + res->setBody(warp(to_json()).to_json_string()); + set_need_refresh(); + }); + svr.Post(api + svr.fall + name , [g, this](HTTP_Param) { + CHECK_JSON_PARAM + HTTP_REQUIRE_VALUE(index, params.try_get_number("index")) + HTTP_REQUIRE_TRUE(map.swap(index, index + 1), "index") + g->save(); + res->setBody(warp(to_json()).to_json_string()); + set_need_refresh(); + }); +} diff --git a/module/Local_Server/server/Source_Feed_Relation.h b/module/Local_Server/server/Source_Feed_Relation.h new file mode 100644 index 0000000..4cd11b3 --- /dev/null +++ b/module/Local_Server/server/Source_Feed_Relation.h @@ -0,0 +1,95 @@ +#ifndef SOURCE_FEED_RELATION_H +#define SOURCE_FEED_RELATION_H + + +#include "Core/Serial/Serial.h" +#include "../global_include.h" + + + +struct Source_Feed_Relation { + std::string key; + std::string type; + std::atomic enable{}; + virtual void from_json(const Psc::JSON* that_json) { + Get_J(key); + Get_J(enable); + Get_J(type); + } + + [[nodiscard]] virtual Psc::JSON to_json() const { + Psc::JSON ret = Psc::JSON::object(); + Ret_J(key) + Ret_J(enable) + Ret_J(type) + return ret; + } + virtual ~Source_Feed_Relation() = default; +}; + +struct One_to_One_Relation : Source_Feed_Relation { + std::string source_key; + std::string feed_key; + void from_json(const Psc::JSON* that_json) override { + Source_Feed_Relation::from_json(that_json); + Get_J(source_key) + Get_J(feed_key) + } + [[nodiscard]] Psc::JSON to_json() const override { + Psc::JSON ret = Source_Feed_Relation::to_json(); + Ret_J(source_key) + Ret_J(feed_key) + return ret; + } + ~One_to_One_Relation() override = default; +}; + +struct First_Source_To_All_Feed_Relation : Source_Feed_Relation { + void from_json(const Psc::JSON* that_json) override { + Source_Feed_Relation::from_json(that_json); + } + [[nodiscard]] Psc::JSON to_json() const override { + Psc::JSON ret = Source_Feed_Relation::to_json(); + return ret; + } + ~First_Source_To_All_Feed_Relation() override = default; +}; + + +inline std::shared_ptr create_source_feed_relation_from_type(const std::string& t) { + std::shared_ptr ret{}; + if (t == "One_to_One_Relation") ret = std::make_shared(); + else if (t == "First_Source_To_All_Feed_Relation") ret = std::make_shared(); + else { + std::cout << "未知的 Source_Feed_Relation type 类型! t:[" << t << "]"<< std::endl; + throw std::invalid_argument("unknown Source_Feed_Relation type: " + t); + } + return ret; +} + +struct Source_Feed_Relation_Config { + void from_json(const Psc::JSON* that_json) { + auto j_list = that_json->get("list"); + for (const Psc::JSON& li : j_list->children) { + auto p = create_source_feed_relation_from_type(li.get_string("type")); + p->from_json(&li); + map.push_back(p); + } + } + [[nodiscard]] Psc::JSON to_json() { + Psc::JSON ret = Psc::JSON::object(); + Psc::JSON j_list = Psc::JSON::array(); + for (auto& p : this->map.list()) { + j_list.append(p->to_json()); + } + ret.append(Psc::JSON("list", j_list)); + return ret; + } + Ordered_Map> map; + + static void set_need_refresh(); //通知每一个data_source 映射关系需要更新 + void server(Global* g); +}; + + +#endif diff --git a/module/Local_Server/server/WebSocket_Manager.cpp b/module/Local_Server/server/WebSocket_Manager.cpp new file mode 100644 index 0000000..c25aba8 --- /dev/null +++ b/module/Local_Server/server/WebSocket_Manager.cpp @@ -0,0 +1,115 @@ +#include "WebSocket_Manager.h" +#include "../global_include.h" +#include "Global.h" +#include +#include +#include +class DSP_Ws_Mgr : public drogon::WebSocketController { +public: + static DSP_Ws_Mgr *instance() { return inst_; } + WS_PATH_LIST_BEGIN + WS_ADD_PATH_VIA_REGEX(R"(^/ws/.*$)", drogon::Get); + WS_PATH_LIST_END + void handleNewMessage(const drogon::WebSocketConnectionPtr &, std::string &&, const drogon::WebSocketMessageType &) override; + void handleConnectionClosed(const drogon::WebSocketConnectionPtr & conn) override; + void handleNewConnection(const drogon::HttpRequestPtr & req, const drogon::WebSocketConnectionPtr & conn) override; + DSP_Ws_Mgr(); +protected: + static DSP_Ws_Mgr *inst_; +}; +DSP_Ws_Mgr *DSP_Ws_Mgr::inst_ = nullptr; +struct WebSocket_Connection { + std::string type; +}; + +WebSocket_Manager::WebSocket_Manager(std::string path) : path(std::move(path)) {} +void WebSocket_Manager::remove(const drogon::WebSocketConnectionPtr &conn) { + std::lock_guard g(mtx); + connections.erase(conn); +} +void WebSocket_Manager::add(const drogon::WebSocketConnectionPtr &conn) { + std::lock_guard g(mtx); + connections.insert(conn); +} +void WebSocket_Manager::visit( + const std::function + &func) { + std::lock_guard g(mtx); + for (const auto &coon: connections) { + func(coon); + } +} +void WebSocket_Manager::push_data(const char *buf, uint64_t len) { + std::lock_guard g(mtx); + for (const auto &conn: connections) { + conn->send(buf, len, drogon::WebSocketMessageType::Binary); + } +} +size_t WebSocket_Manager::get_websocket_connect_num() { + std::lock_guard g(mtx); + return connections.size(); +} + +std::shared_ptr Ws_Mgr::register_ws(std::string path) { + auto it = map.find(path); + if (it != map.end()) { + Psc::fail_fast_core_dump("register_ws:" + VAR_STR_1(path) + "重复创建!"); + return it->second; + } + std::shared_ptr cur = std::make_shared(path); + map[path] = cur; + return cur; +} + +std::shared_ptr Ws_Mgr::get_ws(std::string path) { + auto it = map.find(path); + if (it != map.end()) { + return it->second; + } + return nullptr; +} + + +void DSP_Ws_Mgr::handleNewMessage(const drogon::WebSocketConnectionPtr &, + std::string &&, + const drogon::WebSocketMessageType &) { + +} +void DSP_Ws_Mgr::handleConnectionClosed( +const drogon::WebSocketConnectionPtr &conn) { + auto &s = conn->getContextRef(); + auto rp = s.type; + auto ws = Ws_Mgr::instance()->get_ws(rp); + //LOG_DEBUG + std::ostringstream oss; + oss + << "已有连接数:" << ws->get_websocket_connect_num() << " " + << "关闭websocket连接:" << rp << "\n" + << "local_addr:" << inet_address_to_string(conn->localAddr()) << "\n" + << "peer_addr:" << inet_address_to_string(conn->peerAddr()) << "\n"; + dsp_logger->c_debug("websocket", {},oss.str()); + ws->remove(conn); +} +void DSP_Ws_Mgr::handleNewConnection( + const drogon::HttpRequestPtr &req, + const drogon::WebSocketConnectionPtr &conn) { + auto rpt = req->path(); + auto rp = rpt.substr(std::string("/ws").size()); + auto ws = Ws_Mgr::instance()->get_ws(rp); + std::ostringstream oss; + oss + << "已有连接数:" << ws->get_websocket_connect_num() << " " + << "新建websocket连接:" << rp << " " + << "local_addr:" << inet_address_to_string(conn->localAddr()) << " " + << "peer_addr:" << inet_address_to_string(conn->peerAddr()) << "\n"; + + dsp_logger->c_debug("websocket", {},oss.str()); + + WebSocket_Connection s; + s.type = rp; + conn->setContext(std::make_shared(std::move(s))); + ws->add(conn); +} +DSP_Ws_Mgr::DSP_Ws_Mgr() { + inst_ = this; +} \ No newline at end of file diff --git a/module/Local_Server/server/WebSocket_Manager.h b/module/Local_Server/server/WebSocket_Manager.h new file mode 100644 index 0000000..62f7ab4 --- /dev/null +++ b/module/Local_Server/server/WebSocket_Manager.h @@ -0,0 +1,36 @@ +#pragma once + +#include "Core/Base/global_include.h" +#include "Core/socket/ByteOrder.h" + +#include +#include + + + +class WebSocket_Manager { +public: + explicit WebSocket_Manager(std::string path); + ~WebSocket_Manager() = default; + void remove(const drogon::WebSocketConnectionPtr &conn); + void add(const drogon::WebSocketConnectionPtr &conn); + void visit(const std::function &func); + void push_data(const char *buf, uint64_t len); + size_t get_websocket_connect_num(); + std::string path; +protected: + std::mutex mtx; + std::unordered_set connections; +}; + + +class Ws_Mgr : public Psc::Singleton { +public: + std::shared_ptr register_ws(std::string path); + std::shared_ptr get_ws(std::string path); + std::map> map; +}; + + + + diff --git a/module/Local_Server/server/libarchive.cpp b/module/Local_Server/server/libarchive.cpp new file mode 100644 index 0000000..4af92c8 --- /dev/null +++ b/module/Local_Server/server/libarchive.cpp @@ -0,0 +1,678 @@ +#include "libarchive.h" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; + +namespace { + +constexpr std::size_t kArchiveBlockSize = 64 * 1024; + +[[noreturn]] void throw_invalid_archive(const std::string& reason) { + throw Invalid_Archive_Error("invalid upgrade archive: " + reason); +} + +std::string archive_error_text(archive* a, const std::string& stage) { + const char* err = archive_error_string(a); + if (err == nullptr || *err == '\0') { + return stage; + } + return stage + ": " + err; +} + +void require_archive_ok(archive* a, int code, const std::string& stage) { + if (code != ARCHIVE_OK) { + throw std::runtime_error(archive_error_text(a, stage)); + } +} + +std::string path_to_utf8(const fs::path& path) { + const auto u8 = path.generic_u8string(); + return std::string(u8.begin(), u8.end()); +} + +bool path_is_within(const fs::path& base, const fs::path& target) { + const fs::path canonical_base = fs::weakly_canonical(base); + const fs::path canonical_target = fs::weakly_canonical(target); + + auto base_it = canonical_base.begin(); + auto target_it = canonical_target.begin(); + for (; base_it != canonical_base.end(); ++base_it, ++target_it) { + if (target_it == canonical_target.end() || *base_it != *target_it) { + return false; + } + } + return true; +} + +std::string normalize_archive_path(const std::string& raw, bool allow_empty = false) { + if (raw.empty()) { + if (allow_empty) return {}; + throw_invalid_archive("empty entry path"); + } + if (raw.front() == '/' || raw.find('\\') != std::string::npos || raw.find(':') != std::string::npos) { + throw_invalid_archive("unsafe entry path: " + raw); + } + + std::string normalized; + std::size_t start = 0; + while (start < raw.size()) { + const std::size_t slash = raw.find('/', start); + const std::size_t end = slash == std::string::npos ? raw.size() : slash; + const std::string component = raw.substr(start, end - start); + if (component.empty() || component == "." || component == "..") { + throw_invalid_archive("unsafe entry path: " + raw); + } + if (!normalized.empty()) normalized.push_back('/'); + normalized += component; + if (slash == std::string::npos) break; + start = slash + 1; + if (start == raw.size()) break; + } + return normalized; +} + +std::string entry_path(archive_entry* entry) { + const char* name = archive_entry_pathname_utf8(entry); + if (name == nullptr) { + name = archive_entry_pathname(entry); + } + if (name == nullptr) { + throw_invalid_archive("entry path is unavailable"); + } + return normalize_archive_path(name); +} + +bool is_directory_entry(archive_entry* entry) { + return archive_entry_filetype(entry) == AE_IFDIR; +} + +bool is_regular_entry(archive_entry* entry) { + const auto type = archive_entry_filetype(entry); + return type == AE_IFREG || type == 0; +} + +void reject_unsupported_entry_type(archive_entry* entry, const std::string& path) { + const auto type = archive_entry_filetype(entry); + if (type == AE_IFLNK) { + throw_invalid_archive("symbolic link is not allowed: " + path); + } + if (type != AE_IFDIR && type != AE_IFREG && type != 0) { + throw_invalid_archive("special file is not allowed: " + path); + } +} + +void setup_archive_reader(archive* a) { + require_archive_ok(a, archive_read_support_filter_all(a), "archive_read_support_filter_all failed"); + require_archive_ok(a, archive_read_support_format_all(a), "archive_read_support_format_all failed"); +} + +void consume_entry_data_for_validation( + archive* a, + const std::string& path, + const Archive_Layout_Rules& rules, + std::uint64_t& total_uncompressed_size +) { + std::uint64_t entry_size = 0; + const void* block = nullptr; + std::size_t block_size = 0; + la_int64_t offset = 0; + + while (true) { + const int result = archive_read_data_block(a, &block, &block_size, &offset); + if (result == ARCHIVE_EOF) { + break; + } + if (result != ARCHIVE_OK) { + throw_invalid_archive(archive_error_text(a, "cannot read entry: " + path)); + } + + if (block_size > rules.max_entry_uncompressed_size + || entry_size > rules.max_entry_uncompressed_size - block_size) { + throw_invalid_archive("entry size exceeds limit: " + path); + } + if (block_size > rules.max_total_uncompressed_size + || total_uncompressed_size > rules.max_total_uncompressed_size - block_size) { + throw_invalid_archive("uncompressed size exceeds limit"); + } + + entry_size += block_size; + total_uncompressed_size += block_size; + } +} + +void consume_entry_data_for_validation( + archive* a, + archive_entry* entry, + const std::string& path, + const Archive_Layout_Rules& rules, + std::uint64_t& total_uncompressed_size +) { + if (archive_entry_size_is_set(entry)) { + const auto expected_size = archive_entry_size(entry); + if (expected_size < 0) { + throw_invalid_archive("negative entry size: " + path); + } + const auto size = static_cast(expected_size); + if (size > rules.max_entry_uncompressed_size || size > rules.max_total_uncompressed_size) { + throw_invalid_archive("entry size exceeds limit: " + path); + } + } + + consume_entry_data_for_validation(a, path, rules, total_uncompressed_size); +} + +std::unordered_set make_allowed_entries( + const std::vector& required, + const std::vector& optional +) { + std::unordered_set result; + auto add = [&result](const std::vector& entries) { + for (const auto& entry : entries) { + if (entry.empty() || entry.find('/') != std::string::npos || entry.find('\\') != std::string::npos) { + throw_invalid_archive("invalid layout rule entry: " + entry); + } + result.insert(entry); + } + }; + add(required); + add(optional); + return result; +} + +struct Validated_Archive_Entry { + std::string path; + bool is_directory = false; +}; + +struct Archive_Read_Deleter { + void operator()(archive* a) const noexcept { + if (a != nullptr) { + archive_read_free(a); + } + } +}; + +struct Archive_Write_Deleter { + void operator()(archive* a) const noexcept { + if (a != nullptr) { + archive_write_free(a); + } + } +}; + +using Read_Archive_Ptr = std::unique_ptr; +using Write_Archive_Ptr = std::unique_ptr; + +Read_Archive_Ptr make_archive_reader() { + Read_Archive_Ptr reader(archive_read_new()); + if (!reader) { + throw std::runtime_error("archive_read_new failed"); + } + setup_archive_reader(reader.get()); + return reader; +} + +bool is_safe_archive_name_token(const std::string& value) { + if (value.empty()) { + return false; + } + return std::ranges::all_of(value, [](unsigned char ch) { + return std::isalnum(ch) != 0 || ch == '_' || ch == '-' || ch == '.'; + }); +} + +void validate_archive_write_options(const Archive_Write_Options& options) { + if (!is_safe_archive_name_token(options.format)) { + throw std::invalid_argument("invalid archive format: " + options.format); + } + if (!options.filter.empty() + && options.filter != "none" + && !is_safe_archive_name_token(options.filter)) { + throw std::invalid_argument("invalid archive filter: " + options.filter); + } + if (!is_safe_archive_name_token(options.extension) || options.extension.find('/') != std::string::npos) { + throw std::invalid_argument("invalid archive extension: " + options.extension); + } +} + +void configure_archive_writer(archive* writer, const Archive_Write_Options& options) { + validate_archive_write_options(options); + + if (!options.filter.empty() && options.filter != "none") { + require_archive_ok( + writer, + archive_write_add_filter_by_name(writer, options.filter.c_str()), + "archive_write_add_filter_by_name failed: " + options.filter + ); + } + + require_archive_ok( + writer, + archive_write_set_format_by_name(writer, options.format.c_str()), + "archive_write_set_format_by_name failed: " + options.format + ); + + if (options.format == "zip") { + require_archive_ok( + writer, + archive_write_zip_set_compression_deflate(writer), + "archive_write_zip_set_compression_deflate failed" + ); + } +} + +Write_Archive_Ptr make_archive_writer(const Archive_Write_Options& options) { + Write_Archive_Ptr writer(archive_write_new()); + if (!writer) { + throw std::runtime_error("archive_write_new failed"); + } + configure_archive_writer(writer.get(), options); + return writer; +} + +void extract_archive(archive* a, const fs::path& out_dir) { + fs::create_directories(out_dir); + const fs::path base = fs::weakly_canonical(out_dir); + + archive_entry* entry = nullptr; + while (true) { + const int result = archive_read_next_header(a, &entry); + if (result == ARCHIVE_EOF) { + break; + } + if (result != ARCHIVE_OK) { + throw std::runtime_error(archive_error_text(a, "archive_read_next_header failed")); + } + + const std::string normalized = entry_path(entry); + reject_unsupported_entry_type(entry, normalized); + + const fs::path out_path = (base / fs::path(normalized)).lexically_normal(); + if (!path_is_within(base, out_path)) { + throw std::runtime_error("archive-slip detected: " + normalized); + } + + if (is_directory_entry(entry)) { + fs::create_directories(out_path); + continue; + } + + if (!is_regular_entry(entry)) { + throw std::runtime_error("unsupported archive entry type: " + normalized); + } + + fs::create_directories(out_path.parent_path()); + std::ofstream out(out_path, std::ios::binary); + if (!out) { + throw std::runtime_error("open output failed: " + path_to_utf8(out_path)); + } + + const void* block = nullptr; + std::size_t block_size = 0; + la_int64_t offset = 0; + while (true) { + const int read_result = archive_read_data_block(a, &block, &block_size, &offset); + if (read_result == ARCHIVE_EOF) { + break; + } + if (read_result != ARCHIVE_OK) { + throw std::runtime_error(archive_error_text(a, "archive_read_data_block failed")); + } + out.write(static_cast(block), static_cast(block_size)); + if (!out) { + throw std::runtime_error("write output failed: " + path_to_utf8(out_path)); + } + } + } +} + +struct Ignore_Rules { + std::vector directories; + std::unordered_set files; + std::unordered_set extensions; +}; + +Ignore_Rules parse_ignore_rules(const std::vector& ignore_patterns) { + Ignore_Rules rules; + for (const auto& pattern : ignore_patterns) { + if (pattern.empty()) continue; + if (pattern.ends_with('/')) { + rules.directories.emplace_back(fs::path(pattern.substr(0, pattern.size() - 1)).lexically_normal()); + } + else if (pattern[0] == '.') { + rules.extensions.insert(pattern); + } + else { + rules.files.insert(pattern); + } + } + return rules; +} + +bool should_skip_directory(const fs::path& rel_path, const Ignore_Rules& rules) { + for (const auto& ignored : rules.directories) { + const auto rel_native = rel_path.native(); + const auto ignored_native = ignored.native(); + if (rel_path == ignored || rel_native.starts_with(ignored_native + fs::path::preferred_separator)) { + return true; + } + } + return false; +} + +void add_file_to_archive(archive* writer, const fs::path& base, const fs::path& abs_path, const fs::path& rel_path) { + const std::uintmax_t file_size = fs::file_size(abs_path); + const std::string archive_name = path_to_utf8(rel_path); + if (archive_name.empty() + || archive_name == ".." + || archive_name.starts_with("../") + || archive_name.find("/../") != std::string::npos + || archive_name.ends_with("/..")) { + throw std::runtime_error("invalid path in archive: " + archive_name); + } + + std::unique_ptr entry(archive_entry_new(), archive_entry_free); + if (!entry) { + throw std::runtime_error("archive_entry_new failed"); + } + archive_entry_set_pathname_utf8(entry.get(), archive_name.c_str()); + archive_entry_set_filetype(entry.get(), AE_IFREG); + archive_entry_set_perm(entry.get(), 0644); + archive_entry_set_size(entry.get(), static_cast(file_size)); + + const auto now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); + archive_entry_set_mtime(entry.get(), now, 0); + + require_archive_ok(writer, archive_write_header(writer, entry.get()), "archive_write_header failed"); + + std::ifstream in(abs_path, std::ios::binary); + if (!in) { + throw std::runtime_error("failed to open input file: " + path_to_utf8(abs_path)); + } + + char buffer[kArchiveBlockSize]; + while (in) { + in.read(buffer, sizeof(buffer)); + const auto count = in.gcount(); + if (count <= 0) { + break; + } + const la_ssize_t written = archive_write_data(writer, buffer, static_cast(count)); + if (written < 0 || written != count) { + throw std::runtime_error(archive_error_text(writer, "archive_write_data failed")); + } + } + if (!in.eof()) { + throw std::runtime_error("failed to read input file: " + path_to_utf8(abs_path)); + } + + require_archive_ok(writer, archive_write_finish_entry(writer), "archive_write_finish_entry failed"); + (void)base; +} + +void write_directory_to_archive( + archive* writer, + const fs::path& dir_path, + const std::vector& ignore_patterns +) { + if (!fs::exists(dir_path)) { + throw std::runtime_error("source path does not exist: " + path_to_utf8(dir_path)); + } + if (!fs::is_directory(dir_path)) { + throw std::runtime_error("source path exists but is not a directory: " + path_to_utf8(dir_path)); + } + + const fs::path base = fs::weakly_canonical(dir_path); + const Ignore_Rules ignore_rules = parse_ignore_rules(ignore_patterns); + + fs::recursive_directory_iterator it(base); + const fs::recursive_directory_iterator end; + for (; it != end; ++it) { + const fs::path abs_path = it->path(); + const fs::path rel_path = fs::relative(abs_path, base); + + if (it->is_directory()) { + if (should_skip_directory(rel_path, ignore_rules)) { + it.disable_recursion_pending(); + } + continue; + } + + if (!it->is_regular_file()) { + continue; + } + + const std::string filename = abs_path.filename().string(); + const std::string extension = abs_path.extension().string(); + if (ignore_rules.files.contains(filename) || (!extension.empty() && ignore_rules.extensions.contains(extension))) { + continue; + } + + add_file_to_archive(writer, base, abs_path, rel_path); + } +} + +la_ssize_t archive_string_write_callback(archive*, void* client_data, const void* buffer, std::size_t length) { + auto* out = static_cast(client_data); + out->append(static_cast(buffer), length); + return static_cast(length); +} + +int archive_noop_open_close_callback(archive*, void*) { + return ARCHIVE_OK; +} + +void validate_archive_layout_from_memory_or_throw( + const char* data, + std::size_t size, + const Archive_Layout_Rules& rules +) { + if (data == nullptr || size == 0) { + throw_invalid_archive("empty archive"); + } + if (size > rules.max_archive_size) { + throw_invalid_archive("archive size exceeds limit"); + } + + auto reader = make_archive_reader(); + require_archive_ok( + reader.get(), + archive_read_open_memory(reader.get(), data, size), + "archive_read_open_memory failed" + ); + + std::vector entries; + std::unordered_set unique_paths; + std::uint64_t total_uncompressed_size = 0; + std::size_t entry_count = 0; + + archive_entry* entry = nullptr; + while (true) { + const int result = archive_read_next_header(reader.get(), &entry); + if (result == ARCHIVE_EOF) { + break; + } + if (result != ARCHIVE_OK) { + throw_invalid_archive(archive_error_text(reader.get(), "cannot read archive header")); + } + + ++entry_count; + if (entry_count > rules.max_entry_count) { + throw_invalid_archive("entry count exceeds limit"); + } + + const std::string path = entry_path(entry); + if (!unique_paths.insert(path).second) { + throw_invalid_archive("duplicate entry path: " + path); + } + + if (archive_entry_is_encrypted(entry)) { + throw_invalid_archive("encrypted entry is not allowed: " + path); + } + + reject_unsupported_entry_type(entry, path); + + const bool directory = is_directory_entry(entry); + if (!directory) { + if (!is_regular_entry(entry)) { + throw_invalid_archive("special file is not allowed: " + path); + } + consume_entry_data_for_validation(reader.get(), entry, path, rules, total_uncompressed_size); + } + + entries.push_back({path, directory}); + } + + for (const auto& rule : rules.directories) { + const std::string rule_directory = normalize_archive_path(rule.directory, true); + const auto allowed_files = make_allowed_entries(rule.required_files, rule.optional_files); + const auto allowed_directories = make_allowed_entries(rule.required_directories, rule.optional_directories); + std::unordered_map direct_children; + + for (const auto& entry : entries) { + std::string relative; + if (rule_directory.empty()) { + relative = entry.path; + } + else { + const std::string prefix = rule_directory + "/"; + if (!entry.path.starts_with(prefix)) continue; + relative = entry.path.substr(prefix.size()); + } + + const std::size_t slash = relative.find('/'); + const std::string child = relative.substr(0, slash); + const bool is_directory = slash != std::string::npos || entry.is_directory; + const auto [it, inserted] = direct_children.emplace(child, is_directory); + if (!inserted && it->second != is_directory) { + throw_invalid_archive("entry is both file and directory: " + child); + } + } + + for (const auto& [child, is_directory] : direct_children) { + const auto& allowed = is_directory ? allowed_directories : allowed_files; + if (!allowed.contains(child)) { + throw_invalid_archive("unexpected entry under " + rule_directory + ": " + child); + } + } + for (const auto& required : rule.required_files) { + const auto it = direct_children.find(required); + if (it == direct_children.end() || it->second) { + throw_invalid_archive("missing required file under " + rule_directory + ": " + required); + } + } + for (const auto& required : rule.required_directories) { + const auto it = direct_children.find(required); + if (it == direct_children.end() || !it->second) { + throw_invalid_archive("missing required directory under " + rule_directory + ": " + required); + } + } + } +} + +} // namespace + +Psc::expected validate_archive_layout_from_memory( + const char* data, + std::size_t size, + const Archive_Layout_Rules& rules +) { + try { + validate_archive_layout_from_memory_or_throw(data, size, rules); + return {}; + } + catch (const Invalid_Archive_Error& e) { + return Psc::unexpected(e.what()); + } +} + +void unarchive_file(const fs::path& zipPath, const fs::path& outDir) { + auto reader = make_archive_reader(); +#ifdef _WIN32 + require_archive_ok( + reader.get(), + archive_read_open_filename_w(reader.get(), zipPath.wstring().c_str(), kArchiveBlockSize), + "archive_read_open_filename_w failed" + ); +#else + require_archive_ok( + reader.get(), + archive_read_open_filename(reader.get(), zipPath.c_str(), kArchiveBlockSize), + "archive_read_open_filename failed" + ); +#endif + extract_archive(reader.get(), outDir); +} + +void unarchive_from_memory(const char* data, size_t size, const fs::path& outDir) { + if (data == nullptr || size == 0) { + throw std::runtime_error("empty archive"); + } + + auto reader = make_archive_reader(); + require_archive_ok( + reader.get(), + archive_read_open_memory(reader.get(), data, size), + "archive_read_open_memory failed" + ); + extract_archive(reader.get(), outDir); +} + +void archive_directory( + const fs::path& dirPath, + const fs::path& archive_path, + const Archive_Write_Options& options +) { + auto writer = make_archive_writer(options); +#ifdef _WIN32 + require_archive_ok( + writer.get(), + archive_write_open_filename_w(writer.get(), archive_path.wstring().c_str()), + "archive_write_open_filename_w failed" + ); +#else + require_archive_ok( + writer.get(), + archive_write_open_filename(writer.get(), archive_path.c_str()), + "archive_write_open_filename failed" + ); +#endif + write_directory_to_archive(writer.get(), dirPath, {}); + require_archive_ok(writer.get(), archive_write_close(writer.get()), "archive_write_close failed"); +} + +std::string archive_directory_to_memory( + const fs::path& dirPath, + const std::vector& ignorePatterns, + const Archive_Write_Options& options +) { + std::string out; + auto writer = make_archive_writer(options); + require_archive_ok( + writer.get(), + archive_write_open( + writer.get(), + &out, + archive_noop_open_close_callback, + archive_string_write_callback, + archive_noop_open_close_callback + ), + "archive_write_open failed" + ); + write_directory_to_archive(writer.get(), dirPath, ignorePatterns); + require_archive_ok(writer.get(), archive_write_close(writer.get()), "archive_write_close failed"); + return out; +} diff --git a/module/Local_Server/server/libarchive.h b/module/Local_Server/server/libarchive.h new file mode 100644 index 0000000..f775c15 --- /dev/null +++ b/module/Local_Server/server/libarchive.h @@ -0,0 +1,60 @@ +#ifndef PLANTSUNCAT_ZIP_H +#define PLANTSUNCAT_ZIP_H +#include "Core/Base/global_include.h" +#include +#include +#include +#include +#include +#include + +class Invalid_Archive_Error final : public std::runtime_error { +public: + using std::runtime_error::runtime_error; +}; + +struct Archive_Directory_Layout_Rule { + std::string directory; + std::vector required_files; + std::vector required_directories; + std::vector optional_files; + std::vector optional_directories; +}; + +struct Archive_Layout_Rules { + std::vector directories; + std::size_t max_archive_size = 128 * 1024 * 1024; + std::size_t max_entry_count = 16 * 1024; + std::uint64_t max_entry_uncompressed_size = 256ULL * 1024 * 1024; + std::uint64_t max_total_uncompressed_size = 512ULL * 1024 * 1024; +}; + +struct Archive_Write_Options { + std::string format = "zip"; + std::string filter; + std::string extension = "zip"; +}; + +Psc::expected validate_archive_layout_from_memory( + const char* data, + std::size_t size, + const Archive_Layout_Rules& rules +); + +void unarchive_file(const std::filesystem::path& zipPath, const std::filesystem::path& outDir); +void unarchive_from_memory(const char* data, size_t size, const std::filesystem::path& outDir); +void archive_directory( + const std::filesystem::path& dirPath, + const std::filesystem::path& archive_path, + const Archive_Write_Options& options = {} +); +// std::string zip_directory_to_memory(const std::filesystem::path& dirPath, +// const std::vector& ignoreDirs); + +std::string +archive_directory_to_memory( + const std::filesystem::path& dirPath, + const std::vector& ignorePatterns, + const Archive_Write_Options& options = {} +); +#endif diff --git a/module/Local_Server/server/server.cpp b/module/Local_Server/server/server.cpp new file mode 100644 index 0000000..f202964 --- /dev/null +++ b/module/Local_Server/server/server.cpp @@ -0,0 +1,679 @@ + +#include "Global.h" +#include "Performance_Monitor.h" + +#include +#include +#include + +namespace { + +constexpr std::size_t kMaxLogRequestBodySize = 8 * 1024; + +void Log_Request_Body_If_Small(const drogon::HttpRequestPtr& request) { + const auto& body = request->getBody(); + if (body.empty()) { + return; + } + + if (body.size() <= kMaxLogRequestBodySize) { + LOG_INFO + << "[request body] " + << "path=" << request->path() + << ", size=" << body.size() + << ", body=" << std::string(body.data(), body.size()); + } + else { + LOG_INFO + << "[request body skipped] " + << "path=" << request->path() + << ", size=" << body.size() + << ", max=" << kMaxLogRequestBodySize; + } +} + +bool Is_Invalid_Http_Param(const std::exception& e) { + return dynamic_cast(&e) != nullptr + || dynamic_cast(&e) != nullptr + || dynamic_cast(&e) != nullptr; +} + +bool Is_Safe_Version_Directory_Name(std::string_view name) { + if (name.empty() || name == "." || name == "..") { + return false; + } + return std::ranges::all_of(name, [](unsigned char ch) { + return std::isalnum(ch) != 0 || ch == '.' || ch == '_' || ch == '-'; + }); +} + +bool Is_Safe_Archive_Extension(std::string_view extension) { + if (extension.empty() || extension.front() == '.' || extension.back() == '.') { + return false; + } + return std::ranges::all_of(extension, [](unsigned char ch) { + return std::isalnum(ch) != 0 || ch == '.' || ch == '_' || ch == '-'; + }); +} + +std::string Normalize_Archive_Extension(std::string extension, std::string fallback = "zip") { + while (!extension.empty() && extension.front() == '.') { + extension.erase(extension.begin()); + } + if (extension.empty()) { + extension = std::move(fallback); + } + if (!Is_Safe_Archive_Extension(extension)) { + throw std::invalid_argument("invalid archive extension: " + extension); + } + return extension; +} + +std::optional Try_Get_String_Field(const JSON& object, const std::string& key) { + const JSON* value = object.get(key); + if (value == nullptr) { + return std::nullopt; + } + if (value->valueType != Psc::String) { + throw std::invalid_argument(key + " must be a string"); + } + return value->val; +} + +struct Archive_Export_Request { + std::string version; + Archive_Write_Options archive; +}; + +Archive_Export_Request Parse_Archive_Export_Request( + const drogon::HttpRequestPtr& req, + std::string default_version +) { + Archive_Export_Request result; + result.version = std::move(default_version); + + const auto& body = req->getBody(); + if (body.empty()) { + return result; + } + + auto parsed = Psc::try_parse_json(body.data()); + if (!parsed.has_value()) { + throw_invalid_http_param("request body is not valid JSON"); + } + + const JSON& params = parsed.value(); + if (auto version = Try_Get_String_Field(params, "version")) { + if (!version->empty()) { + result.version = *version; + } + } + if (!Is_Safe_Version_Directory_Name(result.version)) { + throw std::invalid_argument("invalid version name: " + result.version); + } + + if (auto format = Try_Get_String_Field(params, "format")) { + if (!format->empty()) { + result.archive.format = *format; + } + } + if (auto filter = Try_Get_String_Field(params, "filter")) { + result.archive.filter = *filter; + } + if (auto extension = Try_Get_String_Field(params, "extension")) { + if (!extension->empty()) { + result.archive.extension = Normalize_Archive_Extension(*extension); + } + } + else { + result.archive.extension = Normalize_Archive_Extension(result.archive.extension); + } + + return result; +} + +const Archive_Layout_Rules& Upgrade_Zip_Layout_Rules() { + static const Archive_Layout_Rules rules = [] { + Archive_Layout_Rules value; + value.directories = { + { + "", + {"adsb_cfg.ini", "config.json", "ecap_server", "lib9002config.json"}, + {"lib9002", "wwwroot"}, + {}, + {} + }, + { + "lib9002", + {"lib9002.so", "testserver"}, + {"env"}, + {}, + {} + } + }; + return value; + }(); + return rules; +} + +} // namespace + +void setupCors(); +void Global::init_web_server() { + register_http_performance_monitor( + http_monitor_config.access_log, + http_monitor_config.slow_request_threshold_ms); + setupCors(); + static auto &web_server = web_server_config; + Web_Server &svr = this->svr; + auto &da = drogon::app(); + auto return_file = [](const std::string &path) { + auto res = drogon::HttpResponse::newHttpResponse(); + if (std::filesystem::exists(path)) { + std::string content; + httplib::detail::read_file(path, content); + auto content_type = httplib::detail::find_content_type(path, {}, "application/octet-stream"); + res->setContentTypeString(content_type); + res->setBody(content); + // res.set_file_content(path); + } else { + res->setStatusCode(drogon::k404NotFound); + JSON ret = JSON::object(); + ret.append({"LOG_POS", LOG_POS}); + ret.append({"not_found_path", path}); + res->setContentTypeCode(drogon::CT_TEXT_PLAIN); + res->setBody(ret.to_json_string()); + } + return res; + }; + auto add_path = [return_file](const std::string &path) { + drogon::app().registerHandlerViaRegex( + path, + [return_file](const drogon::HttpRequestPtr &req, + std::function &&callback) { + callback(return_file(web_server.get_true_webapp() + "/index.html")); + }, + {drogon::Get}); + }; + + + drogon::app().registerHandlerViaRegex( + R"(^/tiles/.*$)", + [return_file](const drogon::HttpRequestPtr &req, + std::function &&callback) { + auto path = web_server.get_true_tiles() + req->getPath().substr(6); + callback(return_file(path)); + }, + {drogon::Get}); + + + drogon::app().registerHandlerViaRegex( + "/", + [return_file](const drogon::HttpRequestPtr &req, + std::function &&callback) { + callback(return_file(web_server.get_true_webapp() + "/index.html")); + }, + {drogon::Get}); + + + add_path(R"(^/settings)"); + add_path(R"(^/map)"); + add_path(R"(^/dsp)"); + add_path(R"(^/aircraftlist)"); + drogon::app().registerHandlerViaRegex( + R"(^/ui(/.*)?$)", [return_file](const drogon::HttpRequestPtr &req, + std::function &&callback) { + std::cout << req->path() << std::endl; + auto res = drogon::HttpResponse::newHttpResponse(); + auto path = web_server.get_true_webapp(); + auto rp = "/" + req->path().substr(3); + if (rp == "/") { + path += "/index.html"; + } else { + path += rp; + } + callback(return_file(path)); + }); + + State_Report::instance(); + svr.Get(R"(/get_debug_info)", [](HTTP_Param) { + JSON arr = JSON::array(); + auto &sp = Global::instance()->mode_acs.data_feed_config.pool_; + arr.append(JSON::object({{"remain_size", sp.remain_size()}, {"free_size", sp.free_size()}})); + res->setBody(arr.to_json_string("", "\n", "")); + }); + + + mlat.server(this); + database_server(this); + external_resources_manager.server(this); + device_config.server(this); + mode_acs.server(this); + dsp_config.server(this); + + + // s.w.init(); + + drogon::app().registerHandler( + api + "export_logs", + [](const drogon::HttpRequestPtr& req, + std::function&& cb) { + try { + auto export_request = Parse_Archive_Export_Request(req, Global::instance()->version); + const std::string& name = export_request.version; + auto version_dir = std::filesystem::path(get_exe_dir() + "/.."); + std::string data = archive_directory_to_memory(version_dir /name/"logs", + {}, + export_request.archive + ); + auto resp = drogon::HttpResponse::newHttpResponse(); + resp->setBody(data); + resp->setContentTypeString("application/octet-stream"); + resp->addHeader( + "Content-Disposition", + "attachment; filename*=UTF-8''" + name + "_logs." + export_request.archive.extension + ); + resp->addHeader( + "ok", "true" + ); + cb(resp); + } + + + + catch (const std::exception& e) { + auto resp = drogon::HttpResponse::newHttpResponse(); + resp->addHeader( + "ok", "false" + ); + Psc::JSON json = JSON::object({ + {"message", Psc::platform_2_utf8(e.what()) } + }); + resp->setContentTypeCode(drogon::CT_APPLICATION_JSON); + resp->setBody(json.to_json_string()); + cb(resp); + } + } + ); + + drogon::app().registerHandler( + api + "export_version", + [](const drogon::HttpRequestPtr& req, + std::function&& cb) { + try { + auto export_request = Parse_Archive_Export_Request(req, Global::instance()->version); + const std::string& name = export_request.version; + auto version_dir = std::filesystem::path(get_exe_dir() + "/.."); + + std::cout<< "准备压缩:" << std::endl; + std::string data = archive_directory_to_memory(version_dir /name, + { + "logs/", + "uploads/", + "drogon_uploads/", + "backups/", // ghw的什么文件路径 + "stack_trace.txt", + "pt.log", + "ecap_server.log", + "Core", + "core", + name + ".zip", + name + "." + export_request.archive.extension + }, + export_request.archive + ); + std::cout<< "压缩成功:" << data.size() << std::endl; + auto resp = drogon::HttpResponse::newHttpResponse(); + resp->setBody(data); + resp->setContentTypeString("application/octet-stream"); + resp->addHeader( + "Content-Disposition", + "attachment; filename*=UTF-8''" + name + "." + export_request.archive.extension + ); + resp->addHeader( + "ok", "true" + ); + cb(resp); + } + catch (const std::exception& e) { + auto message = Psc::platform_2_utf8(e.what()); + std::cout << "导出异常触发:" << message << " " << LOG_POS << std::endl; + auto resp = drogon::HttpResponse::newHttpResponse(); + + Psc::JSON json = JSON::object({ + {"message", message} + }); + resp->setContentTypeCode(drogon::CT_APPLICATION_JSON); + resp->setBody(json.to_json_string()); + resp->addHeader( + "ok", "false" + ); + cb(resp); + } + } + ); + + + + + drogon::app().registerHandler( + api + "restart_device",[] (const drogon::HttpRequestPtr& req, + std::function&& cb) { + + #ifdef __linux__ + std::string root_dir = Psc::get_exe_dir() + "/.."; + + std::string log_file = fmt::format("{}/restart_device.log", root_dir); + std::string cmd = fmt::format( + R"(systemd-run --scope --slice=system.slice sudo bash "{}/restart_device.bash" > {} 2>&1 &)", + root_dir, + log_file + ); + std::cout << "Generated Command: " << cmd << std::endl; + std::system(cmd.c_str()); + #endif + auto resp = drogon::HttpResponse::newHttpResponse(); + resp->setContentTypeCode(drogon::CT_APPLICATION_JSON); + resp->setBody(R"({"ok":true})"); + cb(resp); + + } + ); + + + drogon::app().registerHandler( + api + "import_version", + [] + (const drogon::HttpRequestPtr& req, + std::function&& cb) + { + try { + // ---------- 参数校验 ---------- + auto dir = req->getHeader("dir"); + if (!Is_Safe_Version_Directory_Name(dir)) { + throw std::invalid_argument("invalid or missing header: dir"); + } + + const auto& body = req->getBody(); + auto archive_layout_result = validate_archive_layout_from_memory( + body.data(), + body.size(), + Upgrade_Zip_Layout_Rules() + ); + if (!archive_layout_result) { + throw Invalid_Archive_Error(archive_layout_result.error()); + } + + auto version_dir = std::filesystem::path(get_exe_dir() + "/.."); + // ---------- 路径准备 ---------- + auto targetDir = version_dir / dir; + + std::cout << "========dir====" << dir << std::endl; + std::cout << "========version_dir====" << version_dir << std::endl; + std::cout << "========targetDir====" << targetDir << std::endl; + + std::filesystem::create_directories(targetDir); + + const auto archive_extension = Normalize_Archive_Extension(req->getHeader("archive-extension")); + auto archivePath = targetDir / (dir + "." + archive_extension); + + // ---------- 写 zip ---------- + std::ofstream ofs(archivePath, std::ios::binary); + if (!ofs) { + throw std::runtime_error("open archive failed: " + archivePath.string()); + } + + ofs.write(body.data(), body.size()); + if (!ofs) { + throw std::runtime_error("write archive failed: " + archivePath.string()); + } + ofs.close(); + if (!ofs) { + throw std::runtime_error("close archive failed: " + archivePath.string()); + } + + + + + #ifdef _WIN32 + std::string root_dir = version_dir.string(); + std::string old_version = Global::instance()->version; // Global version info + std::string new_version = dir; + std::string log_file = fmt::format("{}/upgrade_{}_to_{}.log", root_dir, old_version, new_version); + std::string cmd = fmt::format( + R"(powershell -NoProfile -ExecutionPolicy Bypass -Command "& {{ . '{}/upgrade.legacy' '{}' '{}' > '{}' 2>&1 }}" )", + root_dir, + old_version, + new_version, + log_file + ); + #else + std::string root_dir = version_dir.string(); + std::string old_version = Global::instance()->version; // Global version info + std::string new_version = dir; + std::string log_file = fmt::format("{}/upgrade_{}_to_{}.log",root_dir, old_version, new_version); + std::string cmd = fmt::format( + R"(systemd-run --scope --slice=system.slice sudo bash "{}/upgrade.bash" "{}" "{}" > {} 2>&1 &)", + root_dir, + old_version, + new_version, + log_file + ); + #endif + std::cout << "Generated Command: " << cmd << std::endl; + std::system(cmd.c_str()); + // ---------- 成功响应 ---------- + auto resp = drogon::HttpResponse::newHttpResponse(); + resp->setContentTypeCode(drogon::CT_APPLICATION_JSON); + resp->setBody(R"({"ok":true})"); + cb(resp); + } + catch (const std::exception& e) { + auto resp = drogon::HttpResponse::newHttpResponse(); + const bool invalid_input = + dynamic_cast(&e) != nullptr + || dynamic_cast(&e) != nullptr; + resp->setStatusCode( + invalid_input + ? drogon::k400BadRequest + : drogon::k500InternalServerError + ); + resp->setContentTypeCode(drogon::CT_APPLICATION_JSON); + auto reason = Psc::platform_2_utf8(e.what()); + std::cout << "异常" << reason << std::endl; + Psc::JSON json = JSON::object({ + {"ok", false}, + {"error", reason} + }); + resp->setBody(json.to_json_string()); + cb(resp); + } + }, + {drogon::Post} + ); + + + svr.Post(api + "get_debug_log", [](HTTP_Param) { + CHECK_JSON_PARAM + HTTP_REQUIRE_VALUE(start_serial_number, params.try_get_number("serial_number")) + auto log = base64_encode(debug_logger_info_manager.get_info(start_serial_number)); + JSON ret = JSON::object(); + ret.append({"log", log}); + ret.append({"serial_number", debug_logger_info_manager.get_cur_serial_number()}); + ret.append({"start_serial_number", start_serial_number}); + res->setBody(warp(ret).to_json_string()); + }); + + + svr.Post(api + "get_general_info", [](HTTP_Param) { + auto g = Global::instance(); + // auto &db = *Global::instance()->total_source(); + auto ret = JSON::object(); + // ret.append({"total_source key", db.key}); + // ret.append({"飞机总数", db.get_aircraft_num()}); + // ret.append({"解出位置的数量", db.have_pos_aircraft_num}); + JSON arr = JSON::object(); + for (auto &ds: g->mode_acs.data_source_config.map.list()) { + if (!ds->enable) continue; + arr.append({ds->key, ds->statistic_json()}); + } + ret.append({"统计信息", arr}); + // ret.append({"基站信息", base_station.to_Json()}); + res->setBody(warp(ret).to_json_string()); + }); + + + + + svr.Post(api + "version", [this](HTTP_Param) { + auto ret = JSON::object(); + ret.append({"version", version}); + res->setBody(warp(ret).to_json_string()); + }); + + + auto now = std::chrono::system_clock::now(); + start_server_time = std::chrono::system_clock::to_time_t(now); + svr.Post(api + "start_device_time", [this](HTTP_Param) { + auto ret = JSON::object(); + ret.append({"start_device_time", start_server_time}); + res->setBody(warp(ret).to_json_string()); + }); + + da.setDefaultHandler( + [](const drogon::HttpRequestPtr& req, + std::function&& callback) { + LOG_WARN + << "[http route not found] " + << "path=" << req->path(); + + auto res = drogon::HttpResponse::newHttpResponse(); + + res->setStatusCode(drogon::k404NotFound); + res->setBody("not found"); + res->addHeader("Content-Type", "text/plain; charset=utf-8"); + + callback(res); + } + ); + + da.setCustomErrorHandler( + [](drogon::HttpStatusCode status, + const drogon::HttpRequestPtr& req) -> drogon::HttpResponsePtr { + LOG_WARN + << "[http error] " + << "path=" << req->path() + << ", status=" << static_cast(status); + + auto res = drogon::HttpResponse::newHttpResponse(); + + res->setStatusCode(status); + res->setBody("http error"); + res->addHeader("Content-Type", "text/plain; charset=utf-8"); + + return res; + } + ); + + da.setExceptionHandler( + [](const std::exception& e, + const drogon::HttpRequestPtr& req, + std::function&& callback) { + auto res = drogon::HttpResponse::newHttpResponse(); + + if (Is_Invalid_Http_Param(e)) { + LOG_WARN + << "[invalid http parameters] " + << "path=" << req->path() + << ", detail=" << e.what(); + Log_Request_Body_If_Small(req); + + res->setStatusCode(drogon::k400BadRequest); + res->setContentTypeCode(drogon::CT_APPLICATION_JSON); + res->setBody(R"({"code":400,"message":"invalid http parameters"})"); + } + else { + LOG_ERROR + << "[handler exception] " + << "path=" << req->path() + << ", what=" << e.what(); + + res->setStatusCode(drogon::k500InternalServerError); + res->setContentTypeCode(drogon::CT_APPLICATION_JSON); + res->setBody(R"({"code":500,"message":"internal server error"})"); + } + + callback(res); + } + ); + + + da.setUploadPath(get_exe_dir() + "/drogon_uploads"); + std::cout << "上传路径: " << da.getUploadPath() << std::endl; + + + + init_ok = true; +} + +void setupCors() { + // Register sync advice to handle CORS preflight (OPTIONS) requests + drogon::app().registerSyncAdvice([](const drogon::HttpRequestPtr &req) -> drogon::HttpResponsePtr { + if (req->method() == drogon::HttpMethod::Options) { + auto resp = drogon::HttpResponse::newHttpResponse(); + + // Set Access-Control-Allow-Origin header based on the Origin + // request header + const auto &origin = req->getHeader("Origin"); + if (!origin.empty()) { + resp->addHeader("Access-Control-Allow-Origin", origin); + } + + // Set Access-Control-Allow-Methods based on the requested method + const auto &requestMethod = req->getHeader("Access-Control-Request-Method"); + if (!requestMethod.empty()) { + resp->addHeader("Access-Control-Allow-Methods", requestMethod); + } + + // Allow credentials to be included in cross-origin requests + resp->addHeader("Access-Control-Allow-Credentials", "true"); + + // Set allowed headers from the Access-Control-Request-Headers + // header + const auto &requestHeaders = req->getHeader("Access-Control-Request-Headers"); + if (!requestHeaders.empty()) { + resp->addHeader("Access-Control-Allow-Headers", requestHeaders); + } + + return std::move(resp); + } + return {}; + }); + + // Register post-handling advice to add CORS headers to all responses + drogon::app().registerPostHandlingAdvice( + [](const drogon::HttpRequestPtr &req, const drogon::HttpResponsePtr &resp) -> void { + // Set Access-Control-Allow-Origin based on the Origin request + // header + const auto &origin = req->getHeader("Origin"); + if (!origin.empty()) { + resp->addHeader("Access-Control-Allow-Origin", origin); + } + + // Reflect the requested Access-Control-Request-Method back in the + // response + const auto &requestMethod = req->getHeader("Access-Control-Request-Method"); + if (!requestMethod.empty()) { + resp->addHeader("Access-Control-Allow-Methods", requestMethod); + } + + // Allow credentials to be included in cross-origin requests + resp->addHeader("Access-Control-Allow-Credentials", "true"); + + // Reflect the requested Access-Control-Request-Headers back + const auto &requestHeaders = req->getHeader("Access-Control-Request-Headers"); + if (!requestHeaders.empty()) { + resp->addHeader("Access-Control-Allow-Headers", requestHeaders); + } + }); +} diff --git a/module/Local_Server_main.cpp b/module/Local_Server_main.cpp new file mode 100644 index 0000000..2dfdc57 --- /dev/null +++ b/module/Local_Server_main.cpp @@ -0,0 +1,229 @@ +#include +#include + +#include "Local_Server/Crawler/Crawler.h" +#include "Local_Server/Data_Source/Data_Source.h" +#include "Local_Server/State_Report/State_Report.h" +#include "Local_Server/server/Global.h" + +#include +#include +#include +#include +#include +// ./server ./config.json + +#ifdef __linux__ +#include +#endif + +struct Catch_Memory { + Catch_Memory() { + sm = (std::int64_t)get_system_memory(); + cur = (std::int64_t)get_process_memory(); + } + std::int64_t MB = 1024 * 1024; + bool catch_ok() { + auto old_memory = cur; + cur = (std::int64_t)get_process_memory(); + auto change_mb = (cur - old_memory) / MB; + auto cur_mb = cur / MB; + // std::cout << get_current_date_string() << " 时内存" << cur_mb << "MB " + // << " 变更" << change_mb << "MB" << std::endl; + + if (cur > memory_max) { + auto rate = (double)cur / (double)sm; + std::cout << get_current_date_string() + " 抓住内存暴涨:" << cur_mb + << "MB" << " 变更" << change_mb << "MB" << std::endl; + std::cout << "\t内存占用" << rate << "%" << std::endl; + stop_program = SIGINT; + +#if WIN32 +#else + system("top"); +#endif + return true; + } + return false; + } +#if WIN32 + std::int64_t memory_max = 1 * 1024 * 1024 * 1024; +#else + std::int64_t memory_max = 1 * 1024 * 1024 * 1024; +#endif + std::int64_t cur; + std::int64_t sm; +}; + +int wyc_main(int argc, char *argv[]) { + std::cout << "wyc_main" << std::endl; + + if (argc >= 2) { + std::string config_path = argv[1]; + if (config_path.at(0) == '@') { + config_path.replace(0, 1, get_exe_dir()); + } + ::default_config_path = config_path; + } + + // std::cout << get_stack_trace() << std::endl; + + init_signal_config({SIGINT, SIGTERM}, +#ifdef WIN32 + {} +#else + {SIGPIPE} +#endif + ); + auto clear = []() { + std::cout << "保存配置文件 " << LOG_POS << std::endl; + Config::save(); + std::cout << "shutdown" << std::endl; + + auto i = Global::instance(); + i->svr.stop(); + i->thread_manager.stop_all_thread(); + + Global::instance()->dsp_config.close_dsp_device(); + std::cout << "destroy开始" << std::endl; + Global::destroy(); + std::cout << " Base_Logger_Manager::instance()->destroy()开始" << std::endl; + Base_Logger_Manager::destroy(); + std::cout << " clear完成" << std::endl; + std::cout << " 正常退出" << std::endl; + }; + + + auto g = Global::instance(); + Psc::set_fail_fast([](const std::string& name) { + // 如果是在 Global::instance() 里面失败是不能调用这个处理函数的 + auto g = Global::instance(); + std::cout << "set_fail_fast 退出原因: 222" << name << std::endl; + std::cout << "shutdown" << LOG_POS << std::endl; + + + auto id = std::this_thread::get_id(); + std::cout << "id: " << id << std::endl; + + + + Detach_Thread *dt = g->thread_manager.get_thread(id); + if (!dt) + { + std::cout << VAR_STR_1((void*)dt) << std::endl; + std::terminate(); + } + + + std::set excluded_thread; + excluded_thread.insert(dt->name); + std::cout << dt->name << std::endl; + + + + // std::cout << "保存配置文件 " << LOG_POS << std::endl; + // Config::save(); + + + + g->svr.stop(); + g->thread_manager.stop_all_thread(10000, excluded_thread); + std::cout << "22222222" << std::endl; + Global::instance()->dsp_config.close_dsp_device(); + + std::cout << "destroy开始" << std::endl; + Global::destroy(); + std::cout << " Base_Logger_Manager::instance()->destroy()开始" << std::endl; + Base_Logger_Manager::destroy(); + std::cout << " clear完成" << std::endl; + std::cout << " std::exit(75) " << name << std::endl; + std::exit(75); + std::cout << "std::exit(75) 完成:" << name << std::endl; + }); + + + + Detach_Thread_Manager &manager = g->thread_manager; + std::cout << "[主线程:" << std::this_thread::get_id() << "]" << " \n" + << std::flush; + manager.test_and_start_thread( + "web服务器线程", [g](std::atomic &running) { + auto &c = Global::instance()->device_config; + std::string ip = "0.0.0.0"; +#ifdef WIN32 + ip = "127.0.0.1"; +#endif + Net_Config *device = c.list.get("device").value(); + std::cout << "http://" + ip + ":" + std::to_string(device->port) + "\n" + << std::flush; + std::cout << "http://" + device->ip + ":" + + std::to_string(device->port) + "\n" + << std::flush; + if (!g->svr.listen("0.0.0.0", device->port)) { + if (running.load(std::memory_order_acquire)) { + std::cout << "http://" + ip + ":" + std::to_string(device->port) + + "启动失败 退出!\n" + << std::flush; + std::cout << "http://" + device->ip + ":" + + std::to_string(device->port) + "启动失败 退出!\n" + << std::flush; + std::exit(0); + } + } + }); + manager.test_and_start_thread("data_feed_thread", data_feed_thread); + static int t = Global::instance()->mode_acs.read_milliseconds; + for (auto &source : + Global::instance()->mode_acs.data_source_config.map.list()) { + if (!source->enable) + continue; + source->test_and_attach_thread(); + } + g->dsp_config.init_env(); + + bool enable = g->mlat.enable; + + // Catch_Memory cm; + while (stop_program == 0) { + for (auto &ds : g->mode_acs.data_source_config.map.list()) { + ds->delete_timeout_aircraft(); + } + + if (enable) { + g->mlat.refresh(); + } +#ifdef __linux__ + if (g->mode_acs.monitor_msg_live) + malloc_trim(0); +#endif + std::this_thread::sleep_for(std::chrono::seconds(3)); + if (Global::instance()->init_ok) { + // if (cm.catch_ok()) { + // stop_program = SIGINT; + // break; + // } + } + } + + if (stop_program == SIGINT || stop_program == SIGTERM) { + clear(); + } + + return 0; +} + + +int main(int argc, char* argv[]) { + return redict_main_with_gtest(argc, argv, wyc_main); +} + + + + +// int main(int argc, char* argv[]) { +// +// Psc::set_console_utf8(); +// std::cout << "asio 起点" << std::endl; +// +// return 0; +// } \ No newline at end of file diff --git a/module/Mock/main.cpp b/module/Mock/main.cpp new file mode 100644 index 0000000..bcf534c --- /dev/null +++ b/module/Mock/main.cpp @@ -0,0 +1,56 @@ +#include +#include "mock_core.h" +int main() { + std::cout << "Hello World!\n"; + + std::vector stations; + auto yan_tai = new Mock::BaseStation(); + yan_tai->set_pos(37.5102686, 121.4399498); + stations.push_back(yan_tai); + auto qing_dao = new Mock::BaseStation(); + qing_dao->set_pos(36.0759435, 120.4085225); + stations.push_back(qing_dao); + auto ji_nan = new Mock::BaseStation(); + ji_nan->set_pos(36.6513057, 116.9837594); + stations.push_back(ji_nan); + + + + Mock::Plane plane; + plane.icao = "ABCDEF"; + while (true) { + MLAT_timestamp cur; + + for (auto station : stations) + { + auto i = plane.generate_message(&cur, {37, 121}, station); + auto t = station->generage_message(); + std::cout << memory2hex(i) << std::endl; + std::cout << memory2hex(t) << std::endl; + } + + + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); + + } + + + return 0; +} + + + + +// Mock::BaseStation b; +// b.set_pos(37, 137); +// +// auto mem = b.generage_message(); +// +// auto mem2 = unescape_packet(mem); +// std::cout << mem << std::endl; +// +// std::cout << mem2.size() << " parse_hex:" << memory2hex(mem2) << std::endl; +// +// HULC_Status_Message message = create_HULC_Status_Message(mem2); +// +// std::cout << "完全相等" << bool (unescape_packet(message.toBinary()) == mem2) << std::endl; diff --git a/module/Mock/mock_core.cpp b/module/Mock/mock_core.cpp new file mode 100644 index 0000000..15fc5e4 --- /dev/null +++ b/module/Mock/mock_core.cpp @@ -0,0 +1 @@ +#include "mock_core.h" diff --git a/module/Mock/mock_core.h b/module/Mock/mock_core.h new file mode 100644 index 0000000..13942dc --- /dev/null +++ b/module/Mock/mock_core.h @@ -0,0 +1,84 @@ +#ifndef MOCK_CORE_H +#define MOCK_CORE_H +#include + + +// 通过构造 三个基站 以及 一个飞机 三个数据源 来生成数据 + +namespace Mock { + struct BaseStation { + Psc::socket::Server_Socket server; + HULC_Status_Message hulc_message{}; + // 生成HUCL消息报告 1a34 自身经纬度 1s 1次 + BaseStation() { + hulc_message.SerNum = 3; + hulc_message.Alt = 7500; + hulc_message.HDOP = 0.75; + hulc_message.Sat = 75; + hulc_message.I_U_ = 88; + } + + std::string generage_message() { + auto now = std::chrono::system_clock::now(); + auto epoch = std::chrono::system_clock::to_time_t(now); + hulc_message.xTime = epoch; + // 要经过转义 + return packet_to_escape_format(hulc_message.toBinary()); + } + + void set_pos(CPR::D lat, CPR::D lon) { + hulc_message.set_latitude(lat); + hulc_message.set_longitude(lon); + } + [[nodiscard]] CPR::Position position() const { + CPR::Position pos{}; + pos.latitude = hulc_message.get_latitude(); + pos.longitude = hulc_message.get_longitude(); + return pos; + } + }; + + class Plane { + public: + std::string icao; + std::vector track; + std::string generate_message(MLAT_timestamp* timestamp, CPR::Position pos, BaseStation* station) { + All_Call_Reply::All_Call_Reply r = All_Call_Reply::All_Call_Reply::Builder() + .set_icao(icao) + .set_interrogator_identifier("abc750") + .set_transponder_address(hex2bin("abc617")) + .build(); + + + auto [i1, i2] = CPR::light_time_second_nano(station->position(), pos); + auto total_nanosec = timestamp->nanosec + i2; // 累加纳秒部分 + auto total_sec = timestamp->daysec + i1; // 累加秒部分 + if (total_nanosec >= 1000000000) { + // 纳秒部分超过 1 秒,处理进位 + total_sec += total_nanosec / 1000000000; // 将纳秒转换为秒并加到 total_sec + total_nanosec = total_nanosec % 1000000000; // 保留纳秒部分,取余数 + } + MLAT_timestamp t(total_sec, total_nanosec); + // 默认构造获取系统的描述 已经经过转义 + return create_Binary_Format_memory(bin2hex(r.msg), 75, &t); + } + }; + + + struct Global { + std::vector planes; + + + + std::vector stations; + + }; + + +} + + + + + +#endif diff --git a/module/Radarcape_Core/cpp-httplib/doc.txt b/module/Radarcape_Core/cpp-httplib/doc.txt new file mode 100644 index 0000000..b777ae8 --- /dev/null +++ b/module/Radarcape_Core/cpp-httplib/doc.txt @@ -0,0 +1 @@ +https://github.com/yhirose/cpp-httplib \ No newline at end of file diff --git a/module/Radarcape_Core/cpp-httplib/httplib.h b/module/Radarcape_Core/cpp-httplib/httplib.h new file mode 100644 index 0000000..c068a65 --- /dev/null +++ b/module/Radarcape_Core/cpp-httplib/httplib.h @@ -0,0 +1,11698 @@ +// +// httplib.h +// +// Copyright (c) 2024 Yuji Hirose. All rights reserved. +// MIT License +// + +#ifndef CPPHTTPLIB_HTTPLIB_H +#define CPPHTTPLIB_HTTPLIB_H + +#define CPPHTTPLIB_VERSION "0.18.2" + +/* + * Configuration + */ + +#ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND +#define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5 +#endif + +#ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND +#define CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND 10000 +#endif + +#ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT +#define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 100 +#endif + +#ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND +#define CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND 300 +#endif + +#ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND +#define CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND 0 +#endif + +#ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND +#define CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND 5 +#endif + +#ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND +#define CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND 0 +#endif + +#ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND +#define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND 5 +#endif + +#ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND +#define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND 0 +#endif + +#ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND +#define CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND 300 +#endif + +#ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND +#define CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND 0 +#endif + +#ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND +#define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND 5 +#endif + +#ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND +#define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND 0 +#endif + +#ifndef CPPHTTPLIB_IDLE_INTERVAL_SECOND +#define CPPHTTPLIB_IDLE_INTERVAL_SECOND 0 +#endif + +#ifndef CPPHTTPLIB_IDLE_INTERVAL_USECOND +#ifdef _WIN32 +#define CPPHTTPLIB_IDLE_INTERVAL_USECOND 10000 +#else +#define CPPHTTPLIB_IDLE_INTERVAL_USECOND 0 +#endif +#endif + +#ifndef CPPHTTPLIB_REQUEST_URI_MAX_LENGTH +#define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192 +#endif + +#ifndef CPPHTTPLIB_HEADER_MAX_LENGTH +#define CPPHTTPLIB_HEADER_MAX_LENGTH 8192 +#endif + +#ifndef CPPHTTPLIB_REDIRECT_MAX_COUNT +#define CPPHTTPLIB_REDIRECT_MAX_COUNT 20 +#endif + +#ifndef CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT +#define CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT 1024 +#endif + +#ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH +#define CPPHTTPLIB_PAYLOAD_MAX_LENGTH ((std::numeric_limits::max)()) +#endif + +#ifndef CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH +#define CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH 8192 +#endif + +#ifndef CPPHTTPLIB_RANGE_MAX_COUNT +#define CPPHTTPLIB_RANGE_MAX_COUNT 1024 +#endif + +#ifndef CPPHTTPLIB_TCP_NODELAY +#define CPPHTTPLIB_TCP_NODELAY false +#endif + +#ifndef CPPHTTPLIB_IPV6_V6ONLY +#define CPPHTTPLIB_IPV6_V6ONLY false +#endif + +#ifndef CPPHTTPLIB_RECV_BUFSIZ +#define CPPHTTPLIB_RECV_BUFSIZ size_t(16384u) +#endif + +#ifndef CPPHTTPLIB_COMPRESSION_BUFSIZ +#define CPPHTTPLIB_COMPRESSION_BUFSIZ size_t(16384u) +#endif + +#ifndef CPPHTTPLIB_THREAD_POOL_COUNT +#define CPPHTTPLIB_THREAD_POOL_COUNT \ + ((std::max)(8u, std::thread::hardware_concurrency() > 0 \ + ? std::thread::hardware_concurrency() - 1 \ + : 0)) +#endif + +#ifndef CPPHTTPLIB_RECV_FLAGS +#define CPPHTTPLIB_RECV_FLAGS 0 +#endif + +#ifndef CPPHTTPLIB_SEND_FLAGS +#define CPPHTTPLIB_SEND_FLAGS 0 +#endif + +#ifndef CPPHTTPLIB_LISTEN_BACKLOG +#define CPPHTTPLIB_LISTEN_BACKLOG 5 +#endif + +/* + * Headers + */ + +#ifdef _WIN32 +#ifndef _CRT_SECURE_NO_WARNINGS +#define _CRT_SECURE_NO_WARNINGS +#endif //_CRT_SECURE_NO_WARNINGS + +#ifndef _CRT_NONSTDC_NO_DEPRECATE +#define _CRT_NONSTDC_NO_DEPRECATE +#endif //_CRT_NONSTDC_NO_DEPRECATE + +#if defined(_MSC_VER) +#if _MSC_VER < 1900 +#error Sorry, Visual Studio versions prior to 2015 are not supported +#endif + +#pragma comment(lib, "ws2_32.lib") + +#ifdef _WIN64 +using ssize_t = __int64; +#else +using ssize_t = long; +#endif +#endif // _MSC_VER + +#ifndef S_ISREG +#define S_ISREG(m) (((m) & S_IFREG) == S_IFREG) +#endif // S_ISREG + +#ifndef S_ISDIR +#define S_ISDIR(m) (((m) & S_IFDIR) == S_IFDIR) +#endif // S_ISDIR + +#ifndef NOMINMAX +#define NOMINMAX +#endif // NOMINMAX + +#include +#include +#include + +#ifndef WSA_FLAG_NO_HANDLE_INHERIT +#define WSA_FLAG_NO_HANDLE_INHERIT 0x80 +#endif + +using socket_t = SOCKET; +#ifdef CPPHTTPLIB_USE_POLL +#define poll(fds, nfds, timeout) WSAPoll(fds, nfds, timeout) +#endif + +#else // not _WIN32 + +#include +#if !defined(_AIX) && !defined(__MVS__) +#include +#endif +#ifdef __MVS__ +#include +#ifndef NI_MAXHOST +#define NI_MAXHOST 1025 +#endif +#endif +#include +#include +#include +#ifdef __linux__ +#include +#endif +#include +#ifdef CPPHTTPLIB_USE_POLL +#include +#endif +#include +#include +#include +#include +#include +#include +#include + +using socket_t = int; +#ifndef INVALID_SOCKET +#define INVALID_SOCKET (-1) +#endif +#endif //_WIN32 + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT +#ifdef _WIN32 +#include + +// these are defined in wincrypt.h and it breaks compilation if BoringSSL is +// used +#undef X509_NAME +#undef X509_CERT_PAIR +#undef X509_EXTENSIONS +#undef PKCS7_SIGNER_INFO + +#ifdef _MSC_VER +#pragma comment(lib, "crypt32.lib") +#endif +#elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && defined(__APPLE__) +#include +#if TARGET_OS_OSX +#include +#include +#endif // TARGET_OS_OSX +#endif // _WIN32 + +#include +#include +#include +#include + +#if defined(_WIN32) && defined(OPENSSL_USE_APPLINK) +#include +#endif + +#include +#include + +#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER) +#if OPENSSL_VERSION_NUMBER < 0x1010107f +#error Please use OpenSSL or a current version of BoringSSL +#endif +#define SSL_get1_peer_certificate SSL_get_peer_certificate +#elif OPENSSL_VERSION_NUMBER < 0x30000000L +#error Sorry, OpenSSL versions prior to 3.0.0 are not supported +#endif + +#endif + +#ifdef CPPHTTPLIB_ZLIB_SUPPORT +#include +#endif + +#ifdef CPPHTTPLIB_BROTLI_SUPPORT +#include +#include +#endif + +/* + * Declaration + */ +namespace httplib +{ + namespace detail + { + /* + * Backport std::make_unique from C++14. + * + * NOTE: This code came up with the following stackoverflow post: + * https://stackoverflow.com/questions/10149840/c-arrays-and-make-unique + * + */ + + template + typename std::enable_if::value, std::unique_ptr>::type + make_unique(Args&&... args) + { + return std::unique_ptr(new T(std::forward(args)...)); + } + + template + typename std::enable_if::value, std::unique_ptr>::type + make_unique(std::size_t n) + { + typedef typename std::remove_extent::type RT; + return std::unique_ptr(new RT[n]); + } + + namespace case_ignore + { + inline unsigned char to_lower(int c) + { + const static unsigned char table[256] = { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, + 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, + 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, + 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, + 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, + 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, + 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, + 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, + 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, + 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, + 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, + 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 224, 225, 226, + 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, + 242, 243, 244, 245, 246, 215, 248, 249, 250, 251, 252, 253, 254, 223, 224, + 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, + 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, + 255, + }; + return table[(unsigned char)(char)c]; + } + + inline bool equal(const std::string& a, const std::string& b) + { + return a.size() == b.size() && + std::equal(a.begin(), a.end(), b.begin(), [](char ca, char cb) + { + return to_lower(ca) == to_lower(cb); + }); + } + + struct equal_to + { + bool operator()(const std::string& a, const std::string& b) const + { + return equal(a, b); + } + }; + + struct hash + { + size_t operator()(const std::string& key) const + { + return hash_core(key.data(), key.size(), 0); + } + + size_t hash_core(const char* s, size_t l, size_t h) const + { + return (l == 0) + ? h + : hash_core(s + 1, l - 1, + // Unsets the 6 high bits of h, therefore no + // overflow happens + (((std::numeric_limits::max)() >> 6) & + h * 33) ^ + static_cast(to_lower(*s))); + } + }; + } // namespace case_ignore + + // This is based on + // "http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4189". + + struct scope_exit + { + explicit scope_exit(std::function&& f) : + exit_function(std::move(f)), execute_on_destruction{true} + { + } + + scope_exit(scope_exit&& rhs) noexcept : + exit_function(std::move(rhs.exit_function)), + execute_on_destruction{rhs.execute_on_destruction} + { + rhs.release(); + } + + ~scope_exit() + { + if (execute_on_destruction) { this->exit_function(); } + } + + void release() { this->execute_on_destruction = false; } + + private: + scope_exit(const scope_exit&) = delete; + void operator=(const scope_exit&) = delete; + scope_exit& operator=(scope_exit&&) = delete; + + std::function exit_function; + bool execute_on_destruction; + }; + } // namespace detail + + enum StatusCode + { + // Information responses + Continue_100 = 100, + SwitchingProtocol_101 = 101, + Processing_102 = 102, + EarlyHints_103 = 103, + + // Successful responses + OK_200 = 200, + Created_201 = 201, + Accepted_202 = 202, + NonAuthoritativeInformation_203 = 203, + NoContent_204 = 204, + ResetContent_205 = 205, + PartialContent_206 = 206, + MultiStatus_207 = 207, + AlreadyReported_208 = 208, + IMUsed_226 = 226, + + // Redirection messages + MultipleChoices_300 = 300, + MovedPermanently_301 = 301, + Found_302 = 302, + SeeOther_303 = 303, + NotModified_304 = 304, + UseProxy_305 = 305, + unused_306 = 306, + TemporaryRedirect_307 = 307, + PermanentRedirect_308 = 308, + + // Client error responses + BadRequest_400 = 400, + Unauthorized_401 = 401, + PaymentRequired_402 = 402, + Forbidden_403 = 403, + NotFound_404 = 404, + MethodNotAllowed_405 = 405, + NotAcceptable_406 = 406, + ProxyAuthenticationRequired_407 = 407, + RequestTimeout_408 = 408, + Conflict_409 = 409, + Gone_410 = 410, + LengthRequired_411 = 411, + PreconditionFailed_412 = 412, + PayloadTooLarge_413 = 413, + UriTooLong_414 = 414, + UnsupportedMediaType_415 = 415, + RangeNotSatisfiable_416 = 416, + ExpectationFailed_417 = 417, + ImATeapot_418 = 418, + MisdirectedRequest_421 = 421, + UnprocessableContent_422 = 422, + Locked_423 = 423, + FailedDependency_424 = 424, + TooEarly_425 = 425, + UpgradeRequired_426 = 426, + PreconditionRequired_428 = 428, + TooManyRequests_429 = 429, + RequestHeaderFieldsTooLarge_431 = 431, + UnavailableForLegalReasons_451 = 451, + + // Server error responses + InternalServerError_500 = 500, + NotImplemented_501 = 501, + BadGateway_502 = 502, + ServiceUnavailable_503 = 503, + GatewayTimeout_504 = 504, + HttpVersionNotSupported_505 = 505, + VariantAlsoNegotiates_506 = 506, + InsufficientStorage_507 = 507, + LoopDetected_508 = 508, + NotExtended_510 = 510, + NetworkAuthenticationRequired_511 = 511, + }; + + using Headers = + std::unordered_multimap; + + using Params = std::multimap; + using Match = std::smatch; + + using Progress = std::function; + + struct Response; + using ResponseHandler = std::function; + + struct MultipartFormData + { + std::string name; + std::string content; + std::string filename; + std::string content_type; + }; + + using MultipartFormDataItems = std::vector; + using MultipartFormDataMap = std::multimap; + + class DataSink + { + public: + DataSink() : + os(&sb_), sb_(*this) + { + } + + DataSink(const DataSink&) = delete; + DataSink& operator=(const DataSink&) = delete; + DataSink(DataSink&&) = delete; + DataSink& operator=(DataSink&&) = delete; + + std::function write; + std::function is_writable; + std::function done; + std::function done_with_trailer; + std::ostream os; + + private: + class data_sink_streambuf final : public std::streambuf + { + public: + explicit data_sink_streambuf(DataSink& sink) : + sink_(sink) + { + } + + protected: + std::streamsize xsputn(const char* s, std::streamsize n) override + { + sink_.write(s, static_cast(n)); + return n; + } + + private: + DataSink& sink_; + }; + + data_sink_streambuf sb_; + }; + + using ContentProvider = + std::function; + + using ContentProviderWithoutLength = + std::function; + + using ContentProviderResourceReleaser = std::function; + + struct MultipartFormDataProvider + { + std::string name; + ContentProviderWithoutLength provider; + std::string filename; + std::string content_type; + }; + + using MultipartFormDataProviderItems = std::vector; + + using ContentReceiverWithProgress = + std::function; + + using ContentReceiver = + std::function; + + using MultipartContentHeader = + std::function; + + class ContentReader + { + public: + using Reader = std::function; + using MultipartReader = std::function; + + ContentReader(Reader reader, MultipartReader multipart_reader) : + reader_(std::move(reader)), + multipart_reader_(std::move(multipart_reader)) + { + } + + bool operator()(MultipartContentHeader header, + ContentReceiver receiver) const + { + return multipart_reader_(std::move(header), std::move(receiver)); + } + + bool operator()(ContentReceiver receiver) const + { + return reader_(std::move(receiver)); + } + + Reader reader_; + MultipartReader multipart_reader_; + }; + + using Range = std::pair; + using Ranges = std::vector; + + struct Request + { + std::string method; + std::string path; + Params params; + Headers headers; + std::string body; + + std::string remote_addr; + int remote_port = -1; + std::string local_addr; + int local_port = -1; + + // for server + std::string version; + std::string target; + MultipartFormDataMap files; + Ranges ranges; + Match matches; + std::unordered_map path_params; + + // for client + ResponseHandler response_handler; + ContentReceiverWithProgress content_receiver; + Progress progress; +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + const SSL *ssl = nullptr; +#endif + + bool has_header(const std::string& key) const; + std::string get_header_value(const std::string& key, const char* def = "", + size_t id = 0) const; + uint64_t get_header_value_u64(const std::string& key, uint64_t def = 0, + size_t id = 0) const; + size_t get_header_value_count(const std::string& key) const; + void set_header(const std::string& key, const std::string& val); + + bool has_param(const std::string& key) const; + std::string get_param_value(const std::string& key, size_t id = 0) const; + size_t get_param_value_count(const std::string& key) const; + + bool is_multipart_form_data() const; + + bool has_file(const std::string& key) const; + MultipartFormData get_file_value(const std::string& key) const; + std::vector get_file_values(const std::string& key) const; + + // private members... + size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT; + size_t content_length_ = 0; + ContentProvider content_provider_; + bool is_chunked_content_provider_ = false; + size_t authorization_count_ = 0; + }; + + struct Response + { + std::string version; + int status = -1; + std::string reason; + Headers headers; + std::string body; + std::string location; // Redirect location + + bool has_header(const std::string& key) const; + std::string get_header_value(const std::string& key, const char* def = "", + size_t id = 0) const; + uint64_t get_header_value_u64(const std::string& key, uint64_t def = 0, + size_t id = 0) const; + size_t get_header_value_count(const std::string& key) const; + void set_header(const std::string& key, const std::string& val); + + void set_redirect(const std::string& url, int status = StatusCode::Found_302); + void set_content(const char* s, size_t n, const std::string& content_type); + void set_content(const std::string& s, const std::string& content_type); + void set_content(std::string&& s, const std::string& content_type); + + void set_content_provider( + size_t length, const std::string& content_type, ContentProvider provider, + ContentProviderResourceReleaser resource_releaser = nullptr); + + void set_content_provider( + const std::string& content_type, ContentProviderWithoutLength provider, + ContentProviderResourceReleaser resource_releaser = nullptr); + + void set_chunked_content_provider( + const std::string& content_type, ContentProviderWithoutLength provider, + ContentProviderResourceReleaser resource_releaser = nullptr); + + void set_file_content(const std::string& path, + const std::string& content_type); + void set_file_content(const std::string& path); + + Response() = default; + Response(const Response&) = default; + Response& operator=(const Response&) = default; + Response(Response&&) = default; + Response& operator=(Response&&) = default; + + ~Response() + { + if (content_provider_resource_releaser_) + { + content_provider_resource_releaser_(content_provider_success_); + } + } + + // private members... + size_t content_length_ = 0; + ContentProvider content_provider_; + ContentProviderResourceReleaser content_provider_resource_releaser_; + bool is_chunked_content_provider_ = false; + bool content_provider_success_ = false; + std::string file_content_path_; + std::string file_content_content_type_; + }; + + class Stream + { + public: + virtual ~Stream() = default; + + virtual bool is_readable() const = 0; + virtual bool is_writable() const = 0; + + virtual ssize_t read(char* ptr, size_t size) = 0; + virtual ssize_t write(const char* ptr, size_t size) = 0; + virtual void get_remote_ip_and_port(std::string& ip, int& port) const = 0; + virtual void get_local_ip_and_port(std::string& ip, int& port) const = 0; + virtual socket_t socket() const = 0; + + ssize_t write(const char* ptr); + ssize_t write(const std::string& s); + }; + + class TaskQueue + { + public: + TaskQueue() = default; + virtual ~TaskQueue() = default; + + virtual bool enqueue(std::function fn) = 0; + virtual void shutdown() = 0; + + virtual void on_idle() + { + } + }; + + class ThreadPool final : public TaskQueue + { + public: + explicit ThreadPool(size_t n, size_t mqr = 0) : + shutdown_(false), max_queued_requests_(mqr) + { + while (n) + { + threads_.emplace_back(worker(*this)); + n--; + } + } + + ThreadPool(const ThreadPool&) = delete; + ~ThreadPool() override = default; + + bool enqueue(std::function fn) override + { + { + std::unique_lock lock(mutex_); + if (max_queued_requests_ > 0 && jobs_.size() >= max_queued_requests_) + { + return false; + } + jobs_.push_back(std::move(fn)); + } + + cond_.notify_one(); + return true; + } + + void shutdown() override + { + // Stop all worker threads... + { + std::unique_lock lock(mutex_); + shutdown_ = true; + } + + cond_.notify_all(); + + // Join... + for (auto& t : threads_) + { + t.join(); + } + } + + private: + struct worker + { + explicit worker(ThreadPool& pool) : + pool_(pool) + { + } + + void operator()() + { + for (;;) + { + std::function fn; + { + std::unique_lock lock(pool_.mutex_); + + pool_.cond_.wait( + lock, [&] { return !pool_.jobs_.empty() || pool_.shutdown_; }); + + if (pool_.shutdown_ && pool_.jobs_.empty()) { break; } + + fn = pool_.jobs_.front(); + pool_.jobs_.pop_front(); + } + + assert(true == static_cast(fn)); + fn(); + } + +#if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && \ + !defined(LIBRESSL_VERSION_NUMBER) + OPENSSL_thread_stop(); +#endif + } + + ThreadPool& pool_; + }; + + friend struct worker; + + std::vector threads_; + std::list> jobs_; + + bool shutdown_; + size_t max_queued_requests_ = 0; + + std::condition_variable cond_; + std::mutex mutex_; + }; + + using Logger = std::function; + + using SocketOptions = std::function; + + void default_socket_options(socket_t sock); + + const char* status_message(int status); + + std::string get_bearer_token_auth(const Request& req); + + namespace detail + { + class MatcherBase + { + public: + virtual ~MatcherBase() = default; + + // Match request path and populate its matches and + virtual bool match(Request& request) const = 0; + }; + + /** + * Captures parameters in request path and stores them in Request::path_params + * + * Capture name is a substring of a pattern from : to /. + * The rest of the pattern is matched agains the request path directly + * Parameters are captured starting from the next character after + * the end of the last matched static pattern fragment until the next /. + * + * Example pattern: + * "/path/fragments/:capture/more/fragments/:second_capture" + * Static fragments: + * "/path/fragments/", "more/fragments/" + * + * Given the following request path: + * "/path/fragments/:1/more/fragments/:2" + * the resulting capture will be + * {{"capture", "1"}, {"second_capture", "2"}} + */ + class PathParamsMatcher final : public MatcherBase + { + public: + PathParamsMatcher(const std::string& pattern); + + bool match(Request& request) const override; + + private: + // Treat segment separators as the end of path parameter capture + // Does not need to handle query parameters as they are parsed before path + // matching + static constexpr char separator = '/'; + + // Contains static path fragments to match against, excluding the '/' after + // path params + // Fragments are separated by path params + std::vector static_fragments_; + // Stores the names of the path parameters to be used as keys in the + // Request::path_params map + std::vector param_names_; + }; + + /** + * Performs std::regex_match on request path + * and stores the result in Request::matches + * + * Note that regex match is performed directly on the whole request. + * This means that wildcard patterns may match multiple path segments with /: + * "/begin/(.*)/end" will match both "/begin/middle/end" and "/begin/1/2/end". + */ + class RegexMatcher final : public MatcherBase + { + public: + RegexMatcher(const std::string& pattern) : + regex_(pattern) + { + } + + bool match(Request& request) const override; + + private: + std::regex regex_; + }; + + ssize_t write_headers(Stream& strm, const Headers& headers); + } // namespace detail + + class Server + { + public: + using Handler = std::function; + + using ExceptionHandler = + std::function; + + enum class HandlerResponse + { + Handled, + Unhandled, + }; + + using HandlerWithResponse = + std::function; + + using HandlerWithContentReader = std::function; + + using Expect100ContinueHandler = + std::function; + + Server(); + + virtual ~Server(); + + virtual bool is_valid() const; + + Server& Get(const std::string& pattern, Handler handler); + Server& Post(const std::string& pattern, Handler handler); + Server& Post(const std::string& pattern, HandlerWithContentReader handler); + Server& Put(const std::string& pattern, Handler handler); + Server& Put(const std::string& pattern, HandlerWithContentReader handler); + Server& Patch(const std::string& pattern, Handler handler); + Server& Patch(const std::string& pattern, HandlerWithContentReader handler); + Server& Delete(const std::string& pattern, Handler handler); + Server& Delete(const std::string& pattern, HandlerWithContentReader handler); + Server& Options(const std::string& pattern, Handler handler); + + bool set_base_dir(const std::string& dir, + const std::string& mount_point = std::string()); + bool set_mount_point(const std::string& mount_point, const std::string& dir, + Headers headers = Headers()); + bool remove_mount_point(const std::string& mount_point); + Server& set_file_extension_and_mimetype_mapping(const std::string& ext, + const std::string& mime); + Server& set_default_file_mimetype(const std::string& mime); + Server& set_file_request_handler(Handler handler); + + template + Server& set_error_handler(ErrorHandlerFunc&& handler) + { + return set_error_handler_core( + std::forward(handler), + std::is_convertible{}); + } + + Server& set_exception_handler(ExceptionHandler handler); + Server& set_pre_routing_handler(HandlerWithResponse handler); + Server& set_post_routing_handler(Handler handler); + + Server& set_expect_100_continue_handler(Expect100ContinueHandler handler); + Server& set_logger(Logger logger); + + Server& set_address_family(int family); + Server& set_tcp_nodelay(bool on); + Server& set_ipv6_v6only(bool on); + Server& set_socket_options(SocketOptions socket_options); + + Server& set_default_headers(Headers headers); + Server& + set_header_writer(std::function const& writer); + + Server& set_keep_alive_max_count(size_t count); + Server& set_keep_alive_timeout(time_t sec); + + Server& set_read_timeout(time_t sec, time_t usec = 0); + template + Server& set_read_timeout(const std::chrono::duration& duration); + + Server& set_write_timeout(time_t sec, time_t usec = 0); + template + Server& set_write_timeout(const std::chrono::duration& duration); + + Server& set_idle_interval(time_t sec, time_t usec = 0); + template + Server& set_idle_interval(const std::chrono::duration& duration); + + Server& set_payload_max_length(size_t length); + + bool bind_to_port(const std::string& host, int port, int socket_flags = 0); + int bind_to_any_port(const std::string& host, int socket_flags = 0); + bool listen_after_bind(); + + bool listen(const std::string& host, int port, int socket_flags = 0); + + bool is_running() const; + void wait_until_ready() const; + void stop(); + void decommission(); + + std::function new_task_queue; + + protected: + bool process_request(Stream& strm, const std::string& remote_addr, + int remote_port, const std::string& local_addr, + int local_port, bool close_connection, + bool& connection_closed, + const std::function& setup_request); + + std::atomic svr_sock_{INVALID_SOCKET}; + size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT; + time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND; + time_t read_timeout_sec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND; + time_t read_timeout_usec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND; + time_t write_timeout_sec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND; + time_t write_timeout_usec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND; + time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND; + time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND; + size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH; + + private: + using Handlers = + std::vector, Handler>>; + using HandlersForContentReader = + std::vector, + HandlerWithContentReader>>; + + static std::unique_ptr + make_matcher(const std::string& pattern); + + Server& set_error_handler_core(HandlerWithResponse handler, std::true_type); + Server& set_error_handler_core(Handler handler, std::false_type); + + socket_t create_server_socket(const std::string& host, int port, + int socket_flags, + SocketOptions socket_options) const; + int bind_internal(const std::string& host, int port, int socket_flags); + bool listen_internal(); + + bool routing(Request& req, Response& res, Stream& strm); + bool handle_file_request(const Request& req, Response& res, + bool head = false); + bool dispatch_request(Request& req, Response& res, + const Handlers& handlers) const; + bool dispatch_request_for_content_reader( + Request& req, Response& res, ContentReader content_reader, + const HandlersForContentReader& handlers) const; + + bool parse_request_line(const char* s, Request& req) const; + void apply_ranges(const Request& req, Response& res, + std::string& content_type, std::string& boundary) const; + bool write_response(Stream& strm, bool close_connection, Request& req, + Response& res); + bool write_response_with_content(Stream& strm, bool close_connection, + const Request& req, Response& res); + bool write_response_core(Stream& strm, bool close_connection, + const Request& req, Response& res, + bool need_apply_ranges); + bool write_content_with_provider(Stream& strm, const Request& req, + Response& res, const std::string& boundary, + const std::string& content_type); + bool read_content(Stream& strm, Request& req, Response& res); + bool + read_content_with_content_receiver(Stream& strm, Request& req, Response& res, + ContentReceiver receiver, + MultipartContentHeader multipart_header, + ContentReceiver multipart_receiver); + bool read_content_core(Stream& strm, Request& req, Response& res, + ContentReceiver receiver, + MultipartContentHeader multipart_header, + ContentReceiver multipart_receiver) const; + + virtual bool process_and_close_socket(socket_t sock); + + std::atomic is_running_{false}; + std::atomic is_decommisioned{false}; + + struct MountPointEntry + { + std::string mount_point; + std::string base_dir; + Headers headers; + }; + + std::vector base_dirs_; + std::map file_extension_and_mimetype_map_; + std::string default_file_mimetype_ = "application/octet-stream"; + Handler file_request_handler_; + + Handlers get_handlers_; + Handlers post_handlers_; + HandlersForContentReader post_handlers_for_content_reader_; + Handlers put_handlers_; + HandlersForContentReader put_handlers_for_content_reader_; + Handlers patch_handlers_; + HandlersForContentReader patch_handlers_for_content_reader_; + Handlers delete_handlers_; + HandlersForContentReader delete_handlers_for_content_reader_; + Handlers options_handlers_; + + HandlerWithResponse error_handler_; + ExceptionHandler exception_handler_; + HandlerWithResponse pre_routing_handler_; + Handler post_routing_handler_; + Expect100ContinueHandler expect_100_continue_handler_; + + Logger logger_; + + int address_family_ = AF_UNSPEC; + bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY; + bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY; + SocketOptions socket_options_ = default_socket_options; + + Headers default_headers_; + std::function header_writer_ = + detail::write_headers; + }; + + enum class Error + { + Success = 0, + Unknown, + Connection, + BindIPAddress, + Read, + Write, + ExceedRedirectCount, + Canceled, + SSLConnection, + SSLLoadingCerts, + SSLServerVerification, + SSLServerHostnameVerification, + UnsupportedMultipartBoundaryChars, + Compression, + ConnectionTimeout, + ProxyConnection, + + // For internal use only + SSLPeerCouldBeClosed_, + }; + + std::string to_string(Error error); + + std::ostream& operator<<(std::ostream& os, const Error& obj); + + class Result + { + public: + Result() = default; + + Result(std::unique_ptr&& res, Error err, + Headers&& request_headers = Headers{}) : + res_(std::move(res)), err_(err), + request_headers_(std::move(request_headers)) + { + } + + // Response + operator bool() const { return res_ != nullptr; } + bool operator==(std::nullptr_t) const { return res_ == nullptr; } + bool operator!=(std::nullptr_t) const { return res_ != nullptr; } + const Response& value() const { return *res_; } + Response& value() { return *res_; } + const Response& operator*() const { return *res_; } + Response& operator*() { return *res_; } + const Response* operator->() const { return res_.get(); } + Response* operator->() { return res_.get(); } + + // Error + Error error() const { return err_; } + + // Request Headers + bool has_request_header(const std::string& key) const; + std::string get_request_header_value(const std::string& key, + const char* def = "", + size_t id = 0) const; + uint64_t get_request_header_value_u64(const std::string& key, + uint64_t def = 0, size_t id = 0) const; + size_t get_request_header_value_count(const std::string& key) const; + + private: + std::unique_ptr res_; + Error err_ = Error::Unknown; + Headers request_headers_; + }; + + class ClientImpl + { + public: + explicit ClientImpl(const std::string& host); + + explicit ClientImpl(const std::string& host, int port); + + explicit ClientImpl(const std::string& host, int port, + const std::string& client_cert_path, + const std::string& client_key_path); + + virtual ~ClientImpl(); + + virtual bool is_valid() const; + + Result Get(const std::string& path); + Result Get(const std::string& path, const Headers& headers); + Result Get(const std::string& path, Progress progress); + Result Get(const std::string& path, const Headers& headers, + Progress progress); + Result Get(const std::string& path, ContentReceiver content_receiver); + Result Get(const std::string& path, const Headers& headers, + ContentReceiver content_receiver); + Result Get(const std::string& path, ContentReceiver content_receiver, + Progress progress); + Result Get(const std::string& path, const Headers& headers, + ContentReceiver content_receiver, Progress progress); + Result Get(const std::string& path, ResponseHandler response_handler, + ContentReceiver content_receiver); + Result Get(const std::string& path, const Headers& headers, + ResponseHandler response_handler, + ContentReceiver content_receiver); + Result Get(const std::string& path, ResponseHandler response_handler, + ContentReceiver content_receiver, Progress progress); + Result Get(const std::string& path, const Headers& headers, + ResponseHandler response_handler, ContentReceiver content_receiver, + Progress progress); + + Result Get(const std::string& path, const Params& params, + const Headers& headers, Progress progress = nullptr); + Result Get(const std::string& path, const Params& params, + const Headers& headers, ContentReceiver content_receiver, + Progress progress = nullptr); + Result Get(const std::string& path, const Params& params, + const Headers& headers, ResponseHandler response_handler, + ContentReceiver content_receiver, Progress progress = nullptr); + + Result Head(const std::string& path); + Result Head(const std::string& path, const Headers& headers); + + Result Post(const std::string& path); + Result Post(const std::string& path, const Headers& headers); + Result Post(const std::string& path, const char* body, size_t content_length, + const std::string& content_type); + Result Post(const std::string& path, const Headers& headers, const char* body, + size_t content_length, const std::string& content_type); + Result Post(const std::string& path, const Headers& headers, const char* body, + size_t content_length, const std::string& content_type, + Progress progress); + Result Post(const std::string& path, const std::string& body, + const std::string& content_type); + Result Post(const std::string& path, const std::string& body, + const std::string& content_type, Progress progress); + Result Post(const std::string& path, const Headers& headers, + const std::string& body, const std::string& content_type); + Result Post(const std::string& path, const Headers& headers, + const std::string& body, const std::string& content_type, + Progress progress); + Result Post(const std::string& path, size_t content_length, + ContentProvider content_provider, + const std::string& content_type); + Result Post(const std::string& path, + ContentProviderWithoutLength content_provider, + const std::string& content_type); + Result Post(const std::string& path, const Headers& headers, + size_t content_length, ContentProvider content_provider, + const std::string& content_type); + Result Post(const std::string& path, const Headers& headers, + ContentProviderWithoutLength content_provider, + const std::string& content_type); + Result Post(const std::string& path, const Params& params); + Result Post(const std::string& path, const Headers& headers, + const Params& params); + Result Post(const std::string& path, const Headers& headers, + const Params& params, Progress progress); + Result Post(const std::string& path, const MultipartFormDataItems& items); + Result Post(const std::string& path, const Headers& headers, + const MultipartFormDataItems& items); + Result Post(const std::string& path, const Headers& headers, + const MultipartFormDataItems& items, const std::string& boundary); + Result Post(const std::string& path, const Headers& headers, + const MultipartFormDataItems& items, + const MultipartFormDataProviderItems& provider_items); + + Result Put(const std::string& path); + Result Put(const std::string& path, const char* body, size_t content_length, + const std::string& content_type); + Result Put(const std::string& path, const Headers& headers, const char* body, + size_t content_length, const std::string& content_type); + Result Put(const std::string& path, const Headers& headers, const char* body, + size_t content_length, const std::string& content_type, + Progress progress); + Result Put(const std::string& path, const std::string& body, + const std::string& content_type); + Result Put(const std::string& path, const std::string& body, + const std::string& content_type, Progress progress); + Result Put(const std::string& path, const Headers& headers, + const std::string& body, const std::string& content_type); + Result Put(const std::string& path, const Headers& headers, + const std::string& body, const std::string& content_type, + Progress progress); + Result Put(const std::string& path, size_t content_length, + ContentProvider content_provider, const std::string& content_type); + Result Put(const std::string& path, + ContentProviderWithoutLength content_provider, + const std::string& content_type); + Result Put(const std::string& path, const Headers& headers, + size_t content_length, ContentProvider content_provider, + const std::string& content_type); + Result Put(const std::string& path, const Headers& headers, + ContentProviderWithoutLength content_provider, + const std::string& content_type); + Result Put(const std::string& path, const Params& params); + Result Put(const std::string& path, const Headers& headers, + const Params& params); + Result Put(const std::string& path, const Headers& headers, + const Params& params, Progress progress); + Result Put(const std::string& path, const MultipartFormDataItems& items); + Result Put(const std::string& path, const Headers& headers, + const MultipartFormDataItems& items); + Result Put(const std::string& path, const Headers& headers, + const MultipartFormDataItems& items, const std::string& boundary); + Result Put(const std::string& path, const Headers& headers, + const MultipartFormDataItems& items, + const MultipartFormDataProviderItems& provider_items); + + Result Patch(const std::string& path); + Result Patch(const std::string& path, const char* body, size_t content_length, + const std::string& content_type); + Result Patch(const std::string& path, const char* body, size_t content_length, + const std::string& content_type, Progress progress); + Result Patch(const std::string& path, const Headers& headers, + const char* body, size_t content_length, + const std::string& content_type); + Result Patch(const std::string& path, const Headers& headers, + const char* body, size_t content_length, + const std::string& content_type, Progress progress); + Result Patch(const std::string& path, const std::string& body, + const std::string& content_type); + Result Patch(const std::string& path, const std::string& body, + const std::string& content_type, Progress progress); + Result Patch(const std::string& path, const Headers& headers, + const std::string& body, const std::string& content_type); + Result Patch(const std::string& path, const Headers& headers, + const std::string& body, const std::string& content_type, + Progress progress); + Result Patch(const std::string& path, size_t content_length, + ContentProvider content_provider, + const std::string& content_type); + Result Patch(const std::string& path, + ContentProviderWithoutLength content_provider, + const std::string& content_type); + Result Patch(const std::string& path, const Headers& headers, + size_t content_length, ContentProvider content_provider, + const std::string& content_type); + Result Patch(const std::string& path, const Headers& headers, + ContentProviderWithoutLength content_provider, + const std::string& content_type); + + Result Delete(const std::string& path); + Result Delete(const std::string& path, const Headers& headers); + Result Delete(const std::string& path, const char* body, + size_t content_length, const std::string& content_type); + Result Delete(const std::string& path, const char* body, + size_t content_length, const std::string& content_type, + Progress progress); + Result Delete(const std::string& path, const Headers& headers, + const char* body, size_t content_length, + const std::string& content_type); + Result Delete(const std::string& path, const Headers& headers, + const char* body, size_t content_length, + const std::string& content_type, Progress progress); + Result Delete(const std::string& path, const std::string& body, + const std::string& content_type); + Result Delete(const std::string& path, const std::string& body, + const std::string& content_type, Progress progress); + Result Delete(const std::string& path, const Headers& headers, + const std::string& body, const std::string& content_type); + Result Delete(const std::string& path, const Headers& headers, + const std::string& body, const std::string& content_type, + Progress progress); + + Result Options(const std::string& path); + Result Options(const std::string& path, const Headers& headers); + + bool send(Request& req, Response& res, Error& error); + Result send(const Request& req); + + void stop(); + + std::string host() const; + int port() const; + + size_t is_socket_open() const; + socket_t socket() const; + + void set_hostname_addr_map(std::map addr_map); + + void set_default_headers(Headers headers); + + void + set_header_writer(std::function const& writer); + + void set_address_family(int family); + void set_tcp_nodelay(bool on); + void set_ipv6_v6only(bool on); + void set_socket_options(SocketOptions socket_options); + + void set_connection_timeout(time_t sec, time_t usec = 0); + template + void + set_connection_timeout(const std::chrono::duration& duration); + + void set_read_timeout(time_t sec, time_t usec = 0); + template + void set_read_timeout(const std::chrono::duration& duration); + + void set_write_timeout(time_t sec, time_t usec = 0); + template + void set_write_timeout(const std::chrono::duration& duration); + + void set_basic_auth(const std::string& username, const std::string& password); + void set_bearer_token_auth(const std::string& token); +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + void set_digest_auth(const std::string &username, + const std::string &password); +#endif + + void set_keep_alive(bool on); + void set_follow_location(bool on); + + void set_url_encode(bool on); + + void set_compress(bool on); + + void set_decompress(bool on); + + void set_interface(const std::string& intf); + + void set_proxy(const std::string& host, int port); + void set_proxy_basic_auth(const std::string& username, + const std::string& password); + void set_proxy_bearer_token_auth(const std::string& token); +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + void set_proxy_digest_auth(const std::string &username, + const std::string &password); +#endif + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + void set_ca_cert_path(const std::string &ca_cert_file_path, + const std::string &ca_cert_dir_path = std::string()); + void set_ca_cert_store(X509_STORE *ca_cert_store); + X509_STORE *create_ca_cert_store(const char *ca_cert, std::size_t size) const; +#endif + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + void enable_server_certificate_verification(bool enabled); + void enable_server_hostname_verification(bool enabled); + void set_server_certificate_verifier(std::function verifier); +#endif + + void set_logger(Logger logger); + + protected: + struct Socket + { + socket_t sock = INVALID_SOCKET; +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + SSL *ssl = nullptr; +#endif + + bool is_open() const { return sock != INVALID_SOCKET; } + }; + + virtual bool create_and_connect_socket(Socket& socket, Error& error); + + // All of: + // shutdown_ssl + // shutdown_socket + // close_socket + // should ONLY be called when socket_mutex_ is locked. + // Also, shutdown_ssl and close_socket should also NOT be called concurrently + // with a DIFFERENT thread sending requests using that socket. + virtual void shutdown_ssl(Socket& socket, bool shutdown_gracefully); + void shutdown_socket(Socket& socket) const; + void close_socket(Socket& socket); + + bool process_request(Stream& strm, Request& req, Response& res, + bool close_connection, Error& error); + + bool write_content_with_provider(Stream& strm, const Request& req, + Error& error) const; + + void copy_settings(const ClientImpl& rhs); + + // Socket endpoint information + const std::string host_; + const int port_; + const std::string host_and_port_; + + // Current open socket + Socket socket_; + mutable std::mutex socket_mutex_; + std::recursive_mutex request_mutex_; + + // These are all protected under socket_mutex + size_t socket_requests_in_flight_ = 0; + std::thread::id socket_requests_are_from_thread_ = std::thread::id(); + bool socket_should_be_closed_when_request_is_done_ = false; + + // Hostname-IP map + std::map addr_map_; + + // Default headers + Headers default_headers_; + + // Header writer + std::function header_writer_ = + detail::write_headers; + + // Settings + std::string client_cert_path_; + std::string client_key_path_; + + time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND; + time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND; + time_t read_timeout_sec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND; + time_t read_timeout_usec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND; + time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND; + time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND; + + std::string basic_auth_username_; + std::string basic_auth_password_; + std::string bearer_token_auth_token_; +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + std::string digest_auth_username_; + std::string digest_auth_password_; +#endif + + bool keep_alive_ = false; + bool follow_location_ = false; + + bool url_encode_ = true; + + int address_family_ = AF_UNSPEC; + bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY; + bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY; + SocketOptions socket_options_ = nullptr; + + bool compress_ = false; + bool decompress_ = true; + + std::string interface_; + + std::string proxy_host_; + int proxy_port_ = -1; + + std::string proxy_basic_auth_username_; + std::string proxy_basic_auth_password_; + std::string proxy_bearer_token_auth_token_; +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + std::string proxy_digest_auth_username_; + std::string proxy_digest_auth_password_; +#endif + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + std::string ca_cert_file_path_; + std::string ca_cert_dir_path_; + + X509_STORE *ca_cert_store_ = nullptr; +#endif + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + bool server_certificate_verification_ = true; + bool server_hostname_verification_ = true; + std::function server_certificate_verifier_; +#endif + + Logger logger_; + + private: + bool send_(Request& req, Response& res, Error& error); + Result send_(Request&& req); + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + bool is_ssl_peer_could_be_closed(SSL *ssl) const; +#endif + socket_t create_client_socket(Error& error) const; + bool read_response_line(Stream& strm, const Request& req, + Response& res) const; + bool write_request(Stream& strm, Request& req, bool close_connection, + Error& error); + bool redirect(Request& req, Response& res, Error& error); + bool handle_request(Stream& strm, Request& req, Response& res, + bool close_connection, Error& error); + std::unique_ptr send_with_content_provider( + Request& req, const char* body, size_t content_length, + ContentProvider content_provider, + ContentProviderWithoutLength content_provider_without_length, + const std::string& content_type, Error& error); + Result send_with_content_provider( + const std::string& method, const std::string& path, + const Headers& headers, const char* body, size_t content_length, + ContentProvider content_provider, + ContentProviderWithoutLength content_provider_without_length, + const std::string& content_type, Progress progress); + ContentProviderWithoutLength get_multipart_content_provider( + const std::string& boundary, const MultipartFormDataItems& items, + const MultipartFormDataProviderItems& provider_items) const; + + std::string adjust_host_string(const std::string& host) const; + + virtual bool process_socket(const Socket& socket, + std::function callback); + virtual bool is_ssl() const; + }; + + class Client + { + public: + // Universal interface + explicit Client(const std::string& scheme_host_port); + + explicit Client(const std::string& scheme_host_port, + const std::string& client_cert_path, + const std::string& client_key_path); + + // HTTP only interface + explicit Client(const std::string& host, int port); + + explicit Client(const std::string& host, int port, + const std::string& client_cert_path, + const std::string& client_key_path); + + Client(Client&&) = default; + Client& operator=(Client&&) = default; + + ~Client(); + + bool is_valid() const; + + Result Get(const std::string& path); + Result Get(const std::string& path, const Headers& headers); + Result Get(const std::string& path, Progress progress); + Result Get(const std::string& path, const Headers& headers, + Progress progress); + Result Get(const std::string& path, ContentReceiver content_receiver); + Result Get(const std::string& path, const Headers& headers, + ContentReceiver content_receiver); + Result Get(const std::string& path, ContentReceiver content_receiver, + Progress progress); + Result Get(const std::string& path, const Headers& headers, + ContentReceiver content_receiver, Progress progress); + Result Get(const std::string& path, ResponseHandler response_handler, + ContentReceiver content_receiver); + Result Get(const std::string& path, const Headers& headers, + ResponseHandler response_handler, + ContentReceiver content_receiver); + Result Get(const std::string& path, const Headers& headers, + ResponseHandler response_handler, ContentReceiver content_receiver, + Progress progress); + Result Get(const std::string& path, ResponseHandler response_handler, + ContentReceiver content_receiver, Progress progress); + + Result Get(const std::string& path, const Params& params, + const Headers& headers, Progress progress = nullptr); + Result Get(const std::string& path, const Params& params, + const Headers& headers, ContentReceiver content_receiver, + Progress progress = nullptr); + Result Get(const std::string& path, const Params& params, + const Headers& headers, ResponseHandler response_handler, + ContentReceiver content_receiver, Progress progress = nullptr); + + Result Head(const std::string& path); + Result Head(const std::string& path, const Headers& headers); + + Result Post(const std::string& path); + Result Post(const std::string& path, const Headers& headers); + Result Post(const std::string& path, const char* body, size_t content_length, + const std::string& content_type); + Result Post(const std::string& path, const Headers& headers, const char* body, + size_t content_length, const std::string& content_type); + Result Post(const std::string& path, const Headers& headers, const char* body, + size_t content_length, const std::string& content_type, + Progress progress); + Result Post(const std::string& path, const std::string& body, + const std::string& content_type); + Result Post(const std::string& path, const std::string& body, + const std::string& content_type, Progress progress); + Result Post(const std::string& path, const Headers& headers, + const std::string& body, const std::string& content_type); + Result Post(const std::string& path, const Headers& headers, + const std::string& body, const std::string& content_type, + Progress progress); + Result Post(const std::string& path, size_t content_length, + ContentProvider content_provider, + const std::string& content_type); + Result Post(const std::string& path, + ContentProviderWithoutLength content_provider, + const std::string& content_type); + Result Post(const std::string& path, const Headers& headers, + size_t content_length, ContentProvider content_provider, + const std::string& content_type); + Result Post(const std::string& path, const Headers& headers, + ContentProviderWithoutLength content_provider, + const std::string& content_type); + Result Post(const std::string& path, const Params& params); + Result Post(const std::string& path, const Headers& headers, + const Params& params); + Result Post(const std::string& path, const Headers& headers, + const Params& params, Progress progress); + Result Post(const std::string& path, const MultipartFormDataItems& items); + Result Post(const std::string& path, const Headers& headers, + const MultipartFormDataItems& items); + Result Post(const std::string& path, const Headers& headers, + const MultipartFormDataItems& items, const std::string& boundary); + Result Post(const std::string& path, const Headers& headers, + const MultipartFormDataItems& items, + const MultipartFormDataProviderItems& provider_items); + + Result Put(const std::string& path); + Result Put(const std::string& path, const char* body, size_t content_length, + const std::string& content_type); + Result Put(const std::string& path, const Headers& headers, const char* body, + size_t content_length, const std::string& content_type); + Result Put(const std::string& path, const Headers& headers, const char* body, + size_t content_length, const std::string& content_type, + Progress progress); + Result Put(const std::string& path, const std::string& body, + const std::string& content_type); + Result Put(const std::string& path, const std::string& body, + const std::string& content_type, Progress progress); + Result Put(const std::string& path, const Headers& headers, + const std::string& body, const std::string& content_type); + Result Put(const std::string& path, const Headers& headers, + const std::string& body, const std::string& content_type, + Progress progress); + Result Put(const std::string& path, size_t content_length, + ContentProvider content_provider, const std::string& content_type); + Result Put(const std::string& path, + ContentProviderWithoutLength content_provider, + const std::string& content_type); + Result Put(const std::string& path, const Headers& headers, + size_t content_length, ContentProvider content_provider, + const std::string& content_type); + Result Put(const std::string& path, const Headers& headers, + ContentProviderWithoutLength content_provider, + const std::string& content_type); + Result Put(const std::string& path, const Params& params); + Result Put(const std::string& path, const Headers& headers, + const Params& params); + Result Put(const std::string& path, const Headers& headers, + const Params& params, Progress progress); + Result Put(const std::string& path, const MultipartFormDataItems& items); + Result Put(const std::string& path, const Headers& headers, + const MultipartFormDataItems& items); + Result Put(const std::string& path, const Headers& headers, + const MultipartFormDataItems& items, const std::string& boundary); + Result Put(const std::string& path, const Headers& headers, + const MultipartFormDataItems& items, + const MultipartFormDataProviderItems& provider_items); + + Result Patch(const std::string& path); + Result Patch(const std::string& path, const char* body, size_t content_length, + const std::string& content_type); + Result Patch(const std::string& path, const char* body, size_t content_length, + const std::string& content_type, Progress progress); + Result Patch(const std::string& path, const Headers& headers, + const char* body, size_t content_length, + const std::string& content_type); + Result Patch(const std::string& path, const Headers& headers, + const char* body, size_t content_length, + const std::string& content_type, Progress progress); + Result Patch(const std::string& path, const std::string& body, + const std::string& content_type); + Result Patch(const std::string& path, const std::string& body, + const std::string& content_type, Progress progress); + Result Patch(const std::string& path, const Headers& headers, + const std::string& body, const std::string& content_type); + Result Patch(const std::string& path, const Headers& headers, + const std::string& body, const std::string& content_type, + Progress progress); + Result Patch(const std::string& path, size_t content_length, + ContentProvider content_provider, + const std::string& content_type); + Result Patch(const std::string& path, + ContentProviderWithoutLength content_provider, + const std::string& content_type); + Result Patch(const std::string& path, const Headers& headers, + size_t content_length, ContentProvider content_provider, + const std::string& content_type); + Result Patch(const std::string& path, const Headers& headers, + ContentProviderWithoutLength content_provider, + const std::string& content_type); + + Result Delete(const std::string& path); + Result Delete(const std::string& path, const Headers& headers); + Result Delete(const std::string& path, const char* body, + size_t content_length, const std::string& content_type); + Result Delete(const std::string& path, const char* body, + size_t content_length, const std::string& content_type, + Progress progress); + Result Delete(const std::string& path, const Headers& headers, + const char* body, size_t content_length, + const std::string& content_type); + Result Delete(const std::string& path, const Headers& headers, + const char* body, size_t content_length, + const std::string& content_type, Progress progress); + Result Delete(const std::string& path, const std::string& body, + const std::string& content_type); + Result Delete(const std::string& path, const std::string& body, + const std::string& content_type, Progress progress); + Result Delete(const std::string& path, const Headers& headers, + const std::string& body, const std::string& content_type); + Result Delete(const std::string& path, const Headers& headers, + const std::string& body, const std::string& content_type, + Progress progress); + + Result Options(const std::string& path); + Result Options(const std::string& path, const Headers& headers); + + bool send(Request& req, Response& res, Error& error); + Result send(const Request& req); + + void stop(); + + std::string host() const; + int port() const; + + size_t is_socket_open() const; + socket_t socket() const; + + void set_hostname_addr_map(std::map addr_map); + + void set_default_headers(Headers headers); + + void + set_header_writer(std::function const& writer); + + void set_address_family(int family); + void set_tcp_nodelay(bool on); + void set_socket_options(SocketOptions socket_options); + + void set_connection_timeout(time_t sec, time_t usec = 0); + template + void + set_connection_timeout(const std::chrono::duration& duration); + + void set_read_timeout(time_t sec, time_t usec = 0); + template + void set_read_timeout(const std::chrono::duration& duration); + + void set_write_timeout(time_t sec, time_t usec = 0); + template + void set_write_timeout(const std::chrono::duration& duration); + + void set_basic_auth(const std::string& username, const std::string& password); + void set_bearer_token_auth(const std::string& token); +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + void set_digest_auth(const std::string &username, + const std::string &password); +#endif + + void set_keep_alive(bool on); + void set_follow_location(bool on); + + void set_url_encode(bool on); + + void set_compress(bool on); + + void set_decompress(bool on); + + void set_interface(const std::string& intf); + + void set_proxy(const std::string& host, int port); + void set_proxy_basic_auth(const std::string& username, + const std::string& password); + void set_proxy_bearer_token_auth(const std::string& token); +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + void set_proxy_digest_auth(const std::string &username, + const std::string &password); +#endif + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + void enable_server_certificate_verification(bool enabled); + void enable_server_hostname_verification(bool enabled); + void set_server_certificate_verifier(std::function verifier); +#endif + + void set_logger(Logger logger); + + // SSL +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + void set_ca_cert_path(const std::string &ca_cert_file_path, + const std::string &ca_cert_dir_path = std::string()); + + void set_ca_cert_store(X509_STORE *ca_cert_store); + void load_ca_cert_store(const char *ca_cert, std::size_t size); + + long get_openssl_verify_result() const; + + SSL_CTX *ssl_context() const; +#endif + + private: + std::unique_ptr cli_; + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + bool is_ssl_ = false; +#endif + }; + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT +class SSLServer : public Server { +public: + SSLServer(const char *cert_path, const char *private_key_path, + const char *client_ca_cert_file_path = nullptr, + const char *client_ca_cert_dir_path = nullptr, + const char *private_key_password = nullptr); + + SSLServer(X509 *cert, EVP_PKEY *private_key, + X509_STORE *client_ca_cert_store = nullptr); + + SSLServer( + const std::function &setup_ssl_ctx_callback); + + ~SSLServer() override; + + bool is_valid() const override; + + SSL_CTX *ssl_context() const; + + void update_certs(X509 *cert, EVP_PKEY *private_key, + X509_STORE *client_ca_cert_store = nullptr); + +private: + bool process_and_close_socket(socket_t sock) override; + + SSL_CTX *ctx_; + std::mutex ctx_mutex_; +}; + +class SSLClient final : public ClientImpl { +public: + explicit SSLClient(const std::string &host); + + explicit SSLClient(const std::string &host, int port); + + explicit SSLClient(const std::string &host, int port, + const std::string &client_cert_path, + const std::string &client_key_path, + const std::string &private_key_password = std::string()); + + explicit SSLClient(const std::string &host, int port, X509 *client_cert, + EVP_PKEY *client_key, + const std::string &private_key_password = std::string()); + + ~SSLClient() override; + + bool is_valid() const override; + + void set_ca_cert_store(X509_STORE *ca_cert_store); + void load_ca_cert_store(const char *ca_cert, std::size_t size); + + long get_openssl_verify_result() const; + + SSL_CTX *ssl_context() const; + +private: + bool create_and_connect_socket(Socket &socket, Error &error) override; + void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override; + void shutdown_ssl_impl(Socket &socket, bool shutdown_gracefully); + + bool process_socket(const Socket &socket, + std::function callback) override; + bool is_ssl() const override; + + bool connect_with_proxy(Socket &sock, Response &res, bool &success, + Error &error); + bool initialize_ssl(Socket &socket, Error &error); + + bool load_certs(); + + bool verify_host(X509 *server_cert) const; + bool verify_host_with_subject_alt_name(X509 *server_cert) const; + bool verify_host_with_common_name(X509 *server_cert) const; + bool check_host_name(const char *pattern, size_t pattern_len) const; + + SSL_CTX *ctx_; + std::mutex ctx_mutex_; + std::once_flag initialize_cert_; + + std::vector host_components_; + + long verify_result_ = 0; + + friend class ClientImpl; +}; +#endif + + /* + * Implementation of template methods. + */ + + namespace detail + { + template + inline void duration_to_sec_and_usec(const T& duration, U callback) + { + auto sec = std::chrono::duration_cast(duration).count(); + auto usec = std::chrono::duration_cast( + duration - std::chrono::seconds(sec)) + .count(); + callback(static_cast(sec), static_cast(usec)); + } + + inline uint64_t get_header_value_u64(const Headers& headers, + const std::string& key, uint64_t def, + size_t id) + { + auto rng = headers.equal_range(key); + auto it = rng.first; + std::advance(it, static_cast(id)); + if (it != rng.second) + { + return std::strtoull(it->second.data(), nullptr, 10); + } + return def; + } + } // namespace detail + + inline uint64_t Request::get_header_value_u64(const std::string& key, + uint64_t def, size_t id) const + { + return detail::get_header_value_u64(headers, key, def, id); + } + + inline uint64_t Response::get_header_value_u64(const std::string& key, + uint64_t def, size_t id) const + { + return detail::get_header_value_u64(headers, key, def, id); + } + + inline void default_socket_options(socket_t sock) + { + int opt = 1; +#ifdef _WIN32 + setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, + reinterpret_cast(&opt), sizeof(opt)); + setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, + reinterpret_cast(&opt), sizeof(opt)); +#else +#ifdef SO_REUSEPORT + setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, + reinterpret_cast(&opt), sizeof(opt)); +#else + setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, + reinterpret_cast(&opt), sizeof(opt)); +#endif +#endif + } + + inline const char* status_message(int status) + { + switch (status) + { + case StatusCode::Continue_100: + return "Continue"; + case StatusCode::SwitchingProtocol_101: + return "Switching Protocol"; + case StatusCode::Processing_102: + return "Processing"; + case StatusCode::EarlyHints_103: + return "Early Hints"; + case StatusCode::OK_200: + return "OK"; + case StatusCode::Created_201: + return "Created"; + case StatusCode::Accepted_202: + return "Accepted"; + case StatusCode::NonAuthoritativeInformation_203: + return "Non-Authoritative Information"; + case StatusCode::NoContent_204: + return "No Content"; + case StatusCode::ResetContent_205: + return "Reset Content"; + case StatusCode::PartialContent_206: + return "Partial Content"; + case StatusCode::MultiStatus_207: + return "Multi-Status"; + case StatusCode::AlreadyReported_208: + return "Already Reported"; + case StatusCode::IMUsed_226: + return "IM Used"; + case StatusCode::MultipleChoices_300: + return "Multiple Choices"; + case StatusCode::MovedPermanently_301: + return "Moved Permanently"; + case StatusCode::Found_302: + return "Found"; + case StatusCode::SeeOther_303: + return "See Other"; + case StatusCode::NotModified_304: + return "Not Modified"; + case StatusCode::UseProxy_305: + return "Use Proxy"; + case StatusCode::unused_306: + return "unused"; + case StatusCode::TemporaryRedirect_307: + return "Temporary Redirect"; + case StatusCode::PermanentRedirect_308: + return "Permanent Redirect"; + case StatusCode::BadRequest_400: + return "Bad Request"; + case StatusCode::Unauthorized_401: + return "Unauthorized"; + case StatusCode::PaymentRequired_402: + return "Payment Required"; + case StatusCode::Forbidden_403: + return "Forbidden"; + case StatusCode::NotFound_404: + return "Not Found"; + case StatusCode::MethodNotAllowed_405: + return "Method Not Allowed"; + case StatusCode::NotAcceptable_406: + return "Not Acceptable"; + case StatusCode::ProxyAuthenticationRequired_407: + return "Proxy Authentication Required"; + case StatusCode::RequestTimeout_408: + return "Request Timeout"; + case StatusCode::Conflict_409: + return "Conflict"; + case StatusCode::Gone_410: + return "Gone"; + case StatusCode::LengthRequired_411: + return "Length Required"; + case StatusCode::PreconditionFailed_412: + return "Precondition Failed"; + case StatusCode::PayloadTooLarge_413: + return "Payload Too Large"; + case StatusCode::UriTooLong_414: + return "URI Too Long"; + case StatusCode::UnsupportedMediaType_415: + return "Unsupported Media Type"; + case StatusCode::RangeNotSatisfiable_416: + return "Range Not Satisfiable"; + case StatusCode::ExpectationFailed_417: + return "Expectation Failed"; + case StatusCode::ImATeapot_418: + return "I'm a teapot"; + case StatusCode::MisdirectedRequest_421: + return "Misdirected Request"; + case StatusCode::UnprocessableContent_422: + return "Unprocessable Content"; + case StatusCode::Locked_423: + return "Locked"; + case StatusCode::FailedDependency_424: + return "Failed Dependency"; + case StatusCode::TooEarly_425: + return "Too Early"; + case StatusCode::UpgradeRequired_426: + return "Upgrade Required"; + case StatusCode::PreconditionRequired_428: + return "Precondition Required"; + case StatusCode::TooManyRequests_429: + return "Too Many Requests"; + case StatusCode::RequestHeaderFieldsTooLarge_431: + return "Request Header Fields Too Large"; + case StatusCode::UnavailableForLegalReasons_451: + return "Unavailable For Legal Reasons"; + case StatusCode::NotImplemented_501: + return "Not Implemented"; + case StatusCode::BadGateway_502: + return "Bad Gateway"; + case StatusCode::ServiceUnavailable_503: + return "Service Unavailable"; + case StatusCode::GatewayTimeout_504: + return "Gateway Timeout"; + case StatusCode::HttpVersionNotSupported_505: + return "HTTP Version Not Supported"; + case StatusCode::VariantAlsoNegotiates_506: + return "Variant Also Negotiates"; + case StatusCode::InsufficientStorage_507: + return "Insufficient Storage"; + case StatusCode::LoopDetected_508: + return "Loop Detected"; + case StatusCode::NotExtended_510: + return "Not Extended"; + case StatusCode::NetworkAuthenticationRequired_511: + return "Network Authentication Required"; + + default: + case StatusCode::InternalServerError_500: + return "Internal Server Error"; + } + } + + inline std::string get_bearer_token_auth(const Request& req) + { + if (req.has_header("Authorization")) + { + static std::string BearerHeaderPrefix = "Bearer "; + return req.get_header_value("Authorization") + .substr(BearerHeaderPrefix.length()); + } + return ""; + } + + template + inline Server& + Server::set_read_timeout(const std::chrono::duration& duration) + { + detail::duration_to_sec_and_usec( + duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); }); + return *this; + } + + template + inline Server& + Server::set_write_timeout(const std::chrono::duration& duration) + { + detail::duration_to_sec_and_usec( + duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); }); + return *this; + } + + template + inline Server& + Server::set_idle_interval(const std::chrono::duration& duration) + { + detail::duration_to_sec_and_usec( + duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); }); + return *this; + } + + inline std::string to_string(const Error error) + { + switch (error) + { + case Error::Success: + return "Success (no error)"; + case Error::Connection: + return "Could not establish connection"; + case Error::BindIPAddress: + return "Failed to bind IP address"; + case Error::Read: + return "Failed to read connection"; + case Error::Write: + return "Failed to write connection"; + case Error::ExceedRedirectCount: + return "Maximum redirect count exceeded"; + case Error::Canceled: + return "Connection handling canceled"; + case Error::SSLConnection: + return "SSL connection failed"; + case Error::SSLLoadingCerts: + return "SSL certificate loading failed"; + case Error::SSLServerVerification: + return "SSL server verification failed"; + case Error::SSLServerHostnameVerification: + return "SSL server hostname verification failed"; + case Error::UnsupportedMultipartBoundaryChars: + return "Unsupported HTTP multipart boundary characters"; + case Error::Compression: + return "Compression failed"; + case Error::ConnectionTimeout: + return "Connection timed out"; + case Error::ProxyConnection: + return "Proxy connection failed"; + case Error::Unknown: + return "Unknown"; + default: + break; + } + + return "Invalid"; + } + + inline std::ostream& operator<<(std::ostream& os, const Error& obj) + { + os << to_string(obj); + os << " (" << static_cast::type>(obj) << ')'; + return os; + } + + inline uint64_t Result::get_request_header_value_u64(const std::string& key, + uint64_t def, + size_t id) const + { + return detail::get_header_value_u64(request_headers_, key, def, id); + } + + template + inline void ClientImpl::set_connection_timeout( + const std::chrono::duration& duration) + { + detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) + { + set_connection_timeout(sec, usec); + }); + } + + template + inline void ClientImpl::set_read_timeout( + const std::chrono::duration& duration) + { + detail::duration_to_sec_and_usec( + duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); }); + } + + template + inline void ClientImpl::set_write_timeout( + const std::chrono::duration& duration) + { + detail::duration_to_sec_and_usec( + duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); }); + } + + template + inline void Client::set_connection_timeout( + const std::chrono::duration& duration) + { + cli_->set_connection_timeout(duration); + } + + template + inline void + Client::set_read_timeout(const std::chrono::duration& duration) + { + cli_->set_read_timeout(duration); + } + + template + inline void + Client::set_write_timeout(const std::chrono::duration& duration) + { + cli_->set_write_timeout(duration); + } + + /* + * Forward declarations and types that will be part of the .h file if split into + * .h + .cc. + */ + + std::string hosted_at(const std::string& hostname); + + void hosted_at(const std::string& hostname, std::vector& addrs); + + std::string append_query_params(const std::string& path, const Params& params); + + std::pair make_range_header(const Ranges& ranges); + + std::pair + make_basic_authentication_header(const std::string& username, + const std::string& password, + bool is_proxy = false); + + namespace detail + { +#if defined(_WIN32) + inline std::wstring u8string_to_wstring(const char* s) + { + std::wstring ws; + auto len = static_cast(strlen(s)); + auto wlen = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0); + if (wlen > 0) + { + ws.resize(wlen); + wlen = ::MultiByteToWideChar( + CP_UTF8, 0, s, len, + const_cast(reinterpret_cast(ws.data())), wlen); + if (wlen != static_cast(ws.size())) { ws.clear(); } + } + return ws; + } +#endif + + struct FileStat + { + FileStat(const std::string& path); + bool is_file() const; + bool is_dir() const; + + private: +#if defined(_WIN32) + struct _stat st_; +#else + struct stat st_; +#endif + int ret_ = -1; + }; + + std::string encode_query_param(const std::string& value); + + std::string decode_url(const std::string& s, bool convert_plus_to_space); + + void read_file(const std::string& path, std::string& out); + + std::string trim_copy(const std::string& s); + + void divide( + const char* data, std::size_t size, char d, + std::function + fn); + + void divide( + const std::string& str, char d, + std::function + fn); + + void split(const char* b, const char* e, char d, + std::function fn); + + void split(const char* b, const char* e, char d, size_t m, + std::function fn); + + bool process_client_socket(socket_t sock, time_t read_timeout_sec, + time_t read_timeout_usec, time_t write_timeout_sec, + time_t write_timeout_usec, + std::function callback); + + socket_t create_client_socket(const std::string& host, const std::string& ip, + int port, int address_family, bool tcp_nodelay, + bool ipv6_v6only, SocketOptions socket_options, + time_t connection_timeout_sec, + time_t connection_timeout_usec, + time_t read_timeout_sec, time_t read_timeout_usec, + time_t write_timeout_sec, + time_t write_timeout_usec, + const std::string& intf, Error& error); + + const char* get_header_value(const Headers& headers, const std::string& key, + const char* def, size_t id); + + std::string params_to_query_str(const Params& params); + + void parse_query_text(const char* data, std::size_t size, Params& params); + + void parse_query_text(const std::string& s, Params& params); + + bool parse_multipart_boundary(const std::string& content_type, + std::string& boundary); + + bool parse_range_header(const std::string& s, Ranges& ranges); + + int close_socket(socket_t sock); + + ssize_t send_socket(socket_t sock, const void* ptr, size_t size, int flags); + + ssize_t read_socket(socket_t sock, void* ptr, size_t size, int flags); + + enum class EncodingType { None = 0, Gzip, Brotli }; + + EncodingType encoding_type(const Request& req, const Response& res); + + class BufferStream final : public Stream + { + public: + BufferStream() = default; + ~BufferStream() override = default; + + bool is_readable() const override; + bool is_writable() const override; + ssize_t read(char* ptr, size_t size) override; + ssize_t write(const char* ptr, size_t size) override; + void get_remote_ip_and_port(std::string& ip, int& port) const override; + void get_local_ip_and_port(std::string& ip, int& port) const override; + socket_t socket() const override; + + const std::string& get_buffer() const; + + private: + std::string buffer; + size_t position = 0; + }; + + class compressor + { + public: + virtual ~compressor() = default; + + typedef std::function Callback; + virtual bool compress(const char* data, size_t data_length, bool last, + Callback callback) = 0; + }; + + class decompressor + { + public: + virtual ~decompressor() = default; + + virtual bool is_valid() const = 0; + + typedef std::function Callback; + virtual bool decompress(const char* data, size_t data_length, + Callback callback) = 0; + }; + + class nocompressor final : public compressor + { + public: + ~nocompressor() override = default; + + bool compress(const char* data, size_t data_length, bool /*last*/, + Callback callback) override; + }; + +#ifdef CPPHTTPLIB_ZLIB_SUPPORT +class gzip_compressor final : public compressor { +public: + gzip_compressor(); + ~gzip_compressor() override; + + bool compress(const char *data, size_t data_length, bool last, + Callback callback) override; + +private: + bool is_valid_ = false; + z_stream strm_; +}; + +class gzip_decompressor final : public decompressor { +public: + gzip_decompressor(); + ~gzip_decompressor() override; + + bool is_valid() const override; + + bool decompress(const char *data, size_t data_length, + Callback callback) override; + +private: + bool is_valid_ = false; + z_stream strm_; +}; +#endif + +#ifdef CPPHTTPLIB_BROTLI_SUPPORT +class brotli_compressor final : public compressor { +public: + brotli_compressor(); + ~brotli_compressor(); + + bool compress(const char *data, size_t data_length, bool last, + Callback callback) override; + +private: + BrotliEncoderState *state_ = nullptr; +}; + +class brotli_decompressor final : public decompressor { +public: + brotli_decompressor(); + ~brotli_decompressor(); + + bool is_valid() const override; + + bool decompress(const char *data, size_t data_length, + Callback callback) override; + +private: + BrotliDecoderResult decoder_r; + BrotliDecoderState *decoder_s = nullptr; +}; +#endif + + // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer` + // to store data. The call can set memory on stack for performance. + class stream_line_reader + { + public: + stream_line_reader(Stream& strm, char* fixed_buffer, + size_t fixed_buffer_size); + const char* ptr() const; + size_t size() const; + bool end_with_crlf() const; + bool getline(); + + private: + void append(char c); + + Stream& strm_; + char* fixed_buffer_; + const size_t fixed_buffer_size_; + size_t fixed_buffer_used_size_ = 0; + std::string glowable_buffer_; + }; + + class mmap + { + public: + mmap(const char* path); + ~mmap(); + + bool open(const char* path); + void close(); + + bool is_open() const; + size_t size() const; + const char* data() const; + + private: +#if defined(_WIN32) + HANDLE hFile_ = NULL; + HANDLE hMapping_ = NULL; +#else + int fd_ = -1; +#endif + size_t size_ = 0; + void* addr_ = nullptr; + bool is_open_empty_file = false; + }; + } // namespace detail + + // ---------------------------------------------------------------------------- + + /* + * Implementation that will be part of the .cc file if split into .h + .cc. + */ + + namespace detail + { + inline bool is_hex(char c, int& v) + { + if (0x20 <= c && isdigit(c)) + { + v = c - '0'; + return true; + } + else if ('A' <= c && c <= 'F') + { + v = c - 'A' + 10; + return true; + } + else if ('a' <= c && c <= 'f') + { + v = c - 'a' + 10; + return true; + } + return false; + } + + inline bool from_hex_to_i(const std::string& s, size_t i, size_t cnt, + int& val) + { + if (i >= s.size()) { return false; } + + val = 0; + for (; cnt; i++, cnt--) + { + if (!s[i]) { return false; } + auto v = 0; + if (is_hex(s[i], v)) + { + val = val * 16 + v; + } + else + { + return false; + } + } + return true; + } + + inline std::string from_i_to_hex(size_t n) + { + static const auto charset = "0123456789abcdef"; + std::string ret; + do + { + ret = charset[n & 15] + ret; + n >>= 4; + } + while (n > 0); + return ret; + } + + inline size_t to_utf8(int code, char* buff) + { + if (code < 0x0080) + { + buff[0] = static_cast(code & 0x7F); + return 1; + } + else if (code < 0x0800) + { + buff[0] = static_cast(0xC0 | ((code >> 6) & 0x1F)); + buff[1] = static_cast(0x80 | (code & 0x3F)); + return 2; + } + else if (code < 0xD800) + { + buff[0] = static_cast(0xE0 | ((code >> 12) & 0xF)); + buff[1] = static_cast(0x80 | ((code >> 6) & 0x3F)); + buff[2] = static_cast(0x80 | (code & 0x3F)); + return 3; + } + else if (code < 0xE000) + { + // D800 - DFFF is invalid... + return 0; + } + else if (code < 0x10000) + { + buff[0] = static_cast(0xE0 | ((code >> 12) & 0xF)); + buff[1] = static_cast(0x80 | ((code >> 6) & 0x3F)); + buff[2] = static_cast(0x80 | (code & 0x3F)); + return 3; + } + else if (code < 0x110000) + { + buff[0] = static_cast(0xF0 | ((code >> 18) & 0x7)); + buff[1] = static_cast(0x80 | ((code >> 12) & 0x3F)); + buff[2] = static_cast(0x80 | ((code >> 6) & 0x3F)); + buff[3] = static_cast(0x80 | (code & 0x3F)); + return 4; + } + + // NOTREACHED + return 0; + } + + // NOTE: This code came up with the following stackoverflow post: + // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c + inline std::string base64_encode(const std::string& in) + { + static const auto lookup = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + + std::string out; + out.reserve(in.size()); + + auto val = 0; + auto valb = -6; + + for (auto c : in) + { + val = (val << 8) + static_cast(c); + valb += 8; + while (valb >= 0) + { + out.push_back(lookup[(val >> valb) & 0x3F]); + valb -= 6; + } + } + + if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); } + + while (out.size() % 4) + { + out.push_back('='); + } + + return out; + } + + inline bool is_valid_path(const std::string& path) + { + size_t level = 0; + size_t i = 0; + + // Skip slash + while (i < path.size() && path[i] == '/') + { + i++; + } + + while (i < path.size()) + { + // Read component + auto beg = i; + while (i < path.size() && path[i] != '/') + { + if (path[i] == '\0') + { + return false; + } + else if (path[i] == '\\') + { + return false; + } + i++; + } + + auto len = i - beg; + assert(len > 0); + + if (!path.compare(beg, len, ".")) + { + ; + } + else if (!path.compare(beg, len, "..")) + { + if (level == 0) { return false; } + level--; + } + else + { + level++; + } + + // Skip slash + while (i < path.size() && path[i] == '/') + { + i++; + } + } + + return true; + } + + inline FileStat::FileStat(const std::string& path) + { +#if defined(_WIN32) + auto wpath = u8string_to_wstring(path.c_str()); + ret_ = _wstat(wpath.c_str(), &st_); +#else + ret_ = stat(path.c_str(), &st_); +#endif + } + + inline bool FileStat::is_file() const + { + return ret_ >= 0 && S_ISREG(st_.st_mode); + } + + inline bool FileStat::is_dir() const + { + return ret_ >= 0 && S_ISDIR(st_.st_mode); + } + + inline std::string encode_query_param(const std::string& value) + { + std::ostringstream escaped; + escaped.fill('0'); + escaped << std::hex; + + for (auto c : value) + { + if (std::isalnum(static_cast(c)) || c == '-' || c == '_' || + c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || + c == ')') + { + escaped << c; + } + else + { + escaped << std::uppercase; + escaped << '%' << std::setw(2) + << static_cast(static_cast(c)); + escaped << std::nouppercase; + } + } + + return escaped.str(); + } + + inline std::string encode_url(const std::string& s) + { + std::string result; + result.reserve(s.size()); + + for (size_t i = 0; s[i]; i++) + { + switch (s[i]) + { + case ' ': + result += "%20"; + break; + case '+': + result += "%2B"; + break; + case '\r': + result += "%0D"; + break; + case '\n': + result += "%0A"; + break; + case '\'': + result += "%27"; + break; + case ',': + result += "%2C"; + break; + // case ':': result += "%3A"; break; // ok? probably... + case ';': + result += "%3B"; + break; + default: + auto c = static_cast(s[i]); + if (c >= 0x80) + { + result += '%'; + char hex[4]; + auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c); + assert(len == 2); + result.append(hex, static_cast(len)); + } + else + { + result += s[i]; + } + break; + } + } + + return result; + } + + inline std::string decode_url(const std::string& s, + bool convert_plus_to_space) + { + std::string result; + + for (size_t i = 0; i < s.size(); i++) + { + if (s[i] == '%' && i + 1 < s.size()) + { + if (s[i + 1] == 'u') + { + auto val = 0; + if (from_hex_to_i(s, i + 2, 4, val)) + { + // 4 digits Unicode codes + char buff[4]; + size_t len = to_utf8(val, buff); + if (len > 0) { result.append(buff, len); } + i += 5; // 'u0000' + } + else + { + result += s[i]; + } + } + else + { + auto val = 0; + if (from_hex_to_i(s, i + 1, 2, val)) + { + // 2 digits hex codes + result += static_cast(val); + i += 2; // '00' + } + else + { + result += s[i]; + } + } + } + else if (convert_plus_to_space && s[i] == '+') + { + result += ' '; + } + else + { + result += s[i]; + } + } + + return result; + } + + inline void read_file(const std::string& path, std::string& out) + { + std::ifstream fs(path, std::ios_base::binary); + fs.seekg(0, std::ios_base::end); + auto size = fs.tellg(); + fs.seekg(0); + out.resize(static_cast(size)); + fs.read(&out[0], static_cast(size)); + } + + inline std::string file_extension(const std::string& path) + { + std::smatch m; + static auto re = std::regex("\\.([a-zA-Z0-9]+)$"); + if (std::regex_search(path, m, re)) { return m[1].str(); } + return std::string(); + } + + inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; } + + inline std::pair trim(const char* b, const char* e, size_t left, + size_t right) + { + while (b + left < e && is_space_or_tab(b[left])) + { + left++; + } + while (right > 0 && is_space_or_tab(b[right - 1])) + { + right--; + } + return std::make_pair(left, right); + } + + inline std::string trim_copy(const std::string& s) + { + auto r = trim(s.data(), s.data() + s.size(), 0, s.size()); + return s.substr(r.first, r.second - r.first); + } + + inline std::string trim_double_quotes_copy(const std::string& s) + { + if (s.length() >= 2 && s.front() == '"' && s.back() == '"') + { + return s.substr(1, s.size() - 2); + } + return s; + } + + inline void + divide(const char* data, std::size_t size, char d, + std::function + fn) + { + const auto it = std::find(data, data + size, d); + const auto found = static_cast(it != data + size); + const auto lhs_data = data; + const auto lhs_size = static_cast(it - data); + const auto rhs_data = it + found; + const auto rhs_size = size - lhs_size - found; + + fn(lhs_data, lhs_size, rhs_data, rhs_size); + } + + inline void + divide(const std::string& str, char d, + std::function + fn) + { + divide(str.data(), str.size(), d, std::move(fn)); + } + + inline void split(const char* b, const char* e, char d, + std::function fn) + { + return split(b, e, d, (std::numeric_limits::max)(), std::move(fn)); + } + + inline void split(const char* b, const char* e, char d, size_t m, + std::function fn) + { + size_t i = 0; + size_t beg = 0; + size_t count = 1; + + while (e ? (b + i < e) : (b[i] != '\0')) + { + if (b[i] == d && count < m) + { + auto r = trim(b, e, beg, i); + if (r.first < r.second) { fn(&b[r.first], &b[r.second]); } + beg = i + 1; + count++; + } + i++; + } + + if (i) + { + auto r = trim(b, e, beg, i); + if (r.first < r.second) { fn(&b[r.first], &b[r.second]); } + } + } + + inline stream_line_reader::stream_line_reader(Stream& strm, char* fixed_buffer, + size_t fixed_buffer_size) : + strm_(strm), fixed_buffer_(fixed_buffer), + fixed_buffer_size_(fixed_buffer_size) + { + } + + inline const char* stream_line_reader::ptr() const + { + if (glowable_buffer_.empty()) + { + return fixed_buffer_; + } + else + { + return glowable_buffer_.data(); + } + } + + inline size_t stream_line_reader::size() const + { + if (glowable_buffer_.empty()) + { + return fixed_buffer_used_size_; + } + else + { + return glowable_buffer_.size(); + } + } + + inline bool stream_line_reader::end_with_crlf() const + { + auto end = ptr() + size(); + return size() >= 2 && end[-2] == '\r' && end[-1] == '\n'; + } + + inline bool stream_line_reader::getline() + { + fixed_buffer_used_size_ = 0; + glowable_buffer_.clear(); + +#ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR + char prev_byte = 0; +#endif + + for (size_t i = 0;; i++) + { + char byte; + auto n = strm_.read(&byte, 1); + + if (n < 0) + { + return false; + } + else if (n == 0) + { + if (i == 0) + { + return false; + } + else + { + break; + } + } + + append(byte); + +#ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR + if (byte == '\n') { break; } +#else + if (prev_byte == '\r' && byte == '\n') { break; } + prev_byte = byte; +#endif + } + + return true; + } + + inline void stream_line_reader::append(char c) + { + if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) + { + fixed_buffer_[fixed_buffer_used_size_++] = c; + fixed_buffer_[fixed_buffer_used_size_] = '\0'; + } + else + { + if (glowable_buffer_.empty()) + { + assert(fixed_buffer_[fixed_buffer_used_size_] == '\0'); + glowable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_); + } + glowable_buffer_ += c; + } + } + + inline mmap::mmap(const char* path) { open(path); } + + inline mmap::~mmap() { close(); } + + inline bool mmap::open(const char* path) + { + close(); + +#if defined(_WIN32) + auto wpath = u8string_to_wstring(path); + if (wpath.empty()) { return false; } + +#if _WIN32_WINNT >= _WIN32_WINNT_WIN8 + hFile_ = ::CreateFile2(wpath.c_str(), GENERIC_READ, FILE_SHARE_READ, + OPEN_EXISTING, NULL); +#else + hFile_ = ::CreateFileW(wpath.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); +#endif + + if (hFile_ == INVALID_HANDLE_VALUE) { return false; } + + LARGE_INTEGER size{}; + if (!::GetFileSizeEx(hFile_, &size)) { return false; } + // If the following line doesn't compile due to QuadPart, update Windows SDK. + // See: + // https://github.com/yhirose/cpp-httplib/issues/1903#issuecomment-2316520721 + if (static_cast(size.QuadPart) > + (std::numeric_limits::max)()) + { + // `size_t` might be 32-bits, on 32-bits Windows. + return false; + } + size_ = static_cast(size.QuadPart); + +#if _WIN32_WINNT >= _WIN32_WINNT_WIN8 + hMapping_ = + ::CreateFileMappingFromApp(hFile_, NULL, PAGE_READONLY, size_, NULL); +#else + hMapping_ = ::CreateFileMappingW(hFile_, NULL, PAGE_READONLY, 0, 0, NULL); +#endif + + // Special treatment for an empty file... + if (hMapping_ == NULL && size_ == 0) + { + close(); + is_open_empty_file = true; + return true; + } + + if (hMapping_ == NULL) + { + close(); + return false; + } + +#if _WIN32_WINNT >= _WIN32_WINNT_WIN8 + addr_ = ::MapViewOfFileFromApp(hMapping_, FILE_MAP_READ, 0, 0); +#else + addr_ = ::MapViewOfFile(hMapping_, FILE_MAP_READ, 0, 0, 0); +#endif + + if (addr_ == nullptr) + { + close(); + return false; + } +#else + fd_ = ::open(path, O_RDONLY); + if (fd_ == -1) { return false; } + + struct stat sb; + if (fstat(fd_, &sb) == -1) { + close(); + return false; + } + size_ = static_cast(sb.st_size); + + addr_ = ::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0); + + // Special treatment for an empty file... + if (addr_ == MAP_FAILED && size_ == 0) { + close(); + is_open_empty_file = true; + return false; + } +#endif + + return true; + } + + inline bool mmap::is_open() const + { + return is_open_empty_file ? true : addr_ != nullptr; + } + + inline size_t mmap::size() const { return size_; } + + inline const char* mmap::data() const + { + return is_open_empty_file ? "" : static_cast(addr_); + } + + inline void mmap::close() + { +#if defined(_WIN32) + if (addr_) + { + ::UnmapViewOfFile(addr_); + addr_ = nullptr; + } + + if (hMapping_) + { + ::CloseHandle(hMapping_); + hMapping_ = NULL; + } + + if (hFile_ != INVALID_HANDLE_VALUE) + { + ::CloseHandle(hFile_); + hFile_ = INVALID_HANDLE_VALUE; + } + + is_open_empty_file = false; +#else + if (addr_ != nullptr) { + munmap(addr_, size_); + addr_ = nullptr; + } + + if (fd_ != -1) { + ::close(fd_); + fd_ = -1; + } +#endif + size_ = 0; + } + + inline int close_socket(socket_t sock) + { +#ifdef _WIN32 + return closesocket(sock); +#else + return close(sock); +#endif + } + + template + inline ssize_t handle_EINTR(T fn) + { + ssize_t res = 0; + while (true) + { + res = fn(); + if (res < 0 && errno == EINTR) + { + std::this_thread::sleep_for(std::chrono::microseconds{1}); + continue; + } + break; + } + return res; + } + + inline ssize_t read_socket(socket_t sock, void* ptr, size_t size, int flags) + { + return handle_EINTR([&]() + { + return recv(sock, +#ifdef _WIN32 + static_cast(ptr), static_cast(size), +#else + ptr, size, +#endif + flags); + }); + } + + inline ssize_t send_socket(socket_t sock, const void* ptr, size_t size, + int flags) + { + return handle_EINTR([&]() + { + return send(sock, +#ifdef _WIN32 + static_cast(ptr), static_cast(size), +#else + ptr, size, +#endif + flags); + }); + } + + inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) + { +#ifdef CPPHTTPLIB_USE_POLL + struct pollfd pfd_read; + pfd_read.fd = sock; + pfd_read.events = POLLIN; + + auto timeout = static_cast(sec * 1000 + usec / 1000); + + return handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); }); +#else +#ifndef _WIN32 + if (sock >= FD_SETSIZE) { return -1; } +#endif + + fd_set fds; + FD_ZERO(&fds); + FD_SET(sock, &fds); + + timeval tv; + tv.tv_sec = static_cast(sec); + tv.tv_usec = static_cast(usec); + + return handle_EINTR([&]() + { + return select(static_cast(sock + 1), &fds, nullptr, nullptr, &tv); + }); +#endif + } + + inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) + { +#ifdef CPPHTTPLIB_USE_POLL + struct pollfd pfd_read; + pfd_read.fd = sock; + pfd_read.events = POLLOUT; + + auto timeout = static_cast(sec * 1000 + usec / 1000); + + return handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); }); +#else +#ifndef _WIN32 + if (sock >= FD_SETSIZE) { return -1; } +#endif + + fd_set fds; + FD_ZERO(&fds); + FD_SET(sock, &fds); + + timeval tv; + tv.tv_sec = static_cast(sec); + tv.tv_usec = static_cast(usec); + + return handle_EINTR([&]() + { + return select(static_cast(sock + 1), nullptr, &fds, nullptr, &tv); + }); +#endif + } + + inline Error wait_until_socket_is_ready(socket_t sock, time_t sec, + time_t usec) + { +#ifdef CPPHTTPLIB_USE_POLL + struct pollfd pfd_read; + pfd_read.fd = sock; + pfd_read.events = POLLIN | POLLOUT; + + auto timeout = static_cast(sec * 1000 + usec / 1000); + + auto poll_res = handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); }); + + if (poll_res == 0) { return Error::ConnectionTimeout; } + + if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) { + auto error = 0; + socklen_t len = sizeof(error); + auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR, + reinterpret_cast(&error), &len); + auto successful = res >= 0 && !error; + return successful ? Error::Success : Error::Connection; + } + + return Error::Connection; +#else +#ifndef _WIN32 + if (sock >= FD_SETSIZE) { return Error::Connection; } +#endif + + fd_set fdsr; + FD_ZERO(&fdsr); + FD_SET(sock, &fdsr); + + auto fdsw = fdsr; + auto fdse = fdsr; + + timeval tv; + tv.tv_sec = static_cast(sec); + tv.tv_usec = static_cast(usec); + + auto ret = handle_EINTR([&]() + { + return select(static_cast(sock + 1), &fdsr, &fdsw, &fdse, &tv); + }); + + if (ret == 0) { return Error::ConnectionTimeout; } + + if (ret > 0 && (FD_ISSET(sock, &fdsr) || FD_ISSET(sock, &fdsw))) + { + auto error = 0; + socklen_t len = sizeof(error); + auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR, + reinterpret_cast(&error), &len); + auto successful = res >= 0 && !error; + return successful ? Error::Success : Error::Connection; + } + return Error::Connection; +#endif + } + + inline bool is_socket_alive(socket_t sock) + { + const auto val = detail::select_read(sock, 0, 0); + if (val == 0) + { + return true; + } + else if (val < 0 && errno == EBADF) + { + return false; + } + char buf[1]; + return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0; + } + + class SocketStream final : public Stream + { + public: + SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec, + time_t write_timeout_sec, time_t write_timeout_usec); + ~SocketStream() override; + + bool is_readable() const override; + bool is_writable() const override; + ssize_t read(char* ptr, size_t size) override; + ssize_t write(const char* ptr, size_t size) override; + void get_remote_ip_and_port(std::string& ip, int& port) const override; + void get_local_ip_and_port(std::string& ip, int& port) const override; + socket_t socket() const override; + + private: + socket_t sock_; + time_t read_timeout_sec_; + time_t read_timeout_usec_; + time_t write_timeout_sec_; + time_t write_timeout_usec_; + + std::vector read_buff_; + size_t read_buff_off_ = 0; + size_t read_buff_content_size_ = 0; + + static const size_t read_buff_size_ = 1024l * 4; + }; + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT +class SSLSocketStream final : public Stream { +public: + SSLSocketStream(socket_t sock, SSL *ssl, time_t read_timeout_sec, + time_t read_timeout_usec, time_t write_timeout_sec, + time_t write_timeout_usec); + ~SSLSocketStream() override; + + bool is_readable() const override; + bool is_writable() const override; + ssize_t read(char *ptr, size_t size) override; + ssize_t write(const char *ptr, size_t size) override; + void get_remote_ip_and_port(std::string &ip, int &port) const override; + void get_local_ip_and_port(std::string &ip, int &port) const override; + socket_t socket() const override; + +private: + socket_t sock_; + SSL *ssl_; + time_t read_timeout_sec_; + time_t read_timeout_usec_; + time_t write_timeout_sec_; + time_t write_timeout_usec_; +}; +#endif + + inline bool keep_alive(const std::atomic& svr_sock, socket_t sock, + time_t keep_alive_timeout_sec) + { + using namespace std::chrono; + + const auto interval_usec = + CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND; + + // Avoid expensive `steady_clock::now()` call for the first time + if (select_read(sock, 0, interval_usec) > 0) { return true; } + + const auto start = steady_clock::now() - microseconds{interval_usec}; + const auto timeout = seconds{keep_alive_timeout_sec}; + + while (true) + { + if (svr_sock == INVALID_SOCKET) + { + break; // Server socket is closed + } + + auto val = select_read(sock, 0, interval_usec); + if (val < 0) + { + break; // Ssocket error + } + else if (val == 0) + { + if (steady_clock::now() - start > timeout) + { + break; // Timeout + } + } + else + { + return true; // Ready for read + } + } + + return false; + } + + template + inline bool + process_server_socket_core(const std::atomic& svr_sock, socket_t sock, + size_t keep_alive_max_count, + time_t keep_alive_timeout_sec, T callback) + { + assert(keep_alive_max_count > 0); + auto ret = false; + auto count = keep_alive_max_count; + while (count > 0 && keep_alive(svr_sock, sock, keep_alive_timeout_sec)) + { + auto close_connection = count == 1; + auto connection_closed = false; + ret = callback(close_connection, connection_closed); + if (!ret || connection_closed) { break; } + count--; + } + return ret; + } + + template + inline bool + process_server_socket(const std::atomic& svr_sock, socket_t sock, + size_t keep_alive_max_count, + time_t keep_alive_timeout_sec, time_t read_timeout_sec, + time_t read_timeout_usec, time_t write_timeout_sec, + time_t write_timeout_usec, T callback) + { + return process_server_socket_core( + svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec, + [&](bool close_connection, bool& connection_closed) + { + SocketStream strm(sock, read_timeout_sec, read_timeout_usec, + write_timeout_sec, write_timeout_usec); + return callback(strm, close_connection, connection_closed); + }); + } + + inline bool process_client_socket(socket_t sock, time_t read_timeout_sec, + time_t read_timeout_usec, + time_t write_timeout_sec, + time_t write_timeout_usec, + std::function callback) + { + SocketStream strm(sock, read_timeout_sec, read_timeout_usec, + write_timeout_sec, write_timeout_usec); + return callback(strm); + } + + inline int shutdown_socket(socket_t sock) + { +#ifdef _WIN32 + return shutdown(sock, SD_BOTH); +#else + return shutdown(sock, SHUT_RDWR); +#endif + } + + inline std::string escape_abstract_namespace_unix_domain(const std::string& s) + { + if (s.size() > 1 && s[0] == '\0') + { + auto ret = s; + ret[0] = '@'; + return ret; + } + return s; + } + + inline std::string + unescape_abstract_namespace_unix_domain(const std::string& s) + { + if (s.size() > 1 && s[0] == '@') + { + auto ret = s; + ret[0] = '\0'; + return ret; + } + return s; + } + + template + socket_t create_socket(const std::string& host, const std::string& ip, int port, + int address_family, int socket_flags, bool tcp_nodelay, + bool ipv6_v6only, SocketOptions socket_options, + BindOrConnect bind_or_connect) + { + // Get address info + const char* node = nullptr; + struct addrinfo hints; + struct addrinfo* result; + + memset(&hints, 0, sizeof(struct addrinfo)); + hints.ai_socktype = SOCK_STREAM; + hints.ai_protocol = IPPROTO_IP; + + if (!ip.empty()) + { + node = ip.c_str(); + // Ask getaddrinfo to convert IP in c-string to address + hints.ai_family = AF_UNSPEC; + hints.ai_flags = AI_NUMERICHOST; + } + else + { + if (!host.empty()) { node = host.c_str(); } + hints.ai_family = address_family; + hints.ai_flags = socket_flags; + } + +#ifndef _WIN32 + if (hints.ai_family == AF_UNIX) { + const auto addrlen = host.length(); + if (addrlen > sizeof(sockaddr_un::sun_path)) { return INVALID_SOCKET; } + +#ifdef SOCK_CLOEXEC + auto sock = socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC, + hints.ai_protocol); +#else + auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol); +#endif + + if (sock != INVALID_SOCKET) { + sockaddr_un addr{}; + addr.sun_family = AF_UNIX; + + auto unescaped_host = unescape_abstract_namespace_unix_domain(host); + std::copy(unescaped_host.begin(), unescaped_host.end(), addr.sun_path); + + hints.ai_addr = reinterpret_cast(&addr); + hints.ai_addrlen = static_cast( + sizeof(addr) - sizeof(addr.sun_path) + addrlen); + +#ifndef SOCK_CLOEXEC + fcntl(sock, F_SETFD, FD_CLOEXEC); +#endif + + if (socket_options) { socket_options(sock); } + + bool dummy; + if (!bind_or_connect(sock, hints, dummy)) { + close_socket(sock); + sock = INVALID_SOCKET; + } + } + return sock; + } +#endif + + auto service = std::to_string(port); + + if (getaddrinfo(node, service.c_str(), &hints, &result)) + { +#if defined __linux__ && !defined __ANDROID__ + res_init(); +#endif + return INVALID_SOCKET; + } + auto se = detail::scope_exit([&] { freeaddrinfo(result); }); + + for (auto rp = result; rp; rp = rp->ai_next) + { + // Create a socket +#ifdef _WIN32 + auto sock = + WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0, + WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED); + /** + * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1 + * and above the socket creation fails on older Windows Systems. + * + * Let's try to create a socket the old way in this case. + * + * Reference: + * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa + * + * WSA_FLAG_NO_HANDLE_INHERIT: + * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with + * SP1, and later + * + */ + if (sock == INVALID_SOCKET) + { + sock = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); + } +#else + +#ifdef SOCK_CLOEXEC + auto sock = + socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol); +#else + auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); +#endif + +#endif + if (sock == INVALID_SOCKET) { continue; } + +#if !defined _WIN32 && !defined SOCK_CLOEXEC + if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) { + close_socket(sock); + continue; + } +#endif + + if (tcp_nodelay) + { + auto opt = 1; +#ifdef _WIN32 + setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, + reinterpret_cast(&opt), sizeof(opt)); +#else + setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, + reinterpret_cast(&opt), sizeof(opt)); +#endif + } + + if (rp->ai_family == AF_INET6) + { + auto opt = ipv6_v6only ? 1 : 0; +#ifdef _WIN32 + setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, + reinterpret_cast(&opt), sizeof(opt)); +#else + setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, + reinterpret_cast(&opt), sizeof(opt)); +#endif + } + + if (socket_options) { socket_options(sock); } + + // bind or connect + auto quit = false; + if (bind_or_connect(sock, *rp, quit)) { return sock; } + + close_socket(sock); + + if (quit) { break; } + } + + return INVALID_SOCKET; + } + + inline void set_nonblocking(socket_t sock, bool nonblocking) + { +#ifdef _WIN32 + auto flags = nonblocking ? 1UL : 0UL; + ioctlsocket(sock, FIONBIO, &flags); +#else + auto flags = fcntl(sock, F_GETFL, 0); + fcntl(sock, F_SETFL, + nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK))); +#endif + } + + inline bool is_connection_error() + { +#ifdef _WIN32 + return WSAGetLastError() != WSAEWOULDBLOCK; +#else + return errno != EINPROGRESS; +#endif + } + + inline bool bind_ip_address(socket_t sock, const std::string& host) + { + struct addrinfo hints; + struct addrinfo* result; + + memset(&hints, 0, sizeof(struct addrinfo)); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + hints.ai_protocol = 0; + + if (getaddrinfo(host.c_str(), "0", &hints, &result)) { return false; } + auto se = detail::scope_exit([&] { freeaddrinfo(result); }); + + auto ret = false; + for (auto rp = result; rp; rp = rp->ai_next) + { + const auto& ai = *rp; + if (!::bind(sock, ai.ai_addr, static_cast(ai.ai_addrlen))) + { + ret = true; + break; + } + } + + return ret; + } + +#if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__ +#define USE_IF2IP +#endif + +#ifdef USE_IF2IP +inline std::string if2ip(int address_family, const std::string &ifn) { + struct ifaddrs *ifap; + getifaddrs(&ifap); + auto se = detail::scope_exit([&] { freeifaddrs(ifap); }); + + std::string addr_candidate; + for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) { + if (ifa->ifa_addr && ifn == ifa->ifa_name && + (AF_UNSPEC == address_family || + ifa->ifa_addr->sa_family == address_family)) { + if (ifa->ifa_addr->sa_family == AF_INET) { + auto sa = reinterpret_cast(ifa->ifa_addr); + char buf[INET_ADDRSTRLEN]; + if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) { + return std::string(buf, INET_ADDRSTRLEN); + } + } else if (ifa->ifa_addr->sa_family == AF_INET6) { + auto sa = reinterpret_cast(ifa->ifa_addr); + if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) { + char buf[INET6_ADDRSTRLEN] = {}; + if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) { + // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL + auto s6_addr_head = sa->sin6_addr.s6_addr[0]; + if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) { + addr_candidate = std::string(buf, INET6_ADDRSTRLEN); + } else { + return std::string(buf, INET6_ADDRSTRLEN); + } + } + } + } + } + } + return addr_candidate; +} +#endif + + inline socket_t create_client_socket( + const std::string& host, const std::string& ip, int port, + int address_family, bool tcp_nodelay, bool ipv6_v6only, + SocketOptions socket_options, time_t connection_timeout_sec, + time_t connection_timeout_usec, time_t read_timeout_sec, + time_t read_timeout_usec, time_t write_timeout_sec, + time_t write_timeout_usec, const std::string& intf, Error& error) + { + auto sock = create_socket( + host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only, + std::move(socket_options), + [&](socket_t sock2, struct addrinfo& ai, bool& quit) -> bool + { + if (!intf.empty()) + { +#ifdef USE_IF2IP + auto ip_from_if = if2ip(address_family, intf); + if (ip_from_if.empty()) { ip_from_if = intf; } + if (!bind_ip_address(sock2, ip_from_if)) { + error = Error::BindIPAddress; + return false; + } +#endif + } + + set_nonblocking(sock2, true); + + auto ret = + ::connect(sock2, ai.ai_addr, static_cast(ai.ai_addrlen)); + + if (ret < 0) + { + if (is_connection_error()) + { + error = Error::Connection; + return false; + } + error = wait_until_socket_is_ready(sock2, connection_timeout_sec, + connection_timeout_usec); + if (error != Error::Success) + { + if (error == Error::ConnectionTimeout) { quit = true; } + return false; + } + } + + set_nonblocking(sock2, false); + + { +#ifdef _WIN32 + auto timeout = static_cast(read_timeout_sec * 1000 + + read_timeout_usec / 1000); + setsockopt(sock2, SOL_SOCKET, SO_RCVTIMEO, + reinterpret_cast(&timeout), sizeof(timeout)); +#else + timeval tv; + tv.tv_sec = static_cast(read_timeout_sec); + tv.tv_usec = static_cast(read_timeout_usec); + setsockopt(sock2, SOL_SOCKET, SO_RCVTIMEO, + reinterpret_cast(&tv), sizeof(tv)); +#endif + } + { +#ifdef _WIN32 + auto timeout = static_cast(write_timeout_sec * 1000 + + write_timeout_usec / 1000); + setsockopt(sock2, SOL_SOCKET, SO_SNDTIMEO, + reinterpret_cast(&timeout), sizeof(timeout)); +#else + timeval tv; + tv.tv_sec = static_cast(write_timeout_sec); + tv.tv_usec = static_cast(write_timeout_usec); + setsockopt(sock2, SOL_SOCKET, SO_SNDTIMEO, + reinterpret_cast(&tv), sizeof(tv)); +#endif + } + + error = Error::Success; + return true; + }); + + if (sock != INVALID_SOCKET) + { + error = Error::Success; + } + else + { + if (error == Error::Success) { error = Error::Connection; } + } + + return sock; + } + + inline bool get_ip_and_port(const struct sockaddr_storage& addr, + socklen_t addr_len, std::string& ip, int& port) + { + if (addr.ss_family == AF_INET) + { + port = ntohs(reinterpret_cast(&addr)->sin_port); + } + else if (addr.ss_family == AF_INET6) + { + port = + ntohs(reinterpret_cast(&addr)->sin6_port); + } + else + { + return false; + } + + std::array ipstr{}; + if (getnameinfo(reinterpret_cast(&addr), addr_len, + ipstr.data(), static_cast(ipstr.size()), nullptr, + 0, NI_NUMERICHOST)) + { + return false; + } + + ip = ipstr.data(); + return true; + } + + inline void get_local_ip_and_port(socket_t sock, std::string& ip, int& port) + { + struct sockaddr_storage addr; + socklen_t addr_len = sizeof(addr); + if (!getsockname(sock, reinterpret_cast(&addr), + &addr_len)) + { + get_ip_and_port(addr, addr_len, ip, port); + } + } + + inline void get_remote_ip_and_port(socket_t sock, std::string& ip, int& port) + { + struct sockaddr_storage addr; + socklen_t addr_len = sizeof(addr); + + if (!getpeername(sock, reinterpret_cast(&addr), + &addr_len)) + { +#ifndef _WIN32 + if (addr.ss_family == AF_UNIX) { +#if defined(__linux__) + struct ucred ucred; + socklen_t len = sizeof(ucred); + if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) { + port = ucred.pid; + } +#elif defined(SOL_LOCAL) && defined(SO_PEERPID) // __APPLE__ + pid_t pid; + socklen_t len = sizeof(pid); + if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) { + port = pid; + } +#endif + return; + } +#endif + get_ip_and_port(addr, addr_len, ip, port); + } + } + + inline constexpr unsigned int str2tag_core(const char* s, size_t l, + unsigned int h) + { + return (l == 0) + ? h + : str2tag_core( + s + 1, l - 1, + // Unsets the 6 high bits of h, therefore no overflow happens + (((std::numeric_limits::max)() >> 6) & + h * 33) ^ + static_cast(*s)); + } + + inline unsigned int str2tag(const std::string& s) + { + return str2tag_core(s.data(), s.size(), 0); + } + + namespace udl + { + inline constexpr unsigned int operator""_t(const char* s, size_t l) + { + return str2tag_core(s, l, 0); + } + } // namespace udl + + inline std::string + find_content_type(const std::string& path, + const std::map& user_data, + const std::string& default_content_type) + { + auto ext = file_extension(path); + + auto it = user_data.find(ext); + if (it != user_data.end()) { return it->second; } + + using udl::operator""_t; + + switch (str2tag(ext)) + { + default: + return default_content_type; + + case "css"_t: + return "text/css"; + case "csv"_t: + return "text/csv"; + case "htm"_t: + case "html"_t: + return "text/html"; + case "js"_t: + case "mjs"_t: + return "text/javascript"; + case "txt"_t: + return "text/plain"; + case "vtt"_t: + return "text/vtt"; + + case "apng"_t: + return "image/apng"; + case "avif"_t: + return "image/avif"; + case "bmp"_t: + return "image/bmp"; + case "gif"_t: + return "image/gif"; + case "png"_t: + return "image/png"; + case "svg"_t: + return "image/svg+xml"; + case "webp"_t: + return "image/webp"; + case "ico"_t: + return "image/x-icon"; + case "tif"_t: + return "image/tiff"; + case "tiff"_t: + return "image/tiff"; + case "jpg"_t: + case "jpeg"_t: + return "image/jpeg"; + + case "mp4"_t: + return "video/mp4"; + case "mpeg"_t: + return "video/mpeg"; + case "webm"_t: + return "video/webm"; + + case "mp3"_t: + return "audio/mp3"; + case "mpga"_t: + return "audio/mpeg"; + case "weba"_t: + return "audio/webm"; + case "wav"_t: + return "audio/wave"; + + case "otf"_t: + return "font/otf"; + case "ttf"_t: + return "font/ttf"; + case "woff"_t: + return "font/woff"; + case "woff2"_t: + return "font/woff2"; + + case "7z"_t: + return "application/x-7z-compressed"; + case "atom"_t: + return "application/atom+xml"; + case "pdf"_t: + return "application/pdf"; + case "json"_t: + return "application/json"; + case "rss"_t: + return "application/rss+xml"; + case "tar"_t: + return "application/x-tar"; + case "xht"_t: + case "xhtml"_t: + return "application/xhtml+xml"; + case "xslt"_t: + return "application/xslt+xml"; + case "xml"_t: + return "application/xml"; + case "gz"_t: + return "application/gzip"; + case "zip"_t: + return "application/zip"; + case "wasm"_t: + return "application/wasm"; + } + } + + inline bool can_compress_content_type(const std::string& content_type) + { + using udl::operator""_t; + + auto tag = str2tag(content_type); + + switch (tag) + { + case "image/svg+xml"_t: + case "application/javascript"_t: + case "application/json"_t: + case "application/xml"_t: + case "application/protobuf"_t: + case "application/xhtml+xml"_t: + return true; + + case "text/event-stream"_t: + return false; + + default: + return !content_type.rfind("text/", 0); + } + } + + inline EncodingType encoding_type(const Request& req, const Response& res) + { + auto ret = + detail::can_compress_content_type(res.get_header_value("Content-Type")); + if (!ret) { return EncodingType::None; } + + const auto& s = req.get_header_value("Accept-Encoding"); + (void)(s); + +#ifdef CPPHTTPLIB_BROTLI_SUPPORT + // TODO: 'Accept-Encoding' has br, not br;q=0 + ret = s.find("br") != std::string::npos; + if (ret) { return EncodingType::Brotli; } +#endif + +#ifdef CPPHTTPLIB_ZLIB_SUPPORT + // TODO: 'Accept-Encoding' has gzip, not gzip;q=0 + ret = s.find("gzip") != std::string::npos; + if (ret) { return EncodingType::Gzip; } +#endif + + return EncodingType::None; + } + + inline bool nocompressor::compress(const char* data, size_t data_length, + bool /*last*/, Callback callback) + { + if (!data_length) { return true; } + return callback(data, data_length); + } + +#ifdef CPPHTTPLIB_ZLIB_SUPPORT +inline gzip_compressor::gzip_compressor() { + std::memset(&strm_, 0, sizeof(strm_)); + strm_.zalloc = Z_NULL; + strm_.zfree = Z_NULL; + strm_.opaque = Z_NULL; + + is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8, + Z_DEFAULT_STRATEGY) == Z_OK; +} + +inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); } + +inline bool gzip_compressor::compress(const char *data, size_t data_length, + bool last, Callback callback) { + assert(is_valid_); + + do { + constexpr size_t max_avail_in = + (std::numeric_limits::max)(); + + strm_.avail_in = static_cast( + (std::min)(data_length, max_avail_in)); + strm_.next_in = const_cast(reinterpret_cast(data)); + + data_length -= strm_.avail_in; + data += strm_.avail_in; + + auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH; + auto ret = Z_OK; + + std::array buff{}; + do { + strm_.avail_out = static_cast(buff.size()); + strm_.next_out = reinterpret_cast(buff.data()); + + ret = deflate(&strm_, flush); + if (ret == Z_STREAM_ERROR) { return false; } + + if (!callback(buff.data(), buff.size() - strm_.avail_out)) { + return false; + } + } while (strm_.avail_out == 0); + + assert((flush == Z_FINISH && ret == Z_STREAM_END) || + (flush == Z_NO_FLUSH && ret == Z_OK)); + assert(strm_.avail_in == 0); + } while (data_length > 0); + + return true; +} + +inline gzip_decompressor::gzip_decompressor() { + std::memset(&strm_, 0, sizeof(strm_)); + strm_.zalloc = Z_NULL; + strm_.zfree = Z_NULL; + strm_.opaque = Z_NULL; + + // 15 is the value of wbits, which should be at the maximum possible value + // to ensure that any gzip stream can be decoded. The offset of 32 specifies + // that the stream type should be automatically detected either gzip or + // deflate. + is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK; +} + +inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); } + +inline bool gzip_decompressor::is_valid() const { return is_valid_; } + +inline bool gzip_decompressor::decompress(const char *data, size_t data_length, + Callback callback) { + assert(is_valid_); + + auto ret = Z_OK; + + do { + constexpr size_t max_avail_in = + (std::numeric_limits::max)(); + + strm_.avail_in = static_cast( + (std::min)(data_length, max_avail_in)); + strm_.next_in = const_cast(reinterpret_cast(data)); + + data_length -= strm_.avail_in; + data += strm_.avail_in; + + std::array buff{}; + while (strm_.avail_in > 0 && ret == Z_OK) { + strm_.avail_out = static_cast(buff.size()); + strm_.next_out = reinterpret_cast(buff.data()); + + ret = inflate(&strm_, Z_NO_FLUSH); + + assert(ret != Z_STREAM_ERROR); + switch (ret) { + case Z_NEED_DICT: + case Z_DATA_ERROR: + case Z_MEM_ERROR: inflateEnd(&strm_); return false; + } + + if (!callback(buff.data(), buff.size() - strm_.avail_out)) { + return false; + } + } + + if (ret != Z_OK && ret != Z_STREAM_END) { return false; } + + } while (data_length > 0); + + return true; +} +#endif + +#ifdef CPPHTTPLIB_BROTLI_SUPPORT +inline brotli_compressor::brotli_compressor() { + state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr); +} + +inline brotli_compressor::~brotli_compressor() { + BrotliEncoderDestroyInstance(state_); +} + +inline bool brotli_compressor::compress(const char *data, size_t data_length, + bool last, Callback callback) { + std::array buff{}; + + auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS; + auto available_in = data_length; + auto next_in = reinterpret_cast(data); + + for (;;) { + if (last) { + if (BrotliEncoderIsFinished(state_)) { break; } + } else { + if (!available_in) { break; } + } + + auto available_out = buff.size(); + auto next_out = buff.data(); + + if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in, + &available_out, &next_out, nullptr)) { + return false; + } + + auto output_bytes = buff.size() - available_out; + if (output_bytes) { + callback(reinterpret_cast(buff.data()), output_bytes); + } + } + + return true; +} + +inline brotli_decompressor::brotli_decompressor() { + decoder_s = BrotliDecoderCreateInstance(0, 0, 0); + decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT + : BROTLI_DECODER_RESULT_ERROR; +} + +inline brotli_decompressor::~brotli_decompressor() { + if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); } +} + +inline bool brotli_decompressor::is_valid() const { return decoder_s; } + +inline bool brotli_decompressor::decompress(const char *data, + size_t data_length, + Callback callback) { + if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS || + decoder_r == BROTLI_DECODER_RESULT_ERROR) { + return 0; + } + + auto next_in = reinterpret_cast(data); + size_t avail_in = data_length; + size_t total_out; + + decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT; + + std::array buff{}; + while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) { + char *next_out = buff.data(); + size_t avail_out = buff.size(); + + decoder_r = BrotliDecoderDecompressStream( + decoder_s, &avail_in, &next_in, &avail_out, + reinterpret_cast(&next_out), &total_out); + + if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; } + + if (!callback(buff.data(), buff.size() - avail_out)) { return false; } + } + + return decoder_r == BROTLI_DECODER_RESULT_SUCCESS || + decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT; +} +#endif + + inline bool has_header(const Headers& headers, const std::string& key) + { + return headers.find(key) != headers.end(); + } + + inline const char* get_header_value(const Headers& headers, + const std::string& key, const char* def, + size_t id) + { + auto rng = headers.equal_range(key); + auto it = rng.first; + std::advance(it, static_cast(id)); + if (it != rng.second) { return it->second.c_str(); } + return def; + } + + template + inline bool parse_header(const char* beg, const char* end, T fn) + { + // Skip trailing spaces and tabs. + while (beg < end && is_space_or_tab(end[-1])) + { + end--; + } + + auto p = beg; + while (p < end && *p != ':') + { + p++; + } + + if (p == end) { return false; } + + auto key_end = p; + + if (*p++ != ':') { return false; } + + while (p < end && is_space_or_tab(*p)) + { + p++; + } + + if (p <= end) + { + auto key_len = key_end - beg; + if (!key_len) { return false; } + + auto key = std::string(beg, key_end); + auto val = case_ignore::equal(key, "Location") + ? std::string(p, end) + : decode_url(std::string(p, end), false); + + // NOTE: From RFC 9110: + // Field values containing CR, LF, or NUL characters are + // invalid and dangerous, due to the varying ways that + // implementations might parse and interpret those + // characters; a recipient of CR, LF, or NUL within a field + // value MUST either reject the message or replace each of + // those characters with SP before further processing or + // forwarding of that message. + static const std::string CR_LF_NUL("\r\n\0", 3); + if (val.find_first_of(CR_LF_NUL) != std::string::npos) { return false; } + + fn(key, val); + return true; + } + + return false; + } + + inline bool read_headers(Stream& strm, Headers& headers) + { + const auto bufsiz = 2048; + char buf[bufsiz]; + stream_line_reader line_reader(strm, buf, bufsiz); + + for (;;) + { + if (!line_reader.getline()) { return false; } + + // Check if the line ends with CRLF. + auto line_terminator_len = 2; + if (line_reader.end_with_crlf()) + { + // Blank line indicates end of headers. + if (line_reader.size() == 2) { break; } + } + else + { +#ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR + // Blank line indicates end of headers. + if (line_reader.size() == 1) { break; } + line_terminator_len = 1; +#else + continue; // Skip invalid line. +#endif + } + + if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; } + + // Exclude line terminator + auto end = line_reader.ptr() + line_reader.size() - line_terminator_len; + + if (!parse_header(line_reader.ptr(), end, + [&](const std::string& key, std::string& val) + { + headers.emplace(key, val); + })) + { + return false; + } + } + + return true; + } + + inline bool read_content_with_length(Stream& strm, uint64_t len, + Progress progress, + ContentReceiverWithProgress out) + { + char buf[CPPHTTPLIB_RECV_BUFSIZ]; + + uint64_t r = 0; + while (r < len) + { + auto read_len = static_cast(len - r); + auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ)); + if (n <= 0) { return false; } + + if (!out(buf, static_cast(n), r, len)) { return false; } + r += static_cast(n); + + if (progress) + { + if (!progress(r, len)) { return false; } + } + } + + return true; + } + + inline void skip_content_with_length(Stream& strm, uint64_t len) + { + char buf[CPPHTTPLIB_RECV_BUFSIZ]; + uint64_t r = 0; + while (r < len) + { + auto read_len = static_cast(len - r); + auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ)); + if (n <= 0) { return; } + r += static_cast(n); + } + } + + inline bool read_content_without_length(Stream& strm, + ContentReceiverWithProgress out) + { + char buf[CPPHTTPLIB_RECV_BUFSIZ]; + uint64_t r = 0; + for (;;) + { + auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ); + if (n <= 0) { return true; } + + if (!out(buf, static_cast(n), r, 0)) { return false; } + r += static_cast(n); + } + + return true; + } + + template + inline bool read_content_chunked(Stream& strm, T& x, + ContentReceiverWithProgress out) + { + const auto bufsiz = 16; + char buf[bufsiz]; + + stream_line_reader line_reader(strm, buf, bufsiz); + + if (!line_reader.getline()) { return false; } + + unsigned long chunk_len; + while (true) + { + char* end_ptr; + + chunk_len = std::strtoul(line_reader.ptr(), &end_ptr, 16); + + if (end_ptr == line_reader.ptr()) { return false; } + if (chunk_len == ULONG_MAX) { return false; } + + if (chunk_len == 0) { break; } + + if (!read_content_with_length(strm, chunk_len, nullptr, out)) + { + return false; + } + + if (!line_reader.getline()) { return false; } + + if (strcmp(line_reader.ptr(), "\r\n") != 0) { return false; } + + if (!line_reader.getline()) { return false; } + } + + assert(chunk_len == 0); + + // NOTE: In RFC 9112, '7.1 Chunked Transfer Coding' mentiones "The chunked + // transfer coding is complete when a chunk with a chunk-size of zero is + // received, possibly followed by a trailer section, and finally terminated by + // an empty line". https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1 + // + // In '7.1.3. Decoding Chunked', however, the pseudo-code in the section + // does't care for the existence of the final CRLF. In other words, it seems + // to be ok whether the final CRLF exists or not in the chunked data. + // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1.3 + // + // According to the reference code in RFC 9112, cpp-htpplib now allows + // chuncked transfer coding data without the final CRLF. + if (!line_reader.getline()) { return true; } + + while (strcmp(line_reader.ptr(), "\r\n") != 0) + { + if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; } + + // Exclude line terminator + constexpr auto line_terminator_len = 2; + auto end = line_reader.ptr() + line_reader.size() - line_terminator_len; + + parse_header(line_reader.ptr(), end, + [&](const std::string& key, const std::string& val) + { + x.headers.emplace(key, val); + }); + + if (!line_reader.getline()) { return false; } + } + + return true; + } + + inline bool is_chunked_transfer_encoding(const Headers& headers) + { + return case_ignore::equal( + get_header_value(headers, "Transfer-Encoding", "", 0), "chunked"); + } + + template + bool prepare_content_receiver(T& x, int& status, + ContentReceiverWithProgress receiver, + bool decompress, U callback) + { + if (decompress) + { + std::string encoding = x.get_header_value("Content-Encoding"); + std::unique_ptr decompressor; + + if (encoding == "gzip" || encoding == "deflate") + { +#ifdef CPPHTTPLIB_ZLIB_SUPPORT + decompressor = detail::make_unique(); +#else + status = StatusCode::UnsupportedMediaType_415; + return false; +#endif + } + else if (encoding.find("br") != std::string::npos) + { +#ifdef CPPHTTPLIB_BROTLI_SUPPORT + decompressor = detail::make_unique(); +#else + status = StatusCode::UnsupportedMediaType_415; + return false; +#endif + } + + if (decompressor) + { + if (decompressor->is_valid()) + { + ContentReceiverWithProgress out = [&](const char* buf, size_t n, + uint64_t off, uint64_t len) + { + return decompressor->decompress(buf, n, + [&](const char* buf2, size_t n2) + { + return receiver(buf2, n2, off, len); + }); + }; + return callback(std::move(out)); + } + else + { + status = StatusCode::InternalServerError_500; + return false; + } + } + } + + ContentReceiverWithProgress out = [&](const char* buf, size_t n, uint64_t off, + uint64_t len) + { + return receiver(buf, n, off, len); + }; + return callback(std::move(out)); + } + + template + bool read_content(Stream& strm, T& x, size_t payload_max_length, int& status, + Progress progress, ContentReceiverWithProgress receiver, + bool decompress) + { + return prepare_content_receiver( + x, status, std::move(receiver), decompress, + [&](const ContentReceiverWithProgress& out) + { + auto ret = true; + auto exceed_payload_max_length = false; + + if (is_chunked_transfer_encoding(x.headers)) + { + ret = read_content_chunked(strm, x, out); + } + else if (!has_header(x.headers, "Content-Length")) + { + ret = read_content_without_length(strm, out); + } + else + { + auto len = get_header_value_u64(x.headers, "Content-Length", 0, 0); + if (len > payload_max_length) + { + exceed_payload_max_length = true; + skip_content_with_length(strm, len); + ret = false; + } + else if (len > 0) + { + ret = read_content_with_length(strm, len, std::move(progress), out); + } + } + + if (!ret) + { + status = exceed_payload_max_length + ? StatusCode::PayloadTooLarge_413 + : StatusCode::BadRequest_400; + } + return ret; + }); + } + + inline ssize_t write_request_line(Stream& strm, const std::string& method, + const std::string& path) + { + std::string s = method; + s += " "; + s += path; + s += " HTTP/1.1\r\n"; + return strm.write(s.data(), s.size()); + } + + inline ssize_t write_response_line(Stream& strm, int status) + { + std::string s = "HTTP/1.1 "; + s += std::to_string(status); + s += " "; + s += httplib::status_message(status); + s += "\r\n"; + return strm.write(s.data(), s.size()); + } + + inline ssize_t write_headers(Stream& strm, const Headers& headers) + { + ssize_t write_len = 0; + for (const auto& x : headers) + { + std::string s; + s = x.first; + s += ": "; + s += x.second; + s += "\r\n"; + + auto len = strm.write(s.data(), s.size()); + if (len < 0) { return len; } + write_len += len; + } + auto len = strm.write("\r\n"); + if (len < 0) { return len; } + write_len += len; + return write_len; + } + + inline bool write_data(Stream& strm, const char* d, size_t l) + { + size_t offset = 0; + while (offset < l) + { + auto length = strm.write(d + offset, l - offset); + if (length < 0) { return false; } + offset += static_cast(length); + } + return true; + } + + template + inline bool write_content(Stream& strm, const ContentProvider& content_provider, + size_t offset, size_t length, T is_shutting_down, + Error& error) + { + size_t end_offset = offset + length; + auto ok = true; + DataSink data_sink; + + data_sink.write = [&](const char* d, size_t l) -> bool + { + if (ok) + { + if (strm.is_writable() && write_data(strm, d, l)) + { + offset += l; + } + else + { + ok = false; + } + } + return ok; + }; + + data_sink.is_writable = [&]() -> bool { return strm.is_writable(); }; + + while (offset < end_offset && !is_shutting_down()) + { + if (!strm.is_writable()) + { + error = Error::Write; + return false; + } + else if (!content_provider(offset, end_offset - offset, data_sink)) + { + error = Error::Canceled; + return false; + } + else if (!ok) + { + error = Error::Write; + return false; + } + } + + error = Error::Success; + return true; + } + + template + inline bool write_content(Stream& strm, const ContentProvider& content_provider, + size_t offset, size_t length, + const T& is_shutting_down) + { + auto error = Error::Success; + return write_content(strm, content_provider, offset, length, is_shutting_down, + error); + } + + template + inline bool + write_content_without_length(Stream& strm, + const ContentProvider& content_provider, + const T& is_shutting_down) + { + size_t offset = 0; + auto data_available = true; + auto ok = true; + DataSink data_sink; + + data_sink.write = [&](const char* d, size_t l) -> bool + { + if (ok) + { + offset += l; + if (!strm.is_writable() || !write_data(strm, d, l)) { ok = false; } + } + return ok; + }; + + data_sink.is_writable = [&]() -> bool { return strm.is_writable(); }; + + data_sink.done = [&](void) { data_available = false; }; + + while (data_available && !is_shutting_down()) + { + if (!strm.is_writable()) + { + return false; + } + else if (!content_provider(offset, 0, data_sink)) + { + return false; + } + else if (!ok) + { + return false; + } + } + return true; + } + + template + inline bool + write_content_chunked(Stream& strm, const ContentProvider& content_provider, + const T& is_shutting_down, U& compressor, Error& error) + { + size_t offset = 0; + auto data_available = true; + auto ok = true; + DataSink data_sink; + + data_sink.write = [&](const char* d, size_t l) -> bool + { + if (ok) + { + data_available = l > 0; + offset += l; + + std::string payload; + if (compressor.compress(d, l, false, + [&](const char* data, size_t data_len) + { + payload.append(data, data_len); + return true; + })) + { + if (!payload.empty()) + { + // Emit chunked response header and footer for each chunk + auto chunk = + from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n"; + if (!strm.is_writable() || + !write_data(strm, chunk.data(), chunk.size())) + { + ok = false; + } + } + } + else + { + ok = false; + } + } + return ok; + }; + + data_sink.is_writable = [&]() -> bool { return strm.is_writable(); }; + + auto done_with_trailer = [&](const Headers* trailer) + { + if (!ok) { return; } + + data_available = false; + + std::string payload; + if (!compressor.compress(nullptr, 0, true, + [&](const char* data, size_t data_len) + { + payload.append(data, data_len); + return true; + })) + { + ok = false; + return; + } + + if (!payload.empty()) + { + // Emit chunked response header and footer for each chunk + auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n"; + if (!strm.is_writable() || + !write_data(strm, chunk.data(), chunk.size())) + { + ok = false; + return; + } + } + + static const std::string done_marker("0\r\n"); + if (!write_data(strm, done_marker.data(), done_marker.size())) + { + ok = false; + } + + // Trailer + if (trailer) + { + for (const auto& kv : *trailer) + { + std::string field_line = kv.first + ": " + kv.second + "\r\n"; + if (!write_data(strm, field_line.data(), field_line.size())) + { + ok = false; + } + } + } + + static const std::string crlf("\r\n"); + if (!write_data(strm, crlf.data(), crlf.size())) { ok = false; } + }; + + data_sink.done = [&](void) { done_with_trailer(nullptr); }; + + data_sink.done_with_trailer = [&](const Headers& trailer) + { + done_with_trailer(&trailer); + }; + + while (data_available && !is_shutting_down()) + { + if (!strm.is_writable()) + { + error = Error::Write; + return false; + } + else if (!content_provider(offset, 0, data_sink)) + { + error = Error::Canceled; + return false; + } + else if (!ok) + { + error = Error::Write; + return false; + } + } + + error = Error::Success; + return true; + } + + template + inline bool write_content_chunked(Stream& strm, + const ContentProvider& content_provider, + const T& is_shutting_down, U& compressor) + { + auto error = Error::Success; + return write_content_chunked(strm, content_provider, is_shutting_down, + compressor, error); + } + + template + inline bool redirect(T& cli, Request& req, Response& res, + const std::string& path, const std::string& location, + Error& error) + { + Request new_req = req; + new_req.path = path; + new_req.redirect_count_ -= 1; + + if (res.status == StatusCode::SeeOther_303 && + (req.method != "GET" && req.method != "HEAD")) + { + new_req.method = "GET"; + new_req.body.clear(); + new_req.headers.clear(); + } + + Response new_res; + + auto ret = cli.send(new_req, new_res, error); + if (ret) + { + req = new_req; + res = new_res; + + if (res.location.empty()) { res.location = location; } + } + return ret; + } + + inline std::string params_to_query_str(const Params& params) + { + std::string query; + + for (auto it = params.begin(); it != params.end(); ++it) + { + if (it != params.begin()) { query += "&"; } + query += it->first; + query += "="; + query += encode_query_param(it->second); + } + return query; + } + + inline void parse_query_text(const char* data, std::size_t size, + Params& params) + { + std::set cache; + split(data, data + size, '&', [&](const char* b, const char* e) + { + std::string kv(b, e); + if (cache.find(kv) != cache.end()) { return; } + cache.insert(std::move(kv)); + + std::string key; + std::string val; + divide(b, static_cast(e - b), '=', + [&](const char* lhs_data, std::size_t lhs_size, const char* rhs_data, + std::size_t rhs_size) + { + key.assign(lhs_data, lhs_size); + val.assign(rhs_data, rhs_size); + }); + + if (!key.empty()) + { + params.emplace(decode_url(key, true), decode_url(val, true)); + } + }); + } + + inline void parse_query_text(const std::string& s, Params& params) + { + parse_query_text(s.data(), s.size(), params); + } + + inline bool parse_multipart_boundary(const std::string& content_type, + std::string& boundary) + { + auto boundary_keyword = "boundary="; + auto pos = content_type.find(boundary_keyword); + if (pos == std::string::npos) { return false; } + auto end = content_type.find(';', pos); + auto beg = pos + strlen(boundary_keyword); + boundary = trim_double_quotes_copy(content_type.substr(beg, end - beg)); + return !boundary.empty(); + } + + inline void parse_disposition_params(const std::string& s, Params& params) + { + std::set cache; + split(s.data(), s.data() + s.size(), ';', [&](const char* b, const char* e) + { + std::string kv(b, e); + if (cache.find(kv) != cache.end()) { return; } + cache.insert(kv); + + std::string key; + std::string val; + split(b, e, '=', [&](const char* b2, const char* e2) + { + if (key.empty()) + { + key.assign(b2, e2); + } + else + { + val.assign(b2, e2); + } + }); + + if (!key.empty()) + { + params.emplace(trim_double_quotes_copy((key)), + trim_double_quotes_copy((val))); + } + }); + } + +#ifdef CPPHTTPLIB_NO_EXCEPTIONS +inline bool parse_range_header(const std::string &s, Ranges &ranges) { +#else + inline bool parse_range_header(const std::string& s, Ranges& ranges) try + { +#endif + auto is_valid = [](const std::string& str) + { + return std::all_of(str.cbegin(), str.cend(), + [](unsigned char c) { return std::isdigit(c); }); + }; + + if (s.size() > 7 && s.compare(0, 6, "bytes=") == 0) + { + const auto pos = static_cast(6); + const auto len = static_cast(s.size() - 6); + auto all_valid_ranges = true; + split(&s[pos], &s[pos + len], ',', [&](const char* b, const char* e) + { + if (!all_valid_ranges) { return; } + + const auto it = std::find(b, e, '-'); + if (it == e) + { + all_valid_ranges = false; + return; + } + + const auto lhs = std::string(b, it); + const auto rhs = std::string(it + 1, e); + if (!is_valid(lhs) || !is_valid(rhs)) + { + all_valid_ranges = false; + return; + } + + const auto first = + static_cast(lhs.empty() ? -1 : std::stoll(lhs)); + const auto last = + static_cast(rhs.empty() ? -1 : std::stoll(rhs)); + if ((first == -1 && last == -1) || + (first != -1 && last != -1 && first > last)) + { + all_valid_ranges = false; + return; + } + + ranges.emplace_back(first, last); + }); + return all_valid_ranges && !ranges.empty(); + } + return false; +#ifdef CPPHTTPLIB_NO_EXCEPTIONS +} +#else + } + catch (...) { return false; } +#endif + + class MultipartFormDataParser + { + public: + MultipartFormDataParser() = default; + + void set_boundary(std::string&& boundary) + { + boundary_ = boundary; + dash_boundary_crlf_ = dash_ + boundary_ + crlf_; + crlf_dash_boundary_ = crlf_ + dash_ + boundary_; + } + + bool is_valid() const { return is_valid_; } + + bool parse(const char* buf, size_t n, const ContentReceiver& content_callback, + const MultipartContentHeader& header_callback) + { + buf_append(buf, n); + + while (buf_size() > 0) + { + switch (state_) + { + case 0: + { + // Initial boundary + buf_erase(buf_find(dash_boundary_crlf_)); + if (dash_boundary_crlf_.size() > buf_size()) { return true; } + if (!buf_start_with(dash_boundary_crlf_)) { return false; } + buf_erase(dash_boundary_crlf_.size()); + state_ = 1; + break; + } + case 1: + { + // New entry + clear_file_info(); + state_ = 2; + break; + } + case 2: + { + // Headers + auto pos = buf_find(crlf_); + if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; } + while (pos < buf_size()) + { + // Empty line + if (pos == 0) + { + if (!header_callback(file_)) + { + is_valid_ = false; + return false; + } + buf_erase(crlf_.size()); + state_ = 3; + break; + } + + const auto header = buf_head(pos); + + if (!parse_header(header.data(), header.data() + header.size(), + [&](const std::string&, const std::string&) + { + })) + { + is_valid_ = false; + return false; + } + + static const std::string header_content_type = "Content-Type:"; + + if (start_with_case_ignore(header, header_content_type)) + { + file_.content_type = + trim_copy(header.substr(header_content_type.size())); + } + else + { + static const std::regex re_content_disposition( + R"~(^Content-Disposition:\s*form-data;\s*(.*)$)~", + std::regex_constants::icase); + + std::smatch m; + if (std::regex_match(header, m, re_content_disposition)) + { + Params params; + parse_disposition_params(m[1], params); + + auto it = params.find("name"); + if (it != params.end()) + { + file_.name = it->second; + } + else + { + is_valid_ = false; + return false; + } + + it = params.find("filename"); + if (it != params.end()) { file_.filename = it->second; } + + it = params.find("filename*"); + if (it != params.end()) + { + // Only allow UTF-8 enconnding... + static const std::regex re_rfc5987_encoding( + R"~(^UTF-8''(.+?)$)~", std::regex_constants::icase); + + std::smatch m2; + if (std::regex_match(it->second, m2, re_rfc5987_encoding)) + { + file_.filename = decode_url(m2[1], false); // override... + } + else + { + is_valid_ = false; + return false; + } + } + } + } + buf_erase(pos + crlf_.size()); + pos = buf_find(crlf_); + } + if (state_ != 3) { return true; } + break; + } + case 3: + { + // Body + if (crlf_dash_boundary_.size() > buf_size()) { return true; } + auto pos = buf_find(crlf_dash_boundary_); + if (pos < buf_size()) + { + if (!content_callback(buf_data(), pos)) + { + is_valid_ = false; + return false; + } + buf_erase(pos + crlf_dash_boundary_.size()); + state_ = 4; + } + else + { + auto len = buf_size() - crlf_dash_boundary_.size(); + if (len > 0) + { + if (!content_callback(buf_data(), len)) + { + is_valid_ = false; + return false; + } + buf_erase(len); + } + return true; + } + break; + } + case 4: + { + // Boundary + if (crlf_.size() > buf_size()) { return true; } + if (buf_start_with(crlf_)) + { + buf_erase(crlf_.size()); + state_ = 1; + } + else + { + if (dash_.size() > buf_size()) { return true; } + if (buf_start_with(dash_)) + { + buf_erase(dash_.size()); + is_valid_ = true; + buf_erase(buf_size()); // Remove epilogue + } + else + { + return true; + } + } + break; + } + } + } + + return true; + } + + private: + void clear_file_info() + { + file_.name.clear(); + file_.filename.clear(); + file_.content_type.clear(); + } + + bool start_with_case_ignore(const std::string& a, + const std::string& b) const + { + if (a.size() < b.size()) { return false; } + for (size_t i = 0; i < b.size(); i++) + { + if (case_ignore::to_lower(a[i]) != case_ignore::to_lower(b[i])) + { + return false; + } + } + return true; + } + + const std::string dash_ = "--"; + const std::string crlf_ = "\r\n"; + std::string boundary_; + std::string dash_boundary_crlf_; + std::string crlf_dash_boundary_; + + size_t state_ = 0; + bool is_valid_ = false; + MultipartFormData file_; + + // Buffer + bool start_with(const std::string& a, size_t spos, size_t epos, + const std::string& b) const + { + if (epos - spos < b.size()) { return false; } + for (size_t i = 0; i < b.size(); i++) + { + if (a[i + spos] != b[i]) { return false; } + } + return true; + } + + size_t buf_size() const { return buf_epos_ - buf_spos_; } + + const char* buf_data() const { return &buf_[buf_spos_]; } + + std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); } + + bool buf_start_with(const std::string& s) const + { + return start_with(buf_, buf_spos_, buf_epos_, s); + } + + size_t buf_find(const std::string& s) const + { + auto c = s.front(); + + size_t off = buf_spos_; + while (off < buf_epos_) + { + auto pos = off; + while (true) + { + if (pos == buf_epos_) { return buf_size(); } + if (buf_[pos] == c) { break; } + pos++; + } + + auto remaining_size = buf_epos_ - pos; + if (s.size() > remaining_size) { return buf_size(); } + + if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; } + + off = pos + 1; + } + + return buf_size(); + } + + void buf_append(const char* data, size_t n) + { + auto remaining_size = buf_size(); + if (remaining_size > 0 && buf_spos_ > 0) + { + for (size_t i = 0; i < remaining_size; i++) + { + buf_[i] = buf_[buf_spos_ + i]; + } + } + buf_spos_ = 0; + buf_epos_ = remaining_size; + + if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); } + + for (size_t i = 0; i < n; i++) + { + buf_[buf_epos_ + i] = data[i]; + } + buf_epos_ += n; + } + + void buf_erase(size_t size) { buf_spos_ += size; } + + std::string buf_; + size_t buf_spos_ = 0; + size_t buf_epos_ = 0; + }; + + inline std::string random_string(size_t length) + { + static const char data[] = + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + + // std::random_device might actually be deterministic on some + // platforms, but due to lack of support in the c++ standard library, + // doing better requires either some ugly hacks or breaking portability. + static std::random_device seed_gen; + + // Request 128 bits of entropy for initialization + static std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), + seed_gen()}; + + static std::mt19937 engine(seed_sequence); + + std::string result; + for (size_t i = 0; i < length; i++) + { + result += data[engine() % (sizeof(data) - 1)]; + } + return result; + } + + inline std::string make_multipart_data_boundary() + { + return "--cpp-httplib-multipart-data-" + detail::random_string(16); + } + + inline bool is_multipart_boundary_chars_valid(const std::string& boundary) + { + auto valid = true; + for (size_t i = 0; i < boundary.size(); i++) + { + auto c = boundary[i]; + if (!std::isalnum(c) && c != '-' && c != '_') + { + valid = false; + break; + } + } + return valid; + } + + template + inline std::string + serialize_multipart_formdata_item_begin(const T& item, + const std::string& boundary) + { + std::string body = "--" + boundary + "\r\n"; + body += "Content-Disposition: form-data; name=\"" + item.name + "\""; + if (!item.filename.empty()) + { + body += "; filename=\"" + item.filename + "\""; + } + body += "\r\n"; + if (!item.content_type.empty()) + { + body += "Content-Type: " + item.content_type + "\r\n"; + } + body += "\r\n"; + + return body; + } + + inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; } + + inline std::string + serialize_multipart_formdata_finish(const std::string& boundary) + { + return "--" + boundary + "--\r\n"; + } + + inline std::string + serialize_multipart_formdata_get_content_type(const std::string& boundary) + { + return "multipart/form-data; boundary=" + boundary; + } + + inline std::string + serialize_multipart_formdata(const MultipartFormDataItems& items, + const std::string& boundary, bool finish = true) + { + std::string body; + + for (const auto& item : items) + { + body += serialize_multipart_formdata_item_begin(item, boundary); + body += item.content + serialize_multipart_formdata_item_end(); + } + + if (finish) { body += serialize_multipart_formdata_finish(boundary); } + + return body; + } + + inline bool range_error(Request& req, Response& res) + { + if (!req.ranges.empty() && 200 <= res.status && res.status < 300) + { + ssize_t contant_len = static_cast( + res.content_length_ ? res.content_length_ : res.body.size()); + + ssize_t prev_first_pos = -1; + ssize_t prev_last_pos = -1; + size_t overwrapping_count = 0; + + // NOTE: The following Range check is based on '14.2. Range' in RFC 9110 + // 'HTTP Semantics' to avoid potential denial-of-service attacks. + // https://www.rfc-editor.org/rfc/rfc9110#section-14.2 + + // Too many ranges + if (req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) { return true; } + + for (auto& r : req.ranges) + { + auto& first_pos = r.first; + auto& last_pos = r.second; + + if (first_pos == -1 && last_pos == -1) + { + first_pos = 0; + last_pos = contant_len; + } + + if (first_pos == -1) + { + first_pos = contant_len - last_pos; + last_pos = contant_len - 1; + } + + if (last_pos == -1) { last_pos = contant_len - 1; } + + // Range must be within content length + if (!(0 <= first_pos && first_pos <= last_pos && + last_pos <= contant_len - 1)) + { + return true; + } + + // Ranges must be in ascending order + if (first_pos <= prev_first_pos) { return true; } + + // Request must not have more than two overlapping ranges + if (first_pos <= prev_last_pos) + { + overwrapping_count++; + if (overwrapping_count > 2) { return true; } + } + + prev_first_pos = (std::max)(prev_first_pos, first_pos); + prev_last_pos = (std::max)(prev_last_pos, last_pos); + } + } + + return false; + } + + inline std::pair + get_range_offset_and_length(Range r, size_t content_length) + { + assert(r.first != -1 && r.second != -1); + assert(0 <= r.first && r.first < static_cast(content_length)); + assert(r.first <= r.second && + r.second < static_cast(content_length)); + (void)(content_length); + return std::make_pair(r.first, static_cast(r.second - r.first) + 1); + } + + inline std::string make_content_range_header_field( + const std::pair& offset_and_length, size_t content_length) + { + auto st = offset_and_length.first; + auto ed = st + offset_and_length.second - 1; + + std::string field = "bytes "; + field += std::to_string(st); + field += "-"; + field += std::to_string(ed); + field += "/"; + field += std::to_string(content_length); + return field; + } + + template + bool process_multipart_ranges_data(const Request& req, + const std::string& boundary, + const std::string& content_type, + size_t content_length, SToken stoken, + CToken ctoken, Content content) + { + for (size_t i = 0; i < req.ranges.size(); i++) + { + ctoken("--"); + stoken(boundary); + ctoken("\r\n"); + if (!content_type.empty()) + { + ctoken("Content-Type: "); + stoken(content_type); + ctoken("\r\n"); + } + + auto offset_and_length = + get_range_offset_and_length(req.ranges[i], content_length); + + ctoken("Content-Range: "); + stoken(make_content_range_header_field(offset_and_length, content_length)); + ctoken("\r\n"); + ctoken("\r\n"); + + if (!content(offset_and_length.first, offset_and_length.second)) + { + return false; + } + ctoken("\r\n"); + } + + ctoken("--"); + stoken(boundary); + ctoken("--"); + + return true; + } + + inline void make_multipart_ranges_data(const Request& req, Response& res, + const std::string& boundary, + const std::string& content_type, + size_t content_length, + std::string& data) + { + process_multipart_ranges_data( + req, boundary, content_type, content_length, + [&](const std::string& token) { data += token; }, + [&](const std::string& token) { data += token; }, + [&](size_t offset, size_t length) + { + assert(offset + length <= content_length); + data += res.body.substr(offset, length); + return true; + }); + } + + inline size_t get_multipart_ranges_data_length(const Request& req, + const std::string& boundary, + const std::string& content_type, + size_t content_length) + { + size_t data_length = 0; + + process_multipart_ranges_data( + req, boundary, content_type, content_length, + [&](const std::string& token) { data_length += token.size(); }, + [&](const std::string& token) { data_length += token.size(); }, + [&](size_t /*offset*/, size_t length) + { + data_length += length; + return true; + }); + + return data_length; + } + + template + inline bool + write_multipart_ranges_data(Stream& strm, const Request& req, Response& res, + const std::string& boundary, + const std::string& content_type, + size_t content_length, const T& is_shutting_down) + { + return process_multipart_ranges_data( + req, boundary, content_type, content_length, + [&](const std::string& token) { strm.write(token); }, + [&](const std::string& token) { strm.write(token); }, + [&](size_t offset, size_t length) + { + return write_content(strm, res.content_provider_, offset, length, + is_shutting_down); + }); + } + + inline bool expect_content(const Request& req) + { + if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" || + req.method == "PRI" || req.method == "DELETE") + { + return true; + } + // TODO: check if Content-Length is set + return false; + } + + inline bool has_crlf(const std::string& s) + { + auto p = s.c_str(); + while (*p) + { + if (*p == '\r' || *p == '\n') { return true; } + p++; + } + return false; + } + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT +inline std::string message_digest(const std::string &s, const EVP_MD *algo) { + auto context = std::unique_ptr( + EVP_MD_CTX_new(), EVP_MD_CTX_free); + + unsigned int hash_length = 0; + unsigned char hash[EVP_MAX_MD_SIZE]; + + EVP_DigestInit_ex(context.get(), algo, nullptr); + EVP_DigestUpdate(context.get(), s.c_str(), s.size()); + EVP_DigestFinal_ex(context.get(), hash, &hash_length); + + std::stringstream ss; + for (auto i = 0u; i < hash_length; ++i) { + ss << std::hex << std::setw(2) << std::setfill('0') + << static_cast(hash[i]); + } + + return ss.str(); +} + +inline std::string MD5(const std::string &s) { + return message_digest(s, EVP_md5()); +} + +inline std::string SHA_256(const std::string &s) { + return message_digest(s, EVP_sha256()); +} + +inline std::string SHA_512(const std::string &s) { + return message_digest(s, EVP_sha512()); +} +#endif + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT +#ifdef _WIN32 +// NOTE: This code came up with the following stackoverflow post: +// https://stackoverflow.com/questions/9507184/can-openssl-on-windows-use-the-system-certificate-store +inline bool load_system_certs_on_windows(X509_STORE *store) { + auto hStore = CertOpenSystemStoreW((HCRYPTPROV_LEGACY)NULL, L"ROOT"); + if (!hStore) { return false; } + + auto result = false; + PCCERT_CONTEXT pContext = NULL; + while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) != + nullptr) { + auto encoded_cert = + static_cast(pContext->pbCertEncoded); + + auto x509 = d2i_X509(NULL, &encoded_cert, pContext->cbCertEncoded); + if (x509) { + X509_STORE_add_cert(store, x509); + X509_free(x509); + result = true; + } + } + + CertFreeCertificateContext(pContext); + CertCloseStore(hStore, 0); + + return result; +} +#elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && defined(__APPLE__) +#if TARGET_OS_OSX +template +using CFObjectPtr = + std::unique_ptr::type, void (*)(CFTypeRef)>; + +inline void cf_object_ptr_deleter(CFTypeRef obj) { + if (obj) { CFRelease(obj); } +} + +inline bool retrieve_certs_from_keychain(CFObjectPtr &certs) { + CFStringRef keys[] = {kSecClass, kSecMatchLimit, kSecReturnRef}; + CFTypeRef values[] = {kSecClassCertificate, kSecMatchLimitAll, + kCFBooleanTrue}; + + CFObjectPtr query( + CFDictionaryCreate(nullptr, reinterpret_cast(keys), values, + sizeof(keys) / sizeof(keys[0]), + &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks), + cf_object_ptr_deleter); + + if (!query) { return false; } + + CFTypeRef security_items = nullptr; + if (SecItemCopyMatching(query.get(), &security_items) != errSecSuccess || + CFArrayGetTypeID() != CFGetTypeID(security_items)) { + return false; + } + + certs.reset(reinterpret_cast(security_items)); + return true; +} + +inline bool retrieve_root_certs_from_keychain(CFObjectPtr &certs) { + CFArrayRef root_security_items = nullptr; + if (SecTrustCopyAnchorCertificates(&root_security_items) != errSecSuccess) { + return false; + } + + certs.reset(root_security_items); + return true; +} + +inline bool add_certs_to_x509_store(CFArrayRef certs, X509_STORE *store) { + auto result = false; + for (auto i = 0; i < CFArrayGetCount(certs); ++i) { + const auto cert = reinterpret_cast( + CFArrayGetValueAtIndex(certs, i)); + + if (SecCertificateGetTypeID() != CFGetTypeID(cert)) { continue; } + + CFDataRef cert_data = nullptr; + if (SecItemExport(cert, kSecFormatX509Cert, 0, nullptr, &cert_data) != + errSecSuccess) { + continue; + } + + CFObjectPtr cert_data_ptr(cert_data, cf_object_ptr_deleter); + + auto encoded_cert = static_cast( + CFDataGetBytePtr(cert_data_ptr.get())); + + auto x509 = + d2i_X509(NULL, &encoded_cert, CFDataGetLength(cert_data_ptr.get())); + + if (x509) { + X509_STORE_add_cert(store, x509); + X509_free(x509); + result = true; + } + } + + return result; +} + +inline bool load_system_certs_on_macos(X509_STORE *store) { + auto result = false; + CFObjectPtr certs(nullptr, cf_object_ptr_deleter); + if (retrieve_certs_from_keychain(certs) && certs) { + result = add_certs_to_x509_store(certs.get(), store); + } + + if (retrieve_root_certs_from_keychain(certs) && certs) { + result = add_certs_to_x509_store(certs.get(), store) || result; + } + + return result; +} +#endif // TARGET_OS_OSX +#endif // _WIN32 +#endif // CPPHTTPLIB_OPENSSL_SUPPORT + +#ifdef _WIN32 + class WSInit + { + public: + WSInit() + { + WSADATA wsaData; + if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true; + } + + ~WSInit() + { + if (is_valid_) WSACleanup(); + } + + bool is_valid_ = false; + }; + + static WSInit wsinit_; +#endif + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT +inline std::pair make_digest_authentication_header( + const Request &req, const std::map &auth, + size_t cnonce_count, const std::string &cnonce, const std::string &username, + const std::string &password, bool is_proxy = false) { + std::string nc; + { + std::stringstream ss; + ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count; + nc = ss.str(); + } + + std::string qop; + if (auth.find("qop") != auth.end()) { + qop = auth.at("qop"); + if (qop.find("auth-int") != std::string::npos) { + qop = "auth-int"; + } else if (qop.find("auth") != std::string::npos) { + qop = "auth"; + } else { + qop.clear(); + } + } + + std::string algo = "MD5"; + if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); } + + std::string response; + { + auto H = algo == "SHA-256" ? detail::SHA_256 + : algo == "SHA-512" ? detail::SHA_512 + : detail::MD5; + + auto A1 = username + ":" + auth.at("realm") + ":" + password; + + auto A2 = req.method + ":" + req.path; + if (qop == "auth-int") { A2 += ":" + H(req.body); } + + if (qop.empty()) { + response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2)); + } else { + response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce + + ":" + qop + ":" + H(A2)); + } + } + + auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : ""; + + auto field = "Digest username=\"" + username + "\", realm=\"" + + auth.at("realm") + "\", nonce=\"" + auth.at("nonce") + + "\", uri=\"" + req.path + "\", algorithm=" + algo + + (qop.empty() ? ", response=\"" + : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" + + cnonce + "\", response=\"") + + response + "\"" + + (opaque.empty() ? "" : ", opaque=\"" + opaque + "\""); + + auto key = is_proxy ? "Proxy-Authorization" : "Authorization"; + return std::make_pair(key, field); +} +#endif + + inline bool parse_www_authenticate(const Response& res, + std::map& auth, + bool is_proxy) + { + auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate"; + if (res.has_header(auth_key)) + { + static auto re = std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~"); + auto s = res.get_header_value(auth_key); + auto pos = s.find(' '); + if (pos != std::string::npos) + { + auto type = s.substr(0, pos); + if (type == "Basic") + { + return false; + } + else if (type == "Digest") + { + s = s.substr(pos + 1); + auto beg = std::sregex_iterator(s.begin(), s.end(), re); + for (auto i = beg; i != std::sregex_iterator(); ++i) + { + const auto& m = *i; + auto key = s.substr(static_cast(m.position(1)), + static_cast(m.length(1))); + auto val = m.length(2) > 0 + ? s.substr(static_cast(m.position(2)), + static_cast(m.length(2))) + : s.substr(static_cast(m.position(3)), + static_cast(m.length(3))); + auth[key] = val; + } + return true; + } + } + } + return false; + } + + class ContentProviderAdapter + { + public: + explicit ContentProviderAdapter( + ContentProviderWithoutLength&& content_provider) : + content_provider_(content_provider) + { + } + + bool operator()(size_t offset, size_t, DataSink& sink) + { + return content_provider_(offset, sink); + } + + private: + ContentProviderWithoutLength content_provider_; + }; + } // namespace detail + + inline std::string hosted_at(const std::string& hostname) + { + std::vector addrs; + hosted_at(hostname, addrs); + if (addrs.empty()) { return std::string(); } + return addrs[0]; + } + + inline void hosted_at(const std::string& hostname, + std::vector& addrs) + { + struct addrinfo hints; + struct addrinfo* result; + + memset(&hints, 0, sizeof(struct addrinfo)); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + hints.ai_protocol = 0; + + if (getaddrinfo(hostname.c_str(), nullptr, &hints, &result)) + { +#if defined __linux__ && !defined __ANDROID__ + res_init(); +#endif + return; + } + auto se = detail::scope_exit([&] { freeaddrinfo(result); }); + + for (auto rp = result; rp; rp = rp->ai_next) + { + const auto& addr = + *reinterpret_cast(rp->ai_addr); + std::string ip; + auto dummy = -1; + if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip, + dummy)) + { + addrs.push_back(ip); + } + } + } + + inline std::string append_query_params(const std::string& path, + const Params& params) + { + std::string path_with_query = path; + const static std::regex re("[^?]+\\?.*"); + auto delm = std::regex_match(path, re) ? '&' : '?'; + path_with_query += delm + detail::params_to_query_str(params); + return path_with_query; + } + + // Header utilities + inline std::pair + make_range_header(const Ranges& ranges) + { + std::string field = "bytes="; + auto i = 0; + for (const auto& r : ranges) + { + if (i != 0) { field += ", "; } + if (r.first != -1) { field += std::to_string(r.first); } + field += '-'; + if (r.second != -1) { field += std::to_string(r.second); } + i++; + } + return std::make_pair("Range", std::move(field)); + } + + inline std::pair + make_basic_authentication_header(const std::string& username, + const std::string& password, bool is_proxy) + { + auto field = "Basic " + detail::base64_encode(username + ":" + password); + auto key = is_proxy ? "Proxy-Authorization" : "Authorization"; + return std::make_pair(key, std::move(field)); + } + + inline std::pair + make_bearer_token_authentication_header(const std::string& token, + bool is_proxy = false) + { + auto field = "Bearer " + token; + auto key = is_proxy ? "Proxy-Authorization" : "Authorization"; + return std::make_pair(key, std::move(field)); + } + + // Request implementation + inline bool Request::has_header(const std::string& key) const + { + return detail::has_header(headers, key); + } + + inline std::string Request::get_header_value(const std::string& key, + const char* def, size_t id) const + { + return detail::get_header_value(headers, key, def, id); + } + + inline size_t Request::get_header_value_count(const std::string& key) const + { + auto r = headers.equal_range(key); + return static_cast(std::distance(r.first, r.second)); + } + + inline void Request::set_header(const std::string& key, + const std::string& val) + { + if (!detail::has_crlf(key) && !detail::has_crlf(val)) + { + headers.emplace(key, val); + } + } + + inline bool Request::has_param(const std::string& key) const + { + return params.find(key) != params.end(); + } + + inline std::string Request::get_param_value(const std::string& key, + size_t id) const + { + auto rng = params.equal_range(key); + auto it = rng.first; + std::advance(it, static_cast(id)); + if (it != rng.second) { return it->second; } + return std::string(); + } + + inline size_t Request::get_param_value_count(const std::string& key) const + { + auto r = params.equal_range(key); + return static_cast(std::distance(r.first, r.second)); + } + + inline bool Request::is_multipart_form_data() const + { + const auto& content_type = get_header_value("Content-Type"); + return !content_type.rfind("multipart/form-data", 0); + } + + inline bool Request::has_file(const std::string& key) const + { + return files.find(key) != files.end(); + } + + inline MultipartFormData Request::get_file_value(const std::string& key) const + { + auto it = files.find(key); + if (it != files.end()) { return it->second; } + return MultipartFormData(); + } + + inline std::vector + Request::get_file_values(const std::string& key) const + { + std::vector values; + auto rng = files.equal_range(key); + for (auto it = rng.first; it != rng.second; it++) + { + values.push_back(it->second); + } + return values; + } + + // Response implementation + inline bool Response::has_header(const std::string& key) const + { + return headers.find(key) != headers.end(); + } + + inline std::string Response::get_header_value(const std::string& key, + const char* def, + size_t id) const + { + return detail::get_header_value(headers, key, def, id); + } + + inline size_t Response::get_header_value_count(const std::string& key) const + { + auto r = headers.equal_range(key); + return static_cast(std::distance(r.first, r.second)); + } + + inline void Response::set_header(const std::string& key, + const std::string& val) + { + if (!detail::has_crlf(key) && !detail::has_crlf(val)) + { + headers.emplace(key, val); + } + } + + inline void Response::set_redirect(const std::string& url, int stat) + { + if (!detail::has_crlf(url)) + { + set_header("Location", url); + if (300 <= stat && stat < 400) + { + this->status = stat; + } + else + { + this->status = StatusCode::Found_302; + } + } + } + + inline void Response::set_content(const char* s, size_t n, + const std::string& content_type) + { + body.assign(s, n); + + auto rng = headers.equal_range("Content-Type"); + headers.erase(rng.first, rng.second); + set_header("Content-Type", content_type); + } + + inline void Response::set_content(const std::string& s, + const std::string& content_type) + { + set_content(s.data(), s.size(), content_type); + } + + inline void Response::set_content(std::string&& s, + const std::string& content_type) + { + body = std::move(s); + + auto rng = headers.equal_range("Content-Type"); + headers.erase(rng.first, rng.second); + set_header("Content-Type", content_type); + } + + inline void Response::set_content_provider( + size_t in_length, const std::string& content_type, ContentProvider provider, + ContentProviderResourceReleaser resource_releaser) + { + set_header("Content-Type", content_type); + content_length_ = in_length; + if (in_length > 0) { content_provider_ = std::move(provider); } + content_provider_resource_releaser_ = std::move(resource_releaser); + is_chunked_content_provider_ = false; + } + + inline void Response::set_content_provider( + const std::string& content_type, ContentProviderWithoutLength provider, + ContentProviderResourceReleaser resource_releaser) + { + set_header("Content-Type", content_type); + content_length_ = 0; + content_provider_ = detail::ContentProviderAdapter(std::move(provider)); + content_provider_resource_releaser_ = std::move(resource_releaser); + is_chunked_content_provider_ = false; + } + + inline void Response::set_chunked_content_provider( + const std::string& content_type, ContentProviderWithoutLength provider, + ContentProviderResourceReleaser resource_releaser) + { + set_header("Content-Type", content_type); + content_length_ = 0; + content_provider_ = detail::ContentProviderAdapter(std::move(provider)); + content_provider_resource_releaser_ = std::move(resource_releaser); + is_chunked_content_provider_ = true; + } + + inline void Response::set_file_content(const std::string& path, + const std::string& content_type) + { + file_content_path_ = path; + file_content_content_type_ = content_type; + } + + inline void Response::set_file_content(const std::string& path) + { + file_content_path_ = path; + } + + // Result implementation + inline bool Result::has_request_header(const std::string& key) const + { + return request_headers_.find(key) != request_headers_.end(); + } + + inline std::string Result::get_request_header_value(const std::string& key, + const char* def, + size_t id) const + { + return detail::get_header_value(request_headers_, key, def, id); + } + + inline size_t + Result::get_request_header_value_count(const std::string& key) const + { + auto r = request_headers_.equal_range(key); + return static_cast(std::distance(r.first, r.second)); + } + + // Stream implementation + inline ssize_t Stream::write(const char* ptr) + { + return write(ptr, strlen(ptr)); + } + + inline ssize_t Stream::write(const std::string& s) + { + return write(s.data(), s.size()); + } + + namespace detail + { + // Socket stream implementation + inline SocketStream::SocketStream(socket_t sock, time_t read_timeout_sec, + time_t read_timeout_usec, + time_t write_timeout_sec, + time_t write_timeout_usec) : + sock_(sock), read_timeout_sec_(read_timeout_sec), + read_timeout_usec_(read_timeout_usec), + write_timeout_sec_(write_timeout_sec), + write_timeout_usec_(write_timeout_usec), read_buff_(read_buff_size_, 0) + { + } + + inline SocketStream::~SocketStream() = default; + + inline bool SocketStream::is_readable() const + { + return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0; + } + + inline bool SocketStream::is_writable() const + { + return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 && + is_socket_alive(sock_); + } + + inline ssize_t SocketStream::read(char* ptr, size_t size) + { +#ifdef _WIN32 + size = + (std::min)(size, static_cast((std::numeric_limits::max)())); +#else + size = (std::min)(size, + static_cast((std::numeric_limits::max)())); +#endif + + if (read_buff_off_ < read_buff_content_size_) + { + auto remaining_size = read_buff_content_size_ - read_buff_off_; + if (size <= remaining_size) + { + memcpy(ptr, read_buff_.data() + read_buff_off_, size); + read_buff_off_ += size; + return static_cast(size); + } + else + { + memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size); + read_buff_off_ += remaining_size; + return static_cast(remaining_size); + } + } + + if (!is_readable()) { return -1; } + + read_buff_off_ = 0; + read_buff_content_size_ = 0; + + if (size < read_buff_size_) + { + auto n = read_socket(sock_, read_buff_.data(), read_buff_size_, + CPPHTTPLIB_RECV_FLAGS); + if (n <= 0) + { + return n; + } + else if (n <= static_cast(size)) + { + memcpy(ptr, read_buff_.data(), static_cast(n)); + return n; + } + else + { + memcpy(ptr, read_buff_.data(), size); + read_buff_off_ = size; + read_buff_content_size_ = static_cast(n); + return static_cast(size); + } + } + else + { + return read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS); + } + } + + inline ssize_t SocketStream::write(const char* ptr, size_t size) + { + if (!is_writable()) { return -1; } + +#if defined(_WIN32) && !defined(_WIN64) + size = + (std::min)(size, static_cast((std::numeric_limits::max)())); +#endif + + return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS); + } + + inline void SocketStream::get_remote_ip_and_port(std::string& ip, + int& port) const + { + return detail::get_remote_ip_and_port(sock_, ip, port); + } + + inline void SocketStream::get_local_ip_and_port(std::string& ip, + int& port) const + { + return detail::get_local_ip_and_port(sock_, ip, port); + } + + inline socket_t SocketStream::socket() const { return sock_; } + + // Buffer stream implementation + inline bool BufferStream::is_readable() const { return true; } + + inline bool BufferStream::is_writable() const { return true; } + + inline ssize_t BufferStream::read(char* ptr, size_t size) + { +#if defined(_MSC_VER) && _MSC_VER < 1910 + auto len_read = buffer._Copy_s(ptr, size, size, position); +#else + auto len_read = buffer.copy(ptr, size, position); +#endif + position += static_cast(len_read); + return static_cast(len_read); + } + + inline ssize_t BufferStream::write(const char* ptr, size_t size) + { + buffer.append(ptr, size); + return static_cast(size); + } + + inline void BufferStream::get_remote_ip_and_port(std::string& /*ip*/, + int& /*port*/) const + { + } + + inline void BufferStream::get_local_ip_and_port(std::string& /*ip*/, + int& /*port*/) const + { + } + + inline socket_t BufferStream::socket() const { return 0; } + + inline const std::string& BufferStream::get_buffer() const { return buffer; } + + inline PathParamsMatcher::PathParamsMatcher(const std::string& pattern) + { + static constexpr char marker[] = "/:"; + + // One past the last ending position of a path param substring + std::size_t last_param_end = 0; + +#ifndef CPPHTTPLIB_NO_EXCEPTIONS + // Needed to ensure that parameter names are unique during matcher + // construction + // If exceptions are disabled, only last duplicate path + // parameter will be set + std::unordered_set param_name_set; +#endif + + while (true) + { + const auto marker_pos = pattern.find( + marker, last_param_end == 0 ? last_param_end : last_param_end - 1); + if (marker_pos == std::string::npos) { break; } + + static_fragments_.push_back( + pattern.substr(last_param_end, marker_pos - last_param_end + 1)); + + const auto param_name_start = marker_pos + 2; + + auto sep_pos = pattern.find(separator, param_name_start); + if (sep_pos == std::string::npos) { sep_pos = pattern.length(); } + + auto param_name = + pattern.substr(param_name_start, sep_pos - param_name_start); + +#ifndef CPPHTTPLIB_NO_EXCEPTIONS + if (param_name_set.find(param_name) != param_name_set.cend()) + { + std::string msg = "Encountered path parameter '" + param_name + + "' multiple times in route pattern '" + pattern + "'."; + throw std::invalid_argument(msg); + } +#endif + + param_names_.push_back(std::move(param_name)); + + last_param_end = sep_pos + 1; + } + + if (last_param_end < pattern.length()) + { + static_fragments_.push_back(pattern.substr(last_param_end)); + } + } + + inline bool PathParamsMatcher::match(Request& request) const + { + request.matches = std::smatch(); + request.path_params.clear(); + request.path_params.reserve(param_names_.size()); + + // One past the position at which the path matched the pattern last time + std::size_t starting_pos = 0; + for (size_t i = 0; i < static_fragments_.size(); ++i) + { + const auto& fragment = static_fragments_[i]; + + if (starting_pos + fragment.length() > request.path.length()) + { + return false; + } + + // Avoid unnecessary allocation by using strncmp instead of substr + + // comparison + if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(), + fragment.length()) != 0) + { + return false; + } + + starting_pos += fragment.length(); + + // Should only happen when we have a static fragment after a param + // Example: '/users/:id/subscriptions' + // The 'subscriptions' fragment here does not have a corresponding param + if (i >= param_names_.size()) { continue; } + + auto sep_pos = request.path.find(separator, starting_pos); + if (sep_pos == std::string::npos) { sep_pos = request.path.length(); } + + const auto& param_name = param_names_[i]; + + request.path_params.emplace( + param_name, request.path.substr(starting_pos, sep_pos - starting_pos)); + + // Mark everything up to '/' as matched + starting_pos = sep_pos + 1; + } + // Returns false if the path is longer than the pattern + return starting_pos >= request.path.length(); + } + + inline bool RegexMatcher::match(Request& request) const + { + request.path_params.clear(); + return std::regex_match(request.path, request.matches, regex_); + } + } // namespace detail + + // HTTP server implementation + inline Server::Server() : + new_task_queue( + [] { return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT); }) + { +#ifndef _WIN32 + signal(SIGPIPE, SIG_IGN); +#endif + } + + inline Server::~Server() = default; + + inline std::unique_ptr + Server::make_matcher(const std::string& pattern) + { + if (pattern.find("/:") != std::string::npos) + { + return detail::make_unique(pattern); + } + else + { + return detail::make_unique(pattern); + } + } + + inline Server& Server::Get(const std::string& pattern, Handler handler) + { + get_handlers_.emplace_back(make_matcher(pattern), std::move(handler)); + return *this; + } + + inline Server& Server::Post(const std::string& pattern, Handler handler) + { + std::cout << "post:" << pattern << std::endl; + post_handlers_.emplace_back(make_matcher(pattern), std::move(handler)); + return *this; + } + + inline Server& Server::Post(const std::string& pattern, + HandlerWithContentReader handler) + { + post_handlers_for_content_reader_.emplace_back(make_matcher(pattern), + std::move(handler)); + return *this; + } + + inline Server& Server::Put(const std::string& pattern, Handler handler) + { + put_handlers_.emplace_back(make_matcher(pattern), std::move(handler)); + return *this; + } + + inline Server& Server::Put(const std::string& pattern, + HandlerWithContentReader handler) + { + put_handlers_for_content_reader_.emplace_back(make_matcher(pattern), + std::move(handler)); + return *this; + } + + inline Server& Server::Patch(const std::string& pattern, Handler handler) + { + patch_handlers_.emplace_back(make_matcher(pattern), std::move(handler)); + return *this; + } + + inline Server& Server::Patch(const std::string& pattern, + HandlerWithContentReader handler) + { + patch_handlers_for_content_reader_.emplace_back(make_matcher(pattern), + std::move(handler)); + return *this; + } + + inline Server& Server::Delete(const std::string& pattern, Handler handler) + { + delete_handlers_.emplace_back(make_matcher(pattern), std::move(handler)); + return *this; + } + + inline Server& Server::Delete(const std::string& pattern, + HandlerWithContentReader handler) + { + delete_handlers_for_content_reader_.emplace_back(make_matcher(pattern), + std::move(handler)); + return *this; + } + + inline Server& Server::Options(const std::string& pattern, Handler handler) + { + options_handlers_.emplace_back(make_matcher(pattern), std::move(handler)); + return *this; + } + + inline bool Server::set_base_dir(const std::string& dir, + const std::string& mount_point) + { + return set_mount_point(mount_point, dir); + } + + inline bool Server::set_mount_point(const std::string& mount_point, + const std::string& dir, Headers headers) + { + detail::FileStat stat(dir); + if (stat.is_dir()) + { + std::string mnt = !mount_point.empty() ? mount_point : "/"; + if (!mnt.empty() && mnt[0] == '/') + { + base_dirs_.push_back({mnt, dir, std::move(headers)}); + return true; + } + } + return false; + } + + inline bool Server::remove_mount_point(const std::string& mount_point) + { + for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) + { + if (it->mount_point == mount_point) + { + base_dirs_.erase(it); + return true; + } + } + return false; + } + + inline Server& + Server::set_file_extension_and_mimetype_mapping(const std::string& ext, + const std::string& mime) + { + file_extension_and_mimetype_map_[ext] = mime; + return *this; + } + + inline Server& Server::set_default_file_mimetype(const std::string& mime) + { + default_file_mimetype_ = mime; + return *this; + } + + inline Server& Server::set_file_request_handler(Handler handler) + { + file_request_handler_ = std::move(handler); + return *this; + } + + inline Server& Server::set_error_handler_core(HandlerWithResponse handler, + std::true_type) + { + error_handler_ = std::move(handler); + return *this; + } + + inline Server& Server::set_error_handler_core(Handler handler, + std::false_type) + { + error_handler_ = [handler](const Request& req, Response& res) + { + handler(req, res); + return HandlerResponse::Handled; + }; + return *this; + } + + inline Server& Server::set_exception_handler(ExceptionHandler handler) + { + exception_handler_ = std::move(handler); + return *this; + } + + inline Server& Server::set_pre_routing_handler(HandlerWithResponse handler) + { + pre_routing_handler_ = std::move(handler); + return *this; + } + + inline Server& Server::set_post_routing_handler(Handler handler) + { + post_routing_handler_ = std::move(handler); + return *this; + } + + inline Server& Server::set_logger(Logger logger) + { + logger_ = std::move(logger); + return *this; + } + + inline Server& + Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) + { + expect_100_continue_handler_ = std::move(handler); + return *this; + } + + inline Server& Server::set_address_family(int family) + { + address_family_ = family; + return *this; + } + + inline Server& Server::set_tcp_nodelay(bool on) + { + tcp_nodelay_ = on; + return *this; + } + + inline Server& Server::set_ipv6_v6only(bool on) + { + ipv6_v6only_ = on; + return *this; + } + + inline Server& Server::set_socket_options(SocketOptions socket_options) + { + socket_options_ = std::move(socket_options); + return *this; + } + + inline Server& Server::set_default_headers(Headers headers) + { + default_headers_ = std::move(headers); + return *this; + } + + inline Server& Server::set_header_writer( + std::function const& writer) + { + header_writer_ = writer; + return *this; + } + + inline Server& Server::set_keep_alive_max_count(size_t count) + { + keep_alive_max_count_ = count; + return *this; + } + + inline Server& Server::set_keep_alive_timeout(time_t sec) + { + keep_alive_timeout_sec_ = sec; + return *this; + } + + inline Server& Server::set_read_timeout(time_t sec, time_t usec) + { + read_timeout_sec_ = sec; + read_timeout_usec_ = usec; + return *this; + } + + inline Server& Server::set_write_timeout(time_t sec, time_t usec) + { + write_timeout_sec_ = sec; + write_timeout_usec_ = usec; + return *this; + } + + inline Server& Server::set_idle_interval(time_t sec, time_t usec) + { + idle_interval_sec_ = sec; + idle_interval_usec_ = usec; + return *this; + } + + inline Server& Server::set_payload_max_length(size_t length) + { + payload_max_length_ = length; + return *this; + } + + inline bool Server::bind_to_port(const std::string& host, int port, + int socket_flags) + { + auto ret = bind_internal(host, port, socket_flags); + if (ret == -1) { is_decommisioned = true; } + return ret >= 0; + } + + inline int Server::bind_to_any_port(const std::string& host, int socket_flags) + { + auto ret = bind_internal(host, 0, socket_flags); + if (ret == -1) { is_decommisioned = true; } + return ret; + } + + inline bool Server::listen_after_bind() { return listen_internal(); } + + inline bool Server::listen(const std::string& host, int port, + int socket_flags) + { + bool b1 = bind_to_port(host, port, socket_flags); + if (!b1) + { + std::cout << "端口绑定失败!" << host << ":" << port << std::endl; + } + return b1 && listen_internal(); + } + + inline bool Server::is_running() const { return is_running_; } + + inline void Server::wait_until_ready() const + { + while (!is_running_ && !is_decommisioned) + { + std::this_thread::sleep_for(std::chrono::milliseconds{1}); + } + } + + inline void Server::stop() + { + if (is_running_) + { + assert(svr_sock_ != INVALID_SOCKET); + std::atomic sock(svr_sock_.exchange(INVALID_SOCKET)); + detail::shutdown_socket(sock); + detail::close_socket(sock); + } + is_decommisioned = false; + } + + inline void Server::decommission() { is_decommisioned = true; } + + inline bool Server::parse_request_line(const char* s, Request& req) const + { + auto len = strlen(s); + if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; } + len -= 2; + + { + size_t count = 0; + + detail::split(s, s + len, ' ', [&](const char* b, const char* e) + { + switch (count) + { + case 0: + req.method = std::string(b, e); + break; + case 1: + req.target = std::string(b, e); + break; + case 2: + req.version = std::string(b, e); + break; + default: + break; + } + count++; + }); + + if (count != 3) { return false; } + } + + static const std::set methods{ + "GET", "HEAD", "POST", "PUT", "DELETE", + "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"}; + + if (methods.find(req.method) == methods.end()) { return false; } + + if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") { return false; } + + { + // Skip URL fragment + for (size_t i = 0; i < req.target.size(); i++) + { + if (req.target[i] == '#') + { + req.target.erase(i); + break; + } + } + + detail::divide(req.target, '?', + [&](const char* lhs_data, std::size_t lhs_size, + const char* rhs_data, std::size_t rhs_size) + { + req.path = detail::decode_url( + std::string(lhs_data, lhs_size), false); + detail::parse_query_text(rhs_data, rhs_size, req.params); + }); + } + + return true; + } + + inline bool Server::write_response(Stream& strm, bool close_connection, + Request& req, Response& res) + { + // NOTE: `req.ranges` should be empty, otherwise it will be applied + // incorrectly to the error content. + req.ranges.clear(); + return write_response_core(strm, close_connection, req, res, false); + } + + inline bool Server::write_response_with_content(Stream& strm, + bool close_connection, + const Request& req, + Response& res) + { + return write_response_core(strm, close_connection, req, res, true); + } + + inline bool Server::write_response_core(Stream& strm, bool close_connection, + const Request& req, Response& res, + bool need_apply_ranges) + { + assert(res.status != -1); + + if (400 <= res.status && error_handler_ && + error_handler_(req, res) == HandlerResponse::Handled) + { + need_apply_ranges = true; + } + + std::string content_type; + std::string boundary; + if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); } + + // Prepare additional headers + if (close_connection || req.get_header_value("Connection") == "close") + { + res.set_header("Connection", "close"); + } + else + { + std::string s = "timeout="; + s += std::to_string(keep_alive_timeout_sec_); + s += ", max="; + s += std::to_string(keep_alive_max_count_); + res.set_header("Keep-Alive", s); + } + + if ((!res.body.empty() || res.content_length_ > 0 || res.content_provider_) && + !res.has_header("Content-Type")) + { + res.set_header("Content-Type", "text/plain"); + } + + if (res.body.empty() && !res.content_length_ && !res.content_provider_ && + !res.has_header("Content-Length")) + { + res.set_header("Content-Length", "0"); + } + + if (req.method == "HEAD" && !res.has_header("Accept-Ranges")) + { + res.set_header("Accept-Ranges", "bytes"); + } + + if (post_routing_handler_) { post_routing_handler_(req, res); } + + // Response line and headers + { + detail::BufferStream bstrm; + if (!detail::write_response_line(bstrm, res.status)) { return false; } + if (!header_writer_(bstrm, res.headers)) { return false; } + + // Flush buffer + auto& data = bstrm.get_buffer(); + detail::write_data(strm, data.data(), data.size()); + } + + // Body + auto ret = true; + if (req.method != "HEAD") + { + if (!res.body.empty()) + { + if (!detail::write_data(strm, res.body.data(), res.body.size())) + { + ret = false; + } + } + else if (res.content_provider_) + { + if (write_content_with_provider(strm, req, res, boundary, content_type)) + { + res.content_provider_success_ = true; + } + else + { + ret = false; + } + } + } + + // Log + if (logger_) { logger_(req, res); } + + return ret; + } + + inline bool + Server::write_content_with_provider(Stream& strm, const Request& req, + Response& res, const std::string& boundary, + const std::string& content_type) + { + auto is_shutting_down = [this]() + { + return this->svr_sock_ == INVALID_SOCKET; + }; + + if (res.content_length_ > 0) + { + if (req.ranges.empty()) + { + return detail::write_content(strm, res.content_provider_, 0, + res.content_length_, is_shutting_down); + } + else if (req.ranges.size() == 1) + { + auto offset_and_length = detail::get_range_offset_and_length( + req.ranges[0], res.content_length_); + + return detail::write_content(strm, res.content_provider_, + offset_and_length.first, + offset_and_length.second, is_shutting_down); + } + else + { + return detail::write_multipart_ranges_data( + strm, req, res, boundary, content_type, res.content_length_, + is_shutting_down); + } + } + else + { + if (res.is_chunked_content_provider_) + { + auto type = detail::encoding_type(req, res); + + std::unique_ptr compressor; + if (type == detail::EncodingType::Gzip) + { +#ifdef CPPHTTPLIB_ZLIB_SUPPORT + compressor = detail::make_unique(); +#endif + } + else if (type == detail::EncodingType::Brotli) + { +#ifdef CPPHTTPLIB_BROTLI_SUPPORT + compressor = detail::make_unique(); +#endif + } + else + { + compressor = detail::make_unique(); + } + assert(compressor != nullptr); + + return detail::write_content_chunked(strm, res.content_provider_, + is_shutting_down, *compressor); + } + else + { + return detail::write_content_without_length(strm, res.content_provider_, + is_shutting_down); + } + } + } + + inline bool Server::read_content(Stream& strm, Request& req, Response& res) + { + MultipartFormDataMap::iterator cur; + auto file_count = 0; + if (read_content_core( + strm, req, res, + // Regular + [&](const char* buf, size_t n) + { + if (req.body.size() + n > req.body.max_size()) { return false; } + req.body.append(buf, n); + return true; + }, + // Multipart + [&](const MultipartFormData& file) + { + if (file_count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) + { + return false; + } + cur = req.files.emplace(file.name, file); + return true; + }, + [&](const char* buf, size_t n) + { + auto& content = cur->second.content; + if (content.size() + n > content.max_size()) { return false; } + content.append(buf, n); + return true; + })) + { + const auto& content_type = req.get_header_value("Content-Type"); + if (!content_type.find("application/x-www-form-urlencoded")) + { + if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) + { + res.status = StatusCode::PayloadTooLarge_413; // NOTE: should be 414? + return false; + } + detail::parse_query_text(req.body, req.params); + } + return true; + } + return false; + } + + inline bool Server::read_content_with_content_receiver( + Stream& strm, Request& req, Response& res, ContentReceiver receiver, + MultipartContentHeader multipart_header, + ContentReceiver multipart_receiver) + { + return read_content_core(strm, req, res, std::move(receiver), + std::move(multipart_header), + std::move(multipart_receiver)); + } + + inline bool + Server::read_content_core(Stream& strm, Request& req, Response& res, + ContentReceiver receiver, + MultipartContentHeader multipart_header, + ContentReceiver multipart_receiver) const + { + detail::MultipartFormDataParser multipart_form_data_parser; + ContentReceiverWithProgress out; + + if (req.is_multipart_form_data()) + { + const auto& content_type = req.get_header_value("Content-Type"); + std::string boundary; + if (!detail::parse_multipart_boundary(content_type, boundary)) + { + res.status = StatusCode::BadRequest_400; + return false; + } + + multipart_form_data_parser.set_boundary(std::move(boundary)); + out = [&](const char* buf, size_t n, uint64_t /*off*/, uint64_t /*len*/) + { + /* For debug + size_t pos = 0; + while (pos < n) { + auto read_size = (std::min)(1, n - pos); + auto ret = multipart_form_data_parser.parse( + buf + pos, read_size, multipart_receiver, multipart_header); + if (!ret) { return false; } + pos += read_size; + } + return true; + */ + return multipart_form_data_parser.parse(buf, n, multipart_receiver, + multipart_header); + }; + } + else + { + out = [receiver](const char* buf, size_t n, uint64_t /*off*/, + uint64_t /*len*/) + { + return receiver(buf, n); + }; + } + + if (req.method == "DELETE" && !req.has_header("Content-Length")) + { + return true; + } + + if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr, + out, true)) + { + return false; + } + + if (req.is_multipart_form_data()) + { + if (!multipart_form_data_parser.is_valid()) + { + res.status = StatusCode::BadRequest_400; + return false; + } + } + + return true; + } + + inline bool Server::handle_file_request(const Request& req, Response& res, + bool head) + { + for (const auto& entry : base_dirs_) + { + // Prefix match + if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) + { + std::string sub_path = "/" + req.path.substr(entry.mount_point.size()); + if (detail::is_valid_path(sub_path)) + { + auto path = entry.base_dir + sub_path; + if (path.back() == '/') { path += "index.html"; } + + detail::FileStat stat(path); + + if (stat.is_dir()) + { + res.set_redirect(sub_path + "/", StatusCode::MovedPermanently_301); + return true; + } + + if (stat.is_file()) + { + for (const auto& kv : entry.headers) + { + res.set_header(kv.first, kv.second); + } + + auto mm = std::make_shared(path.c_str()); + if (!mm->is_open()) { return false; } + + res.set_content_provider( + mm->size(), + detail::find_content_type(path, file_extension_and_mimetype_map_, + default_file_mimetype_), + [mm](size_t offset, size_t length, DataSink& sink) -> bool + { + sink.write(mm->data() + offset, length); + return true; + }); + + if (!head && file_request_handler_) + { + file_request_handler_(req, res); + } + + return true; + } + } + } + } + return false; + } + + inline socket_t + Server::create_server_socket(const std::string& host, int port, + int socket_flags, + SocketOptions socket_options) const + { + return detail::create_socket( + host, std::string(), port, address_family_, socket_flags, tcp_nodelay_, + ipv6_v6only_, std::move(socket_options), + [](socket_t sock, struct addrinfo& ai, bool& /*quit*/) -> bool + { + if (::bind(sock, ai.ai_addr, static_cast(ai.ai_addrlen))) + { + return false; + } + if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) { return false; } + return true; + }); + } + + inline int Server::bind_internal(const std::string& host, int port, + int socket_flags) + { + if (is_decommisioned) { return -1; } + + if (!is_valid()) { return -1; } + + svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_); + if (svr_sock_ == INVALID_SOCKET) { return -1; } + + if (port == 0) + { + struct sockaddr_storage addr; + socklen_t addr_len = sizeof(addr); + if (getsockname(svr_sock_, reinterpret_cast(&addr), + &addr_len) == -1) + { + return -1; + } + if (addr.ss_family == AF_INET) + { + return ntohs(reinterpret_cast(&addr)->sin_port); + } + else if (addr.ss_family == AF_INET6) + { + return ntohs(reinterpret_cast(&addr)->sin6_port); + } + else + { + return -1; + } + } + else + { + return port; + } + } + + inline bool Server::listen_internal() + { + if (is_decommisioned) { return false; } + + auto ret = true; + is_running_ = true; + auto se = detail::scope_exit([&]() { is_running_ = false; }); + + { + std::unique_ptr task_queue(new_task_queue()); + + while (svr_sock_ != INVALID_SOCKET) + { +#ifndef _WIN32 + if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) { +#endif + auto val = detail::select_read(svr_sock_, idle_interval_sec_, + idle_interval_usec_); + if (val == 0) + { + // Timeout + task_queue->on_idle(); + continue; + } +#ifndef _WIN32 + } +#endif + +#if defined _WIN32 + // sockets conneced via WASAccept inherit flags NO_HANDLE_INHERIT, + // OVERLAPPED + socket_t sock = WSAAccept(svr_sock_, nullptr, nullptr, nullptr, 0); +#elif defined SOCK_CLOEXEC + socket_t sock = accept4(svr_sock_, nullptr, nullptr, SOCK_CLOEXEC); +#else + socket_t sock = accept(svr_sock_, nullptr, nullptr); +#endif + + if (sock == INVALID_SOCKET) + { + if (errno == EMFILE) + { + // The per-process limit of open file descriptors has been reached. + // Try to accept new connections after a short sleep. + std::this_thread::sleep_for(std::chrono::microseconds{1}); + continue; + } + else if (errno == EINTR || errno == EAGAIN) + { + continue; + } + if (svr_sock_ != INVALID_SOCKET) + { + detail::close_socket(svr_sock_); + ret = false; + } + else + { + ; // The server socket was closed by user. + } + break; + } + + { +#ifdef _WIN32 + auto timeout = static_cast(read_timeout_sec_ * 1000 + + read_timeout_usec_ / 1000); + setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, + reinterpret_cast(&timeout), sizeof(timeout)); +#else + timeval tv; + tv.tv_sec = static_cast(read_timeout_sec_); + tv.tv_usec = static_cast(read_timeout_usec_); + setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, + reinterpret_cast(&tv), sizeof(tv)); +#endif + } + { +#ifdef _WIN32 + auto timeout = static_cast(write_timeout_sec_ * 1000 + + write_timeout_usec_ / 1000); + setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, + reinterpret_cast(&timeout), sizeof(timeout)); +#else + timeval tv; + tv.tv_sec = static_cast(write_timeout_sec_); + tv.tv_usec = static_cast(write_timeout_usec_); + setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, + reinterpret_cast(&tv), sizeof(tv)); +#endif + } + + if (!task_queue->enqueue( + [this, sock]() { process_and_close_socket(sock); })) + { + detail::shutdown_socket(sock); + detail::close_socket(sock); + } + } + + task_queue->shutdown(); + } + + is_decommisioned = !ret; + return ret; + } + + inline bool Server::routing(Request& req, Response& res, Stream& strm) + { + if (pre_routing_handler_ && + pre_routing_handler_(req, res) == HandlerResponse::Handled) + { + return true; + } + + // File handler + auto is_head_request = req.method == "HEAD"; + if ((req.method == "GET" || is_head_request) && + handle_file_request(req, res, is_head_request)) + { + return true; + } + + if (detail::expect_content(req)) + { + // Content reader handler + { + ContentReader reader( + [&](ContentReceiver receiver) + { + return read_content_with_content_receiver( + strm, req, res, std::move(receiver), nullptr, nullptr); + }, + [&](MultipartContentHeader header, ContentReceiver receiver) + { + return read_content_with_content_receiver(strm, req, res, nullptr, + std::move(header), + std::move(receiver)); + }); + + if (req.method == "POST") + { + if (dispatch_request_for_content_reader( + req, res, std::move(reader), + post_handlers_for_content_reader_)) + { + return true; + } + } + else if (req.method == "PUT") + { + if (dispatch_request_for_content_reader( + req, res, std::move(reader), + put_handlers_for_content_reader_)) + { + return true; + } + } + else if (req.method == "PATCH") + { + if (dispatch_request_for_content_reader( + req, res, std::move(reader), + patch_handlers_for_content_reader_)) + { + return true; + } + } + else if (req.method == "DELETE") + { + if (dispatch_request_for_content_reader( + req, res, std::move(reader), + delete_handlers_for_content_reader_)) + { + return true; + } + } + } + + // Read content into `req.body` + if (!read_content(strm, req, res)) { return false; } + } + + // Regular handler + if (req.method == "GET" || req.method == "HEAD") + { + return dispatch_request(req, res, get_handlers_); + } + else if (req.method == "POST") + { + return dispatch_request(req, res, post_handlers_); + } + else if (req.method == "PUT") + { + return dispatch_request(req, res, put_handlers_); + } + else if (req.method == "DELETE") + { + return dispatch_request(req, res, delete_handlers_); + } + else if (req.method == "OPTIONS") + { + return dispatch_request(req, res, options_handlers_); + } + else if (req.method == "PATCH") + { + return dispatch_request(req, res, patch_handlers_); + } + + res.status = StatusCode::BadRequest_400; + return false; + } + + inline bool Server::dispatch_request(Request& req, Response& res, + const Handlers& handlers) const + { + for (const auto& x : handlers) + { + const auto& matcher = x.first; + const auto& handler = x.second; + + if (matcher->match(req)) + { + handler(req, res); + return true; + } + } + return false; + } + + inline void Server::apply_ranges(const Request& req, Response& res, + std::string& content_type, + std::string& boundary) const + { + if (req.ranges.size() > 1 && res.status == StatusCode::PartialContent_206) + { + auto it = res.headers.find("Content-Type"); + if (it != res.headers.end()) + { + content_type = it->second; + res.headers.erase(it); + } + + boundary = detail::make_multipart_data_boundary(); + + res.set_header("Content-Type", + "multipart/byteranges; boundary=" + boundary); + } + + auto type = detail::encoding_type(req, res); + + if (res.body.empty()) + { + if (res.content_length_ > 0) + { + size_t length = 0; + if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) + { + length = res.content_length_; + } + else if (req.ranges.size() == 1) + { + auto offset_and_length = detail::get_range_offset_and_length( + req.ranges[0], res.content_length_); + + length = offset_and_length.second; + + auto content_range = detail::make_content_range_header_field( + offset_and_length, res.content_length_); + res.set_header("Content-Range", content_range); + } + else + { + length = detail::get_multipart_ranges_data_length( + req, boundary, content_type, res.content_length_); + } + res.set_header("Content-Length", std::to_string(length)); + } + else + { + if (res.content_provider_) + { + if (res.is_chunked_content_provider_) + { + res.set_header("Transfer-Encoding", "chunked"); + if (type == detail::EncodingType::Gzip) + { + res.set_header("Content-Encoding", "gzip"); + } + else if (type == detail::EncodingType::Brotli) + { + res.set_header("Content-Encoding", "br"); + } + } + } + } + } + else + { + if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) + { + ; + } + else if (req.ranges.size() == 1) + { + auto offset_and_length = + detail::get_range_offset_and_length(req.ranges[0], res.body.size()); + auto offset = offset_and_length.first; + auto length = offset_and_length.second; + + auto content_range = detail::make_content_range_header_field( + offset_and_length, res.body.size()); + res.set_header("Content-Range", content_range); + + assert(offset + length <= res.body.size()); + res.body = res.body.substr(offset, length); + } + else + { + std::string data; + detail::make_multipart_ranges_data(req, res, boundary, content_type, + res.body.size(), data); + res.body.swap(data); + } + + if (type != detail::EncodingType::None) + { + std::unique_ptr compressor; + std::string content_encoding; + + if (type == detail::EncodingType::Gzip) + { +#ifdef CPPHTTPLIB_ZLIB_SUPPORT + compressor = detail::make_unique(); + content_encoding = "gzip"; +#endif + } + else if (type == detail::EncodingType::Brotli) + { +#ifdef CPPHTTPLIB_BROTLI_SUPPORT + compressor = detail::make_unique(); + content_encoding = "br"; +#endif + } + + if (compressor) + { + std::string compressed; + if (compressor->compress(res.body.data(), res.body.size(), true, + [&](const char* data, size_t data_len) + { + compressed.append(data, data_len); + return true; + })) + { + res.body.swap(compressed); + res.set_header("Content-Encoding", content_encoding); + } + } + } + + auto length = std::to_string(res.body.size()); + res.set_header("Content-Length", length); + } + } + + inline bool Server::dispatch_request_for_content_reader( + Request& req, Response& res, ContentReader content_reader, + const HandlersForContentReader& handlers) const + { + for (const auto& x : handlers) + { + const auto& matcher = x.first; + const auto& handler = x.second; + + if (matcher->match(req)) + { + handler(req, res, content_reader); + return true; + } + } + return false; + } + + inline bool + Server::process_request(Stream& strm, const std::string& remote_addr, + int remote_port, const std::string& local_addr, + int local_port, bool close_connection, + bool& connection_closed, + const std::function& setup_request) + { + std::array buf{}; + + detail::stream_line_reader line_reader(strm, buf.data(), buf.size()); + + // Connection has been closed on client + if (!line_reader.getline()) { return false; } + + Request req; + + Response res; + res.version = "HTTP/1.1"; + res.headers = default_headers_; + +#ifdef _WIN32 + // TODO: Increase FD_SETSIZE statically (libzmq), dynamically (MySQL). +#else +#ifndef CPPHTTPLIB_USE_POLL + // Socket file descriptor exceeded FD_SETSIZE... + if (strm.socket() >= FD_SETSIZE) { + Headers dummy; + detail::read_headers(strm, dummy); + res.status = StatusCode::InternalServerError_500; + return write_response(strm, close_connection, req, res); + } +#endif +#endif + + // Check if the request URI doesn't exceed the limit + if (line_reader.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) + { + Headers dummy; + detail::read_headers(strm, dummy); + res.status = StatusCode::UriTooLong_414; + return write_response(strm, close_connection, req, res); + } + + // Request line and headers + if (!parse_request_line(line_reader.ptr(), req) || + !detail::read_headers(strm, req.headers)) + { + res.status = StatusCode::BadRequest_400; + return write_response(strm, close_connection, req, res); + } + + if (req.get_header_value("Connection") == "close") + { + connection_closed = true; + } + + if (req.version == "HTTP/1.0" && + req.get_header_value("Connection") != "Keep-Alive") + { + connection_closed = true; + } + + req.remote_addr = remote_addr; + req.remote_port = remote_port; + req.set_header("REMOTE_ADDR", req.remote_addr); + req.set_header("REMOTE_PORT", std::to_string(req.remote_port)); + + req.local_addr = local_addr; + req.local_port = local_port; + req.set_header("LOCAL_ADDR", req.local_addr); + req.set_header("LOCAL_PORT", std::to_string(req.local_port)); + + if (req.has_header("Range")) + { + const auto& range_header_value = req.get_header_value("Range"); + if (!detail::parse_range_header(range_header_value, req.ranges)) + { + res.status = StatusCode::RangeNotSatisfiable_416; + return write_response(strm, close_connection, req, res); + } + } + + if (setup_request) { setup_request(req); } + + if (req.get_header_value("Expect") == "100-continue") + { + int status = StatusCode::Continue_100; + if (expect_100_continue_handler_) + { + status = expect_100_continue_handler_(req, res); + } + switch (status) + { + case StatusCode::Continue_100: + case StatusCode::ExpectationFailed_417: + detail::write_response_line(strm, status); + strm.write("\r\n"); + break; + default: + connection_closed = true; + return write_response(strm, true, req, res); + } + } + + // Routing + auto routed = false; +#ifdef CPPHTTPLIB_NO_EXCEPTIONS + routed = routing(req, res, strm); +#else + try + { + routed = routing(req, res, strm); + } + catch (std::exception& e) + { + if (exception_handler_) + { + auto ep = std::current_exception(); + exception_handler_(req, res, ep); + routed = true; + } + else + { + res.status = StatusCode::InternalServerError_500; + std::string val; + auto s = e.what(); + for (size_t i = 0; s[i]; i++) + { + switch (s[i]) + { + case '\r': + val += "\\r"; + break; + case '\n': + val += "\\n"; + break; + default: + val += s[i]; + break; + } + } + res.set_header("EXCEPTION_WHAT", val); + } + } catch (...) + { + if (exception_handler_) + { + auto ep = std::current_exception(); + exception_handler_(req, res, ep); + routed = true; + } + else + { + res.status = StatusCode::InternalServerError_500; + res.set_header("EXCEPTION_WHAT", "UNKNOWN"); + } + } +#endif + if (routed) + { + if (res.status == -1) + { + res.status = req.ranges.empty() + ? StatusCode::OK_200 + : StatusCode::PartialContent_206; + } + + if (detail::range_error(req, res)) + { + res.body.clear(); + res.content_length_ = 0; + res.content_provider_ = nullptr; + res.status = StatusCode::RangeNotSatisfiable_416; + return write_response(strm, close_connection, req, res); + } + + // Serve file content by using a content provider + if (!res.file_content_path_.empty()) + { + const auto& path = res.file_content_path_; + auto mm = std::make_shared(path.c_str()); + if (!mm->is_open()) + { + res.body.clear(); + res.content_length_ = 0; + res.content_provider_ = nullptr; + res.status = StatusCode::NotFound_404; + return write_response(strm, close_connection, req, res); + } + + auto content_type = res.file_content_content_type_; + if (content_type.empty()) + { + content_type = detail::find_content_type( + path, file_extension_and_mimetype_map_, default_file_mimetype_); + } + + res.set_content_provider( + mm->size(), content_type, + [mm](size_t offset, size_t length, DataSink& sink) -> bool + { + sink.write(mm->data() + offset, length); + return true; + }); + } + + return write_response_with_content(strm, close_connection, req, res); + } + else + { + if (res.status == -1) { res.status = StatusCode::NotFound_404; } + + return write_response(strm, close_connection, req, res); + } + } + + inline bool Server::is_valid() const { return true; } + + inline bool Server::process_and_close_socket(socket_t sock) + { + std::string remote_addr; + int remote_port = 0; + detail::get_remote_ip_and_port(sock, remote_addr, remote_port); + + std::string local_addr; + int local_port = 0; + detail::get_local_ip_and_port(sock, local_addr, local_port); + + auto ret = detail::process_server_socket( + svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_, + read_timeout_sec_, read_timeout_usec_, write_timeout_sec_, + write_timeout_usec_, + [&](Stream& strm, bool close_connection, bool& connection_closed) + { + return process_request(strm, remote_addr, remote_port, local_addr, + local_port, close_connection, connection_closed, + nullptr); + }); + + detail::shutdown_socket(sock); + detail::close_socket(sock); + return ret; + } + + // HTTP client implementation + inline ClientImpl::ClientImpl(const std::string& host) : + ClientImpl(host, 80, std::string(), std::string()) + { + } + + inline ClientImpl::ClientImpl(const std::string& host, int port) : + ClientImpl(host, port, std::string(), std::string()) + { + } + + inline ClientImpl::ClientImpl(const std::string& host, int port, + const std::string& client_cert_path, + const std::string& client_key_path) : + host_(detail::escape_abstract_namespace_unix_domain(host)), port_(port), + host_and_port_(adjust_host_string(host_) + ":" + std::to_string(port)), + client_cert_path_(client_cert_path), client_key_path_(client_key_path) + { + } + + inline ClientImpl::~ClientImpl() + { + std::lock_guard guard(socket_mutex_); + shutdown_socket(socket_); + close_socket(socket_); + } + + inline bool ClientImpl::is_valid() const { return true; } + + inline void ClientImpl::copy_settings(const ClientImpl& rhs) + { + client_cert_path_ = rhs.client_cert_path_; + client_key_path_ = rhs.client_key_path_; + connection_timeout_sec_ = rhs.connection_timeout_sec_; + read_timeout_sec_ = rhs.read_timeout_sec_; + read_timeout_usec_ = rhs.read_timeout_usec_; + write_timeout_sec_ = rhs.write_timeout_sec_; + write_timeout_usec_ = rhs.write_timeout_usec_; + basic_auth_username_ = rhs.basic_auth_username_; + basic_auth_password_ = rhs.basic_auth_password_; + bearer_token_auth_token_ = rhs.bearer_token_auth_token_; +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + digest_auth_username_ = rhs.digest_auth_username_; + digest_auth_password_ = rhs.digest_auth_password_; +#endif + keep_alive_ = rhs.keep_alive_; + follow_location_ = rhs.follow_location_; + url_encode_ = rhs.url_encode_; + address_family_ = rhs.address_family_; + tcp_nodelay_ = rhs.tcp_nodelay_; + ipv6_v6only_ = rhs.ipv6_v6only_; + socket_options_ = rhs.socket_options_; + compress_ = rhs.compress_; + decompress_ = rhs.decompress_; + interface_ = rhs.interface_; + proxy_host_ = rhs.proxy_host_; + proxy_port_ = rhs.proxy_port_; + proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_; + proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_; + proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_; +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_; + proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_; +#endif +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + ca_cert_file_path_ = rhs.ca_cert_file_path_; + ca_cert_dir_path_ = rhs.ca_cert_dir_path_; + ca_cert_store_ = rhs.ca_cert_store_; +#endif +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + server_certificate_verification_ = rhs.server_certificate_verification_; + server_hostname_verification_ = rhs.server_hostname_verification_; + server_certificate_verifier_ = rhs.server_certificate_verifier_; +#endif + logger_ = rhs.logger_; + } + + inline socket_t ClientImpl::create_client_socket(Error& error) const + { + if (!proxy_host_.empty() && proxy_port_ != -1) + { + return detail::create_client_socket( + proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_, + ipv6_v6only_, socket_options_, connection_timeout_sec_, + connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_, + write_timeout_sec_, write_timeout_usec_, interface_, error); + } + + // Check is custom IP specified for host_ + std::string ip; + auto it = addr_map_.find(host_); + if (it != addr_map_.end()) { ip = it->second; } + + return detail::create_client_socket( + host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_, + socket_options_, connection_timeout_sec_, connection_timeout_usec_, + read_timeout_sec_, read_timeout_usec_, write_timeout_sec_, + write_timeout_usec_, interface_, error); + } + + inline bool ClientImpl::create_and_connect_socket(Socket& socket, + Error& error) + { + auto sock = create_client_socket(error); + if (sock == INVALID_SOCKET) { return false; } + socket.sock = sock; + return true; + } + + inline void ClientImpl::shutdown_ssl(Socket& /*socket*/, + bool /*shutdown_gracefully*/) + { + // If there are any requests in flight from threads other than us, then it's + // a thread-unsafe race because individual ssl* objects are not thread-safe. + assert(socket_requests_in_flight_ == 0 || + socket_requests_are_from_thread_ == std::this_thread::get_id()); + } + + inline void ClientImpl::shutdown_socket(Socket& socket) const + { + if (socket.sock == INVALID_SOCKET) { return; } + detail::shutdown_socket(socket.sock); + } + + inline void ClientImpl::close_socket(Socket& socket) + { + // If there are requests in flight in another thread, usually closing + // the socket will be fine and they will simply receive an error when + // using the closed socket, but it is still a bug since rarely the OS + // may reassign the socket id to be used for a new socket, and then + // suddenly they will be operating on a live socket that is different + // than the one they intended! + assert(socket_requests_in_flight_ == 0 || + socket_requests_are_from_thread_ == std::this_thread::get_id()); + + // It is also a bug if this happens while SSL is still active +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + assert(socket.ssl == nullptr); +#endif + if (socket.sock == INVALID_SOCKET) { return; } + detail::close_socket(socket.sock); + socket.sock = INVALID_SOCKET; + } + + inline bool ClientImpl::read_response_line(Stream& strm, const Request& req, + Response& res) const + { + std::array buf{}; + + detail::stream_line_reader line_reader(strm, buf.data(), buf.size()); + + if (!line_reader.getline()) { return false; } + +#ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR + const static std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n"); +#else + const static std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n"); +#endif + + std::cmatch m; + if (!std::regex_match(line_reader.ptr(), m, re)) + { + return req.method == "CONNECT"; + } + res.version = std::string(m[1]); + res.status = std::stoi(std::string(m[2])); + res.reason = std::string(m[3]); + + // Ignore '100 Continue' + while (res.status == StatusCode::Continue_100) + { + if (!line_reader.getline()) { return false; } // CRLF + if (!line_reader.getline()) { return false; } // next response line + + if (!std::regex_match(line_reader.ptr(), m, re)) { return false; } + res.version = std::string(m[1]); + res.status = std::stoi(std::string(m[2])); + res.reason = std::string(m[3]); + } + + return true; + } + + inline bool ClientImpl::send(Request& req, Response& res, Error& error) + { + std::lock_guard request_mutex_guard(request_mutex_); + auto ret = send_(req, res, error); + if (error == Error::SSLPeerCouldBeClosed_) + { + assert(!ret); + ret = send_(req, res, error); + } + return ret; + } + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT +inline bool ClientImpl::is_ssl_peer_could_be_closed(SSL *ssl) const { + char buf[1]; + return !SSL_peek(ssl, buf, 1) && + SSL_get_error(ssl, 0) == SSL_ERROR_ZERO_RETURN; +} +#endif + + inline bool ClientImpl::send_(Request& req, Response& res, Error& error) + { + { + std::lock_guard guard(socket_mutex_); + + // Set this to false immediately - if it ever gets set to true by the end of + // the request, we know another thread instructed us to close the socket. + socket_should_be_closed_when_request_is_done_ = false; + + auto is_alive = false; + if (socket_.is_open()) + { + is_alive = detail::is_socket_alive(socket_.sock); + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + if (is_alive && is_ssl()) { + if (is_ssl_peer_could_be_closed(socket_.ssl)) { is_alive = false; } + } +#endif + + if (!is_alive) + { + // Attempt to avoid sigpipe by shutting down nongracefully if it seems + // like the other side has already closed the connection Also, there + // cannot be any requests in flight from other threads since we locked + // request_mutex_, so safe to close everything immediately + const bool shutdown_gracefully = false; + shutdown_ssl(socket_, shutdown_gracefully); + shutdown_socket(socket_); + close_socket(socket_); + } + } + + if (!is_alive) + { + if (!create_and_connect_socket(socket_, error)) { return false; } + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + // TODO: refactoring + if (is_ssl()) { + auto &scli = static_cast(*this); + if (!proxy_host_.empty() && proxy_port_ != -1) { + auto success = false; + if (!scli.connect_with_proxy(socket_, res, success, error)) { + return success; + } + } + + if (!scli.initialize_ssl(socket_, error)) { return false; } + } +#endif + } + + // Mark the current socket as being in use so that it cannot be closed by + // anyone else while this request is ongoing, even though we will be + // releasing the mutex. + if (socket_requests_in_flight_ > 1) + { + assert(socket_requests_are_from_thread_ == std::this_thread::get_id()); + } + socket_requests_in_flight_ += 1; + socket_requests_are_from_thread_ = std::this_thread::get_id(); + } + + for (const auto& header : default_headers_) + { + if (req.headers.find(header.first) == req.headers.end()) + { + req.headers.insert(header); + } + } + + auto ret = false; + auto close_connection = !keep_alive_; + + auto se = detail::scope_exit([&]() + { + // Briefly lock mutex in order to mark that a request is no longer ongoing + std::lock_guard guard(socket_mutex_); + socket_requests_in_flight_ -= 1; + if (socket_requests_in_flight_ <= 0) + { + assert(socket_requests_in_flight_ == 0); + socket_requests_are_from_thread_ = std::thread::id(); + } + + if (socket_should_be_closed_when_request_is_done_ || close_connection || + !ret) + { + shutdown_ssl(socket_, true); + shutdown_socket(socket_); + close_socket(socket_); + } + }); + + ret = process_socket(socket_, [&](Stream& strm) + { + return handle_request(strm, req, res, close_connection, error); + }); + + if (!ret) + { + if (error == Error::Success) { error = Error::Unknown; } + } + + return ret; + } + + inline Result ClientImpl::send(const Request& req) + { + auto req2 = req; + return send_(std::move(req2)); + } + + inline Result ClientImpl::send_(Request&& req) + { + auto res = detail::make_unique(); + auto error = Error::Success; + auto ret = send(req, *res, error); + return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)}; + } + + inline bool ClientImpl::handle_request(Stream& strm, Request& req, + Response& res, bool close_connection, + Error& error) + { + if (req.path.empty()) + { + error = Error::Connection; + return false; + } + + auto req_save = req; + + bool ret; + + if (!is_ssl() && !proxy_host_.empty() && proxy_port_ != -1) + { + auto req2 = req; + req2.path = "http://" + host_and_port_ + req.path; + ret = process_request(strm, req2, res, close_connection, error); + req = req2; + req.path = req_save.path; + } + else + { + ret = process_request(strm, req, res, close_connection, error); + } + + if (!ret) { return false; } + + if (res.get_header_value("Connection") == "close" || + (res.version == "HTTP/1.0" && res.reason != "Connection established")) + { + // TODO this requires a not-entirely-obvious chain of calls to be correct + // for this to be safe. + + // This is safe to call because handle_request is only called by send_ + // which locks the request mutex during the process. It would be a bug + // to call it from a different thread since it's a thread-safety issue + // to do these things to the socket if another thread is using the socket. + std::lock_guard guard(socket_mutex_); + shutdown_ssl(socket_, true); + shutdown_socket(socket_); + close_socket(socket_); + } + + if (300 < res.status && res.status < 400 && follow_location_) + { + req = req_save; + ret = redirect(req, res, error); + } + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + if ((res.status == StatusCode::Unauthorized_401 || + res.status == StatusCode::ProxyAuthenticationRequired_407) && + req.authorization_count_ < 5) { + auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407; + const auto &username = + is_proxy ? proxy_digest_auth_username_ : digest_auth_username_; + const auto &password = + is_proxy ? proxy_digest_auth_password_ : digest_auth_password_; + + if (!username.empty() && !password.empty()) { + std::map auth; + if (detail::parse_www_authenticate(res, auth, is_proxy)) { + Request new_req = req; + new_req.authorization_count_ += 1; + new_req.headers.erase(is_proxy ? "Proxy-Authorization" + : "Authorization"); + new_req.headers.insert(detail::make_digest_authentication_header( + req, auth, new_req.authorization_count_, detail::random_string(10), + username, password, is_proxy)); + + Response new_res; + + ret = send(new_req, new_res, error); + if (ret) { res = new_res; } + } + } + } +#endif + + return ret; + } + + inline bool ClientImpl::redirect(Request& req, Response& res, Error& error) + { + if (req.redirect_count_ == 0) + { + error = Error::ExceedRedirectCount; + return false; + } + + auto location = res.get_header_value("location"); + if (location.empty()) { return false; } + + const static std::regex re( + R"((?:(https?):)?(?://(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)?([^?#]*)(\?[^#]*)?(?:#.*)?)"); + + std::smatch m; + if (!std::regex_match(location, m, re)) { return false; } + + auto scheme = is_ssl() ? "https" : "http"; + + auto next_scheme = m[1].str(); + auto next_host = m[2].str(); + if (next_host.empty()) { next_host = m[3].str(); } + auto port_str = m[4].str(); + auto next_path = m[5].str(); + auto next_query = m[6].str(); + + auto next_port = port_; + if (!port_str.empty()) + { + next_port = std::stoi(port_str); + } + else if (!next_scheme.empty()) + { + next_port = next_scheme == "https" ? 443 : 80; + } + + if (next_scheme.empty()) { next_scheme = scheme; } + if (next_host.empty()) { next_host = host_; } + if (next_path.empty()) { next_path = "/"; } + + auto path = detail::decode_url(next_path, true) + next_query; + + if (next_scheme == scheme && next_host == host_ && next_port == port_) + { + return detail::redirect(*this, req, res, path, location, error); + } + else + { + if (next_scheme == "https") + { +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + SSLClient cli(next_host, next_port); + cli.copy_settings(*this); + if (ca_cert_store_) { cli.set_ca_cert_store(ca_cert_store_); } + return detail::redirect(cli, req, res, path, location, error); +#else + return false; +#endif + } + else + { + ClientImpl cli(next_host, next_port); + cli.copy_settings(*this); + return detail::redirect(cli, req, res, path, location, error); + } + } + } + + inline bool ClientImpl::write_content_with_provider(Stream& strm, + const Request& req, + Error& error) const + { + auto is_shutting_down = []() { return false; }; + + if (req.is_chunked_content_provider_) + { + // TODO: Brotli support + std::unique_ptr compressor; +#ifdef CPPHTTPLIB_ZLIB_SUPPORT + if (compress_) { + compressor = detail::make_unique(); + } else +#endif + { + compressor = detail::make_unique(); + } + + return detail::write_content_chunked(strm, req.content_provider_, + is_shutting_down, *compressor, error); + } + else + { + return detail::write_content(strm, req.content_provider_, 0, + req.content_length_, is_shutting_down, error); + } + } + + inline bool ClientImpl::write_request(Stream& strm, Request& req, + bool close_connection, Error& error) + { + // Prepare additional headers + if (close_connection) + { + if (!req.has_header("Connection")) + { + req.set_header("Connection", "close"); + } + } + + if (!req.has_header("Host")) + { + if (is_ssl()) + { + if (port_ == 443) + { + req.set_header("Host", host_); + } + else + { + req.set_header("Host", host_and_port_); + } + } + else + { + if (port_ == 80) + { + req.set_header("Host", host_); + } + else + { + req.set_header("Host", host_and_port_); + } + } + } + + if (!req.has_header("Accept")) { req.set_header("Accept", "*/*"); } + + if (!req.content_receiver) + { + if (!req.has_header("Accept-Encoding")) + { + std::string accept_encoding; +#ifdef CPPHTTPLIB_BROTLI_SUPPORT + accept_encoding = "br"; +#endif +#ifdef CPPHTTPLIB_ZLIB_SUPPORT + if (!accept_encoding.empty()) { accept_encoding += ", "; } + accept_encoding += "gzip, deflate"; +#endif + req.set_header("Accept-Encoding", accept_encoding); + } + +#ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT + if (!req.has_header("User-Agent")) + { + auto agent = std::string("cpp-httplib/") + CPPHTTPLIB_VERSION; + req.set_header("User-Agent", agent); + } +#endif + }; + + if (req.body.empty()) + { + if (req.content_provider_) + { + if (!req.is_chunked_content_provider_) + { + if (!req.has_header("Content-Length")) + { + auto length = std::to_string(req.content_length_); + req.set_header("Content-Length", length); + } + } + } + else + { + if (req.method == "POST" || req.method == "PUT" || + req.method == "PATCH") + { + req.set_header("Content-Length", "0"); + } + } + } + else + { + if (!req.has_header("Content-Type")) + { + req.set_header("Content-Type", "text/plain"); + } + + if (!req.has_header("Content-Length")) + { + auto length = std::to_string(req.body.size()); + req.set_header("Content-Length", length); + } + } + + if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) + { + if (!req.has_header("Authorization")) + { + req.headers.insert(make_basic_authentication_header( + basic_auth_username_, basic_auth_password_, false)); + } + } + + if (!proxy_basic_auth_username_.empty() && + !proxy_basic_auth_password_.empty()) + { + if (!req.has_header("Proxy-Authorization")) + { + req.headers.insert(make_basic_authentication_header( + proxy_basic_auth_username_, proxy_basic_auth_password_, true)); + } + } + + if (!bearer_token_auth_token_.empty()) + { + if (!req.has_header("Authorization")) + { + req.headers.insert(make_bearer_token_authentication_header( + bearer_token_auth_token_, false)); + } + } + + if (!proxy_bearer_token_auth_token_.empty()) + { + if (!req.has_header("Proxy-Authorization")) + { + req.headers.insert(make_bearer_token_authentication_header( + proxy_bearer_token_auth_token_, true)); + } + } + + // Request line and headers + { + detail::BufferStream bstrm; + + const auto& path_with_query = + req.params.empty() + ? req.path + : append_query_params(req.path, req.params); + + const auto& path = + url_encode_ ? detail::encode_url(path_with_query) : path_with_query; + + detail::write_request_line(bstrm, req.method, path); + + header_writer_(bstrm, req.headers); + + // Flush buffer + auto& data = bstrm.get_buffer(); + if (!detail::write_data(strm, data.data(), data.size())) + { + error = Error::Write; + return false; + } + } + + // Body + if (req.body.empty()) + { + return write_content_with_provider(strm, req, error); + } + + if (!detail::write_data(strm, req.body.data(), req.body.size())) + { + error = Error::Write; + return false; + } + + return true; + } + + inline std::unique_ptr ClientImpl::send_with_content_provider( + Request& req, const char* body, size_t content_length, + ContentProvider content_provider, + ContentProviderWithoutLength content_provider_without_length, + const std::string& content_type, Error& error) + { + if (!content_type.empty()) { req.set_header("Content-Type", content_type); } + +#ifdef CPPHTTPLIB_ZLIB_SUPPORT + if (compress_) { req.set_header("Content-Encoding", "gzip"); } +#endif + +#ifdef CPPHTTPLIB_ZLIB_SUPPORT + if (compress_ && !content_provider_without_length) { + // TODO: Brotli support + detail::gzip_compressor compressor; + + if (content_provider) { + auto ok = true; + size_t offset = 0; + DataSink data_sink; + + data_sink.write = [&](const char *data, size_t data_len) -> bool { + if (ok) { + auto last = offset + data_len == content_length; + + auto ret = compressor.compress( + data, data_len, last, + [&](const char *compressed_data, size_t compressed_data_len) { + req.body.append(compressed_data, compressed_data_len); + return true; + }); + + if (ret) { + offset += data_len; + } else { + ok = false; + } + } + return ok; + }; + + while (ok && offset < content_length) { + if (!content_provider(offset, content_length - offset, data_sink)) { + error = Error::Canceled; + return nullptr; + } + } + } else { + if (!compressor.compress(body, content_length, true, + [&](const char *data, size_t data_len) { + req.body.append(data, data_len); + return true; + })) { + error = Error::Compression; + return nullptr; + } + } + } else +#endif + { + if (content_provider) + { + req.content_length_ = content_length; + req.content_provider_ = std::move(content_provider); + req.is_chunked_content_provider_ = false; + } + else if (content_provider_without_length) + { + req.content_length_ = 0; + req.content_provider_ = detail::ContentProviderAdapter( + std::move(content_provider_without_length)); + req.is_chunked_content_provider_ = true; + req.set_header("Transfer-Encoding", "chunked"); + } + else + { + req.body.assign(body, content_length); + } + } + + auto res = detail::make_unique(); + return send(req, *res, error) ? std::move(res) : nullptr; + } + + inline Result ClientImpl::send_with_content_provider( + const std::string& method, const std::string& path, const Headers& headers, + const char* body, size_t content_length, ContentProvider content_provider, + ContentProviderWithoutLength content_provider_without_length, + const std::string& content_type, Progress progress) + { + Request req; + req.method = method; + req.headers = headers; + req.path = path; + req.progress = progress; + + auto error = Error::Success; + + auto res = send_with_content_provider( + req, body, content_length, std::move(content_provider), + std::move(content_provider_without_length), content_type, error); + + return Result{std::move(res), error, std::move(req.headers)}; + } + + inline std::string + ClientImpl::adjust_host_string(const std::string& host) const + { + if (host.find(':') != std::string::npos) { return "[" + host + "]"; } + return host; + } + + inline bool ClientImpl::process_request(Stream& strm, Request& req, + Response& res, bool close_connection, + Error& error) + { + // Send request + if (!write_request(strm, req, close_connection, error)) { return false; } + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + if (is_ssl()) { + auto is_proxy_enabled = !proxy_host_.empty() && proxy_port_ != -1; + if (!is_proxy_enabled) { + if (is_ssl_peer_could_be_closed(socket_.ssl)) { + error = Error::SSLPeerCouldBeClosed_; + return false; + } + } + } +#endif + + // Receive response and headers + if (!read_response_line(strm, req, res) || + !detail::read_headers(strm, res.headers)) + { + error = Error::Read; + return false; + } + + // Body + if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" && + req.method != "CONNECT") + { + auto redirect = 300 < res.status && res.status < 400 && follow_location_; + + if (req.response_handler && !redirect) + { + if (!req.response_handler(res)) + { + error = Error::Canceled; + return false; + } + } + + auto out = + req.content_receiver + ? static_cast( + [&](const char* buf, size_t n, uint64_t off, uint64_t len) + { + if (redirect) { return true; } + auto ret = req.content_receiver(buf, n, off, len); + if (!ret) { error = Error::Canceled; } + return ret; + }) + : static_cast( + [&](const char* buf, size_t n, uint64_t /*off*/, + uint64_t /*len*/) + { + assert(res.body.size() + n <= res.body.max_size()); + res.body.append(buf, n); + return true; + }); + + auto progress = [&](uint64_t current, uint64_t total) + { + if (!req.progress || redirect) { return true; } + auto ret = req.progress(current, total); + if (!ret) { error = Error::Canceled; } + return ret; + }; + + if (res.has_header("Content-Length")) + { + if (!req.content_receiver) + { + auto len = res.get_header_value_u64("Content-Length"); + if (len > res.body.max_size()) + { + error = Error::Read; + return false; + } + res.body.reserve(len); + } + } + + int dummy_status; + if (!detail::read_content(strm, res, (std::numeric_limits::max)(), + dummy_status, std::move(progress), std::move(out), + decompress_)) + { + if (error != Error::Canceled) { error = Error::Read; } + return false; + } + } + + // Log + if (logger_) { logger_(req, res); } + + return true; + } + + inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider( + const std::string& boundary, const MultipartFormDataItems& items, + const MultipartFormDataProviderItems& provider_items) const + { + size_t cur_item = 0; + size_t cur_start = 0; + // cur_item and cur_start are copied to within the std::function and maintain + // state between successive calls + return [&, cur_item, cur_start](size_t offset, + DataSink& sink) mutable -> bool + { + if (!offset && !items.empty()) + { + sink.os << detail::serialize_multipart_formdata(items, boundary, false); + return true; + } + else if (cur_item < provider_items.size()) + { + if (!cur_start) + { + const auto& begin = detail::serialize_multipart_formdata_item_begin( + provider_items[cur_item], boundary); + offset += begin.size(); + cur_start = offset; + sink.os << begin; + } + + DataSink cur_sink; + auto has_data = true; + cur_sink.write = sink.write; + cur_sink.done = [&]() { has_data = false; }; + + if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) + { + return false; + } + + if (!has_data) + { + sink.os << detail::serialize_multipart_formdata_item_end(); + cur_item++; + cur_start = 0; + } + return true; + } + else + { + sink.os << detail::serialize_multipart_formdata_finish(boundary); + sink.done(); + return true; + } + }; + } + + inline bool + ClientImpl::process_socket(const Socket& socket, + std::function callback) + { + return detail::process_client_socket( + socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_, + write_timeout_usec_, std::move(callback)); + } + + inline bool ClientImpl::is_ssl() const { return false; } + + inline Result ClientImpl::Get(const std::string& path) + { + return Get(path, Headers(), Progress()); + } + + inline Result ClientImpl::Get(const std::string& path, Progress progress) + { + return Get(path, Headers(), std::move(progress)); + } + + inline Result ClientImpl::Get(const std::string& path, const Headers& headers) + { + return Get(path, headers, Progress()); + } + + inline Result ClientImpl::Get(const std::string& path, const Headers& headers, + Progress progress) + { + Request req; + req.method = "GET"; + req.path = path; + req.headers = headers; + req.progress = std::move(progress); + + return send_(std::move(req)); + } + + inline Result ClientImpl::Get(const std::string& path, + ContentReceiver content_receiver) + { + return Get(path, Headers(), nullptr, std::move(content_receiver), nullptr); + } + + inline Result ClientImpl::Get(const std::string& path, + ContentReceiver content_receiver, + Progress progress) + { + return Get(path, Headers(), nullptr, std::move(content_receiver), + std::move(progress)); + } + + inline Result ClientImpl::Get(const std::string& path, const Headers& headers, + ContentReceiver content_receiver) + { + return Get(path, headers, nullptr, std::move(content_receiver), nullptr); + } + + inline Result ClientImpl::Get(const std::string& path, const Headers& headers, + ContentReceiver content_receiver, + Progress progress) + { + return Get(path, headers, nullptr, std::move(content_receiver), + std::move(progress)); + } + + inline Result ClientImpl::Get(const std::string& path, + ResponseHandler response_handler, + ContentReceiver content_receiver) + { + return Get(path, Headers(), std::move(response_handler), + std::move(content_receiver), nullptr); + } + + inline Result ClientImpl::Get(const std::string& path, const Headers& headers, + ResponseHandler response_handler, + ContentReceiver content_receiver) + { + return Get(path, headers, std::move(response_handler), + std::move(content_receiver), nullptr); + } + + inline Result ClientImpl::Get(const std::string& path, + ResponseHandler response_handler, + ContentReceiver content_receiver, + Progress progress) + { + return Get(path, Headers(), std::move(response_handler), + std::move(content_receiver), std::move(progress)); + } + + inline Result ClientImpl::Get(const std::string& path, const Headers& headers, + ResponseHandler response_handler, + ContentReceiver content_receiver, + Progress progress) + { + Request req; + req.method = "GET"; + req.path = path; + req.headers = headers; + req.response_handler = std::move(response_handler); + req.content_receiver = + [content_receiver](const char* data, size_t data_length, + uint64_t /*offset*/, uint64_t /*total_length*/) + { + return content_receiver(data, data_length); + }; + req.progress = std::move(progress); + + return send_(std::move(req)); + } + + inline Result ClientImpl::Get(const std::string& path, const Params& params, + const Headers& headers, Progress progress) + { + if (params.empty()) { return Get(path, headers); } + + std::string path_with_query = append_query_params(path, params); + return Get(path_with_query, headers, std::move(progress)); + } + + inline Result ClientImpl::Get(const std::string& path, const Params& params, + const Headers& headers, + ContentReceiver content_receiver, + Progress progress) + { + return Get(path, params, headers, nullptr, std::move(content_receiver), + std::move(progress)); + } + + inline Result ClientImpl::Get(const std::string& path, const Params& params, + const Headers& headers, + ResponseHandler response_handler, + ContentReceiver content_receiver, + Progress progress) + { + if (params.empty()) + { + return Get(path, headers, std::move(response_handler), + std::move(content_receiver), std::move(progress)); + } + + std::string path_with_query = append_query_params(path, params); + return Get(path_with_query, headers, std::move(response_handler), + std::move(content_receiver), std::move(progress)); + } + + inline Result ClientImpl::Head(const std::string& path) + { + return Head(path, Headers()); + } + + inline Result ClientImpl::Head(const std::string& path, + const Headers& headers) + { + Request req; + req.method = "HEAD"; + req.headers = headers; + req.path = path; + + return send_(std::move(req)); + } + + inline Result ClientImpl::Post(const std::string& path) + { + return Post(path, std::string(), std::string()); + } + + inline Result ClientImpl::Post(const std::string& path, + const Headers& headers) + { + return Post(path, headers, nullptr, 0, std::string()); + } + + inline Result ClientImpl::Post(const std::string& path, const char* body, + size_t content_length, + const std::string& content_type) + { + return Post(path, Headers(), body, content_length, content_type, nullptr); + } + + inline Result ClientImpl::Post(const std::string& path, const Headers& headers, + const char* body, size_t content_length, + const std::string& content_type) + { + return send_with_content_provider("POST", path, headers, body, content_length, + nullptr, nullptr, content_type, nullptr); + } + + inline Result ClientImpl::Post(const std::string& path, const Headers& headers, + const char* body, size_t content_length, + const std::string& content_type, + Progress progress) + { + return send_with_content_provider("POST", path, headers, body, content_length, + nullptr, nullptr, content_type, progress); + } + + inline Result ClientImpl::Post(const std::string& path, const std::string& body, + const std::string& content_type) + { + return Post(path, Headers(), body, content_type); + } + + inline Result ClientImpl::Post(const std::string& path, const std::string& body, + const std::string& content_type, + Progress progress) + { + return Post(path, Headers(), body, content_type, progress); + } + + inline Result ClientImpl::Post(const std::string& path, const Headers& headers, + const std::string& body, + const std::string& content_type) + { + return send_with_content_provider("POST", path, headers, body.data(), + body.size(), nullptr, nullptr, content_type, + nullptr); + } + + inline Result ClientImpl::Post(const std::string& path, const Headers& headers, + const std::string& body, + const std::string& content_type, + Progress progress) + { + return send_with_content_provider("POST", path, headers, body.data(), + body.size(), nullptr, nullptr, content_type, + progress); + } + + inline Result ClientImpl::Post(const std::string& path, const Params& params) + { + return Post(path, Headers(), params); + } + + inline Result ClientImpl::Post(const std::string& path, size_t content_length, + ContentProvider content_provider, + const std::string& content_type) + { + return Post(path, Headers(), content_length, std::move(content_provider), + content_type); + } + + inline Result ClientImpl::Post(const std::string& path, + ContentProviderWithoutLength content_provider, + const std::string& content_type) + { + return Post(path, Headers(), std::move(content_provider), content_type); + } + + inline Result ClientImpl::Post(const std::string& path, const Headers& headers, + size_t content_length, + ContentProvider content_provider, + const std::string& content_type) + { + return send_with_content_provider("POST", path, headers, nullptr, + content_length, std::move(content_provider), + nullptr, content_type, nullptr); + } + + inline Result ClientImpl::Post(const std::string& path, const Headers& headers, + ContentProviderWithoutLength content_provider, + const std::string& content_type) + { + return send_with_content_provider("POST", path, headers, nullptr, 0, nullptr, + std::move(content_provider), content_type, + nullptr); + } + + inline Result ClientImpl::Post(const std::string& path, const Headers& headers, + const Params& params) + { + auto query = detail::params_to_query_str(params); + return Post(path, headers, query, "application/x-www-form-urlencoded"); + } + + inline Result ClientImpl::Post(const std::string& path, const Headers& headers, + const Params& params, Progress progress) + { + auto query = detail::params_to_query_str(params); + return Post(path, headers, query, "application/x-www-form-urlencoded", + progress); + } + + inline Result ClientImpl::Post(const std::string& path, + const MultipartFormDataItems& items) + { + return Post(path, Headers(), items); + } + + inline Result ClientImpl::Post(const std::string& path, const Headers& headers, + const MultipartFormDataItems& items) + { + const auto& boundary = detail::make_multipart_data_boundary(); + const auto& content_type = + detail::serialize_multipart_formdata_get_content_type(boundary); + const auto& body = detail::serialize_multipart_formdata(items, boundary); + return Post(path, headers, body, content_type); + } + + inline Result ClientImpl::Post(const std::string& path, const Headers& headers, + const MultipartFormDataItems& items, + const std::string& boundary) + { + if (!detail::is_multipart_boundary_chars_valid(boundary)) + { + return Result{nullptr, Error::UnsupportedMultipartBoundaryChars}; + } + + const auto& content_type = + detail::serialize_multipart_formdata_get_content_type(boundary); + const auto& body = detail::serialize_multipart_formdata(items, boundary); + return Post(path, headers, body, content_type); + } + + inline Result + ClientImpl::Post(const std::string& path, const Headers& headers, + const MultipartFormDataItems& items, + const MultipartFormDataProviderItems& provider_items) + { + const auto& boundary = detail::make_multipart_data_boundary(); + const auto& content_type = + detail::serialize_multipart_formdata_get_content_type(boundary); + return send_with_content_provider( + "POST", path, headers, nullptr, 0, nullptr, + get_multipart_content_provider(boundary, items, provider_items), + content_type, nullptr); + } + + inline Result ClientImpl::Put(const std::string& path) + { + return Put(path, std::string(), std::string()); + } + + inline Result ClientImpl::Put(const std::string& path, const char* body, + size_t content_length, + const std::string& content_type) + { + return Put(path, Headers(), body, content_length, content_type); + } + + inline Result ClientImpl::Put(const std::string& path, const Headers& headers, + const char* body, size_t content_length, + const std::string& content_type) + { + return send_with_content_provider("PUT", path, headers, body, content_length, + nullptr, nullptr, content_type, nullptr); + } + + inline Result ClientImpl::Put(const std::string& path, const Headers& headers, + const char* body, size_t content_length, + const std::string& content_type, + Progress progress) + { + return send_with_content_provider("PUT", path, headers, body, content_length, + nullptr, nullptr, content_type, progress); + } + + inline Result ClientImpl::Put(const std::string& path, const std::string& body, + const std::string& content_type) + { + return Put(path, Headers(), body, content_type); + } + + inline Result ClientImpl::Put(const std::string& path, const std::string& body, + const std::string& content_type, + Progress progress) + { + return Put(path, Headers(), body, content_type, progress); + } + + inline Result ClientImpl::Put(const std::string& path, const Headers& headers, + const std::string& body, + const std::string& content_type) + { + return send_with_content_provider("PUT", path, headers, body.data(), + body.size(), nullptr, nullptr, content_type, + nullptr); + } + + inline Result ClientImpl::Put(const std::string& path, const Headers& headers, + const std::string& body, + const std::string& content_type, + Progress progress) + { + return send_with_content_provider("PUT", path, headers, body.data(), + body.size(), nullptr, nullptr, content_type, + progress); + } + + inline Result ClientImpl::Put(const std::string& path, size_t content_length, + ContentProvider content_provider, + const std::string& content_type) + { + return Put(path, Headers(), content_length, std::move(content_provider), + content_type); + } + + inline Result ClientImpl::Put(const std::string& path, + ContentProviderWithoutLength content_provider, + const std::string& content_type) + { + return Put(path, Headers(), std::move(content_provider), content_type); + } + + inline Result ClientImpl::Put(const std::string& path, const Headers& headers, + size_t content_length, + ContentProvider content_provider, + const std::string& content_type) + { + return send_with_content_provider("PUT", path, headers, nullptr, + content_length, std::move(content_provider), + nullptr, content_type, nullptr); + } + + inline Result ClientImpl::Put(const std::string& path, const Headers& headers, + ContentProviderWithoutLength content_provider, + const std::string& content_type) + { + return send_with_content_provider("PUT", path, headers, nullptr, 0, nullptr, + std::move(content_provider), content_type, + nullptr); + } + + inline Result ClientImpl::Put(const std::string& path, const Params& params) + { + return Put(path, Headers(), params); + } + + inline Result ClientImpl::Put(const std::string& path, const Headers& headers, + const Params& params) + { + auto query = detail::params_to_query_str(params); + return Put(path, headers, query, "application/x-www-form-urlencoded"); + } + + inline Result ClientImpl::Put(const std::string& path, const Headers& headers, + const Params& params, Progress progress) + { + auto query = detail::params_to_query_str(params); + return Put(path, headers, query, "application/x-www-form-urlencoded", + progress); + } + + inline Result ClientImpl::Put(const std::string& path, + const MultipartFormDataItems& items) + { + return Put(path, Headers(), items); + } + + inline Result ClientImpl::Put(const std::string& path, const Headers& headers, + const MultipartFormDataItems& items) + { + const auto& boundary = detail::make_multipart_data_boundary(); + const auto& content_type = + detail::serialize_multipart_formdata_get_content_type(boundary); + const auto& body = detail::serialize_multipart_formdata(items, boundary); + return Put(path, headers, body, content_type); + } + + inline Result ClientImpl::Put(const std::string& path, const Headers& headers, + const MultipartFormDataItems& items, + const std::string& boundary) + { + if (!detail::is_multipart_boundary_chars_valid(boundary)) + { + return Result{nullptr, Error::UnsupportedMultipartBoundaryChars}; + } + + const auto& content_type = + detail::serialize_multipart_formdata_get_content_type(boundary); + const auto& body = detail::serialize_multipart_formdata(items, boundary); + return Put(path, headers, body, content_type); + } + + inline Result + ClientImpl::Put(const std::string& path, const Headers& headers, + const MultipartFormDataItems& items, + const MultipartFormDataProviderItems& provider_items) + { + const auto& boundary = detail::make_multipart_data_boundary(); + const auto& content_type = + detail::serialize_multipart_formdata_get_content_type(boundary); + return send_with_content_provider( + "PUT", path, headers, nullptr, 0, nullptr, + get_multipart_content_provider(boundary, items, provider_items), + content_type, nullptr); + } + + inline Result ClientImpl::Patch(const std::string& path) + { + return Patch(path, std::string(), std::string()); + } + + inline Result ClientImpl::Patch(const std::string& path, const char* body, + size_t content_length, + const std::string& content_type) + { + return Patch(path, Headers(), body, content_length, content_type); + } + + inline Result ClientImpl::Patch(const std::string& path, const char* body, + size_t content_length, + const std::string& content_type, + Progress progress) + { + return Patch(path, Headers(), body, content_length, content_type, progress); + } + + inline Result ClientImpl::Patch(const std::string& path, const Headers& headers, + const char* body, size_t content_length, + const std::string& content_type) + { + return Patch(path, headers, body, content_length, content_type, nullptr); + } + + inline Result ClientImpl::Patch(const std::string& path, const Headers& headers, + const char* body, size_t content_length, + const std::string& content_type, + Progress progress) + { + return send_with_content_provider("PATCH", path, headers, body, + content_length, nullptr, nullptr, + content_type, progress); + } + + inline Result ClientImpl::Patch(const std::string& path, + const std::string& body, + const std::string& content_type) + { + return Patch(path, Headers(), body, content_type); + } + + inline Result ClientImpl::Patch(const std::string& path, + const std::string& body, + const std::string& content_type, + Progress progress) + { + return Patch(path, Headers(), body, content_type, progress); + } + + inline Result ClientImpl::Patch(const std::string& path, const Headers& headers, + const std::string& body, + const std::string& content_type) + { + return Patch(path, headers, body, content_type, nullptr); + } + + inline Result ClientImpl::Patch(const std::string& path, const Headers& headers, + const std::string& body, + const std::string& content_type, + Progress progress) + { + return send_with_content_provider("PATCH", path, headers, body.data(), + body.size(), nullptr, nullptr, content_type, + progress); + } + + inline Result ClientImpl::Patch(const std::string& path, size_t content_length, + ContentProvider content_provider, + const std::string& content_type) + { + return Patch(path, Headers(), content_length, std::move(content_provider), + content_type); + } + + inline Result ClientImpl::Patch(const std::string& path, + ContentProviderWithoutLength content_provider, + const std::string& content_type) + { + return Patch(path, Headers(), std::move(content_provider), content_type); + } + + inline Result ClientImpl::Patch(const std::string& path, const Headers& headers, + size_t content_length, + ContentProvider content_provider, + const std::string& content_type) + { + return send_with_content_provider("PATCH", path, headers, nullptr, + content_length, std::move(content_provider), + nullptr, content_type, nullptr); + } + + inline Result ClientImpl::Patch(const std::string& path, const Headers& headers, + ContentProviderWithoutLength content_provider, + const std::string& content_type) + { + return send_with_content_provider("PATCH", path, headers, nullptr, 0, nullptr, + std::move(content_provider), content_type, + nullptr); + } + + inline Result ClientImpl::Delete(const std::string& path) + { + return Delete(path, Headers(), std::string(), std::string()); + } + + inline Result ClientImpl::Delete(const std::string& path, + const Headers& headers) + { + return Delete(path, headers, std::string(), std::string()); + } + + inline Result ClientImpl::Delete(const std::string& path, const char* body, + size_t content_length, + const std::string& content_type) + { + return Delete(path, Headers(), body, content_length, content_type); + } + + inline Result ClientImpl::Delete(const std::string& path, const char* body, + size_t content_length, + const std::string& content_type, + Progress progress) + { + return Delete(path, Headers(), body, content_length, content_type, progress); + } + + inline Result ClientImpl::Delete(const std::string& path, + const Headers& headers, const char* body, + size_t content_length, + const std::string& content_type) + { + return Delete(path, headers, body, content_length, content_type, nullptr); + } + + inline Result ClientImpl::Delete(const std::string& path, + const Headers& headers, const char* body, + size_t content_length, + const std::string& content_type, + Progress progress) + { + Request req; + req.method = "DELETE"; + req.headers = headers; + req.path = path; + req.progress = progress; + + if (!content_type.empty()) { req.set_header("Content-Type", content_type); } + req.body.assign(body, content_length); + + return send_(std::move(req)); + } + + inline Result ClientImpl::Delete(const std::string& path, + const std::string& body, + const std::string& content_type) + { + return Delete(path, Headers(), body.data(), body.size(), content_type); + } + + inline Result ClientImpl::Delete(const std::string& path, + const std::string& body, + const std::string& content_type, + Progress progress) + { + return Delete(path, Headers(), body.data(), body.size(), content_type, + progress); + } + + inline Result ClientImpl::Delete(const std::string& path, + const Headers& headers, + const std::string& body, + const std::string& content_type) + { + return Delete(path, headers, body.data(), body.size(), content_type); + } + + inline Result ClientImpl::Delete(const std::string& path, + const Headers& headers, + const std::string& body, + const std::string& content_type, + Progress progress) + { + return Delete(path, headers, body.data(), body.size(), content_type, + progress); + } + + inline Result ClientImpl::Options(const std::string& path) + { + return Options(path, Headers()); + } + + inline Result ClientImpl::Options(const std::string& path, + const Headers& headers) + { + Request req; + req.method = "OPTIONS"; + req.headers = headers; + req.path = path; + + return send_(std::move(req)); + } + + inline void ClientImpl::stop() + { + std::lock_guard guard(socket_mutex_); + + // If there is anything ongoing right now, the ONLY thread-safe thing we can + // do is to shutdown_socket, so that threads using this socket suddenly + // discover they can't read/write any more and error out. Everything else + // (closing the socket, shutting ssl down) is unsafe because these actions are + // not thread-safe. + if (socket_requests_in_flight_ > 0) + { + shutdown_socket(socket_); + + // Aside from that, we set a flag for the socket to be closed when we're + // done. + socket_should_be_closed_when_request_is_done_ = true; + return; + } + + // Otherwise, still holding the mutex, we can shut everything down ourselves + shutdown_ssl(socket_, true); + shutdown_socket(socket_); + close_socket(socket_); + } + + inline std::string ClientImpl::host() const { return host_; } + + inline int ClientImpl::port() const { return port_; } + + inline size_t ClientImpl::is_socket_open() const + { + std::lock_guard guard(socket_mutex_); + return socket_.is_open(); + } + + inline socket_t ClientImpl::socket() const { return socket_.sock; } + + inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) + { + connection_timeout_sec_ = sec; + connection_timeout_usec_ = usec; + } + + inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) + { + read_timeout_sec_ = sec; + read_timeout_usec_ = usec; + } + + inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) + { + write_timeout_sec_ = sec; + write_timeout_usec_ = usec; + } + + inline void ClientImpl::set_basic_auth(const std::string& username, + const std::string& password) + { + basic_auth_username_ = username; + basic_auth_password_ = password; + } + + inline void ClientImpl::set_bearer_token_auth(const std::string& token) + { + bearer_token_auth_token_ = token; + } + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT +inline void ClientImpl::set_digest_auth(const std::string &username, + const std::string &password) { + digest_auth_username_ = username; + digest_auth_password_ = password; +} +#endif + + inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; } + + inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; } + + inline void ClientImpl::set_url_encode(bool on) { url_encode_ = on; } + + inline void + ClientImpl::set_hostname_addr_map(std::map addr_map) + { + addr_map_ = std::move(addr_map); + } + + inline void ClientImpl::set_default_headers(Headers headers) + { + default_headers_ = std::move(headers); + } + + inline void ClientImpl::set_header_writer( + std::function const& writer) + { + header_writer_ = writer; + } + + inline void ClientImpl::set_address_family(int family) + { + address_family_ = family; + } + + inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; } + + inline void ClientImpl::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; } + + inline void ClientImpl::set_socket_options(SocketOptions socket_options) + { + socket_options_ = std::move(socket_options); + } + + inline void ClientImpl::set_compress(bool on) { compress_ = on; } + + inline void ClientImpl::set_decompress(bool on) { decompress_ = on; } + + inline void ClientImpl::set_interface(const std::string& intf) + { + interface_ = intf; + } + + inline void ClientImpl::set_proxy(const std::string& host, int port) + { + proxy_host_ = host; + proxy_port_ = port; + } + + inline void ClientImpl::set_proxy_basic_auth(const std::string& username, + const std::string& password) + { + proxy_basic_auth_username_ = username; + proxy_basic_auth_password_ = password; + } + + inline void ClientImpl::set_proxy_bearer_token_auth(const std::string& token) + { + proxy_bearer_token_auth_token_ = token; + } + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT +inline void ClientImpl::set_proxy_digest_auth(const std::string &username, + const std::string &password) { + proxy_digest_auth_username_ = username; + proxy_digest_auth_password_ = password; +} + +inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path, + const std::string &ca_cert_dir_path) { + ca_cert_file_path_ = ca_cert_file_path; + ca_cert_dir_path_ = ca_cert_dir_path; +} + +inline void ClientImpl::set_ca_cert_store(X509_STORE *ca_cert_store) { + if (ca_cert_store && ca_cert_store != ca_cert_store_) { + ca_cert_store_ = ca_cert_store; + } +} + +inline X509_STORE *ClientImpl::create_ca_cert_store(const char *ca_cert, + std::size_t size) const { + auto mem = BIO_new_mem_buf(ca_cert, static_cast(size)); + auto se = detail::scope_exit([&] { BIO_free_all(mem); }); + if (!mem) { return nullptr; } + + auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr); + if (!inf) { return nullptr; } + + auto cts = X509_STORE_new(); + if (cts) { + for (auto i = 0; i < static_cast(sk_X509_INFO_num(inf)); i++) { + auto itmp = sk_X509_INFO_value(inf, i); + if (!itmp) { continue; } + + if (itmp->x509) { X509_STORE_add_cert(cts, itmp->x509); } + if (itmp->crl) { X509_STORE_add_crl(cts, itmp->crl); } + } + } + + sk_X509_INFO_pop_free(inf, X509_INFO_free); + return cts; +} + +inline void ClientImpl::enable_server_certificate_verification(bool enabled) { + server_certificate_verification_ = enabled; +} + +inline void ClientImpl::enable_server_hostname_verification(bool enabled) { + server_hostname_verification_ = enabled; +} + +inline void ClientImpl::set_server_certificate_verifier( + std::function verifier) { + server_certificate_verifier_ = verifier; +} +#endif + + inline void ClientImpl::set_logger(Logger logger) + { + logger_ = std::move(logger); + } + + /* + * SSL Implementation + */ +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT +namespace detail { + +template +inline SSL *ssl_new(socket_t sock, SSL_CTX *ctx, std::mutex &ctx_mutex, + U SSL_connect_or_accept, V setup) { + SSL *ssl = nullptr; + { + std::lock_guard guard(ctx_mutex); + ssl = SSL_new(ctx); + } + + if (ssl) { + set_nonblocking(sock, true); + auto bio = BIO_new_socket(static_cast(sock), BIO_NOCLOSE); + BIO_set_nbio(bio, 1); + SSL_set_bio(ssl, bio, bio); + + if (!setup(ssl) || SSL_connect_or_accept(ssl) != 1) { + SSL_shutdown(ssl); + { + std::lock_guard guard(ctx_mutex); + SSL_free(ssl); + } + set_nonblocking(sock, false); + return nullptr; + } + BIO_set_nbio(bio, 0); + set_nonblocking(sock, false); + } + + return ssl; +} + +inline void ssl_delete(std::mutex &ctx_mutex, SSL *ssl, socket_t sock, + bool shutdown_gracefully) { + // sometimes we may want to skip this to try to avoid SIGPIPE if we know + // the remote has closed the network connection + // Note that it is not always possible to avoid SIGPIPE, this is merely a + // best-efforts. + if (shutdown_gracefully) { +#ifdef _WIN32 + SSL_shutdown(ssl); +#else + timeval tv; + tv.tv_sec = 1; + tv.tv_usec = 0; + setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, + reinterpret_cast(&tv), sizeof(tv)); + + auto ret = SSL_shutdown(ssl); + while (ret == 0) { + std::this_thread::sleep_for(std::chrono::milliseconds{100}); + ret = SSL_shutdown(ssl); + } +#endif + } + + std::lock_guard guard(ctx_mutex); + SSL_free(ssl); +} + +template +bool ssl_connect_or_accept_nonblocking(socket_t sock, SSL *ssl, + U ssl_connect_or_accept, + time_t timeout_sec, + time_t timeout_usec) { + auto res = 0; + while ((res = ssl_connect_or_accept(ssl)) != 1) { + auto err = SSL_get_error(ssl, res); + switch (err) { + case SSL_ERROR_WANT_READ: + if (select_read(sock, timeout_sec, timeout_usec) > 0) { continue; } + break; + case SSL_ERROR_WANT_WRITE: + if (select_write(sock, timeout_sec, timeout_usec) > 0) { continue; } + break; + default: break; + } + return false; + } + return true; +} + +template +inline bool process_server_socket_ssl( + const std::atomic &svr_sock, SSL *ssl, socket_t sock, + size_t keep_alive_max_count, time_t keep_alive_timeout_sec, + time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec, + time_t write_timeout_usec, T callback) { + return process_server_socket_core( + svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec, + [&](bool close_connection, bool &connection_closed) { + SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec, + write_timeout_sec, write_timeout_usec); + return callback(strm, close_connection, connection_closed); + }); +} + +template +inline bool +process_client_socket_ssl(SSL *ssl, socket_t sock, time_t read_timeout_sec, + time_t read_timeout_usec, time_t write_timeout_sec, + time_t write_timeout_usec, T callback) { + SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec, + write_timeout_sec, write_timeout_usec); + return callback(strm); +} + +class SSLInit { +public: + SSLInit() { + OPENSSL_init_ssl( + OPENSSL_INIT_LOAD_SSL_STRINGS | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL); + } +}; + +// SSL socket stream implementation +inline SSLSocketStream::SSLSocketStream(socket_t sock, SSL *ssl, + time_t read_timeout_sec, + time_t read_timeout_usec, + time_t write_timeout_sec, + time_t write_timeout_usec) + : sock_(sock), ssl_(ssl), read_timeout_sec_(read_timeout_sec), + read_timeout_usec_(read_timeout_usec), + write_timeout_sec_(write_timeout_sec), + write_timeout_usec_(write_timeout_usec) { + SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY); +} + +inline SSLSocketStream::~SSLSocketStream() = default; + +inline bool SSLSocketStream::is_readable() const { + return detail::select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0; +} + +inline bool SSLSocketStream::is_writable() const { + return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 && + is_socket_alive(sock_); +} + +inline ssize_t SSLSocketStream::read(char *ptr, size_t size) { + if (SSL_pending(ssl_) > 0) { + return SSL_read(ssl_, ptr, static_cast(size)); + } else if (is_readable()) { + auto ret = SSL_read(ssl_, ptr, static_cast(size)); + if (ret < 0) { + auto err = SSL_get_error(ssl_, ret); + auto n = 1000; +#ifdef _WIN32 + while (--n >= 0 && (err == SSL_ERROR_WANT_READ || + (err == SSL_ERROR_SYSCALL && + WSAGetLastError() == WSAETIMEDOUT))) { +#else + while (--n >= 0 && err == SSL_ERROR_WANT_READ) { +#endif + if (SSL_pending(ssl_) > 0) { + return SSL_read(ssl_, ptr, static_cast(size)); + } else if (is_readable()) { + std::this_thread::sleep_for(std::chrono::microseconds{10}); + ret = SSL_read(ssl_, ptr, static_cast(size)); + if (ret >= 0) { return ret; } + err = SSL_get_error(ssl_, ret); + } else { + return -1; + } + } + } + return ret; + } + return -1; +} + +inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) { + if (is_writable()) { + auto handle_size = static_cast( + std::min(size, (std::numeric_limits::max)())); + + auto ret = SSL_write(ssl_, ptr, static_cast(handle_size)); + if (ret < 0) { + auto err = SSL_get_error(ssl_, ret); + auto n = 1000; +#ifdef _WIN32 + while (--n >= 0 && (err == SSL_ERROR_WANT_WRITE || + (err == SSL_ERROR_SYSCALL && + WSAGetLastError() == WSAETIMEDOUT))) { +#else + while (--n >= 0 && err == SSL_ERROR_WANT_WRITE) { +#endif + if (is_writable()) { + std::this_thread::sleep_for(std::chrono::microseconds{10}); + ret = SSL_write(ssl_, ptr, static_cast(handle_size)); + if (ret >= 0) { return ret; } + err = SSL_get_error(ssl_, ret); + } else { + return -1; + } + } + } + return ret; + } + return -1; +} + +inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip, + int &port) const { + detail::get_remote_ip_and_port(sock_, ip, port); +} + +inline void SSLSocketStream::get_local_ip_and_port(std::string &ip, + int &port) const { + detail::get_local_ip_and_port(sock_, ip, port); +} + +inline socket_t SSLSocketStream::socket() const { return sock_; } + +static SSLInit sslinit_; + +} // namespace detail + +// SSL HTTP server implementation +inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path, + const char *client_ca_cert_file_path, + const char *client_ca_cert_dir_path, + const char *private_key_password) { + ctx_ = SSL_CTX_new(TLS_server_method()); + + if (ctx_) { + SSL_CTX_set_options(ctx_, + SSL_OP_NO_COMPRESSION | + SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION); + + SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION); + + if (private_key_password != nullptr && (private_key_password[0] != '\0')) { + SSL_CTX_set_default_passwd_cb_userdata( + ctx_, + reinterpret_cast(const_cast(private_key_password))); + } + + if (SSL_CTX_use_certificate_chain_file(ctx_, cert_path) != 1 || + SSL_CTX_use_PrivateKey_file(ctx_, private_key_path, SSL_FILETYPE_PEM) != + 1 || + SSL_CTX_check_private_key(ctx_) != 1) { + SSL_CTX_free(ctx_); + ctx_ = nullptr; + } else if (client_ca_cert_file_path || client_ca_cert_dir_path) { + SSL_CTX_load_verify_locations(ctx_, client_ca_cert_file_path, + client_ca_cert_dir_path); + + SSL_CTX_set_verify( + ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr); + } + } +} + +inline SSLServer::SSLServer(X509 *cert, EVP_PKEY *private_key, + X509_STORE *client_ca_cert_store) { + ctx_ = SSL_CTX_new(TLS_server_method()); + + if (ctx_) { + SSL_CTX_set_options(ctx_, + SSL_OP_NO_COMPRESSION | + SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION); + + SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION); + + if (SSL_CTX_use_certificate(ctx_, cert) != 1 || + SSL_CTX_use_PrivateKey(ctx_, private_key) != 1) { + SSL_CTX_free(ctx_); + ctx_ = nullptr; + } else if (client_ca_cert_store) { + SSL_CTX_set_cert_store(ctx_, client_ca_cert_store); + + SSL_CTX_set_verify( + ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr); + } + } +} + +inline SSLServer::SSLServer( + const std::function &setup_ssl_ctx_callback) { + ctx_ = SSL_CTX_new(TLS_method()); + if (ctx_) { + if (!setup_ssl_ctx_callback(*ctx_)) { + SSL_CTX_free(ctx_); + ctx_ = nullptr; + } + } +} + +inline SSLServer::~SSLServer() { + if (ctx_) { SSL_CTX_free(ctx_); } +} + +inline bool SSLServer::is_valid() const { return ctx_; } + +inline SSL_CTX *SSLServer::ssl_context() const { return ctx_; } + +inline void SSLServer::update_certs(X509 *cert, EVP_PKEY *private_key, + X509_STORE *client_ca_cert_store) { + + std::lock_guard guard(ctx_mutex_); + + SSL_CTX_use_certificate(ctx_, cert); + SSL_CTX_use_PrivateKey(ctx_, private_key); + + if (client_ca_cert_store != nullptr) { + SSL_CTX_set_cert_store(ctx_, client_ca_cert_store); + } +} + +inline bool SSLServer::process_and_close_socket(socket_t sock) { + auto ssl = detail::ssl_new( + sock, ctx_, ctx_mutex_, + [&](SSL *ssl2) { + return detail::ssl_connect_or_accept_nonblocking( + sock, ssl2, SSL_accept, read_timeout_sec_, read_timeout_usec_); + }, + [](SSL * /*ssl2*/) { return true; }); + + auto ret = false; + if (ssl) { + std::string remote_addr; + int remote_port = 0; + detail::get_remote_ip_and_port(sock, remote_addr, remote_port); + + std::string local_addr; + int local_port = 0; + detail::get_local_ip_and_port(sock, local_addr, local_port); + + ret = detail::process_server_socket_ssl( + svr_sock_, ssl, sock, keep_alive_max_count_, keep_alive_timeout_sec_, + read_timeout_sec_, read_timeout_usec_, write_timeout_sec_, + write_timeout_usec_, + [&](Stream &strm, bool close_connection, bool &connection_closed) { + return process_request(strm, remote_addr, remote_port, local_addr, + local_port, close_connection, + connection_closed, + [&](Request &req) { req.ssl = ssl; }); + }); + + // Shutdown gracefully if the result seemed successful, non-gracefully if + // the connection appeared to be closed. + const bool shutdown_gracefully = ret; + detail::ssl_delete(ctx_mutex_, ssl, sock, shutdown_gracefully); + } + + detail::shutdown_socket(sock); + detail::close_socket(sock); + return ret; +} + +// SSL HTTP client implementation +inline SSLClient::SSLClient(const std::string &host) + : SSLClient(host, 443, std::string(), std::string()) {} + +inline SSLClient::SSLClient(const std::string &host, int port) + : SSLClient(host, port, std::string(), std::string()) {} + +inline SSLClient::SSLClient(const std::string &host, int port, + const std::string &client_cert_path, + const std::string &client_key_path, + const std::string &private_key_password) + : ClientImpl(host, port, client_cert_path, client_key_path) { + ctx_ = SSL_CTX_new(TLS_client_method()); + + SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION); + + detail::split(&host_[0], &host_[host_.size()], '.', + [&](const char *b, const char *e) { + host_components_.emplace_back(b, e); + }); + + if (!client_cert_path.empty() && !client_key_path.empty()) { + if (!private_key_password.empty()) { + SSL_CTX_set_default_passwd_cb_userdata( + ctx_, reinterpret_cast( + const_cast(private_key_password.c_str()))); + } + + if (SSL_CTX_use_certificate_file(ctx_, client_cert_path.c_str(), + SSL_FILETYPE_PEM) != 1 || + SSL_CTX_use_PrivateKey_file(ctx_, client_key_path.c_str(), + SSL_FILETYPE_PEM) != 1) { + SSL_CTX_free(ctx_); + ctx_ = nullptr; + } + } +} + +inline SSLClient::SSLClient(const std::string &host, int port, + X509 *client_cert, EVP_PKEY *client_key, + const std::string &private_key_password) + : ClientImpl(host, port) { + ctx_ = SSL_CTX_new(TLS_client_method()); + + detail::split(&host_[0], &host_[host_.size()], '.', + [&](const char *b, const char *e) { + host_components_.emplace_back(b, e); + }); + + if (client_cert != nullptr && client_key != nullptr) { + if (!private_key_password.empty()) { + SSL_CTX_set_default_passwd_cb_userdata( + ctx_, reinterpret_cast( + const_cast(private_key_password.c_str()))); + } + + if (SSL_CTX_use_certificate(ctx_, client_cert) != 1 || + SSL_CTX_use_PrivateKey(ctx_, client_key) != 1) { + SSL_CTX_free(ctx_); + ctx_ = nullptr; + } + } +} + +inline SSLClient::~SSLClient() { + if (ctx_) { SSL_CTX_free(ctx_); } + // Make sure to shut down SSL since shutdown_ssl will resolve to the + // base function rather than the derived function once we get to the + // base class destructor, and won't free the SSL (causing a leak). + shutdown_ssl_impl(socket_, true); +} + +inline bool SSLClient::is_valid() const { return ctx_; } + +inline void SSLClient::set_ca_cert_store(X509_STORE *ca_cert_store) { + if (ca_cert_store) { + if (ctx_) { + if (SSL_CTX_get_cert_store(ctx_) != ca_cert_store) { + // Free memory allocated for old cert and use new store `ca_cert_store` + SSL_CTX_set_cert_store(ctx_, ca_cert_store); + } + } else { + X509_STORE_free(ca_cert_store); + } + } +} + +inline void SSLClient::load_ca_cert_store(const char *ca_cert, + std::size_t size) { + set_ca_cert_store(ClientImpl::create_ca_cert_store(ca_cert, size)); +} + +inline long SSLClient::get_openssl_verify_result() const { + return verify_result_; +} + +inline SSL_CTX *SSLClient::ssl_context() const { return ctx_; } + +inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) { + return is_valid() && ClientImpl::create_and_connect_socket(socket, error); +} + +// Assumes that socket_mutex_ is locked and that there are no requests in flight +inline bool SSLClient::connect_with_proxy(Socket &socket, Response &res, + bool &success, Error &error) { + success = true; + Response proxy_res; + if (!detail::process_client_socket( + socket.sock, read_timeout_sec_, read_timeout_usec_, + write_timeout_sec_, write_timeout_usec_, [&](Stream &strm) { + Request req2; + req2.method = "CONNECT"; + req2.path = host_and_port_; + return process_request(strm, req2, proxy_res, false, error); + })) { + // Thread-safe to close everything because we are assuming there are no + // requests in flight + shutdown_ssl(socket, true); + shutdown_socket(socket); + close_socket(socket); + success = false; + return false; + } + + if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) { + if (!proxy_digest_auth_username_.empty() && + !proxy_digest_auth_password_.empty()) { + std::map auth; + if (detail::parse_www_authenticate(proxy_res, auth, true)) { + proxy_res = Response(); + if (!detail::process_client_socket( + socket.sock, read_timeout_sec_, read_timeout_usec_, + write_timeout_sec_, write_timeout_usec_, [&](Stream &strm) { + Request req3; + req3.method = "CONNECT"; + req3.path = host_and_port_; + req3.headers.insert(detail::make_digest_authentication_header( + req3, auth, 1, detail::random_string(10), + proxy_digest_auth_username_, proxy_digest_auth_password_, + true)); + return process_request(strm, req3, proxy_res, false, error); + })) { + // Thread-safe to close everything because we are assuming there are + // no requests in flight + shutdown_ssl(socket, true); + shutdown_socket(socket); + close_socket(socket); + success = false; + return false; + } + } + } + } + + // If status code is not 200, proxy request is failed. + // Set error to ProxyConnection and return proxy response + // as the response of the request + if (proxy_res.status != StatusCode::OK_200) { + error = Error::ProxyConnection; + res = std::move(proxy_res); + // Thread-safe to close everything because we are assuming there are + // no requests in flight + shutdown_ssl(socket, true); + shutdown_socket(socket); + close_socket(socket); + return false; + } + + return true; +} + +inline bool SSLClient::load_certs() { + auto ret = true; + + std::call_once(initialize_cert_, [&]() { + std::lock_guard guard(ctx_mutex_); + if (!ca_cert_file_path_.empty()) { + if (!SSL_CTX_load_verify_locations(ctx_, ca_cert_file_path_.c_str(), + nullptr)) { + ret = false; + } + } else if (!ca_cert_dir_path_.empty()) { + if (!SSL_CTX_load_verify_locations(ctx_, nullptr, + ca_cert_dir_path_.c_str())) { + ret = false; + } + } else { + auto loaded = false; +#ifdef _WIN32 + loaded = + detail::load_system_certs_on_windows(SSL_CTX_get_cert_store(ctx_)); +#elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && defined(__APPLE__) +#if TARGET_OS_OSX + loaded = detail::load_system_certs_on_macos(SSL_CTX_get_cert_store(ctx_)); +#endif // TARGET_OS_OSX +#endif // _WIN32 + if (!loaded) { SSL_CTX_set_default_verify_paths(ctx_); } + } + }); + + return ret; +} + +inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) { + auto ssl = detail::ssl_new( + socket.sock, ctx_, ctx_mutex_, + [&](SSL *ssl2) { + if (server_certificate_verification_) { + if (!load_certs()) { + error = Error::SSLLoadingCerts; + return false; + } + SSL_set_verify(ssl2, SSL_VERIFY_NONE, nullptr); + } + + if (!detail::ssl_connect_or_accept_nonblocking( + socket.sock, ssl2, SSL_connect, connection_timeout_sec_, + connection_timeout_usec_)) { + error = Error::SSLConnection; + return false; + } + + if (server_certificate_verification_) { + if (server_certificate_verifier_) { + if (!server_certificate_verifier_(ssl2)) { + error = Error::SSLServerVerification; + return false; + } + } else { + verify_result_ = SSL_get_verify_result(ssl2); + + if (verify_result_ != X509_V_OK) { + error = Error::SSLServerVerification; + return false; + } + + auto server_cert = SSL_get1_peer_certificate(ssl2); + auto se = detail::scope_exit([&] { X509_free(server_cert); }); + + if (server_cert == nullptr) { + error = Error::SSLServerVerification; + return false; + } + + if (server_hostname_verification_) { + if (!verify_host(server_cert)) { + error = Error::SSLServerHostnameVerification; + return false; + } + } + } + } + + return true; + }, + [&](SSL *ssl2) { +#if defined(OPENSSL_IS_BORINGSSL) + SSL_set_tlsext_host_name(ssl2, host_.c_str()); +#else + // NOTE: Direct call instead of using the OpenSSL macro to suppress + // -Wold-style-cast warning + SSL_ctrl(ssl2, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name, + static_cast(const_cast(host_.c_str()))); +#endif + return true; + }); + + if (ssl) { + socket.ssl = ssl; + return true; + } + + shutdown_socket(socket); + close_socket(socket); + return false; +} + +inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) { + shutdown_ssl_impl(socket, shutdown_gracefully); +} + +inline void SSLClient::shutdown_ssl_impl(Socket &socket, + bool shutdown_gracefully) { + if (socket.sock == INVALID_SOCKET) { + assert(socket.ssl == nullptr); + return; + } + if (socket.ssl) { + detail::ssl_delete(ctx_mutex_, socket.ssl, socket.sock, + shutdown_gracefully); + socket.ssl = nullptr; + } + assert(socket.ssl == nullptr); +} + +inline bool +SSLClient::process_socket(const Socket &socket, + std::function callback) { + assert(socket.ssl); + return detail::process_client_socket_ssl( + socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_, + write_timeout_sec_, write_timeout_usec_, std::move(callback)); +} + +inline bool SSLClient::is_ssl() const { return true; } + +inline bool SSLClient::verify_host(X509 *server_cert) const { + /* Quote from RFC2818 section 3.1 "Server Identity" + + If a subjectAltName extension of type dNSName is present, that MUST + be used as the identity. Otherwise, the (most specific) Common Name + field in the Subject field of the certificate MUST be used. Although + the use of the Common Name is existing practice, it is deprecated and + Certification Authorities are encouraged to use the dNSName instead. + + Matching is performed using the matching rules specified by + [RFC2459]. If more than one identity of a given type is present in + the certificate (e.g., more than one dNSName name, a match in any one + of the set is considered acceptable.) Names may contain the wildcard + character * which is considered to match any single domain name + component or component fragment. E.g., *.a.com matches foo.a.com but + not bar.foo.a.com. f*.com matches foo.com but not bar.com. + + In some cases, the URI is specified as an IP address rather than a + hostname. In this case, the iPAddress subjectAltName must be present + in the certificate and must exactly match the IP in the URI. + + */ + return verify_host_with_subject_alt_name(server_cert) || + verify_host_with_common_name(server_cert); +} + +inline bool +SSLClient::verify_host_with_subject_alt_name(X509 *server_cert) const { + auto ret = false; + + auto type = GEN_DNS; + + struct in6_addr addr6{}; + struct in_addr addr{}; + size_t addr_len = 0; + +#ifndef __MINGW32__ + if (inet_pton(AF_INET6, host_.c_str(), &addr6)) { + type = GEN_IPADD; + addr_len = sizeof(struct in6_addr); + } else if (inet_pton(AF_INET, host_.c_str(), &addr)) { + type = GEN_IPADD; + addr_len = sizeof(struct in_addr); + } +#endif + + auto alt_names = static_cast( + X509_get_ext_d2i(server_cert, NID_subject_alt_name, nullptr, nullptr)); + + if (alt_names) { + auto dsn_matched = false; + auto ip_matched = false; + + auto count = sk_GENERAL_NAME_num(alt_names); + + for (decltype(count) i = 0; i < count && !dsn_matched; i++) { + auto val = sk_GENERAL_NAME_value(alt_names, i); + if (val->type == type) { + auto name = + reinterpret_cast(ASN1_STRING_get0_data(val->d.ia5)); + auto name_len = static_cast(ASN1_STRING_length(val->d.ia5)); + + switch (type) { + case GEN_DNS: dsn_matched = check_host_name(name, name_len); break; + + case GEN_IPADD: + if (!memcmp(&addr6, name, addr_len) || + !memcmp(&addr, name, addr_len)) { + ip_matched = true; + } + break; + } + } + } + + if (dsn_matched || ip_matched) { ret = true; } + } + + GENERAL_NAMES_free(const_cast( + reinterpret_cast(alt_names))); + return ret; +} + +inline bool SSLClient::verify_host_with_common_name(X509 *server_cert) const { + const auto subject_name = X509_get_subject_name(server_cert); + + if (subject_name != nullptr) { + char name[BUFSIZ]; + auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName, + name, sizeof(name)); + + if (name_len != -1) { + return check_host_name(name, static_cast(name_len)); + } + } + + return false; +} + +inline bool SSLClient::check_host_name(const char *pattern, + size_t pattern_len) const { + if (host_.size() == pattern_len && host_ == pattern) { return true; } + + // Wildcard match + // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484 + std::vector pattern_components; + detail::split(&pattern[0], &pattern[pattern_len], '.', + [&](const char *b, const char *e) { + pattern_components.emplace_back(b, e); + }); + + if (host_components_.size() != pattern_components.size()) { return false; } + + auto itr = pattern_components.begin(); + for (const auto &h : host_components_) { + auto &p = *itr; + if (p != h && p != "*") { + auto partial_match = (p.size() > 0 && p[p.size() - 1] == '*' && + !p.compare(0, p.size() - 1, h)); + if (!partial_match) { return false; } + } + ++itr; + } + + return true; +} +#endif + + // Universal client implementation + inline Client::Client(const std::string& scheme_host_port) : + Client(scheme_host_port, std::string(), std::string()) + { + } + + inline Client::Client(const std::string& scheme_host_port, + const std::string& client_cert_path, + const std::string& client_key_path) + { + const static std::regex re( + R"((?:([a-z]+):\/\/)?(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)"); + + std::smatch m; + if (std::regex_match(scheme_host_port, m, re)) + { + auto scheme = m[1].str(); + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + if (!scheme.empty() && (scheme != "http" && scheme != "https")) { +#else + if (!scheme.empty() && scheme != "http") + { +#endif +#ifndef CPPHTTPLIB_NO_EXCEPTIONS + std::string msg = "'" + scheme + "' scheme is not supported."; + throw std::invalid_argument(msg); +#endif + return; + } + + auto is_ssl = scheme == "https"; + + auto host = m[2].str(); + if (host.empty()) { host = m[3].str(); } + + auto port_str = m[4].str(); + auto port = !port_str.empty() ? std::stoi(port_str) : (is_ssl ? 443 : 80); + + if (is_ssl) + { +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + cli_ = detail::make_unique(host, port, client_cert_path, + client_key_path); + is_ssl_ = is_ssl; +#endif + } + else + { + cli_ = detail::make_unique(host, port, client_cert_path, + client_key_path); + } + } + else + { + // NOTE: Update TEST(UniversalClientImplTest, Ipv6LiteralAddress) + // if port param below changes. + cli_ = detail::make_unique(scheme_host_port, 80, + client_cert_path, client_key_path); + } + } // namespace detail + + inline Client::Client(const std::string& host, int port) : + cli_(detail::make_unique(host, port)) + { + } + + inline Client::Client(const std::string& host, int port, + const std::string& client_cert_path, + const std::string& client_key_path) : + cli_(detail::make_unique(host, port, client_cert_path, + client_key_path)) + { + } + + inline Client::~Client() = default; + + inline bool Client::is_valid() const + { + return cli_ != nullptr && cli_->is_valid(); + } + + inline Result Client::Get(const std::string& path) { return cli_->Get(path); } + + inline Result Client::Get(const std::string& path, const Headers& headers) + { + return cli_->Get(path, headers); + } + + inline Result Client::Get(const std::string& path, Progress progress) + { + return cli_->Get(path, std::move(progress)); + } + + inline Result Client::Get(const std::string& path, const Headers& headers, + Progress progress) + { + return cli_->Get(path, headers, std::move(progress)); + } + + inline Result Client::Get(const std::string& path, + ContentReceiver content_receiver) + { + return cli_->Get(path, std::move(content_receiver)); + } + + inline Result Client::Get(const std::string& path, const Headers& headers, + ContentReceiver content_receiver) + { + return cli_->Get(path, headers, std::move(content_receiver)); + } + + inline Result Client::Get(const std::string& path, + ContentReceiver content_receiver, Progress progress) + { + return cli_->Get(path, std::move(content_receiver), std::move(progress)); + } + + inline Result Client::Get(const std::string& path, const Headers& headers, + ContentReceiver content_receiver, Progress progress) + { + return cli_->Get(path, headers, std::move(content_receiver), + std::move(progress)); + } + + inline Result Client::Get(const std::string& path, + ResponseHandler response_handler, + ContentReceiver content_receiver) + { + return cli_->Get(path, std::move(response_handler), + std::move(content_receiver)); + } + + inline Result Client::Get(const std::string& path, const Headers& headers, + ResponseHandler response_handler, + ContentReceiver content_receiver) + { + return cli_->Get(path, headers, std::move(response_handler), + std::move(content_receiver)); + } + + inline Result Client::Get(const std::string& path, + ResponseHandler response_handler, + ContentReceiver content_receiver, Progress progress) + { + return cli_->Get(path, std::move(response_handler), + std::move(content_receiver), std::move(progress)); + } + + inline Result Client::Get(const std::string& path, const Headers& headers, + ResponseHandler response_handler, + ContentReceiver content_receiver, Progress progress) + { + return cli_->Get(path, headers, std::move(response_handler), + std::move(content_receiver), std::move(progress)); + } + + inline Result Client::Get(const std::string& path, const Params& params, + const Headers& headers, Progress progress) + { + return cli_->Get(path, params, headers, std::move(progress)); + } + + inline Result Client::Get(const std::string& path, const Params& params, + const Headers& headers, + ContentReceiver content_receiver, Progress progress) + { + return cli_->Get(path, params, headers, std::move(content_receiver), + std::move(progress)); + } + + inline Result Client::Get(const std::string& path, const Params& params, + const Headers& headers, + ResponseHandler response_handler, + ContentReceiver content_receiver, Progress progress) + { + return cli_->Get(path, params, headers, std::move(response_handler), + std::move(content_receiver), std::move(progress)); + } + + inline Result Client::Head(const std::string& path) { return cli_->Head(path); } + + inline Result Client::Head(const std::string& path, const Headers& headers) + { + return cli_->Head(path, headers); + } + + inline Result Client::Post(const std::string& path) { return cli_->Post(path); } + + inline Result Client::Post(const std::string& path, const Headers& headers) + { + return cli_->Post(path, headers); + } + + inline Result Client::Post(const std::string& path, const char* body, + size_t content_length, + const std::string& content_type) + { + return cli_->Post(path, body, content_length, content_type); + } + + inline Result Client::Post(const std::string& path, const Headers& headers, + const char* body, size_t content_length, + const std::string& content_type) + { + return cli_->Post(path, headers, body, content_length, content_type); + } + + inline Result Client::Post(const std::string& path, const Headers& headers, + const char* body, size_t content_length, + const std::string& content_type, Progress progress) + { + return cli_->Post(path, headers, body, content_length, content_type, + progress); + } + + inline Result Client::Post(const std::string& path, const std::string& body, + const std::string& content_type) + { + return cli_->Post(path, body, content_type); + } + + inline Result Client::Post(const std::string& path, const std::string& body, + const std::string& content_type, Progress progress) + { + return cli_->Post(path, body, content_type, progress); + } + + inline Result Client::Post(const std::string& path, const Headers& headers, + const std::string& body, + const std::string& content_type) + { + return cli_->Post(path, headers, body, content_type); + } + + inline Result Client::Post(const std::string& path, const Headers& headers, + const std::string& body, + const std::string& content_type, Progress progress) + { + return cli_->Post(path, headers, body, content_type, progress); + } + + inline Result Client::Post(const std::string& path, size_t content_length, + ContentProvider content_provider, + const std::string& content_type) + { + return cli_->Post(path, content_length, std::move(content_provider), + content_type); + } + + inline Result Client::Post(const std::string& path, + ContentProviderWithoutLength content_provider, + const std::string& content_type) + { + return cli_->Post(path, std::move(content_provider), content_type); + } + + inline Result Client::Post(const std::string& path, const Headers& headers, + size_t content_length, + ContentProvider content_provider, + const std::string& content_type) + { + return cli_->Post(path, headers, content_length, std::move(content_provider), + content_type); + } + + inline Result Client::Post(const std::string& path, const Headers& headers, + ContentProviderWithoutLength content_provider, + const std::string& content_type) + { + return cli_->Post(path, headers, std::move(content_provider), content_type); + } + + inline Result Client::Post(const std::string& path, const Params& params) + { + return cli_->Post(path, params); + } + + inline Result Client::Post(const std::string& path, const Headers& headers, + const Params& params) + { + return cli_->Post(path, headers, params); + } + + inline Result Client::Post(const std::string& path, const Headers& headers, + const Params& params, Progress progress) + { + return cli_->Post(path, headers, params, progress); + } + + inline Result Client::Post(const std::string& path, + const MultipartFormDataItems& items) + { + return cli_->Post(path, items); + } + + inline Result Client::Post(const std::string& path, const Headers& headers, + const MultipartFormDataItems& items) + { + return cli_->Post(path, headers, items); + } + + inline Result Client::Post(const std::string& path, const Headers& headers, + const MultipartFormDataItems& items, + const std::string& boundary) + { + return cli_->Post(path, headers, items, boundary); + } + + inline Result + Client::Post(const std::string& path, const Headers& headers, + const MultipartFormDataItems& items, + const MultipartFormDataProviderItems& provider_items) + { + return cli_->Post(path, headers, items, provider_items); + } + + inline Result Client::Put(const std::string& path) { return cli_->Put(path); } + + inline Result Client::Put(const std::string& path, const char* body, + size_t content_length, + const std::string& content_type) + { + return cli_->Put(path, body, content_length, content_type); + } + + inline Result Client::Put(const std::string& path, const Headers& headers, + const char* body, size_t content_length, + const std::string& content_type) + { + return cli_->Put(path, headers, body, content_length, content_type); + } + + inline Result Client::Put(const std::string& path, const Headers& headers, + const char* body, size_t content_length, + const std::string& content_type, Progress progress) + { + return cli_->Put(path, headers, body, content_length, content_type, progress); + } + + inline Result Client::Put(const std::string& path, const std::string& body, + const std::string& content_type) + { + return cli_->Put(path, body, content_type); + } + + inline Result Client::Put(const std::string& path, const std::string& body, + const std::string& content_type, Progress progress) + { + return cli_->Put(path, body, content_type, progress); + } + + inline Result Client::Put(const std::string& path, const Headers& headers, + const std::string& body, + const std::string& content_type) + { + return cli_->Put(path, headers, body, content_type); + } + + inline Result Client::Put(const std::string& path, const Headers& headers, + const std::string& body, + const std::string& content_type, Progress progress) + { + return cli_->Put(path, headers, body, content_type, progress); + } + + inline Result Client::Put(const std::string& path, size_t content_length, + ContentProvider content_provider, + const std::string& content_type) + { + return cli_->Put(path, content_length, std::move(content_provider), + content_type); + } + + inline Result Client::Put(const std::string& path, + ContentProviderWithoutLength content_provider, + const std::string& content_type) + { + return cli_->Put(path, std::move(content_provider), content_type); + } + + inline Result Client::Put(const std::string& path, const Headers& headers, + size_t content_length, + ContentProvider content_provider, + const std::string& content_type) + { + return cli_->Put(path, headers, content_length, std::move(content_provider), + content_type); + } + + inline Result Client::Put(const std::string& path, const Headers& headers, + ContentProviderWithoutLength content_provider, + const std::string& content_type) + { + return cli_->Put(path, headers, std::move(content_provider), content_type); + } + + inline Result Client::Put(const std::string& path, const Params& params) + { + return cli_->Put(path, params); + } + + inline Result Client::Put(const std::string& path, const Headers& headers, + const Params& params) + { + return cli_->Put(path, headers, params); + } + + inline Result Client::Put(const std::string& path, const Headers& headers, + const Params& params, Progress progress) + { + return cli_->Put(path, headers, params, progress); + } + + inline Result Client::Put(const std::string& path, + const MultipartFormDataItems& items) + { + return cli_->Put(path, items); + } + + inline Result Client::Put(const std::string& path, const Headers& headers, + const MultipartFormDataItems& items) + { + return cli_->Put(path, headers, items); + } + + inline Result Client::Put(const std::string& path, const Headers& headers, + const MultipartFormDataItems& items, + const std::string& boundary) + { + return cli_->Put(path, headers, items, boundary); + } + + inline Result + Client::Put(const std::string& path, const Headers& headers, + const MultipartFormDataItems& items, + const MultipartFormDataProviderItems& provider_items) + { + return cli_->Put(path, headers, items, provider_items); + } + + inline Result Client::Patch(const std::string& path) + { + return cli_->Patch(path); + } + + inline Result Client::Patch(const std::string& path, const char* body, + size_t content_length, + const std::string& content_type) + { + return cli_->Patch(path, body, content_length, content_type); + } + + inline Result Client::Patch(const std::string& path, const char* body, + size_t content_length, + const std::string& content_type, + Progress progress) + { + return cli_->Patch(path, body, content_length, content_type, progress); + } + + inline Result Client::Patch(const std::string& path, const Headers& headers, + const char* body, size_t content_length, + const std::string& content_type) + { + return cli_->Patch(path, headers, body, content_length, content_type); + } + + inline Result Client::Patch(const std::string& path, const Headers& headers, + const char* body, size_t content_length, + const std::string& content_type, + Progress progress) + { + return cli_->Patch(path, headers, body, content_length, content_type, + progress); + } + + inline Result Client::Patch(const std::string& path, const std::string& body, + const std::string& content_type) + { + return cli_->Patch(path, body, content_type); + } + + inline Result Client::Patch(const std::string& path, const std::string& body, + const std::string& content_type, + Progress progress) + { + return cli_->Patch(path, body, content_type, progress); + } + + inline Result Client::Patch(const std::string& path, const Headers& headers, + const std::string& body, + const std::string& content_type) + { + return cli_->Patch(path, headers, body, content_type); + } + + inline Result Client::Patch(const std::string& path, const Headers& headers, + const std::string& body, + const std::string& content_type, + Progress progress) + { + return cli_->Patch(path, headers, body, content_type, progress); + } + + inline Result Client::Patch(const std::string& path, size_t content_length, + ContentProvider content_provider, + const std::string& content_type) + { + return cli_->Patch(path, content_length, std::move(content_provider), + content_type); + } + + inline Result Client::Patch(const std::string& path, + ContentProviderWithoutLength content_provider, + const std::string& content_type) + { + return cli_->Patch(path, std::move(content_provider), content_type); + } + + inline Result Client::Patch(const std::string& path, const Headers& headers, + size_t content_length, + ContentProvider content_provider, + const std::string& content_type) + { + return cli_->Patch(path, headers, content_length, std::move(content_provider), + content_type); + } + + inline Result Client::Patch(const std::string& path, const Headers& headers, + ContentProviderWithoutLength content_provider, + const std::string& content_type) + { + return cli_->Patch(path, headers, std::move(content_provider), content_type); + } + + inline Result Client::Delete(const std::string& path) + { + return cli_->Delete(path); + } + + inline Result Client::Delete(const std::string& path, const Headers& headers) + { + return cli_->Delete(path, headers); + } + + inline Result Client::Delete(const std::string& path, const char* body, + size_t content_length, + const std::string& content_type) + { + return cli_->Delete(path, body, content_length, content_type); + } + + inline Result Client::Delete(const std::string& path, const char* body, + size_t content_length, + const std::string& content_type, + Progress progress) + { + return cli_->Delete(path, body, content_length, content_type, progress); + } + + inline Result Client::Delete(const std::string& path, const Headers& headers, + const char* body, size_t content_length, + const std::string& content_type) + { + return cli_->Delete(path, headers, body, content_length, content_type); + } + + inline Result Client::Delete(const std::string& path, const Headers& headers, + const char* body, size_t content_length, + const std::string& content_type, + Progress progress) + { + return cli_->Delete(path, headers, body, content_length, content_type, + progress); + } + + inline Result Client::Delete(const std::string& path, const std::string& body, + const std::string& content_type) + { + return cli_->Delete(path, body, content_type); + } + + inline Result Client::Delete(const std::string& path, const std::string& body, + const std::string& content_type, + Progress progress) + { + return cli_->Delete(path, body, content_type, progress); + } + + inline Result Client::Delete(const std::string& path, const Headers& headers, + const std::string& body, + const std::string& content_type) + { + return cli_->Delete(path, headers, body, content_type); + } + + inline Result Client::Delete(const std::string& path, const Headers& headers, + const std::string& body, + const std::string& content_type, + Progress progress) + { + return cli_->Delete(path, headers, body, content_type, progress); + } + + inline Result Client::Options(const std::string& path) + { + return cli_->Options(path); + } + + inline Result Client::Options(const std::string& path, const Headers& headers) + { + return cli_->Options(path, headers); + } + + inline bool Client::send(Request& req, Response& res, Error& error) + { + return cli_->send(req, res, error); + } + + inline Result Client::send(const Request& req) { return cli_->send(req); } + + inline void Client::stop() { cli_->stop(); } + + inline std::string Client::host() const { return cli_->host(); } + + inline int Client::port() const { return cli_->port(); } + + inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); } + + inline socket_t Client::socket() const { return cli_->socket(); } + + inline void + Client::set_hostname_addr_map(std::map addr_map) + { + cli_->set_hostname_addr_map(std::move(addr_map)); + } + + inline void Client::set_default_headers(Headers headers) + { + cli_->set_default_headers(std::move(headers)); + } + + inline void Client::set_header_writer( + std::function const& writer) + { + cli_->set_header_writer(writer); + } + + inline void Client::set_address_family(int family) + { + cli_->set_address_family(family); + } + + inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); } + + inline void Client::set_socket_options(SocketOptions socket_options) + { + cli_->set_socket_options(std::move(socket_options)); + } + + inline void Client::set_connection_timeout(time_t sec, time_t usec) + { + cli_->set_connection_timeout(sec, usec); + } + + inline void Client::set_read_timeout(time_t sec, time_t usec) + { + cli_->set_read_timeout(sec, usec); + } + + inline void Client::set_write_timeout(time_t sec, time_t usec) + { + cli_->set_write_timeout(sec, usec); + } + + inline void Client::set_basic_auth(const std::string& username, + const std::string& password) + { + cli_->set_basic_auth(username, password); + } + + inline void Client::set_bearer_token_auth(const std::string& token) + { + cli_->set_bearer_token_auth(token); + } +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT +inline void Client::set_digest_auth(const std::string &username, + const std::string &password) { + cli_->set_digest_auth(username, password); +} +#endif + + inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); } + + inline void Client::set_follow_location(bool on) + { + cli_->set_follow_location(on); + } + + inline void Client::set_url_encode(bool on) { cli_->set_url_encode(on); } + + inline void Client::set_compress(bool on) { cli_->set_compress(on); } + + inline void Client::set_decompress(bool on) { cli_->set_decompress(on); } + + inline void Client::set_interface(const std::string& intf) + { + cli_->set_interface(intf); + } + + inline void Client::set_proxy(const std::string& host, int port) + { + cli_->set_proxy(host, port); + } + + inline void Client::set_proxy_basic_auth(const std::string& username, + const std::string& password) + { + cli_->set_proxy_basic_auth(username, password); + } + + inline void Client::set_proxy_bearer_token_auth(const std::string& token) + { + cli_->set_proxy_bearer_token_auth(token); + } +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT +inline void Client::set_proxy_digest_auth(const std::string &username, + const std::string &password) { + cli_->set_proxy_digest_auth(username, password); +} +#endif + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT +inline void Client::enable_server_certificate_verification(bool enabled) { + cli_->enable_server_certificate_verification(enabled); +} + +inline void Client::enable_server_hostname_verification(bool enabled) { + cli_->enable_server_hostname_verification(enabled); +} + +inline void Client::set_server_certificate_verifier( + std::function verifier) { + cli_->set_server_certificate_verifier(verifier); +} +#endif + + inline void Client::set_logger(Logger logger) + { + cli_->set_logger(std::move(logger)); + } + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT +inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path, + const std::string &ca_cert_dir_path) { + cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path); +} + +inline void Client::set_ca_cert_store(X509_STORE *ca_cert_store) { + if (is_ssl_) { + static_cast(*cli_).set_ca_cert_store(ca_cert_store); + } else { + cli_->set_ca_cert_store(ca_cert_store); + } +} + +inline void Client::load_ca_cert_store(const char *ca_cert, std::size_t size) { + set_ca_cert_store(cli_->create_ca_cert_store(ca_cert, size)); +} + +inline long Client::get_openssl_verify_result() const { + if (is_ssl_) { + return static_cast(*cli_).get_openssl_verify_result(); + } + return -1; // NOTE: -1 doesn't match any of X509_V_ERR_??? +} + +inline SSL_CTX *Client::ssl_context() const { + if (is_ssl_) { return static_cast(*cli_).ssl_context(); } + return nullptr; +} +#endif + + // ---------------------------------------------------------------------------- +} // namespace httplib + +#if defined(_WIN32) && defined(CPPHTTPLIB_USE_POLL) +#undef poll +#endif + +#endif // CPPHTTPLIB_HTTPLIB_H diff --git a/module/Radarcape_Core/main.cpp b/module/Radarcape_Core/main.cpp new file mode 100644 index 0000000..64ab62b --- /dev/null +++ b/module/Radarcape_Core/main.cpp @@ -0,0 +1,9 @@ +#include "../../../../core_library/Core/Core/ThreadManager.h" +#include "Core/JSON.h" +#ifdef _build_exe +// int main(){ +// return 0; +// } + +#endif + diff --git a/module/Radarcape_Core/todo b/module/Radarcape_Core/todo new file mode 100644 index 0000000..daefad2 --- /dev/null +++ b/module/Radarcape_Core/todo @@ -0,0 +1,9 @@ + + + + +写接受格式 接受从 radar cape 传来的数据 +比对和 radarcape 数据的差异 + + + diff --git a/module/crc_check.cpp b/module/crc_check.cpp new file mode 100644 index 0000000..714956b --- /dev/null +++ b/module/crc_check.cpp @@ -0,0 +1,240 @@ +#include "Local_Server/Data_Source/Data_Source.h" + +#include "SSR/export.h" +#include +#include +#include +using namespace Psc; +int max_distance = 700; +namespace fs = std::filesystem; +class MY_File_Data_Source : public File_Data_Source { +public: + BaseLogger* logger{}; + void pre_handle(const std::string& data) override {} + void handle_mode_s(std::string& packet) override {} + size_t line_num = 0; + size_t line_num_ex = 0; + std::map air_map; + MY_File_Data_Source(const fs::path& file_path, const fs::path& rel_path) { + auto u8_string = rel_path.u8string(); + std::string t(u8_string.begin(), u8_string.end()); + auto ttt = file_path.u8string(); + std::string fp(ttt.begin(), ttt.end()); + key = fp; + std::replace(key.begin(), key.end(), '/', '_'); + std::replace(key.begin(), key.end(), '\\', '_'); + auto path = get_exe_dir() + "/crc_check/" + t; + this->logger = new BaseLogger(path, 100 * 100 * 10000, 1); + this->key = key; + this->data_type = File_Data_Type::BIN_Blank_One_Line_With_Escape; + this->file_path = fp; + this->play_mode = Play_Mode::analysis; + this->open(); + } + + + void handle() { + std::string buffer; + auto mode_data = read(); + while (!mode_data.empty()) { + line_num_ex++; + Binary_Format_handle_buffer(buffer, mode_data, [&](std::string& packet) { + + if (packet[0] != 0x1a) { + std::cout << "first:" << mem2hex(packet) << std::endl; + return; + } + std::string error_len = key + " " + LOG_POS_SIMPLE + " mode_s_error_length"; + auto type = packet[1]; + if (type == Msg::AC) { + if (packet.size() != Msg::AC_len) { + logger->c_debug(error_len, {}, + std::to_string(type) + " size:" + std::to_string(packet.size()) + " hex:" + + mem2hex(packet) + " should:" + std::to_string(Msg::AC_len)); + return; + } + } else if (type == Msg::S7) { + if (packet.size() != Mode_S_Msg::S7_len) { + logger->c_debug(error_len, {}, + std::to_string(type) + " size:" + std::to_string(packet.size()) + " hex:" + + mem2hex(packet) + " should:" + std::to_string(Msg::S7_len)); + return; + } + } else if (type == Msg::S14) { + if (packet.size() != Msg::S14_len) { + logger->c_debug(error_len, {}, + std::to_string(type) + " size:" + std::to_string(packet.size()) + " hex:" + + mem2hex(packet) + " should:" + std::to_string(Msg::S14_len)); + return; + } + } else if (type == Msg::Radarcape_status) { + return; // 这个报文不会解析 + if (packet.size() != Msg::Radarcape_status_len) { + logger->c_debug(error_len, {}, + std::to_string(type) + " size:" + std::to_string(packet.size()) + " hex:" + + mem2hex(packet) + " should:" + std::to_string(Msg::Radarcape_status_len)); + return; + } + } else if (type == Msg::HULC_Status) { + if (packet.size() != Msg::HULC_len) { + logger->c_debug(error_len, {}, + std::to_string(type) + " HULC size:" + std::to_string(packet.size()) + " hex:" + + mem2hex(packet)); + return; + } + } else { + // std::cout << "unknown_type:" << mem2hex(packet); + rotating_log("unknown_type", mem2hex(packet)); + return; + } + bool mode_s = type == Msg::S7 || type == Msg::S14; + + if (mode_s) { + line_num++; + auto msg = std::make_shared(shared_from_this(), packet); + std::optional base_station_pos; + Mode_S::parse_mode_s_bin(this, msg, base_station_pos); + } + }); + mode_data = read(); + } + this->close(); + std::cout << "line_num: " << line_num << std::endl; + std::cout << "line_num_ex: " << line_num_ex << std::endl; + } +}; + +// "C:/wyc/CLionProjects/plantSunCat/mainProjects/Radarcape/data/pos/110.txt" +void handle(const fs::path& file_path, const fs::path& rel_path) { + auto fs = std::make_shared(file_path, rel_path); + + + Mode_S::parse_ok_json = [&](Aircraft_Info* aircraft_info, Mode_S::P_S mode_s_msg, Psc::JSON json) { + + Log_Type lt({}, { + {"line:", std::to_string( fs->line_num) }, + {"df", to_string((int)(mode_s_msg->df))}, + {"icao", mode_s_msg->icao}, + // {"icao_size", std::to_string(mode_s_msg->icao.size())}, + {"hex", mode_s_msg->msg_hex}, + + //{"packet", mem2hex(mode_s_msg->packet)}, + {"packet22222222222", mem2hex(packet_to_escape_format(mode_s_msg->packet), true, " ")}, + }); + + + + // fs->logger->debug("", lt, "crc ok"); + }; + + Mode_S::parse_call_back = [&](Mode_S::Parse_Call_Back_Type type, + Aircraft_Info* aircraft_info, + const std::string& field_name_or_error_info, + std::vector bds_list, + void* cur_parser, Mode_S::P_S mode_s_msg + ) { + + if (type == Mode_S::Parse_Call_Back_Type::Normal_Block) return; + + // Log_Type lt({}, { + // {"line", std::to_string( fs->line_num) }, + // {"type", to_string(type) }, + // {"icao", mode_s_msg->icao}, + // {"hex", mode_s_msg->msg_hex}, + // {"df", to_string((int)(mode_s_msg->df))}, + // {"df", to_string(type)}, + // {"packet", mem2hex(mode_s_msg->packet)} + // }); + + auto c1 = crc_hex(mode_s_msg->msg_bin, true); + // auto c2 = crc_hex(mode_s_msg->msg_bin, false); + + + Log_Type lt({}, { + // {"line:", std::to_string( fs->line_num) }, + // {"df", to_string((int)(mode_s_msg->df))}, + // {"icao", mode_s_msg->icao}, + // {"icao_size", std::to_string(mode_s_msg->icao.size())}, + // {"hex", "\"" + mode_s_msg->msg_hex + "\","}, + + + {"data", mem2hex(packet_to_escape_format(mode_s_msg->packet), true, " ")}, + + {"hex", mode_s_msg->msg_hex }, + {"c1", c1}, + + //{"packet", mem2hex(mode_s_msg->packet)}, + }); + if (type == Mode_S::Parse_Call_Back_Type::CRC_Error) { + if (mode_s_msg->df == Downlink_Format::Extended_Squitter_17) { + auto tc = type_code(mode_s_msg->msg_bin); + lt.set("tc", std::to_string(tc)); + } + + + fs->logger->debug("", lt, ""); + } + + }; + fs->handle(); +} + +void list_directory(const fs::path& dir_path, const fs::path& base_path) { + for (const auto& entry : fs::directory_iterator(dir_path)) { + fs::path file_path = entry.path(); + auto relative_path = fs::relative(file_path, base_path); // 计算相对路径 + if (fs::is_directory(entry.status())) { + list_directory(file_path, base_path); // 递归遍历子目录 + } else { + std::cout << "Full path: " << (const char*)file_path.u8string().c_str() << std::endl; // 输出完整路径 + std::cout << "Relative path: " << (const char*)relative_path.u8string().c_str() << std::endl; // 输出相对路径 + handle(file_path, relative_path); + } + } +} +std::wstring _transformString2Wstring(const std::string& s) { + setlocale(LC_CTYPE, "en_US.UTF-8"); + const char* _Source = s.c_str(); + size_t len = strlen(_Source) + 1; + size_t converted = 0; + wchar_t* wStr = new wchar_t[len]; + mbstowcs_s(&converted, wStr, len, _Source, _TRUNCATE); + std::wstring result(wStr); + delete[] wStr; + return result; +} +std::wstring gbk_to_wstring(const std::string& gbk) { + int len = MultiByteToWideChar(CP_ACP, 0, gbk.c_str(), -1, nullptr, 0); + std::wstring wstr(len, L'\0'); + MultiByteToWideChar(CP_ACP, 0, gbk.c_str(), -1, &wstr[0], len); + // 去掉末尾'\0' + if (!wstr.empty() && wstr.back() == L'\0') wstr.pop_back(); + return wstr; +} +int main(int argc, char* argv[]) { + // 检查命令行参数是否提供了目录路径 + if (argc < 2) { + std::cerr << "Usage: " << argv[0] << " " << std::endl; + return 1; + } + set_console_utf8(); + Base_Logger_Manager::instance().init(); + auto path = Psc::get_exe_dir() + "/crc_check/mode_s.log"; + + + + mode_s_logger = new BaseLogger(path, 100 * 100 * 10000, 1); + std::string aaa = argv[1]; + std::u8string dp((char8_t*)platform_2_utf8(aaa).data()); + auto dir_path = std::filesystem::path(dp); + if (!fs::exists(dir_path)) { + std::cerr << "!fs::exists(pa)." << std::endl; + return 1; + } + if (!fs::is_directory(dir_path)) { + std::cerr << "!fs::is_directory(pa)." << std::endl; + return 1; + } + list_directory(dir_path, dir_path); + return 0; +} diff --git a/module/dll_source/Dll_Global.cpp b/module/dll_source/Dll_Global.cpp new file mode 100644 index 0000000..bbdf5f5 --- /dev/null +++ b/module/dll_source/Dll_Global.cpp @@ -0,0 +1,266 @@ +#include "Dll_Global.h" + +#include "../../../../core_library/Core/Core/Base/JSON.h" +#include "Core/Base/SM_RingBuffer.h" + +Dll_Global *dg = new Dll_Global(); + +std::string Dll_Global::get_config_path() { return get_exe_dir() + "/" + "data_progress_config.json"; } + +void Dll_Global::init_when_exe() { + rb = new SM_RingBuffer; + rb->init("rb", 2112 * 1000); + json_func_call = new SM_RingBuffer; + json_func_call->init("json_func_call2", 1000); + mode_acs = new SM_RingBuffer; + mode_acs->init("mode_acs", 2112 * 1000); + + + void* lib; + { + auto r = try_load_library(Psc::get_abs_path(library_path)); + if (!r) { + Psc::fail_fast(); + } + lib = r.value(); + } + + { + auto r = Psc::try_load_function(lib, "adsb_set_iq_cbk"); + if (!r) { + Psc::fail_fast(); + } + set_iq_cbk = (adsb_set_iq_cbk_t)r.value(); + } + { + auto r = Psc::try_load_function(lib, "adsb_set_less_30Mhz_ddc_param"); + if (!r) { + Psc::fail_fast(); + } + set_less_30Mhz_ddc_param = (adsb_set_less_30Mhz_ddc_param_t)r.value(); + } + { + auto r = Psc::try_load_function(lib, "adsb_set_less_30Mhz_fft_param"); + if (!r) { + Psc::fail_fast(); + } + set_less_30Mhz_fft_param = (adsb_set_less_30Mhz_fft_param_t)r.value(); + } + + + + std::cout << "set_less_30Mhz_ddc_param " << VAR_STR_3(center_freq, sample_rate, band_width) << std::endl; + set_less_30Mhz_ddc_param(center_freq, sample_rate, band_width, 1); + std::cout << "set_less_30Mhz_fft_param " << VAR_STR_3(center_freq, sample_rate, band_width) << std::endl; + set_less_30Mhz_fft_param(fft_win_type, fft_point_number, fft_period_ms, 1); + std::cout << "set_iq_cbk " << std::endl; + set_iq_cbk( + [](void *phandle, void *pdata, uint64_t length) { + if (length != 2112) { + std::cout << LOG_POS << " IQ回调传入的长度不对!" << std::endl; + return; + } + auto dg = (Dll_Global *) phandle; + // + dg->handle_2112(pdata); + + // auto sk = (UHD_Struct_KFFT *) pdata; + // std::cout << (int)sk->DataType << std::endl; + + //dg->iq_memory_buffer.push(pdata, length); // length 永远等于2112 + }, + this); +} +void Dll_Global::init_when_dll() { + + Detach_Thread_Manager &manager = dtm; + + manager.test_and_start_thread("Dll_Global", [&](std::atomic& run) { + std::mt19937 rng(std::random_device{}()); // 随机数引擎 + std::uniform_int_distribution dist(0 * 256, 70 * 256); + constexpr int size = 64 + 1024 * sizeof(uint16_t); + uint8_t buf[size]; + + while (run) { + int fn = fft_point_number / 1024; + auto sk = (UHD_Struct_KFFT *) buf; + + + uint16_t *fft = (uint16_t *) (buf + 64); + for (int fi = 0; fi < fn; fi++) { + sk->DataType = kd_fft; + sk->Param.FFT.SubFrame = fi; + for (int i = 0; i < 1024; ++i) { + fft[i] = dist(rng); + } + give_call_back(buf, size); + } + + + + uint64_t sleep_ms = fft_period_ms; + uint64_t num = sample_rate / sleep_ms; + uint64_t times = num / 2048; + if (times < 1) { + times = 1; + } + + sk->DataType = zd_ddc; + uint16_t *iq = (uint16_t *) (buf + 64); + for (int i = 0; i < 1024; ++i) { + auto random = dist(rng); + iq[i] = random; + } + + sk->UsefullLen = 2048; + for (int i = 0; i < times; ++i) { + give_call_back(buf, size); + } + std::this_thread::sleep_for(std::chrono::milliseconds(fft_period_ms)); + } + }); + +} + +Dll_Global::Dll_Global() { + auto config = try_parse_json_file(get_config_path()); + if (!config.has_value()) { + std::cout << "Dll_Global 配置文件加载失败!" << std::endl; + Psc::fail_fast(); + } + load(&config.value()); + psm = new std::uint8_t[65536 * 2]; +} + +Dll_Global::~Dll_Global() { + + + delete psm; + + + +} + + +void adsb_close() { + std::cout << " adsb_close()" << std::endl; + Dll_Global::instance()->dtm.stop_all_thread(); + +} + + + +void Dll_Global::save() { + std::ofstream config_file; + config_file.open(get_config_path()); + std::string json = to_json().to_json_string(); + config_file.write(json.c_str(), static_cast(json.size())); + config_file.close(); +} + +void Dll_Global::give_call_back(std::uint8_t *data, size_t len) { + recv_cbk(puser, data, len); + auto sk = (UHD_Struct_KFFT *) data; + if (sk->DataType == kd_fft) { + auto idx_max = fft_point_number/1024; + auto idx = sk->Param.FFT.SubFrame; + if (idx >= idx_max) { + std::cout << "give_call_back idx 越界" << idx << " >= " << idx_max << std::endl; + } + } + +} + +void Dll_Global::handle_2112_test(void *data) { + // 记录开始时间 + auto start = std::chrono::high_resolution_clock::now(); + + // 调用目标函数 + handle_2112_pure(data); + + // 记录结束时间 + auto end = std::chrono::high_resolution_clock::now(); + + // 计算持续时间(微秒) + auto duration = std::chrono::duration_cast(end - start); + + // 输出每次调用的时间 + std::cout << "Average time per call: " + << duration.count() << " microseconds" << std::endl; +} + +void Dll_Global::handle_2112(void *data) { + handle_2112_pure(data); + // static Frequency_Limit fl(freq); + // if (fl.test()) { + // handle_2112_test(data); + // } else { + // handle_2112_pure(data); + // } +} + +void Dll_Global::handle_2112_pure(void *data) { + auto d = (UHD_Struct_KFFT *) (data); + auto pdata = (std::uint8_t*)data + 64; + auto idx_max = fft_point_number/1024; + auto type = d->DataType; + if (type == kd_fft) { + auto idx = d->Param.FFT.SubFrame; + if (idx >= idx_max) { + std::cout << "idx 越界" << idx << " >= " << idx_max << std::endl; + } else { + memcpy( psm + idx * 2048, pdata, 2048); + } + } +#if WIN32 + else if (type == kd_ddc || type == zd_ddc) { + dg->rb->write((uint8_t *) data, 2112); + } else { + Psc::fail_fast(); + } +#else + else { + dg->rb->write((uint8_t *) data, 2112); + } +#endif + +} + + +void Dll_Global::handle_json_call() { + size_t length = 0; + uint8_t json_func_data[1000]; + json_func_call->read(json_func_data, length); + + + std::string json((const char *) json_func_data, length); + if (!json.empty()) { + auto func_call = Psc::parse_json(json); + auto method = func_call.get_string("method"); + std::cout << func_call.to_json_string() << std::endl; + + if (method == "adsb_set_less_30Mhz_ddc_param") { + center_freq = func_call.get_number("center_freq"); + sample_rate = func_call.get_number("sample_rate"); + band_width = func_call.get_number("band_width"); + auto sw = func_call.get_number("sw"); + save(); + set_less_30Mhz_ddc_param(center_freq, sample_rate, band_width, sw); + } + + if (method == "adsb_set_less_30Mhz_fft_param") { + fft_win_type = (UHD_FFTWin) func_call.get_number("fft_win_type"); + fft_point_number = func_call.get_number("fft_point_number"); + fft_period_ms = func_call.get_number("fft_period_ms"); + auto sw = func_call.get_number("sw"); + save(); + set_less_30Mhz_fft_param(fft_win_type, fft_point_number, fft_period_ms, sw); + } + + if (method == "restart_device") { + std::cout << "关闭进程, 然后会被守护进程拉起来" << std::endl; + stop_program = true; + } + } +} +void set_error_cbk(error_cbk_t cbk) {} diff --git a/module/dll_source/Dll_Global.h b/module/dll_source/Dll_Global.h new file mode 100644 index 0000000..7ac42a3 --- /dev/null +++ b/module/dll_source/Dll_Global.h @@ -0,0 +1,94 @@ +#ifndef PLANTSUNCAT_DLL_GLOBAL_H +#define PLANTSUNCAT_DLL_GLOBAL_H +#include "main.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "Core/Base/global_include.h" +#include "Core/Shared_Memory/Shared_Memory.h" +#include "Core/system/export.h" +#include "../Local_Server/DSP/global.h" +#include "Core/Base/JSON.h" +#include "Core/Base/ThreadManager.h" +#include "Core/spdlog/export.h" + +namespace Psc { +class SM_RingBuffer; +} +using namespace Psc; + + +struct Memory_Buffer { + std::vector get_all() { + std::lock_guard lock(m); + std::swap(cache, data_list); + return data_list; + } + void push(void *pdata, uint64_t length) { + auto buf = pool.get(); + buf->resize(length); + std::memcpy(buf->data(), pdata, length); + { + std::lock_guard lock(m); + cache.push_back(buf); + } + } + String_Pool pool = String_Pool(2112, 8 * 1024); +protected: + std::vector data; + std::vector cache; + std::vector data_list; + Psc::Spin_Lock m; +}; + +struct BB : Base_DSP { + BB() { + + } +}; +#define freq 0.1 + +struct Dll_Global : BB, public Singleton{ + SM_RingBuffer *rb{}; + SM_RingBuffer *json_func_call{}; + SM_RingBuffer *mode_acs{}; + // Pure_Share_Memory psm = Pure_Share_Memory("fft_data", 65536); + std::uint8_t* psm; + + Memory_Buffer iq_memory_buffer; + Detach_Thread_Manager dtm; + adsb_set_iq_cbk_t set_iq_cbk; + adsb_set_less_30Mhz_ddc_param_t set_less_30Mhz_ddc_param; + adsb_set_less_30Mhz_fft_param_t set_less_30Mhz_fft_param; + static std::string get_config_path(); + void init_when_exe(); + void init_when_dll(); + Dll_Global(); + ~Dll_Global(); + + void save(); + void handle_json_call(); + iq_cbk_t recv_cbk{}; + void *puser{}; + void give_call_back(std::uint8_t* data, size_t len); + + void handle_2112(void* data); + void handle_2112_pure(void* data); + + void handle_2112_test(void* data); +}; + + + + +#endif diff --git a/module/dll_source/device_uhd_c.h b/module/dll_source/device_uhd_c.h new file mode 100644 index 0000000..8c3d2ff --- /dev/null +++ b/module/dll_source/device_uhd_c.h @@ -0,0 +1,98 @@ +#ifndef _DEVICE_UHD_C_H_ +#define _DEVICE_UHD_C_H_ + + +#include "device_uhd_struct.h" +// #include "device_uhd_cpp.h" +#include + + + + + +typedef void (*rx_data_cbk_t)(int channel, void *pdata, int length); + +extern "C" +{ + int32_t ex_declare init9002(void **phandle); + int32_t ex_declare free9002(void **phandle); + int32_t ex_declare isDevOpened(void *phandle, int32_t *result); + // int32_t ex_declare findDevices(void *phandle, uhd::device_addrs_t *addrs); + // int32_t ex_declare openDevice(void *phandle,uhd::device_addr_t addr); + int32_t ex_declare closeDevice(void *phandle); + int32_t ex_declare findDevInfos(void *phandle, char infos[1000]); + int32_t ex_declare findDevInfos2(void *phandle, char infos[1000]); + int32_t ex_declare getDevTree(void *phandle, char tree_infos[1000]); + int32_t ex_declare setDevClockSource(void *phandle, char sourceStr[1000]); + int32_t ex_declare getDevClockSource(void *phandle, char sourceStr[1000]); + int32_t ex_declare setDevInClock(void *phandle, double clockFreq); + int32_t ex_declare getDevInClockRange(void *phandle, double *min, double *max); + int32_t ex_declare getDevInClock(void *phandle, double *val); + int32_t ex_declare getDevRXChCount(void *phandle, size_t *val); + int32_t ex_declare getDevTXChCount(void *phandle, size_t *val); + int32_t ex_declare setDevParam(void *phandle, char chStr[50], UHD_ParamType paramType, double paramValue); + int32_t ex_declare getDevParam(void *phandle, char chStr[50], UHD_ParamType paramType,double *paramValue); + int32_t ex_declare getDevParamMin(void *phandle, double *val); + int32_t ex_declare getDevParamMax(void *phandle, double *val); + int32_t ex_declare setAllAntenna(void *phandle, int32_t *result); + int32_t ex_declare setDevDDCParam_Any(void *phandle, char chStr[50], unsigned int jcqOffset, unsigned int jcqData); + int32_t ex_declare getDevDDCParam_Any(void *phandle, char chStr[50], unsigned int jcqOffset, unsigned int *jcqData); + int32_t ex_declare setDevDataSwitch(void *phandle, char chStr[50], UHD_ParamType dataType, unsigned char ZDCh, int bSwitch); + int32_t ex_declare getDevDataSwitch(void *phandle, char chStr[50], UHD_ParamType dataType, unsigned char ZDCh, int *bSwitch); + int32_t ex_declare setDevZDParam(void *phandle, char chStr[50], unsigned char ZDCh, long long centerfreq, int bw, int sample); + int32_t ex_declare getDevZDParam(void *phandle, char chStr[50], unsigned char ZDCh, long long *centerfreq, int *bw, int *sample); + int32_t ex_declare getDevZDCenterRange(void *phandle, char chStr[50], long long &min, long long &max); + int32_t ex_declare getDevZDBandWidthRange(void *phandle, char chStr[50], int &min, int &max); + int32_t ex_declare getDevZDSampleFreqRange(void *phandle, char chStr[50], int arr[13], int *valid_len); + int32_t ex_declare setDevFFTParam(void *phandle, UHD_FFTWin fftWin, UHD_FFTLen fftLen, int fftPeriod_ms); + int32_t ex_declare getDevFFTParam(void *phandle, UHD_FFTWin *fftWin, UHD_FFTLen *fftLen, int *fftPeriod_ms); + int32_t ex_declare getDevRecvSpeed(void *phandle, int channel, double *val); + int32_t ex_declare isDevRecving(void *phandle,int channel, int32_t *result); + int32_t ex_declare startDevRecv(void *phandle, int channel, rx_data_cbk_t rx_cbk); + int32_t ex_declare stopDevRecv(void *phandle, int channel); + int32_t ex_declare getDevSendSpeed(void *phandle, int channel, double *val); + int32_t ex_declare isDevSending(void *phandle, int channel, int32_t *rusult); + int32_t ex_declare startDevSend(void *phandle, int channel, unsigned long long send_cf, unsigned long long data_sf, char *filename, int bwhile); + int32_t ex_declare stopDevSend(void *phandle, int channel); + int32_t ex_declare getGPSInfo(void *phandle, char gps_info[50]); + int32_t ex_declare setLedEnable(void *phandle, int led_num, int bEnable); + int32_t ex_declare getLedEnable(void *phandle,int led_num, int *bEnable); + + + + + typedef void(*adsb_msg_cbk_t)(void *pusr,char *pmsg,int msglen); + + int32_t ex_declare init_adsb9002(void **phandle,adsb_msg_cbk_t cbk,void *pusr); + int32_t ex_declare free_adsb9002(void **phandle); + + + + // 新接口 :时间 20251107 , + //TODO: 1 增加 dma 回调函数 iq 的(ddc,ffc) +} + +#include +#include "device_uhd_c.h" +#include +#include + + +extern "C" +{ + + + ex_declare void adsb_close(); + + typedef void (*iq_cbk_t)(void* phandle, void* pdata, uint64_t length); + + typedef int (*adsb_set_less_30Mhz_ddc_param_t)(uint64_t cf_hz, uint64_t sf_hz, uint64_t bw_hz, int8_t sw); + typedef int (*adsb_set_less_30Mhz_fft_param_t)(uint64_t fftWin, uint64_t fftLen, int fftPeriod_ms, int8_t sw); + ex_declare int adsb_set_iq_cbk(iq_cbk_t recv_cbk, void* pusr); + ex_declare int adsb_set_less_30Mhz_ddc_param(uint64_t cf_hz, uint64_t sf_hz, uint64_t bw_hz, int8_t sw); + ex_declare int adsb_set_less_30Mhz_fft_param(uint64_t fftWin, uint64_t fftLen, int fftPeriod_ms, int8_t sw); + +} + + +#endif //_DEVICE_UHD_C_H_ \ No newline at end of file diff --git a/module/dll_source/device_uhd_struct.h b/module/dll_source/device_uhd_struct.h new file mode 100644 index 0000000..c5da56f --- /dev/null +++ b/module/dll_source/device_uhd_struct.h @@ -0,0 +1,259 @@ +#ifndef device_uhd_struct_h +#define device_uhd_struct_h + +#include +#include +#include + + +#define ZDSamSum 200000000//8路窄带采样率之和 +#define ZDChMax 8 //每路大通道下窄带通道总数 +enum UHD_ParamType : int +{ + CenterFreq = 0, + BandWidth = 1, + SampleFreq = 2, + Gain = 3, + PowerRef = 4, + KDDCSwitch = 5, + KFFTSwitch = 6, + ZDDCSwitch = 7, + ZDDCParam = 8, + KFFTParam = 9, + ClockSource = 10, + SnapshotSwitch = 11, + Snapshot_tm_s = 12, +}; +enum UHD_FFTWin : unsigned char +{ + jxc =0,// 矩形窗 = 0, + hnc = 1,// 汉宁窗 = 1, + hmc = 2, // 海明窗 = 2, + blkmc = 3,// 布莱克曼窗 = 3, +}; +enum UHD_FFTLen : unsigned int +{ + _1024 = 1024, + _2048 = 2048, + _4096 = 4096, + _8192 = 8192, + _16384 = 16384, + _32768 = 32768, +}; +#pragma pack(push) +#pragma pack(1) +struct UHD_ZDParam +{ + unsigned char KCH = 0;//宽带通道号 + unsigned short ZCH = 0;//窄带通道号 + long long CenterFreq = 0; // 中频 + int BandWidth = 0; //带宽 + int SampleFreq = 0; // 采样率 + int ExtraPer = 1024;//抽取率 4-4096,2的指数 + bool bSwitch_ZDDC = false; + +}; +struct UHD_KDParam +{ + unsigned char KCH = 0;//宽带通道号 + long long CenterFreq = 10000000; + + int BandWidth = 160000000; + int SampleFreq = 200000000; + + bool bSwitch_6GCH = false; + + bool bSwitch_KDDC = false; + bool bSwitch_KFFT = false; + double gain = 0; + UHD_ZDParam ZDParam[ZDChMax]; + int ExtraPer; + bool Snapshot_Switch=false; + int Snapshot_tm_s = 0; + + unsigned long long old_sf; + unsigned long long old_cf; + unsigned long long old_bw; + +}; +#pragma region 枚举/结构体 + +/** @brief TODO: 时码类型枚举 + * @enum LibWZ57_Enum_TimeType + */ +enum Enum_TimeType : uint8_t +{ + Enum_TimeType_Invlid = 0, /**< 无效的*/ + Enum_TimeType_IRIG_B = 1, /**< IRIG-B*/ + Enum_TimeType_RMC = 2, /**< RMC*/ + Enum_TimeType_ABSCNTTM = 3, /**< 绝对计数时间*/ + Enum_TimeType_REFCNTTM = 4, /**< 相对计数时间*/ +}; +typedef struct struct_DateTime +{ + + Enum_TimeType TimeType; /**< 10 时码类型*/ + + /** @brief 10个字节的时码信息 + * @details + * 根据 @ref LibWZ57_Enum_TimeType TimeType,对应不同的 联合体 + */ + union TimeInfo + { + ///@brief IRIG-B + ///@struct IRIGB_Head + struct IRIGB_Head + { + uint8_t Year; /**< 年 字节1*/ + uint16_t Day; /**< 日 字节2*/ + uint8_t Hour; /**< 时 字节1*/ + uint8_t Minute; /**< 分 字节1*/ + uint8_t Second; /**< 秒 字节1*/ + uint32_t NanoSec; /**< 纳 字节4*/ + } IRIGB_Head; + + ///@brief RMC + ///@struct RMC_Head + struct RMC_Head + { + uint8_t Year; /**< 年 字节1*/ + uint8_t Month; /**< 月 字节1*/ + uint8_t Day; /**< 日 字节1*/ + uint8_t Hour; /**< 时 字节1*/ + uint8_t Minute; /**< 分 字节1*/ + uint8_t Second; /**< 秒 字节1*/ + uint32_t NanoSec; /**< 纳 字节4*/ + } RMC_Head; + + ///@brief 绝对计数时间 + ///@struct ABSCNTTM_Head + struct ABSCNTTM_Head + { + ///@brief 秒 字节6; 基准秒计数时间+相对秒计数时间 单位:秒 + uint8_t Second[6]; + ///@brief 纳秒 字节4; + uint32_t NanoSec; + } ABSCNTTM_Head; + + ///@brief 相对计数时间 + ///@struct REFCNTTM_Head + struct REFCNTTM_Head + { + ///@brief 秒 字节6; 相对秒计数时间单位:秒 + uint8_t Second[6]; + ///@brief 纳秒 字节4; + uint32_t NanoSec; + } REFCNTTM_Head; + } TimeInfo; + +} struct_DataTime; + + + +#pragma region 枚举 +/***************************** +*数据类型 +*****************************/ +enum UHD_Enum_DataType : unsigned char +{ + zd_ddc = 1, + kd_ddc = 2, + kd_fft = 3, + GPS_Info = 16, + // 窄带DDC = 0x01, + // 宽带DDC = 0x02, + // 宽带FFT = 0x03, +}; +#pragma endregion +#pragma region 结构体 +#pragma region UHD_Struct_KFFT UHD_Struct_KDDC UHD_Struct_ZDDC +/// +/// 宽带FFT头 +/// +typedef struct +{ + /// + /// 帧标识 6 0x2828F628F6F6 固定值 + /// + unsigned int Head; + /// + /// + /// + unsigned short Head2; + /// + /// 协议版本 1 0x80 + /// + unsigned char DealVersion; + /// + /// 帧头长度 1 64 + /// + unsigned char FrameHeadLen; + /// + /// 数据长度 2 2048 + /// + unsigned short DataLen; + /// + /// 有效数据长度 2 2048 + /// + unsigned short UsefullLen; + /// + /// 数据类型 1 + /// + UHD_Enum_DataType DataType; + unsigned char Other1; + /// + /// 通道号 + /// + unsigned char Channel; + unsigned char Other2; + unsigned short ZDChannel; + /// + /// 帧计数 2 0 ~ 65535 循环递增 + /// + unsigned short FrameIndex; + /// + /// 帧起止标识 1 0x0 + /// + unsigned char FrameBeginFlag; + struct_DateTime DateTm; + /// + /// 采样率 4 单位Hz + /// + unsigned int SampleFreq_Hz; + /// + /// 带宽 4 单位Hz + /// + unsigned int BandWidth_Hz; + /// + /// 中心频点 4 单位Hz,低位 + /// + unsigned int CenterFreq_Hz_Low; + /// + /// 中心频点 2 单位Hz,高位 + /// + unsigned short CenterFreq_Hz_High; + union + { + unsigned char other5[18]; + struct + { + unsigned char other4[6]; + /// + /// FFT长度 65536 + /// + int FFTPoint; + unsigned char other5[2]; + float other6; + /// + /// 段内帧号 + /// + unsigned short SubFrame; + } FFT; + } Param; + //数据 2048 共1024个数据,1个数据2字节。 +} UHD_Struct_KFFT, UHD_Struct_KDDC, UHD_Struct_ZDDC; +#pragma endregion +#pragma endregion +#pragma pack(pop) +#pragma endregion +#endif diff --git a/module/dll_source/error_callback.h b/module/dll_source/error_callback.h new file mode 100644 index 0000000..5deac4d --- /dev/null +++ b/module/dll_source/error_callback.h @@ -0,0 +1,19 @@ +#ifndef __ERROR_CALLBACK_H__ +#define __ERROR_CALLBACK_H__ + +extern "C" { + typedef void (*error_cbk_t)(const char *file_name ,const char *func_name,const char *err_msg); + extern error_cbk_t g_error_callback; + + ex_declare void error_callback_call( const char *file_name ,const char *func_name,const char *err_msg); + ex_declare const char *extract_filename_in_cbk(const char *full_path); + + + ex_declare void set_error_cbk(error_cbk_t cbk); + #define MACROS_ERROR_CBK_CALL(msg) error_callback_call(__FILE__,__func__,msg) + + + typedef int (*set_error_cbk_t)(error_cbk_t cbk); +} + +#endif // __ERROR_CALLBACK_H__ diff --git a/module/dll_source/main.cpp b/module/dll_source/main.cpp new file mode 100644 index 0000000..2409921 --- /dev/null +++ b/module/dll_source/main.cpp @@ -0,0 +1,207 @@ +#include "main.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "Core/Base/JSON.h" +#include "Core/Base/ThreadManager.h" +#include "Core/Base/global_include.h" +#include "Core/Shared_Memory/Shared_Memory.h" +#include "Core/system/export.h" +#include "Core/spdlog/export.h" + +#include "Core/Base/SM_RingBuffer.h" +#include "Dll_Global.h" + + +std::vector ddd = { + "1A 33 1A 1A F1 DA 08 2A 73 60 8D 78 12 0A EA 28 88 64 25 3C 08 33 22 41", + "1A 33 1A 1A F1 D9 13 EA E7 11 8D 78 1D 40 58 BF 41 E2 45 49 09 7B C8 24", + "1A 33 1A 1A F1 DA 08 2A 73 60 8D 78 12 0A EA 28 88 64 25 3C 08 33 22 41", + "1A 33 1A 1A F1 DA D4 35 F9 69 A0 00 15 BC C2 9E 14 F0 A8 00 00 DE E7 37", + "1A 33 1A 1A F1 DB 45 5D 1C 68 A0 00 15 BC FF DD 11 2B 60 04 DB 2F 06 E2", + "1A 33 1A 1A F1 DD 0F 74 3E 20 A0 00 15 BC EE 0A 13 30 20 37 FF A9 CE DC", + "1A 33 1A 1A F1 DD 50 97 59 30 8D 78 00 6C E1 1F 2E 00 00 00 00 09 43 55", + "1A 33 1A 1A F1 DD 73 6B 25 2B 8D 78 16 2D F8 33 00 06 00 49 B8 CF B0 D7", + "1A 33 1A 1A F1 DD F1 C2 C2 1D A0 00 15 BC 10 03 0A 80 ED 00 00 98 54 C8", + "1A 33 1A 1A F1 DE 62 E9 B6 2A A0 00 15 BC 10 03 0A 80 ED 00 00 98 54 C8", + "1A 33 1A 1A F1 DE B4 E1 1E 23 8D 79 A0 53 EA 3E C8 66 57 3C 08 71 74 65", + "1A 33 1A 1A F1 DF 17 8E 3F 5D 8D 78 00 6C 58 63 44 5B 32 CB 60 C5 DD 2E", + "1A 33 1A 1A F1 DF 3E 49 FD 76 A0 00 0E 3E A8 7A 23 26 E1 0C 22 4E D9 88", + "1A 33 1A 1A F1 DF AF 71 5F 6C A0 00 0E 3E A8 7A 23 26 E1 0C 22 4E D9 88", + "1A 33 1A 1A F1 E2 0A DD 76 2A A0 00 11 B1 B5 E8 00 30 AA 00 00 D5 D0 A3", +}; + + +std::string get_absb() { + static size_t index = 0; // 静态变量用于保存当前读取位置 + index++; + if (index == ddd.size()) { + index = 0; + } + return ddd[index]; +} + +class TextLineReader { +public: + explicit TextLineReader(const std::string& file_path) { + load(file_path); + } + + // 每调用一次,返回一行 + // 返回 true 表示成功取到一行 + // 返回 false 表示已经没有更多行 + bool get(std::string& ret_line) { + if (index_ >= lines_.size()) { + return false; + } + + ret_line = lines_[index_]; + ++index_; + return true; + } + + // 重新从第一行开始读 + void reset() { + index_ = 0; + } + + // 总行数 + std::size_t size() const { + return lines_.size(); + } + + // 是否已经读完 + bool empty() const { + return lines_.empty(); + } + +private: + void load(const std::string& file_path) { + std::ifstream file(file_path); + if (!file.is_open()) { + throw std::runtime_error("Failed to open file: " + file_path); + } + + std::string line; + while (std::getline(file, line)) { + lines_.push_back(line); + } + + index_ = 0; + } + +private: + std::vector lines_; + std::size_t index_ = 0; +}; + + + + +std::size_t adsb_read(char *buf, std::size_t len) { + + + static TextLineReader reader(get_exe_dir() + "/ADS-B_195_0205.txt"); + std::string line; + reader.get(line); + auto l = line.size(); + std::memcpy(buf, line.c_str(), l); + return l; +} + +int adsb_set_iq_cbk(iq_cbk_t recv_cbk, void *pusr) { + auto dg = Dll_Global::instance(); + dg->recv_cbk = recv_cbk; + dg->puser = pusr; + + + + dg->init_when_dll(); + return 0; +} +int adsb_set_less_30Mhz_ddc_param(uint64_t cf_hz, uint64_t sf_hz, uint64_t bw_hz, int8_t sw) { + auto dg = Dll_Global::instance(); + dg->center_freq = cf_hz; + dg->sample_rate = sf_hz; // 设置采样率 + dg->band_width = bw_hz; + return 0; +} +int adsb_set_less_30Mhz_fft_param(uint64_t fftWin, uint64_t fftLen, int fftPeriod_ms, int8_t sw) { + auto dg = Dll_Global::instance(); + dg->fft_point_number = fftLen; + dg->fft_period_ms = fftPeriod_ms; + dg->fft_win_type = (UHD_FFTWin)fftWin; + return 0; +} + + + + + +int main() { + init_signal_config(); + auto dg = Dll_Global::instance(); + + + dg->init_when_exe(); + bool debug = false; + + auto mb = get_system_memory()/(1024*1024); + auto gb = mb/(1024); + std::cout << "当前系统的物理内存大小" << mb << " MB" << std::endl; + std::cout << "当前系统的物理内存大小" << gb << " GB" << std::endl; + + dg->dtm.test_and_start_thread("dsp共享内存数据推送", [dg](std::atomic & running) { + bool debug = true; + while (running) { + auto list = dg->iq_memory_buffer.get_all(); + // 释放内存池 + Pool_Guard pg(&dg->iq_memory_buffer.pool, list); + + if (debug && list.size() > 1000) { + static Frequency_Limit fl(1.0/60.0); + std::ostringstream oss; + oss << get_current_millisecond_timestamp() << " 警告: dsp共享内存数据推送数据过多 当前数据队列长度:" << list.size() << std::endl; + if (fl.test()) { + std::cout << oss.str() << std::endl; + } + } + if (list.empty()) { + std::this_thread::sleep_for(std::chrono::microseconds(1)); + continue; + } + auto frame_number = list.size(); + static Frequency_Limit fl(freq); + if (fl.test()) { + + std::cout << dg->rb->state_str() << " dsp数据推送" << frame_number << "条" << std::endl; + } + + for (int i = 0; i < frame_number; i++) { + auto buf = list[i]; + dg->handle_2112(buf->data()); + } + } + }); + while (!stop_program) { + dg->handle_json_call(); + + } + if (stop_program == SIGINT) { + std::cout << "开始关闭所有子线程!" << std::endl; + + } + return 0; +} + + diff --git a/module/dll_source/main.h b/module/dll_source/main.h new file mode 100644 index 0000000..119a31b --- /dev/null +++ b/module/dll_source/main.h @@ -0,0 +1,50 @@ +#pragma once + +#define MY_LIBRARY_EXPORTS +#ifdef _WIN32 // Windows 平台 +#ifdef MY_LIBRARY_EXPORTS // 如果正在构建库 +#define ex_declare __declspec(dllexport) // 导出符号 +#else +#define ex_declare __declspec(dllimport) // 导入符号 +#endif +#else // 对于 Linux 和其他 Unix-like 系统 +#define ex_declare __attribute__((visibility("default"))) // 导出符号 +#endif +#include +#include "./error_callback.h" +#include "./device_uhd_c.h" + +extern "C" { + ex_declare void adsb_close(); + ex_declare std::size_t adsb_read(char* buf, std::size_t len); + + // IQ 数据接口 + typedef void (*iq_cbk_t)(void* phandle, void* pdata, uint64_t length); + typedef int (*adsb_set_iq_cbk_t)(iq_cbk_t recv_cbk, void* pusr); + typedef int (*adsb_set_less_30Mhz_ddc_param_t)(uint64_t cf_hz, uint64_t sf_hz, uint64_t bw_hz, int8_t sw); + typedef int (*adsb_set_less_30Mhz_fft_param_t)(uint64_t fftWin, uint64_t fftLen, int fftPeriod_ms, int8_t sw); + ex_declare int adsb_set_iq_cbk(iq_cbk_t recv_cbk, void* pusr); + ex_declare int adsb_set_less_30Mhz_ddc_param(uint64_t cf_hz, uint64_t sf_hz, uint64_t bw_hz, int8_t sw); + ex_declare int adsb_set_less_30Mhz_fft_param(uint64_t fftWin, uint64_t fftLen, int fftPeriod_ms, int8_t sw); + + + + + int32_t ex_declare init_adsb9002(void **phandle, adsb_msg_cbk_t cbk, void *pusr); + int32_t ex_declare free_adsb9002(void **phandle); + int ex_declare set_iq_cbk(void *phandle, iq_cbk_t recv_cbk, void *pusr); + int ex_declare set_less_30Mhz_ddc_param(void *phandle, uint64_t cf_hz, uint64_t sf_hz, uint64_t bw_hz, int8_t sw); + int ex_declare set_less_30Mhz_fft_param(void *phandle, int fftWin, int fftLen, int fftPeriod_ms, int8_t sw); + + + + + + + using init_adsb9002_ptr_t = int32_t (*)(void **phandle, adsb_msg_cbk_t cbk, void *pusr); + using free_adsb9002_ptr_t = int32_t (*)(void **phandle); + using set_iq_cbk_ptr_t = int (*)(void *phandle, iq_cbk_t recv_cbk, void *pusr); + using set_less_30Mhz_ddc_param_ptr_t = int (*)(void *phandle, uint64_t cf_hz, uint64_t sf_hz, uint64_t bw_hz, int8_t sw); + using set_less_30Mhz_fft_param_ptr_t = int (*)(void *phandle, int fftWin, int fftLen, int fftPeriod_ms, int8_t sw); +} + diff --git a/module/dll_source_lzy/114/out.tar b/module/dll_source_lzy/114/out.tar new file mode 100644 index 0000000..b05f3ea Binary files /dev/null and b/module/dll_source_lzy/114/out.tar differ diff --git a/module/dll_source_lzy/114/out/lib/.device_uhd_c.cpp.swp b/module/dll_source_lzy/114/out/lib/.device_uhd_c.cpp.swp new file mode 100644 index 0000000..c2b24d4 Binary files /dev/null and b/module/dll_source_lzy/114/out/lib/.device_uhd_c.cpp.swp differ diff --git a/module/dll_source_lzy/114/out/lib/.idea/.gitignore b/module/dll_source_lzy/114/out/lib/.idea/.gitignore new file mode 100644 index 0000000..35410ca --- /dev/null +++ b/module/dll_source_lzy/114/out/lib/.idea/.gitignore @@ -0,0 +1,8 @@ +# 默认忽略的文件 +/shelf/ +/workspace.xml +# 基于编辑器的 HTTP 客户端请求 +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/module/dll_source_lzy/114/out/lib/.idea/deployment.xml b/module/dll_source_lzy/114/out/lib/.idea/deployment.xml new file mode 100644 index 0000000..d88a5d7 --- /dev/null +++ b/module/dll_source_lzy/114/out/lib/.idea/deployment.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/module/dll_source_lzy/114/out/lib/.idea/editor.xml b/module/dll_source_lzy/114/out/lib/.idea/editor.xml new file mode 100644 index 0000000..9a0064f --- /dev/null +++ b/module/dll_source_lzy/114/out/lib/.idea/editor.xml @@ -0,0 +1,335 @@ + + + + + \ No newline at end of file diff --git a/module/dll_source_lzy/114/out/lib/.idea/lib.iml b/module/dll_source_lzy/114/out/lib/.idea/lib.iml new file mode 100644 index 0000000..bc2cd87 --- /dev/null +++ b/module/dll_source_lzy/114/out/lib/.idea/lib.iml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/module/dll_source_lzy/114/out/lib/.idea/misc.xml b/module/dll_source_lzy/114/out/lib/.idea/misc.xml new file mode 100644 index 0000000..369389b --- /dev/null +++ b/module/dll_source_lzy/114/out/lib/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/module/dll_source_lzy/114/out/lib/.idea/modules.xml b/module/dll_source_lzy/114/out/lib/.idea/modules.xml new file mode 100644 index 0000000..b0c4ff6 --- /dev/null +++ b/module/dll_source_lzy/114/out/lib/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/module/dll_source_lzy/114/out/lib/DDCSampTable.h b/module/dll_source_lzy/114/out/lib/DDCSampTable.h new file mode 100644 index 0000000..264626e --- /dev/null +++ b/module/dll_source_lzy/114/out/lib/DDCSampTable.h @@ -0,0 +1,28 @@ +#ifndef DDCSAMPTABLE_H +#define DDCSAMPTABLE_H +#include +using namespace std; +// adsb +const double KDDCSampTab0[11][2] = {{24000000, 1}, {12000000, 2}, {6000000, 4}, {3000000, 8}, {1500000, 16}, {750000, 32}, {375000, 64}, {187500, 128}, {93750, 256}, {46875, 512}, {23437, 1024}}; +const string KDDCSampTabStr0[11] = {"24000000 ", "12000000 ", "6000000 ", "3000000 ", "1500000 ", "750000 ", "375000 ", "187500 ", "93750 ", "46875 ", "23437 "}; +const int KDDCSampIndxMin0 = 0; +const int KDDCSampIndxMax0 = 10; +const double define_KDDCSampleMax0 = 24000000; +const double X0 = 0.8; +const int ZDDCSampIndxMin0 = 0; +const int ZDDCSampIndxMax0 = 12; +const double ZDDCSampTab0[13] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; +const double TXSFTab0[11] = {24000000, 12000000, 6000000, 3000000, 1500000, 750000, 375000, 187500, 93750, 46875, 23437}; + +// less 30 mhz +const double KDDCSampTab1[11][2] = {{61440000, 1}, {30720000, 2}, {15360000, 4}, {7680000, 8}, {3840000, 16}, {1920000, 32}, {960000, 64}, {480000, 128}, {240000, 256}, {120000, 512}, {60000, 1024}}; +const string KDDCSampTabStr1[11] = {"61440000", "30720000", "15360000", "7680000", "3840000", "1920000", "960000", "480000", "240000", "120000", "60000"}; +const int KDDCSampIndxMin1 = 0; +const int KDDCSampIndxMax1 = 10; +const double define_KDDCSampleMax1 = 61440000; +const double X1 = 0.8; +const int ZDDCSampIndxMin1 = 0; +const int ZDDCSampIndxMax1 = 12; +const double ZDDCSampTab1[13] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; +const double TXSFTab1[11] = {61440000, 30720000, 15360000, 7680000, 3840000, 1920000, 960000, 480000, 240000, 120000, 60000}; +#endif // DDCSAMPTABLE_H diff --git a/module/dll_source_lzy/114/out/lib/FIRGenLowpass_no_ipp.h b/module/dll_source_lzy/114/out/lib/FIRGenLowpass_no_ipp.h new file mode 100644 index 0000000..717bd54 --- /dev/null +++ b/module/dll_source_lzy/114/out/lib/FIRGenLowpass_no_ipp.h @@ -0,0 +1,105 @@ +#ifndef _FIRGenLowpass_H_ +#define _FIRGenLowpass_H_ +// #include "ipp/ipps.h" +#include +#include +#define FIRGenLowpassLen 256 //滤波器长度 +#define FIRGenLowpassLen2 192 //滤波器长度 + double m_dFilterCoef[FIRGenLowpassLen]; //滤波器系数 +unsigned char m_dFilterBuff[FIRGenLowpassLen*2]; +#define PI (3.1415926) +#define POINT_SIZE (1024) +//int m_nFIRPnt; //????? +double m_dFIRCoef_ptr[POINT_SIZE]; //????? +float m_fFIRCoef_ptr[POINT_SIZE]; //????? +bool GenLowpass(double rFreq, double **coef, int point,float mult) +{ + if (NULL == *coef) + { + *coef =(double *) m_fFIRCoef_ptr; + } + int nFIRPnt0 = point - 1; + float fFIRPnt0D2 = nFIRPnt0 / 2.0f; + for (int i = 0; i < point; i++) + { + m_dFIRCoef_ptr[i] = 0.54 - 0.46 * cos((2 * PI * i) / nFIRPnt0); + } + double dTheta = 2 * PI * rFreq, dCoefSum = 0; + + for (int i = 0; i < point; i++) + { + if (fFIRPnt0D2 == i) + { + m_dFIRCoef_ptr[i] *= (dTheta / PI); + } + else + { + m_dFIRCoef_ptr[i] *= (sin((i - fFIRPnt0D2) * dTheta) / ((i - fFIRPnt0D2) * PI)); + } + dCoefSum += m_dFIRCoef_ptr[i]; + } + mult /= dCoefSum; + for(int i = 0; i < point; ++i) + { + (*coef)[i] = m_dFIRCoef_ptr[i] * mult; + } + return true; +} +/***************************** +*函数名:SetFIRLpCoef +*功能描述:设置滤波器参数 +*参数名称:coef 滤波器系数 + length 滤波器系数长度 + rate 带宽采样率之比 = 带宽 / 采样率 + bitLen 量化位宽 + mult 带宽放大系数 +*返回:成功有效滤波器长度, 失败返回0 +*****************************/ +int SetFIRLpCoef2(int *coef, int length, double rate, int bitLen, double mult = 1.0) +{ + int ret = 0; + if (NULL == coef) + { + return ret; + } + double* dFIRCoef = new double[length]; + std::fill(dFIRCoef, dFIRCoef + length, 0); + if (!GenLowpass(rate * 0.5 * mult, &dFIRCoef, length, (float ) pow(2.0, bitLen - 1) - 1)) + { + ret = 0; + } + if (bitLen <= 16) + { + for (int i = 0; i < length; ++i) { + if (dFIRCoef[i] >= 0) + { + ((short *)coef)[i] = (short)(dFIRCoef[i] + 0.5); + } + else + { + ((short *)coef)[i] = (short)(dFIRCoef[i] - 0.5); + } + } + ret = length / 2; + } + else + { + for (int i = 0; i < length; ++i) { + if (dFIRCoef[i] >= 0) + { + coef[i] = (int)(dFIRCoef[i] + 0.5); + } + else + { + coef[i] = (int)(dFIRCoef[i] - 0.5); + } + } + ret = length; + } + if (dFIRCoef != nullptr) + { + delete[] dFIRCoef; + } + return ret; +} +#endif //_FIRGenLowpass_H_ diff --git a/module/dll_source_lzy/114/out/lib/a.dat b/module/dll_source_lzy/114/out/lib/a.dat new file mode 100644 index 0000000..e69de29 diff --git a/module/dll_source_lzy/114/out/lib/cJSON.c b/module/dll_source_lzy/114/out/lib/cJSON.c new file mode 100644 index 0000000..d7c7236 --- /dev/null +++ b/module/dll_source_lzy/114/out/lib/cJSON.c @@ -0,0 +1,3164 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +/* cJSON */ +/* JSON parser in C. */ + +/* disable warnings about old C89 functions in MSVC */ +#if !defined(_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) +#define _CRT_SECURE_NO_DEPRECATE +#endif + +#ifdef __GNUC__ +#pragma GCC visibility push(default) +#endif +#if defined(_MSC_VER) +#pragma warning (push) +/* disable warning about single line comments in system headers */ +#pragma warning (disable : 4001) +#endif + +#include +#include +#include +#include +#include +#include +#include + +#ifdef ENABLE_LOCALES +#include +#endif + +#if defined(_MSC_VER) +#pragma warning (pop) +#endif +#ifdef __GNUC__ +#pragma GCC visibility pop +#endif + +#include "cJSON.h" + +/* define our own boolean type */ +#ifdef true +#undef true +#endif +#define true ((cJSON_bool)1) + +#ifdef false +#undef false +#endif +#define false ((cJSON_bool)0) + +/* define isnan and isinf for ANSI C, if in C99 or above, isnan and isinf has been defined in math.h */ +#ifndef isinf +#define isinf(d) (isnan((d - d)) && !isnan(d)) +#endif +#ifndef isnan +#define isnan(d) (d != d) +#endif + +#ifndef NAN +#ifdef _WIN32 +#define NAN sqrt(-1.0) +#else +#define NAN 0.0/0.0 +#endif +#endif + +typedef struct { + const unsigned char *json; + size_t position; +} error; +static error global_error = { NULL, 0 }; + +CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void) +{ + return (const char*) (global_error.json + global_error.position); +} + +CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item) +{ + if (!cJSON_IsString(item)) + { + return NULL; + } + + return item->valuestring; +} + +CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item) +{ + if (!cJSON_IsNumber(item)) + { + return (double) NAN; + } + + return item->valuedouble; +} + +/* This is a safeguard to prevent copy-pasters from using incompatible C and header files */ +#if (CJSON_VERSION_MAJOR != 1) || (CJSON_VERSION_MINOR != 7) || (CJSON_VERSION_PATCH != 18) + #error cJSON.h and cJSON.c have different versions. Make sure that both have the same. +#endif + +CJSON_PUBLIC(const char*) cJSON_Version(void) +{ + static char version[15]; + sprintf(version, "%i.%i.%i", CJSON_VERSION_MAJOR, CJSON_VERSION_MINOR, CJSON_VERSION_PATCH); + + return version; +} + +/* Case insensitive string comparison, doesn't consider two NULL pointers equal though */ +static int case_insensitive_strcmp(const unsigned char *string1, const unsigned char *string2) +{ + if ((string1 == NULL) || (string2 == NULL)) + { + return 1; + } + + if (string1 == string2) + { + return 0; + } + + for(; tolower(*string1) == tolower(*string2); (void)string1++, string2++) + { + if (*string1 == '\0') + { + return 0; + } + } + + return tolower(*string1) - tolower(*string2); +} + +typedef struct internal_hooks +{ + void *(CJSON_CDECL *allocate)(size_t size); + void (CJSON_CDECL *deallocate)(void *pointer); + void *(CJSON_CDECL *reallocate)(void *pointer, size_t size); +} internal_hooks; + +#if defined(_MSC_VER) +/* work around MSVC error C2322: '...' address of dllimport '...' is not static */ +static void * CJSON_CDECL internal_malloc(size_t size) +{ + return malloc(size); +} +static void CJSON_CDECL internal_free(void *pointer) +{ + free(pointer); +} +static void * CJSON_CDECL internal_realloc(void *pointer, size_t size) +{ + return realloc(pointer, size); +} +#else +#define internal_malloc malloc +#define internal_free free +#define internal_realloc realloc +#endif + +/* strlen of character literals resolved at compile time */ +#define static_strlen(string_literal) (sizeof(string_literal) - sizeof("")) + +static internal_hooks global_hooks = { internal_malloc, internal_free, internal_realloc }; + +static unsigned char* cJSON_strdup(const unsigned char* string, const internal_hooks * const hooks) +{ + size_t length = 0; + unsigned char *copy = NULL; + + if (string == NULL) + { + return NULL; + } + + length = strlen((const char*)string) + sizeof(""); + copy = (unsigned char*)hooks->allocate(length); + if (copy == NULL) + { + return NULL; + } + memcpy(copy, string, length); + + return copy; +} + +CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks) +{ + if (hooks == NULL) + { + /* Reset hooks */ + global_hooks.allocate = malloc; + global_hooks.deallocate = free; + global_hooks.reallocate = realloc; + return; + } + + global_hooks.allocate = malloc; + if (hooks->malloc_fn != NULL) + { + global_hooks.allocate = hooks->malloc_fn; + } + + global_hooks.deallocate = free; + if (hooks->free_fn != NULL) + { + global_hooks.deallocate = hooks->free_fn; + } + + /* use realloc only if both free and malloc are used */ + global_hooks.reallocate = NULL; + if ((global_hooks.allocate == malloc) && (global_hooks.deallocate == free)) + { + global_hooks.reallocate = realloc; + } +} + +/* Internal constructor. */ +static cJSON *cJSON_New_Item(const internal_hooks * const hooks) +{ + cJSON* node = (cJSON*)hooks->allocate(sizeof(cJSON)); + if (node) + { + memset(node, '\0', sizeof(cJSON)); + } + + return node; +} + +/* Delete a cJSON structure. */ +CJSON_PUBLIC(void) cJSON_Delete(cJSON *item) +{ + cJSON *next = NULL; + while (item != NULL) + { + next = item->next; + if (!(item->type & cJSON_IsReference) && (item->child != NULL)) + { + cJSON_Delete(item->child); + } + if (!(item->type & cJSON_IsReference) && (item->valuestring != NULL)) + { + global_hooks.deallocate(item->valuestring); + item->valuestring = NULL; + } + if (!(item->type & cJSON_StringIsConst) && (item->string != NULL)) + { + global_hooks.deallocate(item->string); + item->string = NULL; + } + global_hooks.deallocate(item); + item = next; + } +} + +/* get the decimal point character of the current locale */ +static unsigned char get_decimal_point(void) +{ +#ifdef ENABLE_LOCALES + struct lconv *lconv = localeconv(); + return (unsigned char) lconv->decimal_point[0]; +#else + return '.'; +#endif +} + +typedef struct +{ + const unsigned char *content; + size_t length; + size_t offset; + size_t depth; /* How deeply nested (in arrays/objects) is the input at the current offset. */ + internal_hooks hooks; +} parse_buffer; + +/* check if the given size is left to read in a given parse buffer (starting with 1) */ +#define can_read(buffer, size) ((buffer != NULL) && (((buffer)->offset + size) <= (buffer)->length)) +/* check if the buffer can be accessed at the given index (starting with 0) */ +#define can_access_at_index(buffer, index) ((buffer != NULL) && (((buffer)->offset + index) < (buffer)->length)) +#define cannot_access_at_index(buffer, index) (!can_access_at_index(buffer, index)) +/* get a pointer to the buffer at the position */ +#define buffer_at_offset(buffer) ((buffer)->content + (buffer)->offset) + +/* Parse the input text to generate a number, and populate the result into item. */ +static cJSON_bool parse_number(cJSON * const item, parse_buffer * const input_buffer) +{ + double number = 0; + unsigned char *after_end = NULL; + unsigned char number_c_string[64]; + unsigned char decimal_point = get_decimal_point(); + size_t i = 0; + + if ((input_buffer == NULL) || (input_buffer->content == NULL)) + { + return false; + } + + /* copy the number into a temporary buffer and replace '.' with the decimal point + * of the current locale (for strtod) + * This also takes care of '\0' not necessarily being available for marking the end of the input */ + for (i = 0; (i < (sizeof(number_c_string) - 1)) && can_access_at_index(input_buffer, i); i++) + { + switch (buffer_at_offset(input_buffer)[i]) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + case '+': + case '-': + case 'e': + case 'E': + number_c_string[i] = buffer_at_offset(input_buffer)[i]; + break; + + case '.': + number_c_string[i] = decimal_point; + break; + + default: + goto loop_end; + } + } +loop_end: + number_c_string[i] = '\0'; + + number = strtod((const char*)number_c_string, (char**)&after_end); + if (number_c_string == after_end) + { + return false; /* parse_error */ + } + + item->valuedouble = number; + + /* use saturation in case of overflow */ + if (number >= INT_MAX) + { + item->valueint = INT_MAX; + } + else if (number <= (double)INT_MIN) + { + item->valueint = INT_MIN; + } + else + { + item->valueint = (int)number; + } + + item->type = cJSON_Number; + + input_buffer->offset += (size_t)(after_end - number_c_string); + return true; +} + +/* don't ask me, but the original cJSON_SetNumberValue returns an integer or double */ +CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number) +{ + if (number >= INT_MAX) + { + object->valueint = INT_MAX; + } + else if (number <= (double)INT_MIN) + { + object->valueint = INT_MIN; + } + else + { + object->valueint = (int)number; + } + + return object->valuedouble = number; +} + +/* Note: when passing a NULL valuestring, cJSON_SetValuestring treats this as an error and return NULL */ +CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring) +{ + char *copy = NULL; + size_t v1_len; + size_t v2_len; + /* if object's type is not cJSON_String or is cJSON_IsReference, it should not set valuestring */ + if ((object == NULL) || !(object->type & cJSON_String) || (object->type & cJSON_IsReference)) + { + return NULL; + } + /* return NULL if the object is corrupted or valuestring is NULL */ + if (object->valuestring == NULL || valuestring == NULL) + { + return NULL; + } + + v1_len = strlen(valuestring); + v2_len = strlen(object->valuestring); + + if (v1_len <= v2_len) + { + /* strcpy does not handle overlapping string: [X1, X2] [Y1, Y2] => X2 < Y1 or Y2 < X1 */ + if (!( valuestring + v1_len < object->valuestring || object->valuestring + v2_len < valuestring )) + { + return NULL; + } + strcpy(object->valuestring, valuestring); + return object->valuestring; + } + copy = (char*) cJSON_strdup((const unsigned char*)valuestring, &global_hooks); + if (copy == NULL) + { + return NULL; + } + if (object->valuestring != NULL) + { + cJSON_free(object->valuestring); + } + object->valuestring = copy; + + return copy; +} + +typedef struct +{ + unsigned char *buffer; + size_t length; + size_t offset; + size_t depth; /* current nesting depth (for formatted printing) */ + cJSON_bool noalloc; + cJSON_bool format; /* is this print a formatted print */ + internal_hooks hooks; +} printbuffer; + +/* realloc printbuffer if necessary to have at least "needed" bytes more */ +static unsigned char* ensure(printbuffer * const p, size_t needed) +{ + unsigned char *newbuffer = NULL; + size_t newsize = 0; + + if ((p == NULL) || (p->buffer == NULL)) + { + return NULL; + } + + if ((p->length > 0) && (p->offset >= p->length)) + { + /* make sure that offset is valid */ + return NULL; + } + + if (needed > INT_MAX) + { + /* sizes bigger than INT_MAX are currently not supported */ + return NULL; + } + + needed += p->offset + 1; + if (needed <= p->length) + { + return p->buffer + p->offset; + } + + if (p->noalloc) { + return NULL; + } + + /* calculate new buffer size */ + if (needed > (INT_MAX / 2)) + { + /* overflow of int, use INT_MAX if possible */ + if (needed <= INT_MAX) + { + newsize = INT_MAX; + } + else + { + return NULL; + } + } + else + { + newsize = needed * 2; + } + + if (p->hooks.reallocate != NULL) + { + /* reallocate with realloc if available */ + newbuffer = (unsigned char*)p->hooks.reallocate(p->buffer, newsize); + if (newbuffer == NULL) + { + p->hooks.deallocate(p->buffer); + p->length = 0; + p->buffer = NULL; + + return NULL; + } + } + else + { + /* otherwise reallocate manually */ + newbuffer = (unsigned char*)p->hooks.allocate(newsize); + if (!newbuffer) + { + p->hooks.deallocate(p->buffer); + p->length = 0; + p->buffer = NULL; + + return NULL; + } + + memcpy(newbuffer, p->buffer, p->offset + 1); + p->hooks.deallocate(p->buffer); + } + p->length = newsize; + p->buffer = newbuffer; + + return newbuffer + p->offset; +} + +/* calculate the new length of the string in a printbuffer and update the offset */ +static void update_offset(printbuffer * const buffer) +{ + const unsigned char *buffer_pointer = NULL; + if ((buffer == NULL) || (buffer->buffer == NULL)) + { + return; + } + buffer_pointer = buffer->buffer + buffer->offset; + + buffer->offset += strlen((const char*)buffer_pointer); +} + +/* securely comparison of floating-point variables */ +static cJSON_bool compare_double(double a, double b) +{ + double maxVal = fabs(a) > fabs(b) ? fabs(a) : fabs(b); + return (fabs(a - b) <= maxVal * DBL_EPSILON); +} + +/* Render the number nicely from the given item into a string. */ +static cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output_pointer = NULL; + double d = item->valuedouble; + int length = 0; + size_t i = 0; + unsigned char number_buffer[26] = {0}; /* temporary buffer to print the number into */ + unsigned char decimal_point = get_decimal_point(); + double test = 0.0; + + if (output_buffer == NULL) + { + return false; + } + + /* This checks for NaN and Infinity */ + if (isnan(d) || isinf(d)) + { + length = sprintf((char*)number_buffer, "null"); + } + else if(d == (double)item->valueint) + { + length = sprintf((char*)number_buffer, "%d", item->valueint); + } + else + { + /* Try 15 decimal places of precision to avoid nonsignificant nonzero digits */ + length = sprintf((char*)number_buffer, "%1.15g", d); + + /* Check whether the original double can be recovered */ + if ((sscanf((char*)number_buffer, "%lg", &test) != 1) || !compare_double((double)test, d)) + { + /* If not, print with 17 decimal places of precision */ + length = sprintf((char*)number_buffer, "%1.17g", d); + } + } + + /* sprintf failed or buffer overrun occurred */ + if ((length < 0) || (length > (int)(sizeof(number_buffer) - 1))) + { + return false; + } + + /* reserve appropriate space in the output */ + output_pointer = ensure(output_buffer, (size_t)length + sizeof("")); + if (output_pointer == NULL) + { + return false; + } + + /* copy the printed number to the output and replace locale + * dependent decimal point with '.' */ + for (i = 0; i < ((size_t)length); i++) + { + if (number_buffer[i] == decimal_point) + { + output_pointer[i] = '.'; + continue; + } + + output_pointer[i] = number_buffer[i]; + } + output_pointer[i] = '\0'; + + output_buffer->offset += (size_t)length; + + return true; +} + +/* parse 4 digit hexadecimal number */ +static unsigned parse_hex4(const unsigned char * const input) +{ + unsigned int h = 0; + size_t i = 0; + + for (i = 0; i < 4; i++) + { + /* parse digit */ + if ((input[i] >= '0') && (input[i] <= '9')) + { + h += (unsigned int) input[i] - '0'; + } + else if ((input[i] >= 'A') && (input[i] <= 'F')) + { + h += (unsigned int) 10 + input[i] - 'A'; + } + else if ((input[i] >= 'a') && (input[i] <= 'f')) + { + h += (unsigned int) 10 + input[i] - 'a'; + } + else /* invalid */ + { + return 0; + } + + if (i < 3) + { + /* shift left to make place for the next nibble */ + h = h << 4; + } + } + + return h; +} + +/* converts a UTF-16 literal to UTF-8 + * A literal can be one or two sequences of the form \uXXXX */ +static unsigned char utf16_literal_to_utf8(const unsigned char * const input_pointer, const unsigned char * const input_end, unsigned char **output_pointer) +{ + long unsigned int codepoint = 0; + unsigned int first_code = 0; + const unsigned char *first_sequence = input_pointer; + unsigned char utf8_length = 0; + unsigned char utf8_position = 0; + unsigned char sequence_length = 0; + unsigned char first_byte_mark = 0; + + if ((input_end - first_sequence) < 6) + { + /* input ends unexpectedly */ + goto fail; + } + + /* get the first utf16 sequence */ + first_code = parse_hex4(first_sequence + 2); + + /* check that the code is valid */ + if (((first_code >= 0xDC00) && (first_code <= 0xDFFF))) + { + goto fail; + } + + /* UTF16 surrogate pair */ + if ((first_code >= 0xD800) && (first_code <= 0xDBFF)) + { + const unsigned char *second_sequence = first_sequence + 6; + unsigned int second_code = 0; + sequence_length = 12; /* \uXXXX\uXXXX */ + + if ((input_end - second_sequence) < 6) + { + /* input ends unexpectedly */ + goto fail; + } + + if ((second_sequence[0] != '\\') || (second_sequence[1] != 'u')) + { + /* missing second half of the surrogate pair */ + goto fail; + } + + /* get the second utf16 sequence */ + second_code = parse_hex4(second_sequence + 2); + /* check that the code is valid */ + if ((second_code < 0xDC00) || (second_code > 0xDFFF)) + { + /* invalid second half of the surrogate pair */ + goto fail; + } + + + /* calculate the unicode codepoint from the surrogate pair */ + codepoint = 0x10000 + (((first_code & 0x3FF) << 10) | (second_code & 0x3FF)); + } + else + { + sequence_length = 6; /* \uXXXX */ + codepoint = first_code; + } + + /* encode as UTF-8 + * takes at maximum 4 bytes to encode: + * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */ + if (codepoint < 0x80) + { + /* normal ascii, encoding 0xxxxxxx */ + utf8_length = 1; + } + else if (codepoint < 0x800) + { + /* two bytes, encoding 110xxxxx 10xxxxxx */ + utf8_length = 2; + first_byte_mark = 0xC0; /* 11000000 */ + } + else if (codepoint < 0x10000) + { + /* three bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx */ + utf8_length = 3; + first_byte_mark = 0xE0; /* 11100000 */ + } + else if (codepoint <= 0x10FFFF) + { + /* four bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx */ + utf8_length = 4; + first_byte_mark = 0xF0; /* 11110000 */ + } + else + { + /* invalid unicode codepoint */ + goto fail; + } + + /* encode as utf8 */ + for (utf8_position = (unsigned char)(utf8_length - 1); utf8_position > 0; utf8_position--) + { + /* 10xxxxxx */ + (*output_pointer)[utf8_position] = (unsigned char)((codepoint | 0x80) & 0xBF); + codepoint >>= 6; + } + /* encode first byte */ + if (utf8_length > 1) + { + (*output_pointer)[0] = (unsigned char)((codepoint | first_byte_mark) & 0xFF); + } + else + { + (*output_pointer)[0] = (unsigned char)(codepoint & 0x7F); + } + + *output_pointer += utf8_length; + + return sequence_length; + +fail: + return 0; +} + +/* Parse the input text into an unescaped cinput, and populate item. */ +static cJSON_bool parse_string(cJSON * const item, parse_buffer * const input_buffer) +{ + const unsigned char *input_pointer = buffer_at_offset(input_buffer) + 1; + const unsigned char *input_end = buffer_at_offset(input_buffer) + 1; + unsigned char *output_pointer = NULL; + unsigned char *output = NULL; + + /* not a string */ + if (buffer_at_offset(input_buffer)[0] != '\"') + { + goto fail; + } + + { + /* calculate approximate size of the output (overestimate) */ + size_t allocation_length = 0; + size_t skipped_bytes = 0; + while (((size_t)(input_end - input_buffer->content) < input_buffer->length) && (*input_end != '\"')) + { + /* is escape sequence */ + if (input_end[0] == '\\') + { + if ((size_t)(input_end + 1 - input_buffer->content) >= input_buffer->length) + { + /* prevent buffer overflow when last input character is a backslash */ + goto fail; + } + skipped_bytes++; + input_end++; + } + input_end++; + } + if (((size_t)(input_end - input_buffer->content) >= input_buffer->length) || (*input_end != '\"')) + { + goto fail; /* string ended unexpectedly */ + } + + /* This is at most how much we need for the output */ + allocation_length = (size_t) (input_end - buffer_at_offset(input_buffer)) - skipped_bytes; + output = (unsigned char*)input_buffer->hooks.allocate(allocation_length + sizeof("")); + if (output == NULL) + { + goto fail; /* allocation failure */ + } + } + + output_pointer = output; + /* loop through the string literal */ + while (input_pointer < input_end) + { + if (*input_pointer != '\\') + { + *output_pointer++ = *input_pointer++; + } + /* escape sequence */ + else + { + unsigned char sequence_length = 2; + if ((input_end - input_pointer) < 1) + { + goto fail; + } + + switch (input_pointer[1]) + { + case 'b': + *output_pointer++ = '\b'; + break; + case 'f': + *output_pointer++ = '\f'; + break; + case 'n': + *output_pointer++ = '\n'; + break; + case 'r': + *output_pointer++ = '\r'; + break; + case 't': + *output_pointer++ = '\t'; + break; + case '\"': + case '\\': + case '/': + *output_pointer++ = input_pointer[1]; + break; + + /* UTF-16 literal */ + case 'u': + sequence_length = utf16_literal_to_utf8(input_pointer, input_end, &output_pointer); + if (sequence_length == 0) + { + /* failed to convert UTF16-literal to UTF-8 */ + goto fail; + } + break; + + default: + goto fail; + } + input_pointer += sequence_length; + } + } + + /* zero terminate the output */ + *output_pointer = '\0'; + + item->type = cJSON_String; + item->valuestring = (char*)output; + + input_buffer->offset = (size_t) (input_end - input_buffer->content); + input_buffer->offset++; + + return true; + +fail: + if (output != NULL) + { + input_buffer->hooks.deallocate(output); + output = NULL; + } + + if (input_pointer != NULL) + { + input_buffer->offset = (size_t)(input_pointer - input_buffer->content); + } + + return false; +} + +/* Render the cstring provided to an escaped version that can be printed. */ +static cJSON_bool print_string_ptr(const unsigned char * const input, printbuffer * const output_buffer) +{ + const unsigned char *input_pointer = NULL; + unsigned char *output = NULL; + unsigned char *output_pointer = NULL; + size_t output_length = 0; + /* numbers of additional characters needed for escaping */ + size_t escape_characters = 0; + + if (output_buffer == NULL) + { + return false; + } + + /* empty string */ + if (input == NULL) + { + output = ensure(output_buffer, sizeof("\"\"")); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "\"\""); + + return true; + } + + /* set "flag" to 1 if something needs to be escaped */ + for (input_pointer = input; *input_pointer; input_pointer++) + { + switch (*input_pointer) + { + case '\"': + case '\\': + case '\b': + case '\f': + case '\n': + case '\r': + case '\t': + /* one character escape sequence */ + escape_characters++; + break; + default: + if (*input_pointer < 32) + { + /* UTF-16 escape sequence uXXXX */ + escape_characters += 5; + } + break; + } + } + output_length = (size_t)(input_pointer - input) + escape_characters; + + output = ensure(output_buffer, output_length + sizeof("\"\"")); + if (output == NULL) + { + return false; + } + + /* no characters have to be escaped */ + if (escape_characters == 0) + { + output[0] = '\"'; + memcpy(output + 1, input, output_length); + output[output_length + 1] = '\"'; + output[output_length + 2] = '\0'; + + return true; + } + + output[0] = '\"'; + output_pointer = output + 1; + /* copy the string */ + for (input_pointer = input; *input_pointer != '\0'; (void)input_pointer++, output_pointer++) + { + if ((*input_pointer > 31) && (*input_pointer != '\"') && (*input_pointer != '\\')) + { + /* normal character, copy */ + *output_pointer = *input_pointer; + } + else + { + /* character needs to be escaped */ + *output_pointer++ = '\\'; + switch (*input_pointer) + { + case '\\': + *output_pointer = '\\'; + break; + case '\"': + *output_pointer = '\"'; + break; + case '\b': + *output_pointer = 'b'; + break; + case '\f': + *output_pointer = 'f'; + break; + case '\n': + *output_pointer = 'n'; + break; + case '\r': + *output_pointer = 'r'; + break; + case '\t': + *output_pointer = 't'; + break; + default: + /* escape and print as unicode codepoint */ + sprintf((char*)output_pointer, "u%04x", *input_pointer); + output_pointer += 4; + break; + } + } + } + output[output_length + 1] = '\"'; + output[output_length + 2] = '\0'; + + return true; +} + +/* Invoke print_string_ptr (which is useful) on an item. */ +static cJSON_bool print_string(const cJSON * const item, printbuffer * const p) +{ + return print_string_ptr((unsigned char*)item->valuestring, p); +} + +/* Predeclare these prototypes. */ +static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer); +static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer); +static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer); +static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer); +static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer); +static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer); + +/* Utility to jump whitespace and cr/lf */ +static parse_buffer *buffer_skip_whitespace(parse_buffer * const buffer) +{ + if ((buffer == NULL) || (buffer->content == NULL)) + { + return NULL; + } + + if (cannot_access_at_index(buffer, 0)) + { + return buffer; + } + + while (can_access_at_index(buffer, 0) && (buffer_at_offset(buffer)[0] <= 32)) + { + buffer->offset++; + } + + if (buffer->offset == buffer->length) + { + buffer->offset--; + } + + return buffer; +} + +/* skip the UTF-8 BOM (byte order mark) if it is at the beginning of a buffer */ +static parse_buffer *skip_utf8_bom(parse_buffer * const buffer) +{ + if ((buffer == NULL) || (buffer->content == NULL) || (buffer->offset != 0)) + { + return NULL; + } + + if (can_access_at_index(buffer, 4) && (strncmp((const char*)buffer_at_offset(buffer), "\xEF\xBB\xBF", 3) == 0)) + { + buffer->offset += 3; + } + + return buffer; +} + +CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated) +{ + size_t buffer_length; + + if (NULL == value) + { + return NULL; + } + + /* Adding null character size due to require_null_terminated. */ + buffer_length = strlen(value) + sizeof(""); + + return cJSON_ParseWithLengthOpts(value, buffer_length, return_parse_end, require_null_terminated); +} + +/* Parse an object - create a new root, and populate. */ +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated) +{ + parse_buffer buffer = { 0, 0, 0, 0, { 0, 0, 0 } }; + cJSON *item = NULL; + + /* reset error position */ + global_error.json = NULL; + global_error.position = 0; + + if (value == NULL || 0 == buffer_length) + { + goto fail; + } + + buffer.content = (const unsigned char*)value; + buffer.length = buffer_length; + buffer.offset = 0; + buffer.hooks = global_hooks; + + item = cJSON_New_Item(&global_hooks); + if (item == NULL) /* memory fail */ + { + goto fail; + } + + if (!parse_value(item, buffer_skip_whitespace(skip_utf8_bom(&buffer)))) + { + /* parse failure. ep is set. */ + goto fail; + } + + /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */ + if (require_null_terminated) + { + buffer_skip_whitespace(&buffer); + if ((buffer.offset >= buffer.length) || buffer_at_offset(&buffer)[0] != '\0') + { + goto fail; + } + } + if (return_parse_end) + { + *return_parse_end = (const char*)buffer_at_offset(&buffer); + } + + return item; + +fail: + if (item != NULL) + { + cJSON_Delete(item); + } + + if (value != NULL) + { + error local_error; + local_error.json = (const unsigned char*)value; + local_error.position = 0; + + if (buffer.offset < buffer.length) + { + local_error.position = buffer.offset; + } + else if (buffer.length > 0) + { + local_error.position = buffer.length - 1; + } + + if (return_parse_end != NULL) + { + *return_parse_end = (const char*)local_error.json + local_error.position; + } + + global_error = local_error; + } + + return NULL; +} + +/* Default options for cJSON_Parse */ +CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value) +{ + return cJSON_ParseWithOpts(value, 0, 0); +} + +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length) +{ + return cJSON_ParseWithLengthOpts(value, buffer_length, 0, 0); +} + +#define cjson_min(a, b) (((a) < (b)) ? (a) : (b)) + +static unsigned char *print(const cJSON * const item, cJSON_bool format, const internal_hooks * const hooks) +{ + static const size_t default_buffer_size = 256; + printbuffer buffer[1]; + unsigned char *printed = NULL; + + memset(buffer, 0, sizeof(buffer)); + + /* create buffer */ + buffer->buffer = (unsigned char*) hooks->allocate(default_buffer_size); + buffer->length = default_buffer_size; + buffer->format = format; + buffer->hooks = *hooks; + if (buffer->buffer == NULL) + { + goto fail; + } + + /* print the value */ + if (!print_value(item, buffer)) + { + goto fail; + } + update_offset(buffer); + + /* check if reallocate is available */ + if (hooks->reallocate != NULL) + { + printed = (unsigned char*) hooks->reallocate(buffer->buffer, buffer->offset + 1); + if (printed == NULL) { + goto fail; + } + buffer->buffer = NULL; + } + else /* otherwise copy the JSON over to a new buffer */ + { + printed = (unsigned char*) hooks->allocate(buffer->offset + 1); + if (printed == NULL) + { + goto fail; + } + memcpy(printed, buffer->buffer, cjson_min(buffer->length, buffer->offset + 1)); + printed[buffer->offset] = '\0'; /* just to be sure */ + + /* free the buffer */ + hooks->deallocate(buffer->buffer); + buffer->buffer = NULL; + } + + return printed; + +fail: + if (buffer->buffer != NULL) + { + hooks->deallocate(buffer->buffer); + buffer->buffer = NULL; + } + + if (printed != NULL) + { + hooks->deallocate(printed); + printed = NULL; + } + + return NULL; +} + +/* Render a cJSON item/entity/structure to text. */ +CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item) +{ + return (char*)print(item, true, &global_hooks); +} + +CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item) +{ + return (char*)print(item, false, &global_hooks); +} + +CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt) +{ + printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; + + if (prebuffer < 0) + { + return NULL; + } + + p.buffer = (unsigned char*)global_hooks.allocate((size_t)prebuffer); + if (!p.buffer) + { + return NULL; + } + + p.length = (size_t)prebuffer; + p.offset = 0; + p.noalloc = false; + p.format = fmt; + p.hooks = global_hooks; + + if (!print_value(item, &p)) + { + global_hooks.deallocate(p.buffer); + p.buffer = NULL; + return NULL; + } + + return (char*)p.buffer; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format) +{ + printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; + + if ((length < 0) || (buffer == NULL)) + { + return false; + } + + p.buffer = (unsigned char*)buffer; + p.length = (size_t)length; + p.offset = 0; + p.noalloc = true; + p.format = format; + p.hooks = global_hooks; + + return print_value(item, &p); +} + +/* Parser core - when encountering text, process appropriately. */ +static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer) +{ + if ((input_buffer == NULL) || (input_buffer->content == NULL)) + { + return false; /* no input */ + } + + /* parse the different types of values */ + /* null */ + if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "null", 4) == 0)) + { + item->type = cJSON_NULL; + input_buffer->offset += 4; + return true; + } + /* false */ + if (can_read(input_buffer, 5) && (strncmp((const char*)buffer_at_offset(input_buffer), "false", 5) == 0)) + { + item->type = cJSON_False; + input_buffer->offset += 5; + return true; + } + /* true */ + if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "true", 4) == 0)) + { + item->type = cJSON_True; + item->valueint = 1; + input_buffer->offset += 4; + return true; + } + /* string */ + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '\"')) + { + return parse_string(item, input_buffer); + } + /* number */ + if (can_access_at_index(input_buffer, 0) && ((buffer_at_offset(input_buffer)[0] == '-') || ((buffer_at_offset(input_buffer)[0] >= '0') && (buffer_at_offset(input_buffer)[0] <= '9')))) + { + return parse_number(item, input_buffer); + } + /* array */ + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '[')) + { + return parse_array(item, input_buffer); + } + /* object */ + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '{')) + { + return parse_object(item, input_buffer); + } + + return false; +} + +/* Render a value to text. */ +static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output = NULL; + + if ((item == NULL) || (output_buffer == NULL)) + { + return false; + } + + switch ((item->type) & 0xFF) + { + case cJSON_NULL: + output = ensure(output_buffer, 5); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "null"); + return true; + + case cJSON_False: + output = ensure(output_buffer, 6); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "false"); + return true; + + case cJSON_True: + output = ensure(output_buffer, 5); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "true"); + return true; + + case cJSON_Number: + return print_number(item, output_buffer); + + case cJSON_Raw: + { + size_t raw_length = 0; + if (item->valuestring == NULL) + { + return false; + } + + raw_length = strlen(item->valuestring) + sizeof(""); + output = ensure(output_buffer, raw_length); + if (output == NULL) + { + return false; + } + memcpy(output, item->valuestring, raw_length); + return true; + } + + case cJSON_String: + return print_string(item, output_buffer); + + case cJSON_Array: + return print_array(item, output_buffer); + + case cJSON_Object: + return print_object(item, output_buffer); + + default: + return false; + } +} + +/* Build an array from input text. */ +static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer) +{ + cJSON *head = NULL; /* head of the linked list */ + cJSON *current_item = NULL; + + if (input_buffer->depth >= CJSON_NESTING_LIMIT) + { + return false; /* to deeply nested */ + } + input_buffer->depth++; + + if (buffer_at_offset(input_buffer)[0] != '[') + { + /* not an array */ + goto fail; + } + + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ']')) + { + /* empty array */ + goto success; + } + + /* check if we skipped to the end of the buffer */ + if (cannot_access_at_index(input_buffer, 0)) + { + input_buffer->offset--; + goto fail; + } + + /* step back to character in front of the first element */ + input_buffer->offset--; + /* loop through the comma separated array elements */ + do + { + /* allocate next item */ + cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks)); + if (new_item == NULL) + { + goto fail; /* allocation failure */ + } + + /* attach next item to list */ + if (head == NULL) + { + /* start the linked list */ + current_item = head = new_item; + } + else + { + /* add to the end and advance */ + current_item->next = new_item; + new_item->prev = current_item; + current_item = new_item; + } + + /* parse next value */ + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (!parse_value(current_item, input_buffer)) + { + goto fail; /* failed to parse value */ + } + buffer_skip_whitespace(input_buffer); + } + while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ',')); + + if (cannot_access_at_index(input_buffer, 0) || buffer_at_offset(input_buffer)[0] != ']') + { + goto fail; /* expected end of array */ + } + +success: + input_buffer->depth--; + + if (head != NULL) { + head->prev = current_item; + } + + item->type = cJSON_Array; + item->child = head; + + input_buffer->offset++; + + return true; + +fail: + if (head != NULL) + { + cJSON_Delete(head); + } + + return false; +} + +/* Render an array to text */ +static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output_pointer = NULL; + size_t length = 0; + cJSON *current_element = item->child; + + if (output_buffer == NULL) + { + return false; + } + + /* Compose the output array. */ + /* opening square bracket */ + output_pointer = ensure(output_buffer, 1); + if (output_pointer == NULL) + { + return false; + } + + *output_pointer = '['; + output_buffer->offset++; + output_buffer->depth++; + + while (current_element != NULL) + { + if (!print_value(current_element, output_buffer)) + { + return false; + } + update_offset(output_buffer); + if (current_element->next) + { + length = (size_t) (output_buffer->format ? 2 : 1); + output_pointer = ensure(output_buffer, length + 1); + if (output_pointer == NULL) + { + return false; + } + *output_pointer++ = ','; + if(output_buffer->format) + { + *output_pointer++ = ' '; + } + *output_pointer = '\0'; + output_buffer->offset += length; + } + current_element = current_element->next; + } + + output_pointer = ensure(output_buffer, 2); + if (output_pointer == NULL) + { + return false; + } + *output_pointer++ = ']'; + *output_pointer = '\0'; + output_buffer->depth--; + + return true; +} + +/* Build an object from the text. */ +static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer) +{ + cJSON *head = NULL; /* linked list head */ + cJSON *current_item = NULL; + + if (input_buffer->depth >= CJSON_NESTING_LIMIT) + { + return false; /* to deeply nested */ + } + input_buffer->depth++; + + if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '{')) + { + goto fail; /* not an object */ + } + + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '}')) + { + goto success; /* empty object */ + } + + /* check if we skipped to the end of the buffer */ + if (cannot_access_at_index(input_buffer, 0)) + { + input_buffer->offset--; + goto fail; + } + + /* step back to character in front of the first element */ + input_buffer->offset--; + /* loop through the comma separated array elements */ + do + { + /* allocate next item */ + cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks)); + if (new_item == NULL) + { + goto fail; /* allocation failure */ + } + + /* attach next item to list */ + if (head == NULL) + { + /* start the linked list */ + current_item = head = new_item; + } + else + { + /* add to the end and advance */ + current_item->next = new_item; + new_item->prev = current_item; + current_item = new_item; + } + + if (cannot_access_at_index(input_buffer, 1)) + { + goto fail; /* nothing comes after the comma */ + } + + /* parse the name of the child */ + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (!parse_string(current_item, input_buffer)) + { + goto fail; /* failed to parse name */ + } + buffer_skip_whitespace(input_buffer); + + /* swap valuestring and string, because we parsed the name */ + current_item->string = current_item->valuestring; + current_item->valuestring = NULL; + + if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != ':')) + { + goto fail; /* invalid object */ + } + + /* parse the value */ + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (!parse_value(current_item, input_buffer)) + { + goto fail; /* failed to parse value */ + } + buffer_skip_whitespace(input_buffer); + } + while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ',')); + + if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '}')) + { + goto fail; /* expected end of object */ + } + +success: + input_buffer->depth--; + + if (head != NULL) { + head->prev = current_item; + } + + item->type = cJSON_Object; + item->child = head; + + input_buffer->offset++; + return true; + +fail: + if (head != NULL) + { + cJSON_Delete(head); + } + + return false; +} + +/* Render an object to text. */ +static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output_pointer = NULL; + size_t length = 0; + cJSON *current_item = item->child; + + if (output_buffer == NULL) + { + return false; + } + + /* Compose the output: */ + length = (size_t) (output_buffer->format ? 2 : 1); /* fmt: {\n */ + output_pointer = ensure(output_buffer, length + 1); + if (output_pointer == NULL) + { + return false; + } + + *output_pointer++ = '{'; + output_buffer->depth++; + if (output_buffer->format) + { + *output_pointer++ = '\n'; + } + output_buffer->offset += length; + + while (current_item) + { + if (output_buffer->format) + { + size_t i; + output_pointer = ensure(output_buffer, output_buffer->depth); + if (output_pointer == NULL) + { + return false; + } + for (i = 0; i < output_buffer->depth; i++) + { + *output_pointer++ = '\t'; + } + output_buffer->offset += output_buffer->depth; + } + + /* print key */ + if (!print_string_ptr((unsigned char*)current_item->string, output_buffer)) + { + return false; + } + update_offset(output_buffer); + + length = (size_t) (output_buffer->format ? 2 : 1); + output_pointer = ensure(output_buffer, length); + if (output_pointer == NULL) + { + return false; + } + *output_pointer++ = ':'; + if (output_buffer->format) + { + *output_pointer++ = '\t'; + } + output_buffer->offset += length; + + /* print value */ + if (!print_value(current_item, output_buffer)) + { + return false; + } + update_offset(output_buffer); + + /* print comma if not last */ + length = ((size_t)(output_buffer->format ? 1 : 0) + (size_t)(current_item->next ? 1 : 0)); + output_pointer = ensure(output_buffer, length + 1); + if (output_pointer == NULL) + { + return false; + } + if (current_item->next) + { + *output_pointer++ = ','; + } + + if (output_buffer->format) + { + *output_pointer++ = '\n'; + } + *output_pointer = '\0'; + output_buffer->offset += length; + + current_item = current_item->next; + } + + output_pointer = ensure(output_buffer, output_buffer->format ? (output_buffer->depth + 1) : 2); + if (output_pointer == NULL) + { + return false; + } + if (output_buffer->format) + { + size_t i; + for (i = 0; i < (output_buffer->depth - 1); i++) + { + *output_pointer++ = '\t'; + } + } + *output_pointer++ = '}'; + *output_pointer = '\0'; + output_buffer->depth--; + + return true; +} + +/* Get Array size/item / object item. */ +CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array) +{ + cJSON *child = NULL; + size_t size = 0; + + if (array == NULL) + { + return 0; + } + + child = array->child; + + while(child != NULL) + { + size++; + child = child->next; + } + + /* FIXME: Can overflow here. Cannot be fixed without breaking the API */ + + return (int)size; +} + +static cJSON* get_array_item(const cJSON *array, size_t index) +{ + cJSON *current_child = NULL; + + if (array == NULL) + { + return NULL; + } + + current_child = array->child; + while ((current_child != NULL) && (index > 0)) + { + index--; + current_child = current_child->next; + } + + return current_child; +} + +CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index) +{ + if (index < 0) + { + return NULL; + } + + return get_array_item(array, (size_t)index); +} + +static cJSON *get_object_item(const cJSON * const object, const char * const name, const cJSON_bool case_sensitive) +{ + cJSON *current_element = NULL; + + if ((object == NULL) || (name == NULL)) + { + return NULL; + } + + current_element = object->child; + if (case_sensitive) + { + while ((current_element != NULL) && (current_element->string != NULL) && (strcmp(name, current_element->string) != 0)) + { + current_element = current_element->next; + } + } + else + { + while ((current_element != NULL) && (case_insensitive_strcmp((const unsigned char*)name, (const unsigned char*)(current_element->string)) != 0)) + { + current_element = current_element->next; + } + } + + if ((current_element == NULL) || (current_element->string == NULL)) { + return NULL; + } + + return current_element; +} + +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string) +{ + return get_object_item(object, string, false); +} + +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string) +{ + return get_object_item(object, string, true); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string) +{ + return cJSON_GetObjectItem(object, string) ? 1 : 0; +} + +/* Utility for array list handling. */ +static void suffix_object(cJSON *prev, cJSON *item) +{ + prev->next = item; + item->prev = prev; +} + +/* Utility for handling references. */ +static cJSON *create_reference(const cJSON *item, const internal_hooks * const hooks) +{ + cJSON *reference = NULL; + if (item == NULL) + { + return NULL; + } + + reference = cJSON_New_Item(hooks); + if (reference == NULL) + { + return NULL; + } + + memcpy(reference, item, sizeof(cJSON)); + reference->string = NULL; + reference->type |= cJSON_IsReference; + reference->next = reference->prev = NULL; + return reference; +} + +static cJSON_bool add_item_to_array(cJSON *array, cJSON *item) +{ + cJSON *child = NULL; + + if ((item == NULL) || (array == NULL) || (array == item)) + { + return false; + } + + child = array->child; + /* + * To find the last item in array quickly, we use prev in array + */ + if (child == NULL) + { + /* list is empty, start new one */ + array->child = item; + item->prev = item; + item->next = NULL; + } + else + { + /* append to the end */ + if (child->prev) + { + suffix_object(child->prev, item); + array->child->prev = item; + } + } + + return true; +} + +/* Add item to array/object. */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item) +{ + return add_item_to_array(array, item); +} + +#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) + #pragma GCC diagnostic push +#endif +#ifdef __GNUC__ +#pragma GCC diagnostic ignored "-Wcast-qual" +#endif +/* helper function to cast away const */ +static void* cast_away_const(const void* string) +{ + return (void*)string; +} +#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) + #pragma GCC diagnostic pop +#endif + + +static cJSON_bool add_item_to_object(cJSON * const object, const char * const string, cJSON * const item, const internal_hooks * const hooks, const cJSON_bool constant_key) +{ + char *new_key = NULL; + int new_type = cJSON_Invalid; + + if ((object == NULL) || (string == NULL) || (item == NULL) || (object == item)) + { + return false; + } + + if (constant_key) + { + new_key = (char*)cast_away_const(string); + new_type = item->type | cJSON_StringIsConst; + } + else + { + new_key = (char*)cJSON_strdup((const unsigned char*)string, hooks); + if (new_key == NULL) + { + return false; + } + + new_type = item->type & ~cJSON_StringIsConst; + } + + if (!(item->type & cJSON_StringIsConst) && (item->string != NULL)) + { + hooks->deallocate(item->string); + } + + item->string = new_key; + item->type = new_type; + + return add_item_to_array(object, item); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item) +{ + return add_item_to_object(object, string, item, &global_hooks, false); +} + +/* Add an item to an object with constant string as key */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item) +{ + return add_item_to_object(object, string, item, &global_hooks, true); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item) +{ + if (array == NULL) + { + return false; + } + + return add_item_to_array(array, create_reference(item, &global_hooks)); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item) +{ + if ((object == NULL) || (string == NULL)) + { + return false; + } + + return add_item_to_object(object, string, create_reference(item, &global_hooks), &global_hooks, false); +} + +CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name) +{ + cJSON *null = cJSON_CreateNull(); + if (add_item_to_object(object, name, null, &global_hooks, false)) + { + return null; + } + + cJSON_Delete(null); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name) +{ + cJSON *true_item = cJSON_CreateTrue(); + if (add_item_to_object(object, name, true_item, &global_hooks, false)) + { + return true_item; + } + + cJSON_Delete(true_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name) +{ + cJSON *false_item = cJSON_CreateFalse(); + if (add_item_to_object(object, name, false_item, &global_hooks, false)) + { + return false_item; + } + + cJSON_Delete(false_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean) +{ + cJSON *bool_item = cJSON_CreateBool(boolean); + if (add_item_to_object(object, name, bool_item, &global_hooks, false)) + { + return bool_item; + } + + cJSON_Delete(bool_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number) +{ + cJSON *number_item = cJSON_CreateNumber(number); + if (add_item_to_object(object, name, number_item, &global_hooks, false)) + { + return number_item; + } + + cJSON_Delete(number_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string) +{ + cJSON *string_item = cJSON_CreateString(string); + if (add_item_to_object(object, name, string_item, &global_hooks, false)) + { + return string_item; + } + + cJSON_Delete(string_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw) +{ + cJSON *raw_item = cJSON_CreateRaw(raw); + if (add_item_to_object(object, name, raw_item, &global_hooks, false)) + { + return raw_item; + } + + cJSON_Delete(raw_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name) +{ + cJSON *object_item = cJSON_CreateObject(); + if (add_item_to_object(object, name, object_item, &global_hooks, false)) + { + return object_item; + } + + cJSON_Delete(object_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name) +{ + cJSON *array = cJSON_CreateArray(); + if (add_item_to_object(object, name, array, &global_hooks, false)) + { + return array; + } + + cJSON_Delete(array); + return NULL; +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item) +{ + if ((parent == NULL) || (item == NULL) || (item != parent->child && item->prev == NULL)) + { + return NULL; + } + + if (item != parent->child) + { + /* not the first element */ + item->prev->next = item->next; + } + if (item->next != NULL) + { + /* not the last element */ + item->next->prev = item->prev; + } + + if (item == parent->child) + { + /* first element */ + parent->child = item->next; + } + else if (item->next == NULL) + { + /* last element */ + parent->child->prev = item->prev; + } + + /* make sure the detached item doesn't point anywhere anymore */ + item->prev = NULL; + item->next = NULL; + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which) +{ + if (which < 0) + { + return NULL; + } + + return cJSON_DetachItemViaPointer(array, get_array_item(array, (size_t)which)); +} + +CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which) +{ + cJSON_Delete(cJSON_DetachItemFromArray(array, which)); +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string) +{ + cJSON *to_detach = cJSON_GetObjectItem(object, string); + + return cJSON_DetachItemViaPointer(object, to_detach); +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string) +{ + cJSON *to_detach = cJSON_GetObjectItemCaseSensitive(object, string); + + return cJSON_DetachItemViaPointer(object, to_detach); +} + +CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string) +{ + cJSON_Delete(cJSON_DetachItemFromObject(object, string)); +} + +CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string) +{ + cJSON_Delete(cJSON_DetachItemFromObjectCaseSensitive(object, string)); +} + +/* Replace array/object items with new ones. */ +CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem) +{ + cJSON *after_inserted = NULL; + + if (which < 0 || newitem == NULL) + { + return false; + } + + after_inserted = get_array_item(array, (size_t)which); + if (after_inserted == NULL) + { + return add_item_to_array(array, newitem); + } + + if (after_inserted != array->child && after_inserted->prev == NULL) { + /* return false if after_inserted is a corrupted array item */ + return false; + } + + newitem->next = after_inserted; + newitem->prev = after_inserted->prev; + after_inserted->prev = newitem; + if (after_inserted == array->child) + { + array->child = newitem; + } + else + { + newitem->prev->next = newitem; + } + return true; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement) +{ + if ((parent == NULL) || (parent->child == NULL) || (replacement == NULL) || (item == NULL)) + { + return false; + } + + if (replacement == item) + { + return true; + } + + replacement->next = item->next; + replacement->prev = item->prev; + + if (replacement->next != NULL) + { + replacement->next->prev = replacement; + } + if (parent->child == item) + { + if (parent->child->prev == parent->child) + { + replacement->prev = replacement; + } + parent->child = replacement; + } + else + { /* + * To find the last item in array quickly, we use prev in array. + * We can't modify the last item's next pointer where this item was the parent's child + */ + if (replacement->prev != NULL) + { + replacement->prev->next = replacement; + } + if (replacement->next == NULL) + { + parent->child->prev = replacement; + } + } + + item->next = NULL; + item->prev = NULL; + cJSON_Delete(item); + + return true; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem) +{ + if (which < 0) + { + return false; + } + + return cJSON_ReplaceItemViaPointer(array, get_array_item(array, (size_t)which), newitem); +} + +static cJSON_bool replace_item_in_object(cJSON *object, const char *string, cJSON *replacement, cJSON_bool case_sensitive) +{ + if ((replacement == NULL) || (string == NULL)) + { + return false; + } + + /* replace the name in the replacement */ + if (!(replacement->type & cJSON_StringIsConst) && (replacement->string != NULL)) + { + cJSON_free(replacement->string); + } + replacement->string = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks); + if (replacement->string == NULL) + { + return false; + } + + replacement->type &= ~cJSON_StringIsConst; + + return cJSON_ReplaceItemViaPointer(object, get_object_item(object, string, case_sensitive), replacement); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem) +{ + return replace_item_in_object(object, string, newitem, false); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object, const char *string, cJSON *newitem) +{ + return replace_item_in_object(object, string, newitem, true); +} + +/* Create basic types: */ +CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_NULL; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_True; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_False; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = boolean ? cJSON_True : cJSON_False; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_Number; + item->valuedouble = num; + + /* use saturation in case of overflow */ + if (num >= INT_MAX) + { + item->valueint = INT_MAX; + } + else if (num <= (double)INT_MIN) + { + item->valueint = INT_MIN; + } + else + { + item->valueint = (int)num; + } + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_String; + item->valuestring = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks); + if(!item->valuestring) + { + cJSON_Delete(item); + return NULL; + } + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item != NULL) + { + item->type = cJSON_String | cJSON_IsReference; + item->valuestring = (char*)cast_away_const(string); + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item != NULL) { + item->type = cJSON_Object | cJSON_IsReference; + item->child = (cJSON*)cast_away_const(child); + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child) { + cJSON *item = cJSON_New_Item(&global_hooks); + if (item != NULL) { + item->type = cJSON_Array | cJSON_IsReference; + item->child = (cJSON*)cast_away_const(child); + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_Raw; + item->valuestring = (char*)cJSON_strdup((const unsigned char*)raw, &global_hooks); + if(!item->valuestring) + { + cJSON_Delete(item); + return NULL; + } + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type=cJSON_Array; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item) + { + item->type = cJSON_Object; + } + + return item; +} + +/* Create Arrays: */ +CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (numbers == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for(i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateNumber(numbers[i]); + if (!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p, n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (numbers == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for(i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateNumber((double)numbers[i]); + if(!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p, n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (numbers == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for(i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateNumber(numbers[i]); + if(!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p, n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (strings == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for (i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateString(strings[i]); + if(!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p,n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +/* Duplication */ +cJSON * cJSON_Duplicate_rec(const cJSON *item, size_t depth, cJSON_bool recurse); + +CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse) +{ + return cJSON_Duplicate_rec(item, 0, recurse ); +} + +cJSON * cJSON_Duplicate_rec(const cJSON *item, size_t depth, cJSON_bool recurse) +{ + cJSON *newitem = NULL; + cJSON *child = NULL; + cJSON *next = NULL; + cJSON *newchild = NULL; + + /* Bail on bad ptr */ + if (!item) + { + goto fail; + } + /* Create new item */ + newitem = cJSON_New_Item(&global_hooks); + if (!newitem) + { + goto fail; + } + /* Copy over all vars */ + newitem->type = item->type & (~cJSON_IsReference); + newitem->valueint = item->valueint; + newitem->valuedouble = item->valuedouble; + if (item->valuestring) + { + newitem->valuestring = (char*)cJSON_strdup((unsigned char*)item->valuestring, &global_hooks); + if (!newitem->valuestring) + { + goto fail; + } + } + if (item->string) + { + newitem->string = (item->type&cJSON_StringIsConst) ? item->string : (char*)cJSON_strdup((unsigned char*)item->string, &global_hooks); + if (!newitem->string) + { + goto fail; + } + } + /* If non-recursive, then we're done! */ + if (!recurse) + { + return newitem; + } + /* Walk the ->next chain for the child. */ + child = item->child; + while (child != NULL) + { + if(depth >= CJSON_CIRCULAR_LIMIT) { + goto fail; + } + newchild = cJSON_Duplicate_rec(child, depth + 1, true); /* Duplicate (with recurse) each item in the ->next chain */ + if (!newchild) + { + goto fail; + } + if (next != NULL) + { + /* If newitem->child already set, then crosswire ->prev and ->next and move on */ + next->next = newchild; + newchild->prev = next; + next = newchild; + } + else + { + /* Set newitem->child and move to it */ + newitem->child = newchild; + next = newchild; + } + child = child->next; + } + if (newitem && newitem->child) + { + newitem->child->prev = newchild; + } + + return newitem; + +fail: + if (newitem != NULL) + { + cJSON_Delete(newitem); + } + + return NULL; +} + +static void skip_oneline_comment(char **input) +{ + *input += static_strlen("//"); + + for (; (*input)[0] != '\0'; ++(*input)) + { + if ((*input)[0] == '\n') { + *input += static_strlen("\n"); + return; + } + } +} + +static void skip_multiline_comment(char **input) +{ + *input += static_strlen("/*"); + + for (; (*input)[0] != '\0'; ++(*input)) + { + if (((*input)[0] == '*') && ((*input)[1] == '/')) + { + *input += static_strlen("*/"); + return; + } + } +} + +static void minify_string(char **input, char **output) { + (*output)[0] = (*input)[0]; + *input += static_strlen("\""); + *output += static_strlen("\""); + + + for (; (*input)[0] != '\0'; (void)++(*input), ++(*output)) { + (*output)[0] = (*input)[0]; + + if ((*input)[0] == '\"') { + (*output)[0] = '\"'; + *input += static_strlen("\""); + *output += static_strlen("\""); + return; + } else if (((*input)[0] == '\\') && ((*input)[1] == '\"')) { + (*output)[1] = (*input)[1]; + *input += static_strlen("\""); + *output += static_strlen("\""); + } + } +} + +CJSON_PUBLIC(void) cJSON_Minify(char *json) +{ + char *into = json; + + if (json == NULL) + { + return; + } + + while (json[0] != '\0') + { + switch (json[0]) + { + case ' ': + case '\t': + case '\r': + case '\n': + json++; + break; + + case '/': + if (json[1] == '/') + { + skip_oneline_comment(&json); + } + else if (json[1] == '*') + { + skip_multiline_comment(&json); + } else { + json++; + } + break; + + case '\"': + minify_string(&json, (char**)&into); + break; + + default: + into[0] = json[0]; + json++; + into++; + } + } + + /* and null-terminate. */ + *into = '\0'; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Invalid; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_False; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xff) == cJSON_True; +} + + +CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & (cJSON_True | cJSON_False)) != 0; +} +CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_NULL; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Number; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_String; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Array; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Object; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Raw; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive) +{ + if ((a == NULL) || (b == NULL) || ((a->type & 0xFF) != (b->type & 0xFF))) + { + return false; + } + + /* check if type is valid */ + switch (a->type & 0xFF) + { + case cJSON_False: + case cJSON_True: + case cJSON_NULL: + case cJSON_Number: + case cJSON_String: + case cJSON_Raw: + case cJSON_Array: + case cJSON_Object: + break; + + default: + return false; + } + + /* identical objects are equal */ + if (a == b) + { + return true; + } + + switch (a->type & 0xFF) + { + /* in these cases and equal type is enough */ + case cJSON_False: + case cJSON_True: + case cJSON_NULL: + return true; + + case cJSON_Number: + if (compare_double(a->valuedouble, b->valuedouble)) + { + return true; + } + return false; + + case cJSON_String: + case cJSON_Raw: + if ((a->valuestring == NULL) || (b->valuestring == NULL)) + { + return false; + } + if (strcmp(a->valuestring, b->valuestring) == 0) + { + return true; + } + + return false; + + case cJSON_Array: + { + cJSON *a_element = a->child; + cJSON *b_element = b->child; + + for (; (a_element != NULL) && (b_element != NULL);) + { + if (!cJSON_Compare(a_element, b_element, case_sensitive)) + { + return false; + } + + a_element = a_element->next; + b_element = b_element->next; + } + + /* one of the arrays is longer than the other */ + if (a_element != b_element) { + return false; + } + + return true; + } + + case cJSON_Object: + { + cJSON *a_element = NULL; + cJSON *b_element = NULL; + cJSON_ArrayForEach(a_element, a) + { + /* TODO This has O(n^2) runtime, which is horrible! */ + b_element = get_object_item(b, a_element->string, case_sensitive); + if (b_element == NULL) + { + return false; + } + + if (!cJSON_Compare(a_element, b_element, case_sensitive)) + { + return false; + } + } + + /* doing this twice, once on a and b to prevent true comparison if a subset of b + * TODO: Do this the proper way, this is just a fix for now */ + cJSON_ArrayForEach(b_element, b) + { + a_element = get_object_item(a, b_element->string, case_sensitive); + if (a_element == NULL) + { + return false; + } + + if (!cJSON_Compare(b_element, a_element, case_sensitive)) + { + return false; + } + } + + return true; + } + + default: + return false; + } +} + +CJSON_PUBLIC(void *) cJSON_malloc(size_t size) +{ + return global_hooks.allocate(size); +} + +CJSON_PUBLIC(void) cJSON_free(void *object) +{ + global_hooks.deallocate(object); + object = NULL; +} diff --git a/module/dll_source_lzy/114/out/lib/cJSON.h b/module/dll_source_lzy/114/out/lib/cJSON.h new file mode 100644 index 0000000..37520bb --- /dev/null +++ b/module/dll_source_lzy/114/out/lib/cJSON.h @@ -0,0 +1,306 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#ifndef cJSON__h +#define cJSON__h + +#ifdef __cplusplus +extern "C" +{ +#endif + +#if !defined(__WINDOWS__) && (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) || defined(_WIN32)) +#define __WINDOWS__ +#endif + +#ifdef __WINDOWS__ + +/* When compiling for windows, we specify a specific calling convention to avoid issues where we are being called from a project with a different default calling convention. For windows you have 3 define options: + +CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever dllexport symbols +CJSON_EXPORT_SYMBOLS - Define this on library build when you want to dllexport symbols (default) +CJSON_IMPORT_SYMBOLS - Define this if you want to dllimport symbol + +For *nix builds that support visibility attribute, you can define similar behavior by + +setting default visibility to hidden by adding +-fvisibility=hidden (for gcc) +or +-xldscope=hidden (for sun cc) +to CFLAGS + +then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJSON_EXPORT_SYMBOLS does + +*/ + +#define CJSON_CDECL __cdecl +#define CJSON_STDCALL __stdcall + +/* export symbols by default, this is necessary for copy pasting the C and header file */ +#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && !defined(CJSON_EXPORT_SYMBOLS) +#define CJSON_EXPORT_SYMBOLS +#endif + +#if defined(CJSON_HIDE_SYMBOLS) +#define CJSON_PUBLIC(type) type CJSON_STDCALL +#elif defined(CJSON_EXPORT_SYMBOLS) +#define CJSON_PUBLIC(type) __declspec(dllexport) type CJSON_STDCALL +#elif defined(CJSON_IMPORT_SYMBOLS) +#define CJSON_PUBLIC(type) __declspec(dllimport) type CJSON_STDCALL +#endif +#else /* !__WINDOWS__ */ +#define CJSON_CDECL +#define CJSON_STDCALL + +#if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined (__SUNPRO_C)) && defined(CJSON_API_VISIBILITY) +#define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type +#else +#define CJSON_PUBLIC(type) type +#endif +#endif + +/* project version */ +#define CJSON_VERSION_MAJOR 1 +#define CJSON_VERSION_MINOR 7 +#define CJSON_VERSION_PATCH 18 + +#include + +/* cJSON Types: */ +#define cJSON_Invalid (0) +#define cJSON_False (1 << 0) +#define cJSON_True (1 << 1) +#define cJSON_NULL (1 << 2) +#define cJSON_Number (1 << 3) +#define cJSON_String (1 << 4) +#define cJSON_Array (1 << 5) +#define cJSON_Object (1 << 6) +#define cJSON_Raw (1 << 7) /* raw json */ + +#define cJSON_IsReference 256 +#define cJSON_StringIsConst 512 + +/* The cJSON structure: */ +typedef struct cJSON +{ + /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */ + struct cJSON *next; + struct cJSON *prev; + /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */ + struct cJSON *child; + + /* The type of the item, as above. */ + int type; + + /* The item's string, if type==cJSON_String and type == cJSON_Raw */ + char *valuestring; + /* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */ + int valueint; + /* The item's number, if type==cJSON_Number */ + double valuedouble; + + /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */ + char *string; +} cJSON; + +typedef struct cJSON_Hooks +{ + /* malloc/free are CDECL on Windows regardless of the default calling convention of the compiler, so ensure the hooks allow passing those functions directly. */ + void *(CJSON_CDECL *malloc_fn)(size_t sz); + void (CJSON_CDECL *free_fn)(void *ptr); +} cJSON_Hooks; + +typedef int cJSON_bool; + +/* Limits how deeply nested arrays/objects can be before cJSON rejects to parse them. + * This is to prevent stack overflows. */ +#ifndef CJSON_NESTING_LIMIT +#define CJSON_NESTING_LIMIT 1000 +#endif + +/* Limits the length of circular references can be before cJSON rejects to parse them. + * This is to prevent stack overflows. */ +#ifndef CJSON_CIRCULAR_LIMIT +#define CJSON_CIRCULAR_LIMIT 10000 +#endif + +/* returns the version of cJSON as a string */ +CJSON_PUBLIC(const char*) cJSON_Version(void); + +/* Supply malloc, realloc and free functions to cJSON */ +CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks); + +/* Memory Management: the caller is always responsible to free the results from all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is cJSON_PrintPreallocated, where the caller has full responsibility of the buffer. */ +/* Supply a block of JSON, and this returns a cJSON object you can interrogate. */ +CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value); +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length); +/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */ +/* If you supply a ptr in return_parse_end and parsing fails, then return_parse_end will contain a pointer to the error so will match cJSON_GetErrorPtr(). */ +CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated); +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated); + +/* Render a cJSON entity to text for transfer/storage. */ +CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item); +/* Render a cJSON entity to text for transfer/storage without any formatting. */ +CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item); +/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */ +CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt); +/* Render a cJSON entity to text using a buffer already allocated in memory with given length. Returns 1 on success and 0 on failure. */ +/* NOTE: cJSON is not always 100% accurate in estimating how much memory it will use, so to be safe allocate 5 bytes more than you actually need */ +CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format); +/* Delete a cJSON entity and all subentities. */ +CJSON_PUBLIC(void) cJSON_Delete(cJSON *item); + +/* Returns the number of items in an array (or object). */ +CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array); +/* Retrieve item number "index" from array "array". Returns NULL if unsuccessful. */ +CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index); +/* Get item "string" from object. Case insensitive. */ +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string); +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string); +CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string); +/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */ +CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void); + +/* Check item type and return its value */ +CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item); +CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item); + +/* These functions check the type of an item */ +CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item); + +/* These calls create a cJSON item of the appropriate type. */ +CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean); +CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num); +CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string); +/* raw json */ +CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw); +CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void); + +/* Create a string where valuestring references a string so + * it will not be freed by cJSON_Delete */ +CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string); +/* Create an object/array that only references it's elements so + * they will not be freed by cJSON_Delete */ +CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child); +CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child); + +/* These utilities create an Array of count items. + * The parameter count cannot be greater than the number of elements in the number array, otherwise array access will be out of bounds.*/ +CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count); +CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count); +CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count); +CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count); + +/* Append item to the specified array/object. */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item); +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item); +/* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object. + * WARNING: When this function was used, make sure to always check that (item->type & cJSON_StringIsConst) is zero before + * writing to `item->string` */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item); +/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item); +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item); + +/* Remove/Detach items from Arrays/Objects. */ +CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item); +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which); +CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which); +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string); +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string); +CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string); +CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string); + +/* Update array items. */ +CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem); /* Shifts pre-existing items to the right. */ +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement); +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem); +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem); +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object,const char *string,cJSON *newitem); + +/* Duplicate a cJSON item */ +CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse); +/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will + * need to be released. With recurse!=0, it will duplicate any children connected to the item. + * The item->next and ->prev pointers are always zero on return from Duplicate. */ +/* Recursively compare two cJSON items for equality. If either a or b is NULL or invalid, they will be considered unequal. + * case_sensitive determines if object keys are treated case sensitive (1) or case insensitive (0) */ +CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive); + +/* Minify a strings, remove blank characters(such as ' ', '\t', '\r', '\n') from strings. + * The input pointer json cannot point to a read-only address area, such as a string constant, + * but should point to a readable and writable address area. */ +CJSON_PUBLIC(void) cJSON_Minify(char *json); + +/* Helper functions for creating and adding items to an object at the same time. + * They return the added item or NULL on failure. */ +CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean); +CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number); +CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string); +CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw); +CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name); + +/* When assigning an integer value, it needs to be propagated to valuedouble too. */ +#define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number)) +/* helper for the cJSON_SetNumberValue macro */ +CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number); +#define cJSON_SetNumberValue(object, number) ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number)) +/* Change the valuestring of a cJSON_String object, only takes effect when type of object is cJSON_String */ +CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring); + +/* If the object is not a boolean type this does nothing and returns cJSON_Invalid else it returns the new type*/ +#define cJSON_SetBoolValue(object, boolValue) ( \ + (object != NULL && ((object)->type & (cJSON_False|cJSON_True))) ? \ + (object)->type=((object)->type &(~(cJSON_False|cJSON_True)))|((boolValue)?cJSON_True:cJSON_False) : \ + cJSON_Invalid\ +) + +/* Macro for iterating over an array or object */ +#define cJSON_ArrayForEach(element, array) for(element = (array != NULL) ? (array)->child : NULL; element != NULL; element = element->next) + +/* malloc/free objects using the malloc/free functions that have been set with cJSON_InitHooks */ +CJSON_PUBLIC(void *) cJSON_malloc(size_t size); +CJSON_PUBLIC(void) cJSON_free(void *object); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/module/dll_source_lzy/114/out/lib/device_uhd_c.cpp b/module/dll_source_lzy/114/out/lib/device_uhd_c.cpp new file mode 100644 index 0000000..18f7dd9 --- /dev/null +++ b/module/dll_source_lzy/114/out/lib/device_uhd_c.cpp @@ -0,0 +1,1804 @@ + +#include "device_uhd_c.h" +#include "CtrlSpecialDecode.h" +#include "_AlgmDemodulate.h" +#include "cJSON.h" +#include "device_uhd_cpp.h" +#include "device_uhd_struct.h" +#include "error_callback.h" +#include "hulc/DataOutputFormats.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +using namespace std; + +rx_data_cbk_t s_cbk; + +#include +#include +#include + +#include +using namespace std; + +// stringstream error_ss; +// mutex error_ss_mutex; +// device_uhd_c_error_out_cbk_t error_out_cbk; + +typedef struct config_struct_t +{ + char cwd[PATH_MAX]; + char dirpath[PATH_MAX]; + double rx_gain_val = 0; + char rx_clock_ref[50] = {0}; + + char config_name[255]; // = "lib9002config.json"; + char config_path[PATH_MAX]; + char is_save_adsb; + char is_save_yuanshi_iq; + int new_file_zhouqi_s; + int max_save_file_count; + + uint64_t save_yuanshi_size_MByte; + bool need_new_file; + + uint64_t cache_over_byte; + char is_save_gps; + + char is_trans_gps; + + int end_flag = 3; + +} config_struct_t; +ofstream ofs_adsb; +ofstream ofs_yuanshi_iq; +ofstream ofs_gps; +config_struct_t cfg; +std::mutex cfg_mutex; +std::thread *pread_cfg_thread; +bool b_read_cfg_running = false; +deque yuanshi_iq_file_path_dq; + +#include +#include +#include +#include + +void read_cfg_func() +{ + time_t read_cfg_t0 = time(0); + bool b_once = false; + while (b_read_cfg_running) + { + + time_t read_cfg_t1 = time(0); + + if (difftime(read_cfg_t1, read_cfg_t0) > cfg.new_file_zhouqi_s || b_once == false) + { + b_once = true; + { + ifstream ifs(cfg.config_path); + string str; + + if (ifs.is_open()) + { + std::stringstream ss; + ss << ifs.rdbuf(); + str = ss.str(); + ifs.close(); + } + else + { + ofstream ofs(cfg.config_path); + string tmp_str = "{\"gain\":\"30.0\",\"clock_ref\":\"external\",\"is_save_adsb\":\"0\",\"new_file_zhouqi_s\":\"60\",\"max_save_file_count\":\"3\",\"is_save_yuanshi_iq\":\"0\",\"save_yuanshi_size_MByte\":\"0\",\"is_trans_gps\":\"0\",\"is_save_gps\":\"0\"}"; + + ofs.write(tmp_str.c_str(), tmp_str.size()); + str = tmp_str; + ofs.close(); + } + + cJSON *root = nullptr; + if (str.size() > 2) + { + root = cJSON_Parse(str.data()); + } + else + { + sleep(5); + continue; + } + + cJSON *obj_gain = nullptr; + obj_gain = cJSON_GetObjectItem(root, "gain"); + if (obj_gain != nullptr) + { + lock_guard lg(cfg_mutex); + char *value = obj_gain->valuestring; + + cfg.rx_gain_val = std::stof(value); + } + else + { + cJSON_AddItemToObject(root, "gain", cJSON_CreateString("30.0")); + } + + cJSON *obj_clock_ref = nullptr; + obj_clock_ref = cJSON_GetObjectItem(root, "clock_ref"); + if (obj_clock_ref != nullptr) + { + lock_guard lg(cfg_mutex); + char *value = obj_clock_ref->valuestring; + + strcpy(cfg.rx_clock_ref, value); + } + else + { + cJSON_AddItemToObject(root, "clock_ref", cJSON_CreateString("external")); + } + + cJSON *obj_is_save_adsb = nullptr; + obj_is_save_adsb = cJSON_GetObjectItem(root, "is_save_adsb"); + if (obj_is_save_adsb != nullptr) + { + lock_guard lg(cfg_mutex); + char *value = obj_is_save_adsb->valuestring; + + cfg.is_save_adsb = std::stod(value); + } + else + { + cJSON_AddItemToObject(root, "is_save_adsb", cJSON_CreateString("0")); + } + + cJSON *obj_is_save_yuanshi_iq = nullptr; + obj_is_save_yuanshi_iq = cJSON_GetObjectItem(root, "is_save_yuanshi_iq"); + if (obj_is_save_adsb != nullptr) + { + lock_guard lg(cfg_mutex); + char *value = obj_is_save_yuanshi_iq->valuestring; + + cfg.is_save_yuanshi_iq = std::stod(value); + } + else + { + cJSON_AddItemToObject(root, "is_save_yuanshi_iq", cJSON_CreateString("0")); + } + + { + cJSON *obj_new_file_zhouqi_s = nullptr; + obj_new_file_zhouqi_s = cJSON_GetObjectItem(root, "new_file_zhouqi_s"); + if (obj_new_file_zhouqi_s != nullptr) + { + lock_guard lg(cfg_mutex); + char *value = obj_new_file_zhouqi_s->valuestring; + + cfg.new_file_zhouqi_s = std::stod(value); + } + else + { + cJSON_AddItemToObject(root, "new_file_zhouqi_s", cJSON_CreateString("60")); + } + } + + { + cJSON *obj_max_save_file_count = nullptr; + obj_max_save_file_count = cJSON_GetObjectItem(root, "max_save_file_count"); + if (obj_max_save_file_count != nullptr) + { + lock_guard lg(cfg_mutex); + char *value = obj_max_save_file_count->valuestring; + + cfg.max_save_file_count = std::stod(value); + } + else + { + cJSON_AddItemToObject(root, "max_save_file_count", cJSON_CreateString("3")); + } + } + + cJSON *obj_save_yuanshi_size_MByte = nullptr; + obj_save_yuanshi_size_MByte = cJSON_GetObjectItem(root, "save_yuanshi_size_MByte"); + if (obj_save_yuanshi_size_MByte != nullptr) + { + lock_guard lg(cfg_mutex); + char *value = obj_save_yuanshi_size_MByte->valuestring; + + cfg.save_yuanshi_size_MByte = std::stod(value); + } + else + { + cJSON_AddItemToObject(root, "save_yuanshi_size_MByte", cJSON_CreateString("0")); + } + // is_save_gps + + cJSON *obj_is_save_gps = nullptr; + obj_is_save_gps = cJSON_GetObjectItem(root, "is_save_gps"); + if (obj_is_save_gps != nullptr) + { + lock_guard lg(cfg_mutex); + char *value = obj_is_save_gps->valuestring; + + cfg.is_save_gps = std::stod(value); + } + else + { + cJSON_AddItemToObject(root, "is_save_gps", cJSON_CreateString("0")); + } + + // is_trans_gps + cJSON *obj_is_trans_gps = nullptr; + obj_is_trans_gps = cJSON_GetObjectItem(root, "is_trans_gps"); + if (obj_is_trans_gps != nullptr) + { + lock_guard lg(cfg_mutex); + char *value = obj_is_trans_gps->valuestring; + + cfg.is_trans_gps = std::stod(value); + } + else + { + cJSON_AddItemToObject(root, "is_trans_gps", cJSON_CreateString("0")); + } + char *rootstr = cJSON_Print(root); + + ofstream ofs(cfg.config_path); + if (ofs.is_open()) + { + ofs.write(rootstr, strlen(rootstr)); + ofs.close(); + } + free(rootstr); + + cJSON_Delete(root); + + if (cfg.is_save_adsb & !ofs_adsb.is_open()) + { + lock_guard lg(cfg_mutex); + string adsb_path; + + time_t t = time(0); + char t_str[30]; + memset(t_str, 0, 30); + strftime(t_str, sizeof(t_str), "%Y_%m_%d_%H_%M_%S", localtime(&t)); + + adsb_path.append(cfg.dirpath); + adsb_path.append("/adsb").append(t_str).append(".txt"); + ofs_adsb.open(adsb_path); + } + else if (!cfg.is_save_adsb && ofs_adsb.is_open()) + { + + ofs_adsb.close(); + } + if (cfg.is_save_gps && !ofs_gps.is_open()) + { + lock_guard lg(cfg_mutex); + string gps_path; + + time_t t = time(0); + char t_str[30]; + memset(t_str, 0, 30); + strftime(t_str, sizeof(t_str), "%Y_%m_%d_%H_%M_%S", localtime(&t)); + + gps_path.append(cfg.dirpath); + gps_path.append("/gps").append(t_str).append(".txt"); + } + else if (!cfg.is_save_gps && ofs_gps.is_open()) + { + + ofs_gps.close(); + } + + if (cfg.is_save_yuanshi_iq && cfg.save_yuanshi_size_MByte > 0) + { + + lock_guard lg(cfg_mutex); + + if (cfg.need_new_file == true) + { + string yuanshi_path; + if (ofs_yuanshi_iq.is_open()) + { + ofs_yuanshi_iq.close(); + } + + time_t t = time(0); + char t_str[30]; + memset(t_str, 0, 30); + strftime(t_str, sizeof(t_str), "%Y_%m_%d_%H_%M_%S", localtime(&t)); + + yuanshi_path.append(cfg.dirpath); + yuanshi_path.append("/yuanshi").append(t_str).append(".dat"); + + yuanshi_iq_file_path_dq.push_back(yuanshi_path); + if (yuanshi_iq_file_path_dq.size() > cfg.max_save_file_count) + { + + string first = yuanshi_iq_file_path_dq.front(); + yuanshi_iq_file_path_dq.pop_front(); + + std::remove(first.c_str()); + } + + ofs_yuanshi_iq.open(yuanshi_path, ios::binary); + + cfg.need_new_file = false; + } + } + } + read_cfg_t0 = read_cfg_t1; + } + + sleep(5); + } +} +int32_t init9002(void **phandle) +{ + + // + { + memset(cfg.cwd, 0, sizeof(cfg.cwd)); + strcpy(cfg.rx_clock_ref, "external"); + memset(cfg.config_name, 0, sizeof(cfg.config_name)); + memset(cfg.config_path, 0, sizeof(cfg.config_path)); + cfg.rx_gain_val = 30.0; + cfg.is_save_adsb = 0; + cfg.is_save_gps = 0; + cfg.is_save_yuanshi_iq = 0; + cfg.save_yuanshi_size_MByte = 0; + cfg.cache_over_byte = 0; + cfg.need_new_file = true; + cfg.end_flag = 3; + } + Device_UHD *pthis = new Device_UHD(); + // getcwd(cwd, sizeof(cwd) - 1); + + strcpy(cfg.config_name, "lib9002config.json"); + int len = readlink("/proc/self/exe", cfg.cwd, sizeof(cfg.cwd) - 1); + cfg.cwd[len] = '\0'; + char *dir = dirname(cfg.cwd); + + strcpy(cfg.dirpath, dir); + sprintf(cfg.config_path, "%s/%s", dir, cfg.config_name); + // printf("config_path = %s\n", cfg.config_path); + + b_read_cfg_running = true; + + ifstream ifs(cfg.config_path); + string str; + + if (ifs.is_open()) + { + std::stringstream ss; + ss << ifs.rdbuf(); + str = ss.str(); + ifs.close(); + } + else + { + ofstream ofs(cfg.config_path); + string tmp_str = "{\"gain\":\"30.0\",\"clock_ref\":\"external\",\"is_save_adsb\":\"0\",\"new_file_zhouqi_s\":\"60\",\"max_save_file_count\":\"20\",\"is_save_yuanshi_iq\":\"0\",\"save_yuanshi_size_MByte\":\"0\",\"is_trans_gps\":\"0\",\"is_save_gps\":\"0\"}"; + + ofs.write(tmp_str.c_str(), tmp_str.size()); + str = tmp_str; + ofs.close(); + } + + stringstream ss; + + ss << "json_str = " << str << endl; + MACROS_ERROR_CBK_CALL(ss.str().c_str()); + + pread_cfg_thread = new thread(read_cfg_func); + + *phandle = pthis; + return 0; +} +int32_t free9002(void **phandle) +{ + if (phandle != nullptr) + { + b_read_cfg_running = false; + if (pread_cfg_thread && pread_cfg_thread->joinable()) + { + pread_cfg_thread->join(); + delete pread_cfg_thread; + } + Device_UHD *pthis = (Device_UHD *)*phandle; + delete pthis; + pthis = nullptr; + phandle = nullptr; + + return 0; + } + return 0; +} +int32_t isDevOpened(void *phandle, int32_t *result) +{ + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + *result = (int32_t)pthis->isDevOpened(); + return 0; + } + return -1; +} +int32_t findDevices(void *phandle, uhd::device_addrs_t *addrs) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + *addrs = pthis->findDevices(); + return 0; + } + return -1; +} +int32_t openDevice(void *phandle, uhd::device_addr_t addr) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + pthis->openDevice(addr); + return 0; + } + return -1; +} +int32_t closeDevice(void *phandle) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + pthis->closeDevice(); + return 0; + } + return -1; +} +int32_t findDevInfos(void *phandle, char infos[1000]) +{ + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + string str = pthis->findDevInfos(); + strcpy(infos, str.c_str()); + return 0; + } + return -1; +} +int32_t findDevInfos2(void *phandle, char infos[1000]) +{ + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + string str = pthis->findDevInfos2(); + strcpy(infos, str.c_str()); + return 0; + } + return -1; +} +int32_t getDevTree(void *phandle, char tree_infos[1000]) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + string str = pthis->getDevTree(); + strcpy(tree_infos, str.c_str()); + return 0; + } + return -1; +} +int32_t setDevClockSource(void *phandle, char sourceStr[1000]) +{ + stringstream ss; + ss << "sourceStr v:[" << sourceStr << "]" << endl; + MACROS_ERROR_CBK_CALL(ss.str().c_str()); + if (phandle) + { + + Device_UHD *pthis = (Device_UHD *)phandle; + pthis->setDevClockSource(sourceStr); + return 0; + } + return -1; +} +int32_t getDevClockSource(void *phandle, char sourceStr[1000]) +{ + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + string str = pthis->getDevClockSource(); + strcpy(sourceStr, str.c_str()); + return 0; + } + return -1; +} +int32_t setDevInClock(void *phandle, double clockFreq) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + pthis->setDevInClock(clockFreq); + return 0; + } + return -1; +} +int32_t getDevInClockRange(void *phandle, double *min, double *max) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + pthis->getDevInClockRange(); + *min = pthis->getDevParamMin(); + *max = pthis->getDevParamMax(); + return 0; + } + return -1; +} +int32_t getDevInClock(void *phandle, double *val) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + *val = pthis->getDevInClock(); + return 0; + } + return -1; +} +int32_t getDevRXChCount(void *phandle, size_t *val) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + *val = pthis->getDevRXChCount(); + return 0; + } + return -1; +} +int32_t getDevTXChCount(void *phandle, size_t *val) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + *val = pthis->getDevTXChCount(); + return 0; + } + return -1; +} +int32_t setDevParam(void *phandle, char chStr[50], UHD_ParamType paramType, double paramValue) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + pthis->setDevParam(chStr, paramType, paramValue); + return 0; + } + return -1; +} +int32_t getDevParam(void *phandle, char chStr[50], UHD_ParamType paramType, double *paramValue) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + *paramValue = pthis->getDevParam(chStr, paramType); + return 0; + } + return -1; +} +int32_t getDevParamMin(void *phandle, double *val) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + *val = pthis->getDevParamMin(); + return 0; + } + return -1; +} +int32_t getDevParamMax(void *phandle, double *val) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + *val = pthis->getDevParamMax(); + return 0; + } + return -1; +} +int32_t setAllAntenna(void *phandle, int32_t *result) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + *result = pthis->setAllAntenna(); + return 0; + } + return -1; +} +int32_t setDevDDCParam_Any(void *phandle, char chStr[50], unsigned int jcqOffset, unsigned int jcqData) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + pthis->setDevDDCParam_Any(chStr, jcqOffset, jcqData); + return 0; + } + return -1; +} +int32_t getDevDDCParam_Any(void *phandle, char chStr[50], unsigned int jcqOffset, unsigned int *jcqData) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + unsigned int t = 0; + pthis->getDevDDCParam_Any(chStr, jcqOffset, t); + *jcqData = t; + return 0; + } + return -1; +} +int32_t setDevDataSwitch(void *phandle, char chStr[50], UHD_ParamType dataType, unsigned char ZDCh, int bSwitch) +{ + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + pthis->setDevDataSwitch(chStr, dataType, ZDCh, bSwitch); + return 0; + } + return -1; +} +int32_t getDevDataSwitch(void *phandle, char chStr[50], UHD_ParamType dataType, unsigned char ZDCh, int *bSwitch) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + bool b = false; + pthis->getDevDataSwitch(chStr, dataType, ZDCh, b); + *bSwitch = b; + return 0; + } + return -1; +} +int32_t setDevZDParam(void *phandle, char chStr[50], unsigned char ZDCh, long long centerfreq, int bw, int sample) +{ + + if (phandle) + { + + Device_UHD *pthis = (Device_UHD *)phandle; + pthis->setDevZDParam(chStr, ZDCh, centerfreq, bw, sample); + + return 0; + } + return -1; +} +int32_t getDevZDParam(void *phandle, char chStr[50], unsigned char ZDCh, long long *centerfreq, int *bw, int *sample) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + long long c = 0; + int b = 0; + int s = 0; + pthis->getDevZDParam(chStr, ZDCh, c, b, s); + + *centerfreq = c; + *bw = b; + *sample = s; + return 0; + } + return -1; +} +int32_t getDevZDCenterRange(void *phandle, char chStr[50], long long &min, long long &max) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + pthis->getDevZDCenterRange(chStr, min, max); + return 0; + } + return -1; +} +int32_t getDevZDBandWidthRange(void *phandle, char chStr[50], int &min, int &max) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + pthis->getDevZDBandWidthRange(chStr, min, max); + return 0; + } + return -1; +} +int32_t getDevZDSampleFreqRange(void *phandle, char chStr[50], int arr[13], int *valid_len) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + vector v = pthis->getDevZDSampleFreqRange(chStr); + *valid_len = v.size(); + for (int i = 0; i < v.size(); ++i) + { + arr[i] = v[i]; + } + return 0; + } + return -1; +} +int32_t setDevFFTParam(void *phandle, UHD_FFTWin fftWin, UHD_FFTLen fftLen, int fftPeriod_ms) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + pthis->setDevFFTParam(fftWin, fftLen, fftPeriod_ms); + return 0; + } + return -1; +} +int32_t getDevFFTParam(void *phandle, UHD_FFTWin *fftWin, UHD_FFTLen *fftLen, int *fftPeriod_ms) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + UHD_FFTWin _fftWin; + UHD_FFTLen _fftLen; + int _fftPeriod_ms; + pthis->getDevFFTParam(_fftWin, _fftLen, _fftPeriod_ms); + *fftWin = _fftWin; + *fftLen = _fftLen; + *fftPeriod_ms = _fftPeriod_ms; + return 0; + } + return -1; +} +int32_t getDevRecvSpeed(void *phandle, int channel, double *val) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + *val = pthis->getDevSendSpeed(channel); + return 0; + } + return -1; +} +int32_t isDevRecving(void *phandle, int channel, int *result) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + *result = pthis->isDevRecving(channel); + return 0; + } + return -1; +} + +class A +{ + public: + void callBackData_Func(int channel, void *pData, int iLength) { s_cbk(channel, pData, iLength); } +}; +A a; +int32_t startDevRecv(void *phandle, int channel, rx_data_cbk_t rx_cbk) +{ + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + + s_cbk = rx_cbk; + + pthis->callBackData = std::bind(&A::callBackData_Func, &a, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3); + pthis->startDevRecv(channel); + return 0; + } + return -1; +} +int32_t stopDevRecv(void *phandle, int channel) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + pthis->stopDevRecv(channel); + return 0; + } + return -1; +} +int32_t getDevSendSpeed(void *phandle, int channel, double *val) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + *val = pthis->getDevSendSpeed(channel); + return 0; + } + return -1; +} +int32_t isDevSending(void *phandle, int channel, int32_t *result) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + *result = (int32_t)pthis->isDevSending(channel); + + return 0; + } + return -1; +} +int32_t startDevSend(void *phandle, int channel, unsigned long long send_cf, unsigned long long data_sf, char *filename, int bwhile) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + pthis->startDevSend(channel, send_cf, data_sf, filename, bwhile); + return 0; + } + return -1; +} +int32_t stopDevSend(void *phandle, int channel) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + pthis->stopDevSend(channel); + return 0; + } + return -1; +} +int32_t getGPSInfo(void *phandle, char gps_info[50]) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + string str = pthis->getGPSInfo(); + + strcpy(gps_info, str.c_str()); + return 0; + } + return -1; +} +int32_t setLedEnable(void *phandle, int led_num, int bEnable) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + pthis->setLedEnable(led_num, bEnable); + return 0; + } + return -1; +} +int32_t getLedEnable(void *phandle, int led_num, int *bEnable) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + bool b = false; + pthis->getLedEnable(led_num, b); + *bEnable = b; + return 0; + } + return -1; +} + +#include +#include +typedef struct context_t +{ + public: + void *pdev; + adsb_msg_cbk_t adsb_cbk; + thread *t_getgps; + + bool b_pool_over; + void *adsb_pusr; +} context_t; +unsigned long long msgNo = 0; +void *phandle_math_3a_decode = nullptr; +int lastframindex_ch0_zdddc = 0; +int lastframindex_ch0_fft = 0; +int lastframindex_ch1_zdddc = 0; +int lastframindex_ch1_fft = 0; +iq_cbk_t iq_cbk; +void *iq_pusr; +extern volatile bool iio_context_find_err[2]; + +#include +int BCDToDec(int bcd, int byt) +{ + if (1 == byt) + { + return bcd - (bcd >> 4) * 6; + } + else + { + int nDec = 0; + for (int i = 0; i < byt; i++) + { + uint8_t ucBcd = (uint8_t)(bcd >> (8 * i)); + nDec += ((ucBcd - (ucBcd >> 4) * 6) * (int)std::pow(100, i)); + } + return nDec; + } +} + +time_t get_2000_1_1_000_time_t() +{ + struct tm tt; + tt.tm_year = 2000 - 1900; + tt.tm_mon = 0; + tt.tm_mday = 1; + tt.tm_hour = 0; + tt.tm_min = 0; + tt.tm_sec = 0; + return mktime(&tt); +} + +int flag1 = 0; +int is_leap_year(int year) +{ + return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); +} +void day_of_year_to_month_day(int year, int day_of_year, int *month, int *day) +{ + int days_per_month[] = { + 31, // 1 月 大 + 28, // 2 月 平 + 31, // 3 月 大 + 30, // 4 月 小 + 31, // 5 月 大 + 30, // 6 月 小 + 31, // 7 月 大 + 31, // 8 月 大 + 30, // 9 月 小 + 31, // 10月 大 + 30, // 11月 小 + 31 // 12月 大 + }; + if (is_leap_year(year)) + { + days_per_month[1] = 29; + } + *month = 1; + *day = day_of_year; + for (int i = 0; i < 12 && *day > days_per_month[i]; ++i) + { + *day -= days_per_month[i]; + (*month)++; + } +} + +// uint64_t rev_cbk_lenght_per_s = 0; +// time_t recv_time_t0 = time(0); + +int last_type = 0; + +time_t print_t1; +time_t print_t2; + +string get_UHD_Enum_DataType(UHD_Enum_DataType v) +{ + string ttttttt; + switch (v) + { + + case zd_ddc: { + ttttttt = "zd_ddc"; + } + break; + case kd_ddc: { + ttttttt = "kd_ddc"; + } + break; + case kd_fft: { + ttttttt = "kd_fft"; + } + break; + case GPS_Info: { + ttttttt = "GPS_Info"; + } + break; + default: + break; + } + return ttttttt; +} +void _rx_data_cbk_t(int channel, void *pdata, int length) +{ + + if (iq_cbk != NULL && channel != 0) + { + iq_cbk(iq_pusr, pdata, length); + } + // if (phandle_math_3a_decode) + // { + // + // int nErr = SpecDecdInput(phandle_math_3a_decode, ((char *)pdata + 64), 2048, 0); + // int a = 0; + // } + + UHD_Struct_KDDC *p = (UHD_Struct_KDDC *)pdata; + if (last_type != (int)p->DataType) + { + last_type = (int)p->DataType; + } + + // 丢帧打印t + { + + int data_channel = p->Channel; + + if (data_channel == 0 && p->DataType == UHD_Enum_DataType::zd_ddc) + { + int cha = p->FrameIndex - lastframindex_ch0_zdddc; + time_t tmp_t = time(0); + if (p->FrameIndex != 0 && lastframindex_ch0_zdddc != 0 && cha != 1 && cha != -65535 && difftime(tmp_t, print_t1) > 5) + { + stringstream ss; + ss << "loseframe!!!=> channel:[" << channel << "]\tcurrent_index:[" << p->FrameIndex << "]\tlast_index:[" << lastframindex_ch0_zdddc << "]" << endl; + MACROS_ERROR_CBK_CALL(ss.str().c_str()); + print_t1 = tmp_t; + } + lastframindex_ch0_zdddc = p->FrameIndex; + } + // TODO:test else if (channel == 1 && p->DataType == UHD_Enum_DataType::zd_ddc) + else if (data_channel == 1 && p->DataType == UHD_Enum_DataType::zd_ddc) + { + int cha = p->FrameIndex - lastframindex_ch1_zdddc; + time_t tmp_t = time(0); + if (p->FrameIndex != 0 && lastframindex_ch1_zdddc != 0 && cha != 1 && cha != -65535 && difftime(tmp_t, print_t2) > 5) + { + stringstream ss; + ss << "loseframe!!!=> channel:[" << channel << "]\tcurrent_index:[" << p->FrameIndex << "]\tlast_index:[" << lastframindex_ch1_zdddc << "]" << endl; + MACROS_ERROR_CBK_CALL(ss.str().c_str()); + print_t2 = tmp_t; + } + lastframindex_ch1_zdddc = p->FrameIndex; + } + } + + // 原始文件存储 + + if (p->DataType == zd_ddc && channel == 0) + { + { + lock_guard lg(cfg_mutex); + cfg.cache_over_byte += length; + int mbyte = cfg.cache_over_byte / (1024 * 1024); + + if (cfg.is_save_yuanshi_iq && cfg.save_yuanshi_size_MByte > 0 && ofs_yuanshi_iq.is_open() && (mbyte < (cfg.save_yuanshi_size_MByte))) + { + ofs_yuanshi_iq.write((char *)pdata, length); + return; + } + else if (cfg.save_yuanshi_size_MByte >= mbyte) + { + + cfg.cache_over_byte = 0; + cfg.is_save_yuanshi_iq = 0; + cfg.need_new_file = true; + } + } + + struct_DataTime *dt = &p->DateTm; + struct tm tt2; + memset(&tt2, 0, sizeof(struct tm)); + uint64_t result_nsec = 0; + + switch (dt->TimeType) + { + case Enum_TimeType_Invlid: { + result_nsec = 0; + } + break; + case Enum_TimeType_IRIG_B: { + int B_Year = BCDToDec(dt->TimeInfo.IRIGB_Head.Year, 1) + 2000; + int B_Day = BCDToDec(dt->TimeInfo.IRIGB_Head.Day, 2); + int B_Hour = BCDToDec(dt->TimeInfo.IRIGB_Head.Hour, 1); + int B_Minute = BCDToDec(dt->TimeInfo.IRIGB_Head.Minute, 1); + int B_Second = BCDToDec(dt->TimeInfo.IRIGB_Head.Second, 1); + uint32_t B_NSec = dt->TimeInfo.IRIGB_Head.NanoSec; + + tm my_tm; + int month; + int day; + day_of_year_to_month_day(B_Year, B_Day, &month, &day); + + tt2.tm_year = B_Year - 1900; + tt2.tm_mon = month - 1; + tt2.tm_mday = day; + tt2.tm_hour = B_Hour; + tt2.tm_min = B_Minute; + tt2.tm_sec = B_Second; + + // stringstream ss; + // ss << " y1=" << tt2.tm_year << "\n" + // << " M1=" << tt2.tm_mon << "\n" + // << " D1=" << tt2.tm_mday << "\n" + // << " H1=" << tt2.tm_hour << "\n" + // << " m1=" << tt2.tm_min << "\n" + // << " s1=" << tt2.tm_sec << "\n" + // << " nsec" << B_NSec << endl; + // error_callback_call(ss.str().c_str()); + + time_t t2 = mktime(&tt2); + // t2+= dt->TimeInfo.RMC_Head.NanoSec; + result_nsec = t2 * 1000000000 + B_NSec; + } + break; + case Enum_TimeType_RMC: { + + // time_t t1 = get_2000_1_1_000_time_t(); + + tt2.tm_year = dt->TimeInfo.RMC_Head.Year + 2000 - 1900; + tt2.tm_mon = dt->TimeInfo.RMC_Head.Month - 1; + tt2.tm_mday = dt->TimeInfo.RMC_Head.Day; + tt2.tm_hour = dt->TimeInfo.RMC_Head.Hour; + tt2.tm_min = dt->TimeInfo.RMC_Head.Minute; + tt2.tm_sec = dt->TimeInfo.RMC_Head.Second; + + time_t t2 = mktime(&tt2); + // t2+= dt->TimeInfo.RMC_Head.NanoSec; + result_nsec = t2 * 1000000000 + dt->TimeInfo.RMC_Head.NanoSec + (8ull * 3600 * 1000000000ull); + + if (flag1 == 0) + { + // stringstream ss; + // ss << "\n dt_type" << (int)dt->TimeType << "\n" + // << " y1=" << tt2.tm_year<< "\n" + // << " M1=" << tt2.tm_mon<< "\n" + // << " D1=" << tt2.tm_mday<< "\n" + // << " H1=" << tt2.tm_hour<< "\n" + // << " m1=" << tt2.tm_min<< "\n" + // << " s1=" << tt2.tm_sec << "\n" + // << " nsec" << tt2.tm_sec << "\n" + // << "result_nsec" << result_nsec << "\n" + // << "this is for input" << endl; + // error_callback_call(ss.str().c_str()); + flag1 = 1; + } + } + break; + case Enum_TimeType_ABSCNTTM: { + uint64_t sec_n = ((uint64_t)dt->TimeInfo.ABSCNTTM_Head.Second) * 1000000000; + result_nsec = dt->TimeInfo.ABSCNTTM_Head.NanoSec + sec_n; + } + break; + case Enum_TimeType_REFCNTTM: { + uint64_t sec_n = ((uint64_t)dt->TimeInfo.REFCNTTM_Head.Second) * 1000000000; + result_nsec = dt->TimeInfo.REFCNTTM_Head.NanoSec + sec_n; + } + break; + default: + break; + } + + if (result_nsec > 0 && phandle_math_3a_decode) + { + + int nErr = SpecDecdInput(phandle_math_3a_decode, ((char *)pdata + 64), 2048, result_nsec); + if (nErr != 0) + { + stringstream ss; + ss << "t数据溢出" << endl; + MACROS_ERROR_CBK_CALL(ss.str().c_str()); + } + } + } +} + +int flag2 = 0; + +// // // TODO:以下三行测试用,没有关闭操作,记得及时删除 +// #include +// fstream g_fsTst2("test_time.txt",ios::app); +// fstream g_fsTst1("test_for_server.txt",ios::app); +time_t mesc_to_time_t(int64_t mesc) +{ + auto sec = std::chrono::duration_cast(std::chrono::milliseconds(mesc)); + auto time_point = std::chrono::system_clock::time_point(sec); + return std::chrono::system_clock::to_time_t(time_point); +} +void SpecDecdRetClbkFun(void *hdl, int taskId, MSpecDecdSigType sigType, char *data, int length) +{ + context_t *pthis = (context_t *)hdl; + USpecDecdRet *pRet = (USpecDecdRet *)data; + char cRet[1024] = {0}; + char cRet2[1024] = {0}; + switch (sigType) + { + case MSpecDecdSigType::ADSB: { + time_t u64Time = pRet->ADSBRet.Time / 1000000000; + // time_t l_tm_t = u64Time + 8 * 3600; + time_t l_tm_t = u64Time; // 改为UTC时间基准 + + tm TmTime = *(gmtime(&l_tm_t)); + TmTime.tm_year += 1900; + TmTime.tm_mon += 1; + TmTime.tm_hour; + + // // TODO:测试用 + // { + // unsigned long long ullSec = ((TmTime.tm_hour * 60) + TmTime.tm_min) * 60 + TmTime.tm_sec; + // unsigned long long ullNSec = pRet->ADSBRet.Time % 1000000000; + // unsigned long long ullTime = ((ullSec & 0x3FFFF)) << 30 | (ullNSec & 0x3FFFFFFF); + // char cTime[6] = {0}; + // memcpy(cTime, &ullTime, 6); + // for (int i = 0, j = 5; i < j; i++, j--) //小端转大端 + // { + // char cTemp = cTime[i]; + // cTime[i] = cTime[j]; + // cTime[j] = cTemp; + // } + // std::string strMsg = ""; + // for (int i = 0; i < 6; i++) + // { + // char cByte[16] = {0}; + // sprintf(cByte, " %02X", cTime[i] & 0xFF); + // strMsg += cByte; + // } + // //测试用 + // char cMsg[256] = {0}; + // sprintf(cMsg, "%s\n", strMsg.c_str()); + // // g_fsTst2.write(cMsg, strlen(cMsg)); + // // g_fsTst2.flush(); + // } + + if (flag2 == 0) + { + // stringstream ss; + // ss << " y2=" << TmTime.tm_year << "\n" + // << " M2=" << TmTime.tm_mon << "\n" + // << " D2=" << TmTime.tm_mday << "\n" + // << " H2=" << TmTime.tm_hour << "\n" + // << " m2=" << TmTime.tm_min << "\n" + // << " s2=" << TmTime.tm_sec << "\n" + // << " SpecDecdRetClbkFun " << "\n" + // << " TmTime.tm_hour" << TmTime.tm_hour << " pRet->ADSBRet.Time" << pRet->ADSBRet.Time << " u64Time" << u64Time << std::endl; + // error_callback_call(ss.str().c_str()); + flag2 = 1; + } + int nMsgLen = 0; + for (int i = sizeof(pRet->ADSBRet.Msg) - 1; i >= 0; i--) + { + if (0 != pRet->ADSBRet.Msg[i]) + { + nMsgLen = i + 1; + break; + } + } + if (nMsgLen >= 28) + { + nMsgLen = 28; + } + else if (nMsgLen >= 14) + { + nMsgLen = 14; + } + else + { + nMsgLen = 4; + } + // char cMsg[1024] = {0}; + // for (int i = 0; i < nMsgLen; i++) + // { + // sprintf(&cMsg[i*2], "%02x", pRet->ADSBRet.Msg[i]); + // } + // sprintf(cRet, "#%03d 0x%06x %08s %02d Lon:%f Lat:%f Alt:%f %s, %04d-%02d-%02d %02d:%02d:%02d\r", + // ++msgNo, pRet->ADSBRet.ICAO, pRet->ADSBRet.FltNo, pRet->ADSBRet.Label, pRet->ADSBRet.Longitude, pRet->ADSBRet.Latitude, pRet->ADSBRet.Altitude, cMsg, + // TmTime.tm_year, TmTime.tm_mon, TmTime.tm_mday, TmTime.tm_hour, TmTime.tm_min, TmTime.tm_sec); + // 按规定格式输出报文 + std::string strMsg = "1A"; + switch (nMsgLen / 2) + { + case 2: + strMsg += " 31"; + break; + case 7: + strMsg += " 32"; + break; + case 14: + strMsg += " 33"; + break; + default: + break; + } + unsigned long long ullSec = ((TmTime.tm_hour * 60) + TmTime.tm_min) * 60 + TmTime.tm_sec; + // if (ullSec > 86400) //86400 = 24*60*60 + // { + // return; + // } + unsigned long long ullNSec = pRet->ADSBRet.Time % 1000000000; + unsigned long long ullTime = ((ullSec & 0x3FFFF) << 30) | (ullNSec & 0x3FFFFFFF); + char cTime[6] = {0}; + memcpy(cTime, &ullTime, 6); + for (int i = 0, j = 5; i < j; i++, j--) // 小端转大端 + { + char cTemp = cTime[i]; + cTime[i] = cTime[j]; + cTime[j] = cTemp; + } + for (int i = 0; i < 6; i++) + { + if (26 == cTime[i]) + { + strMsg += " 1A"; + } + char cByte[16] = {0}; + sprintf(cByte, " %02X", cTime[i] & 0xFF); + strMsg += cByte; + } + int nRSSI = (int)(pRet->ADSBRet.RSSI + 0.5); + if (26 == (nRSSI & 0xFF)) + { + strMsg += " 1A"; + } + char cRSSI[16] = {0}; + sprintf(cRSSI, " %02X", nRSSI & 0xFF); + strMsg += cRSSI; + for (int i = 0; i < nMsgLen / 2; i++) + { + if ('1' == pRet->ADSBRet.Msg[2 * i] && ('a' == pRet->ADSBRet.Msg[2 * i + 1] || 'A' == pRet->ADSBRet.Msg[2 * i + 1])) + { + strMsg += " 1A"; + } + char cByte[8] = {0}; + sprintf(cByte, " %C%C", toupper(pRet->ADSBRet.Msg[2 * i]), toupper(pRet->ADSBRet.Msg[2 * i + 1])); + strMsg += cByte; + } + sprintf(cRet, "%s", strMsg.c_str()); + } + break; + default: + break; + } + // if (strlen(cRet) > 0) + // { + // // printf(cRet); + // // printf("\n"); + // } + + // //TODO:测试用 + // { + // char cMsg[256] = {0}; + // sprintf(cMsg, "%s\r", cRet); + // g_fsTst1.write(cMsg, strlen(cMsg)); + // g_fsTst1.flush(); + // } + + if (cfg.is_save_adsb && ofs_adsb.is_open()) + { + ofs_adsb << cRet; + } + pthis->adsb_cbk(pthis->adsb_pusr, cRet, strlen(cRet)); +} + +int32_t ex_declare init_adsb9002(void **phandle, adsb_msg_cbk_t cbk, void *pusr) +{ + context_t *pthis = new context_t(); + pthis->adsb_cbk = cbk; + pthis->adsb_pusr = pusr; + phandle_math_3a_decode = 0; + pthis->pdev = nullptr; + init9002(&pthis->pdev); + if (!pthis->pdev) + { + + stringstream ss; + ss << "pdev init error" << endl; + MACROS_ERROR_CBK_CALL(ss.str().c_str()); + return -1; + } + uhd::device_addrs_t s; + + if (findDevices(pthis->pdev, &s) != 0) + { + + stringstream ss; + ss << "findDevices error!" << endl; + MACROS_ERROR_CBK_CALL(ss.str().c_str()); + return -1; + } + else + { + } + if (openDevice(pthis->pdev, s[0]) != 0) + { + + stringstream ss; + ss << "openDevice error!" << endl; + MACROS_ERROR_CBK_CALL(ss.str().c_str()); + + return -1; + } + else + { + } + // 关闭开关 + setDevDataSwitch(pthis->pdev, "RX0", UHD_ParamType::ZDDCSwitch, 0, false); + setDevDataSwitch(pthis->pdev, "RX0", UHD_ParamType::KFFTSwitch, 0, false); + setDevDataSwitch(pthis->pdev, "RX0", UHD_ParamType::KDDCSwitch, 0, false); + + setDevDataSwitch(pthis->pdev, "RX1", UHD_ParamType::ZDDCSwitch, 8, false); + setDevDataSwitch(pthis->pdev, "RX1", UHD_ParamType::KFFTSwitch, 8, false); + setDevDataSwitch(pthis->pdev, "RX1", UHD_ParamType::KDDCSwitch, 8, false); + // 启动接收线程 + if (startDevRecv(pthis->pdev, 0, _rx_data_cbk_t) != 0) + { + stringstream ss; + ss << "startDevRecv 0 error!" << endl; + MACROS_ERROR_CBK_CALL(ss.str().c_str()); + return -1; + } + else + { + } + if (startDevRecv(pthis->pdev, 1, _rx_data_cbk_t) != 0) + { + stringstream ss; + ss << "startDevRecv 1 error!" << endl; + MACROS_ERROR_CBK_CALL(ss.str().c_str()); + return -1; + } + else + { + } + // 设置默认参数 + setDevParam(pthis->pdev, "RX0", UHD_ParamType::CenterFreq, 1089000000); + setDevParam(pthis->pdev, "RX0", UHD_ParamType::BandWidth, 6000000); + setDevParam(pthis->pdev, "RX0", UHD_ParamType::SampleFreq, 24000000); + setDevParam(pthis->pdev, "RX0", UHD_ParamType::Gain, cfg.rx_gain_val); + + setDevParam(pthis->pdev, "RX1", UHD_ParamType::CenterFreq, 15000000); + setDevParam(pthis->pdev, "RX1", UHD_ParamType::BandWidth, 30000000); + setDevParam(pthis->pdev, "RX1", UHD_ParamType::SampleFreq, 61440000); + setDevParam(pthis->pdev, "RX1", UHD_ParamType::Gain, cfg.rx_gain_val); + + setDevZDParam(pthis->pdev, "RX0", 0, 1090000000, 3000000, 12000000); + setDevClockSource(pthis->pdev, cfg.rx_clock_ref); + setDevDataSwitch(pthis->pdev, "RX0", UHD_ParamType::ZDDCSwitch, 0, true); + + int nFs = 12000000; + SpecDecdInit(&phandle_math_3a_decode, 0, MSpecDecdSigType::ADSB, MSpecDecdDaType::ShortC, nFs, 1, SpecDecdRetClbkFun, pthis); + + pthis->b_pool_over = false; + pthis->t_getgps = new thread( + [=](context_t *ppthis) { + time_t t1 = time(0); + int print_times = 0; + while (ppthis->b_pool_over == false) + { + time_t t2 = time(0); + if (difftime(t2, t1) > 2) + { + t1 = t2; + char gpsinfo[50]; + memset(gpsinfo, 0, 50); + + getGPSInfo(ppthis->pdev, gpsinfo); + string gpsinfostr = gpsinfo; + if (gpsinfostr.size() <= 0) + { + continue; + } + + int mposi = gpsinfostr.find('M'); + + if (mposi != std::string::npos || mposi < 10) + { + + string sub; + double h = stod(gpsinfostr.substr(0, mposi)); + char zl = gpsinfostr.substr(mposi + 1, 1).at(0); + if (zl != '1') + { + continue; + } + char ew = gpsinfostr.substr(mposi + 2, 1).at(0); + int lon_du = stoi(gpsinfostr.substr(mposi + 3, 3)); + int lon_fen_zhengshu = stoi(gpsinfostr.substr(mposi + 6, 2)); + int lon_fen_xiaoshu = stoi(gpsinfostr.substr(mposi + 8, 4)); + + char ns = gpsinfostr.substr(mposi + 12, 1).at(0); + int lat_du = stoi(gpsinfostr.substr(mposi + 13, 2)); + int lat_fen_zhengshu = stoi(gpsinfostr.substr(mposi + 15, 2)); + int lat_fen_xiaoshu = stoi(gpsinfostr.substr(mposi + 17, 4)); + + double lon_fen = lon_fen_zhengshu + lon_fen_xiaoshu / 10000.0; + double longitude = lon_du + lon_fen / 60.0; + + // 根据东西经度调整符号 + if (ew == 'W') + { + longitude = -longitude; + } + + // 计算纬度 + // 将分数的小数部分转换为小数形式(假设小数部分是4位数字) + double lat_fen = lat_fen_zhengshu + lat_fen_xiaoshu / 10000.0; + double latitude = lat_du + lat_fen / 60.0; + + // 根据南北纬度调整符号 + if (ns == 'S') + { + latitude = -latitude; + } + + if (print_times < 3) + { + print_times++; + stringstream ss; + ss << "经度:[" << longitude << "°]\t纬度:[" << latitude << "°]\t\t海拔:[" << h << "m]" << endl; + MACROS_ERROR_CBK_CALL(ss.str().c_str()); + } + + HULC_Status_Message message; + + message.set_latitude(latitude); + message.set_longitude(longitude); + message.Alt = (int16_t)h; + + auto lat = message.get_latitude(); + auto lon = message.get_longitude(); + auto alt = message.Alt; + + auto bin = mem2hex(packet_to_escape_format(message.toBinary())); + + char *c = (char *)bin.c_str(); + int len = bin.size(); + + if (cfg.is_trans_gps == 1) + { + pthis->adsb_cbk(pthis->adsb_pusr, c, len); + } + if (cfg.is_save_gps && ofs_gps.is_open()) + { + ofs_gps << "经度:" << longitude << "°" << "\t纬度: " << latitude << "°" << "\t海拔: " << h << "m" << "\tbin_str:" << bin.c_str() << endl; + } + } + } + usleep(500000); + } + }, + pthis); + int a = 1; + *phandle = pthis; + if (iio_context_find_err[0] || iio_context_find_err[1]) + { + + stringstream ss; + ss << "9002 init failed!" << endl; + MACROS_ERROR_CBK_CALL(ss.str().c_str()); + return -1; + } + return 0; +} + +int32_t ex_declare free_adsb9002(void **phandle) +{ + context_t *pthis = (context_t *)*phandle; + if (pthis->pdev) + { + int32_t result = 0; + isDevOpened(pthis->pdev, &result); + if (result > 0) + { + setDevDataSwitch(pthis->pdev, "RX0", UHD_ParamType::ZDDCSwitch, 0, 0); + setDevDataSwitch(pthis->pdev, "RX0", UHD_ParamType::KFFTSwitch, 0, 0); + setDevDataSwitch(pthis->pdev, "RX0", UHD_ParamType::KDDCSwitch, 0, 0); + setDevDataSwitch(pthis->pdev, "RX1", UHD_ParamType::ZDDCSwitch, 8, 0); + setDevDataSwitch(pthis->pdev, "RX1", UHD_ParamType::KFFTSwitch, 8, 0); + setDevDataSwitch(pthis->pdev, "RX1", UHD_ParamType::KDDCSwitch, 8, 0); + if (stopDevRecv(pthis->pdev, 0) != 0) + { + + stringstream ss; + ss << "stopDevRecv 0 error!" << endl; + MACROS_ERROR_CBK_CALL(ss.str().c_str()); + } + else + { + } + if (stopDevRecv(pthis->pdev, 1) != 0) + { + + stringstream ss; + ss << "stopDevRecv 1 error!" << endl; + MACROS_ERROR_CBK_CALL(ss.str().c_str()); + } + else + { + } + closeDevice(pthis->pdev); + if (pthis->t_getgps->joinable()) + { + pthis->b_pool_over = true; + pthis->t_getgps->join(); + } + pthis->t_getgps = nullptr; + } + free9002(&pthis->pdev); + } + pthis->pdev = nullptr; + SpecDecdFree(&phandle_math_3a_decode); + if (ofs_adsb.is_open()) + { + ofs_adsb.close(); + } + if (ofs_gps.is_open()) + { + ofs_gps.close(); + } + if (ofs_yuanshi_iq.is_open()) + { + ofs_yuanshi_iq.close(); + } + return 0; +} + +int ex_declare set_iq_cbk(void *phandle, iq_cbk_t recv_cbk, void *pusr) +{ + if (phandle) + { + context_t *pthis = (context_t *)phandle; + iq_cbk = recv_cbk; + iq_pusr = pusr; + return 0; + } + return -1; +} + +int ex_declare set_less_30Mhz_ddc_param(void *phandle, uint64_t cf_hz, uint64_t sf_hz, uint64_t bw_hz, int8_t sw) +{ + if (phandle) + { + context_t *pthis = (context_t *)phandle; + // setDevDataSwitch(pthis->pdev, "RX1", UHD_ParamType::ZDDCSwitch, 0, false); + setDevDataSwitch(pthis->pdev, "RX1", UHD_ParamType::ZDDCSwitch, 8, false); + setDevZDParam(pthis->pdev, "RX1", 8, cf_hz, bw_hz, sf_hz); + setDevDataSwitch(pthis->pdev, "RX1", UHD_ParamType::ZDDCSwitch, 8, true); + return 0; + } + return -1; +} + +int ex_declare set_less_30Mhz_fft_param(void *phandle, int fftWin, int fftLen, int fftPeriod_ms, int8_t sw) +{ + if (phandle) + { + context_t *pthis = (context_t *)phandle; + setDevDataSwitch(pthis->pdev, "RX1", UHD_ParamType::KFFTSwitch, 8, false); + setDevFFTParam(pthis->pdev, (UHD_FFTWin)fftWin, (UHD_FFTLen)fftLen, fftPeriod_ms); + setDevDataSwitch(pthis->pdev, "RX1", UHD_ParamType::KFFTSwitch, 8, true); + + return 0; + } + return -1; +} + +#pragma region 王永琛代码 +struct Global_Read_Buffer +{ + Global_Read_Buffer(); + ~Global_Read_Buffer(); + std::string read() + { + std::lock_guard g(mtx); + std::string ret; + std::swap(ret, buffer); + return ret; + } + void append(std::string buf) + { + std::lock_guard g(mtx); + buffer.append(buf); + } + + void *phandle{}; + std::mutex mtx; + std::string buffer; +}; + +#include "error_callback.h" +void my_error_cbk_t(const char *err_msg) +{ + cout << err_msg << endl; +} + +Global_Read_Buffer t; + +void adsb2(void *pusr, char *pmsg, int msglen) +{ + t.append(std::string(pmsg, msglen)); +} +void _iq_cbk_t(void *phandle, void *pdata, uint64_t length) +{ + // cout << "FUNC:[dev_uhd_c::" << __func__ << "]\tcbk called!!!!!!!" << endl; +} +Global_Read_Buffer::Global_Read_Buffer() +{ + init_adsb9002(&phandle, adsb2, nullptr); + set_iq_cbk(phandle, _iq_cbk_t, nullptr); +} + +Global_Read_Buffer::~Global_Read_Buffer() +{ + free_adsb9002(&phandle); +} + +std::string adsb_read() +{ + // return t.read(); + return t.read(); +} + +#include +void adsb_read(char *buf, std::uint16_t *len) +{ + auto s = t.read(); + *len = s.size(); + std::memcpy(buf, s.c_str(), *len); +} + +int adsb_set_iq_cbk(iq_cbk_t recv_cbk, void *pusr) +{ + stringstream ss; + ss << "adsb_set_iq_cbk " << pusr << " " << recv_cbk << " " << std::endl; + MACROS_ERROR_CBK_CALL(ss.str().c_str()); + return set_iq_cbk(t.phandle, recv_cbk, pusr); +} + +int adsb_set_less_30Mhz_ddc_param(uint64_t cf_hz, uint64_t sf_hz, uint64_t bw_hz, int8_t sw) +{ + + stringstream ss; + ss << "adsb_set_less_30Mhz_ddc_param " << cf_hz << " " << sf_hz << " " << bw_hz << " " << sw << " " << std::endl; + MACROS_ERROR_CBK_CALL(ss.str().c_str()); + return set_less_30Mhz_ddc_param(t.phandle, cf_hz, sf_hz, bw_hz, sw); +} + +int adsb_set_less_30Mhz_fft_param(uint64_t fftWin, uint64_t fftLen, int fftPeriod_ms, int8_t sw) +{ + stringstream ss; + ss << "adsb_set_less_30Mhz_fft_param " << fftWin << " " << fftLen << " " << fftPeriod_ms << " " << sw << std::endl; + MACROS_ERROR_CBK_CALL(ss.str().c_str()); + return set_less_30Mhz_fft_param(t.phandle, fftWin, fftLen, fftPeriod_ms, sw); +} + +#pragma endregion \ No newline at end of file diff --git a/module/dll_source_lzy/114/out/lib/device_uhd_c.h b/module/dll_source_lzy/114/out/lib/device_uhd_c.h new file mode 100644 index 0000000..8f4f347 --- /dev/null +++ b/module/dll_source_lzy/114/out/lib/device_uhd_c.h @@ -0,0 +1,108 @@ +#ifndef _DEVICE_UHD_C_H_ +#define _DEVICE_UHD_C_H_ + +#include "device_uhd_struct.h" +#include "makelib_common.h" +#include "error_callback.h" +// #include "device_uhd_cpp.h" +#include + +typedef void (*rx_data_cbk_t)(int channel, void *pdata, int length); + +extern "C" +{ + int32_t ex_declare init9002(void **phandle); + int32_t ex_declare free9002(void **phandle); + int32_t ex_declare isDevOpened(void *phandle, int32_t *result); + int32_t ex_declare findDevices(void *phandle, uhd::device_addrs_t *addrs); + int32_t ex_declare openDevice(void *phandle, uhd::device_addr_t addr); + int32_t ex_declare closeDevice(void *phandle); + int32_t ex_declare findDevInfos(void *phandle, char infos[1000]); + int32_t ex_declare findDevInfos2(void *phandle, char infos[1000]); + int32_t ex_declare getDevTree(void *phandle, char tree_infos[1000]); + int32_t ex_declare setDevClockSource(void *phandle, char sourceStr[1000]); + int32_t ex_declare getDevClockSource(void *phandle, char sourceStr[1000]); + int32_t ex_declare setDevInClock(void *phandle, double clockFreq); + int32_t ex_declare getDevInClockRange(void *phandle, double *min, double *max); + int32_t ex_declare getDevInClock(void *phandle, double *val); + int32_t ex_declare getDevRXChCount(void *phandle, size_t *val); + int32_t ex_declare getDevTXChCount(void *phandle, size_t *val); + int32_t ex_declare setDevParam(void *phandle, char chStr[50], UHD_ParamType paramType, double paramValue); + int32_t ex_declare getDevParam(void *phandle, char chStr[50], UHD_ParamType paramType, double *paramValue); + int32_t ex_declare getDevParamMin(void *phandle, double *val); + int32_t ex_declare getDevParamMax(void *phandle, double *val); + int32_t ex_declare setAllAntenna(void *phandle, int32_t *result); + int32_t ex_declare setDevDDCParam_Any(void *phandle, char chStr[50], unsigned int jcqOffset, unsigned int jcqData); + int32_t ex_declare getDevDDCParam_Any(void *phandle, char chStr[50], unsigned int jcqOffset, unsigned int *jcqData); + int32_t ex_declare setDevDataSwitch(void *phandle, char chStr[50], UHD_ParamType dataType, unsigned char ZDCh, int bSwitch); + int32_t ex_declare getDevDataSwitch(void *phandle, char chStr[50], UHD_ParamType dataType, unsigned char ZDCh, int *bSwitch); + int32_t ex_declare setDevZDParam(void *phandle, char chStr[50], unsigned char ZDCh, long long centerfreq, int bw, int sample); + int32_t ex_declare getDevZDParam(void *phandle, char chStr[50], unsigned char ZDCh, long long *centerfreq, int *bw, int *sample); + int32_t ex_declare getDevZDCenterRange(void *phandle, char chStr[50], long long &min, long long &max); + int32_t ex_declare getDevZDBandWidthRange(void *phandle, char chStr[50], int &min, int &max); + int32_t ex_declare getDevZDSampleFreqRange(void *phandle, char chStr[50], int arr[13], int *valid_len); + int32_t ex_declare setDevFFTParam(void *phandle, UHD_FFTWin fftWin, UHD_FFTLen fftLen, int fftPeriod_ms); + int32_t ex_declare getDevFFTParam(void *phandle, UHD_FFTWin *fftWin, UHD_FFTLen *fftLen, int *fftPeriod_ms); + int32_t ex_declare getDevRecvSpeed(void *phandle, int channel, double *val); + int32_t ex_declare isDevRecving(void *phandle, int channel, int32_t *result); + int32_t ex_declare startDevRecv(void *phandle, int channel, rx_data_cbk_t rx_cbk); + int32_t ex_declare stopDevRecv(void *phandle, int channel); + int32_t ex_declare getDevSendSpeed(void *phandle, int channel, double *val); + int32_t ex_declare isDevSending(void *phandle, int channel, int32_t *rusult); + int32_t ex_declare startDevSend(void *phandle, int channel, unsigned long long send_cf, unsigned long long data_sf, char *filename, int bwhile); + int32_t ex_declare stopDevSend(void *phandle, int channel); + int32_t ex_declare getGPSInfo(void *phandle, char gps_info[50]); + int32_t ex_declare setLedEnable(void *phandle, int led_num, int bEnable); + int32_t ex_declare getLedEnable(void *phandle, int led_num, int *bEnable); + + typedef void (*adsb_msg_cbk_t)(void *pusr, char *pmsg, int msglen); + + int32_t ex_declare init_adsb9002(void **phandle, adsb_msg_cbk_t cbk, void *pusr); + int32_t ex_declare free_adsb9002(void **phandle); + + // 新接口 :时间 20251107 , + // TODO: 1 增加 dma 回调函数 iq 的(ddc,ffc) + + // iq 数据回调 + + typedef void (*iq_cbk_t)(void *phandle, void *pdata, uint64_t length); + int ex_declare set_iq_cbk(void *phandle, iq_cbk_t recv_cbk, void *pusr); + + int ex_declare set_less_30Mhz_ddc_param(void *phandle, uint64_t cf_hz, uint64_t sf_hz, uint64_t bw_hz, int8_t sw); + int ex_declare set_less_30Mhz_fft_param(void *phandle, int fftWin, int fftLen, int fftPeriod_ms, int8_t sw); + + + + +} + +#include "device_uhd_c.h" +#include +#include + +#define MY_LIBRARY_EXPORTS +#ifdef _WIN32 // Windows 平台 +#ifdef MY_LIBRARY_EXPORTS // 如果正在构建库 +#define ex_declare __declspec(dllexport) // 导出符号 +#else +#define ex_declare __declspec(dllimport) // 导入符号 +#endif +#else // 对于 Linux 和其他 Unix-like 系统 +#define ex_declare __attribute__((visibility("default"))) // 导出符号 +#endif +#include +extern "C" +{ + ex_declare void adsb_read(char *buf, std::uint16_t *len); + // IQ 数据接口 + typedef void (*iq_cbk_t)(void *phandle, void *pdata, uint64_t length); + typedef int (*adsb_set_iq_cbk_t)(iq_cbk_t recv_cbk, void *pusr); + typedef int (*adsb_set_less_30Mhz_ddc_param_t)(uint64_t cf_hz, uint64_t sf_hz, uint64_t bw_hz, int8_t sw); + typedef int (*adsb_set_less_30Mhz_fft_param_t)(uint64_t fftWin, uint64_t fftLen, int fftPeriod_ms, int8_t sw); + ex_declare int adsb_set_iq_cbk(iq_cbk_t recv_cbk, void *pusr); + ex_declare int adsb_set_less_30Mhz_ddc_param(uint64_t cf_hz, uint64_t sf_hz, uint64_t bw_hz, int8_t sw); + ex_declare int adsb_set_less_30Mhz_fft_param(uint64_t fftWin, uint64_t fftLen, int fftPeriod_ms, int8_t sw); + +} + +#endif //_DEVICE_UHD_C_H_ \ No newline at end of file diff --git a/module/dll_source_lzy/114/out/lib/device_uhd_cpp.cpp b/module/dll_source_lzy/114/out/lib/device_uhd_cpp.cpp new file mode 100644 index 0000000..0b903f4 --- /dev/null +++ b/module/dll_source_lzy/114/out/lib/device_uhd_cpp.cpp @@ -0,0 +1,2615 @@ +#include "device_uhd_cpp.h" +// #include "UHD_Probe.h" +#include "DDCSampTable.h" +#include "FIRGenLowpass_no_ipp.h" +#include "device_uhd_c.h" +#include "device_uhd_struct.h" +#include +#include +#include +#include +#include +#include +using namespace std; +using namespace uhd; + +#define addr_dev_ref_time 0x4200 // "参考时钟" b:0101 GPS ; b:1010 外参考 ; b:1001 内参考 +#define addr_dev_version 0x420c // "设备版本" +#define addr_rx_data_sw 0x4210 //"数据接收开关" +#define addr_dev_led 0x421c +#define addr_rx_kd_fft_sw 0x4220 // fft 开关 +#define addr_rx_kd_fft_len 0x4224 // fft 长度 1k,2k,4k,8k,16k,32k +#define addr_rx_kd_fft_type 0x4228 // fft 类型 0jxc,1hnc,2hmc,3blackman +#define addr_rx_kd_fft_preiod 0x422c // fft 周期 1-1000 ms +#define addr_rx_kd_ddc_data_sw 0x4240 // 宽带数据开关 +#define addr_rx_kd_ddc_ch 0x4264 // 宽带通道号 +#define addr_rx_kd_ddc_fc 0x4270 //"过滤系数" +#define addr_rx_kd_ddc_ch_sw 0x4208 //"中频开关" 切换通道 接收模块 1:9002模块 0:30M模块 +#define addr_rx_kd_kz_speed 0x4214 // 快照速度 +#define addr_rx_ch0_30Mhz_cw 0x4278 // 接收30Mhz 控制字 +#define addr_rx_ch1_30MHz_cw 0x427c // 接收30Mhz 控制字 +#define addr_rx_kd_ch0_ddc_sf 0x4244 //"采样率" +#define addr_rx_kd_ch0_ddc_bw 0x4248 //"带宽" +#define addr_rx_kd_ch0_ddc_cf_h16 0x424c //"中心频率 高16" +#define addr_rx_kd_ch0_ddc_cf_l32 0x4250 //"中心频率 低32" +#define addr_rx_kd_ch0_ddc_df 0x4268 //"采样因子/抽取率因子" +#define addr_rx_kd_ch0_kz_sw 0x4230 // 快照开关 +#define addr_rx_kd_ch0_kz_pack_size 0x4234 // 快照包大小 +#define addr_rx_kd_ch1_ddc_sf 0x4254 //"采样率" +#define addr_rx_kd_ch1_ddc_bw 0x4258 //"带宽" +#define addr_rx_kd_ch1_ddc_cf_h16 0x425c //"中心频率 高16" +#define addr_rx_kd_ch1_ddc_cf_l32 0x4260 //"中心频率 低32" +#define addr_rx_kd_ch1_ddc_df 0x426c //"采样因子/抽取率因子" +#define addr_rx_kd_ch1_kz_sw 0x4238 // 快照开关 +#define addr_rx_kd_ch1_kz_pack_size 0x423c // 快照包大小 +#define addr_rx_zd_ch 0x4280 // 窄带通道号 +#define addr_rx_zd_ddc_data_sw 0x4284 // 窄带数据开关 +#define addr_rx_zd_df 0x4288 // 窄带抽取倍数 +#define addr_rx_zd_bw 0x428c // 窄带带宽 +#define addr_rx_zd_cw 0x4290 // 窄带控制字 +#define addr_rx_zd_fc 0x4294 // 窄带过滤系数 +#define addr_rx_zd_sf 0x4298 // 窄带采样率 +#define addr_tx_send_data_cw 0x42c0 // 发送总开关 +#define addr_tx_send_ch_sw 0x42c4 // 发送通道选择 +#define addr_tx_ch0_insert_rate 0x42c8 // 插值率 +#define addr_tx_ch1_insert_rate 0x42cc // 插值率 +#define addr_tx_ch0_30MHz_cw 0x42d0 // 发送30Mhz 控制字 +#define addr_tx_ch1_30MHz_cw 0x42d4 // 发送30Mhz 控制字 +#define addr_tm_set_h 0x42e0 // 计时高位 +#define addr_tm_set_l 0x42e4 // 计时低位 +//----------------------------------------------------------------------------------------- + +#define my_iio_rx_block_point_size_big (2112 * 512) // #define my_iio_block_point_size (2112*4) +#define my_iio_block_point_size_little (2112 * 512) +#define my_iio_tx_block_point_size (2112 * 512) +#define ach_sf_count_max_hz (15.36 * 1000 * 1000) +#define rx_kz_speed_hz (1.62 * 1000 * 1000) +// #define rx_net_speed_max (500*1024*1024) +#define ZDExtraMin 0 // 窄带抽取倍数的序号,最小 +#define ZDExtraMax 12 // 窄带抽取倍数的序号,最大 +#define kz_sum ((double)(491520000 / 2)) +#define GHz (1000 * 1000 * 1000.0) +#define MHz (1000 * 1000.0) + +static unsigned long long kd_sf_all = 0; +static unsigned long long sf_all = 0; +static unsigned long long tmp_block_size[2] = {0, 0}; +static unsigned long long tmp_sf_all = 0; +volatile bool iio_context_find_err[2] = {false}; //[0]find_device [1]find_channel +typedef struct ThreadRecvParam +{ + int channel; + void *pThis; +} ThreadRecvParam; + +std::string get_Addr_string(int addr) +{ + string tmp; + switch (addr) + { + case addr_dev_ref_time: { + tmp = "参考时钟"; + } + break; + case addr_dev_version: { + tmp = "设备版本"; + } + break; + case addr_rx_data_sw: { + tmp = "rx开关"; + } + break; + case addr_dev_led: { + tmp = "led灯"; + } + break; + case addr_rx_kd_fft_sw: { + tmp = "rx_kd_fft开关"; + } + break; + case addr_rx_kd_fft_len: { + tmp = "rx_kd_fft长度"; + } + break; + case addr_rx_kd_fft_type: { + tmp = "rx_kd_fft类型"; + } + break; + case addr_rx_kd_fft_preiod: { + tmp = "rx_kd_fft周期"; + } + break; + case addr_rx_kd_ddc_data_sw: { + tmp = "rx_kd数据开关"; + } + break; + case addr_rx_kd_ddc_ch: { + tmp = "rx_kd通道号"; + } + break; + case addr_rx_kd_ddc_fc: { + tmp = "rx_kd_过滤系数"; + } + break; + case addr_rx_kd_ddc_ch_sw: { + tmp = "rx_kd_中频切换通道开关"; + } + break; + case addr_rx_kd_kz_speed: { + tmp = "rx_kd_快照速度"; + } + break; + case addr_rx_ch0_30Mhz_cw: { + tmp = "kd_ch0接收30Mhz控制字"; + } + break; + case addr_rx_ch1_30MHz_cw: { + tmp = "kd_ch1接收30Mhz控制字"; + } + break; + case addr_rx_kd_ch0_ddc_sf: { + tmp = "kd_ch0采样率"; + } + break; + case addr_rx_kd_ch0_ddc_bw: { + tmp = "kd_ch0带宽"; + } + break; + case addr_rx_kd_ch0_ddc_cf_h16: { + tmp = "kd_ch0中心频率高16"; + } + break; + case addr_rx_kd_ch0_ddc_cf_l32: { + tmp = "kd_ch0中心频率低32"; + } + break; + case addr_rx_kd_ch0_ddc_df: { + tmp = "kd_ch0采样抽取率因子"; + } + break; + case addr_rx_kd_ch0_kz_sw: { + tmp = "kd_ch0快照开关"; + } + break; + case addr_rx_kd_ch0_kz_pack_size: { + tmp = "kd_ch0快照包大小"; + } + break; + case addr_rx_kd_ch1_ddc_sf: { + tmp = "kd_ch1采样率"; + } + break; + case addr_rx_kd_ch1_ddc_bw: { + tmp = "kd_ch1带宽"; + } + break; + case addr_rx_kd_ch1_ddc_cf_h16: { + tmp = "kd_ch1中心频率高16"; + } + break; + case addr_rx_kd_ch1_ddc_cf_l32: { + tmp = "kd_ch1中心频率低32"; + } + break; + case addr_rx_kd_ch1_ddc_df: { + tmp = "kd_ch1采样抽取率因子"; + } + break; + case addr_rx_kd_ch1_kz_sw: { + tmp = "kd_ch1快照开关"; + } + break; + case addr_rx_kd_ch1_kz_pack_size: { + tmp = "kd_ch1快照包大小"; + } + break; + case addr_rx_zd_ch: { + tmp = "zd_通道号"; + } + break; + case addr_rx_zd_ddc_data_sw: { + tmp = "zd_数据开关"; + } + break; + case addr_rx_zd_df: { + tmp = "zd_抽取倍数"; + } + break; + case addr_rx_zd_bw: { + tmp = "zd_带宽"; + } + break; + case addr_rx_zd_cw: { + tmp = "zd_控制字"; + } + break; + case addr_rx_zd_fc: { + tmp = "zd_过滤系数"; + } + break; + case addr_rx_zd_sf: { + tmp = "zd_采样率"; + } + break; + case addr_tx_send_data_cw: { + tmp = "tx总开关"; + } + break; + case addr_tx_send_ch_sw: { + tmp = "tx通道选择"; + } + break; + case addr_tx_ch0_insert_rate: { + tmp = "tx0插值率"; + } + break; + case addr_tx_ch1_insert_rate: { + tmp = "tx1插值率"; + } + break; + case addr_tx_ch0_30MHz_cw: { + tmp = "tx030Mhz控制字"; + } + break; + case addr_tx_ch1_30MHz_cw: { + tmp = "tx130Mhz控制字"; + } + break; + case addr_tm_set_h: { + tmp = "计时高位"; + } + break; + case addr_tm_set_l: { + tmp = "计时低位"; + } + break; + default: + tmp = "未知类型"; + break; + } + return tmp; +} +std::string get_UHD_ParamType(UHD_ParamType v) +{ + + string tmp; + switch (v) + { + case CenterFreq: { + tmp = "CenterFreq"; + } + break; + case BandWidth: { + tmp = "BandWidth"; + } + break; + case SampleFreq: { + tmp = "SampleFreq"; + } + break; + case Gain: { + tmp = "Gain"; + } + break; + case PowerRef: { + tmp = "PowerRef"; + } + break; + case KDDCSwitch: { + tmp = "KDDCSwitch"; + } + break; + case KFFTSwitch: { + tmp = "KFFTSwitch"; + } + break; + case ZDDCSwitch: { + tmp = "ZDDCSwitch"; + } + break; + case ZDDCParam: { + tmp = "ZDDCParam"; + } + break; + case KFFTParam: { + tmp = "KFFTParam"; + } + break; + case ClockSource: { + tmp = "ClockSource"; + } + break; + case SnapshotSwitch: { + tmp = "SnapshotSwitch"; + } + break; + case Snapshot_tm_s: { + tmp = "Snapshot_tm_s"; + } + break; + + default: + break; + } + return tmp; +}; + +void addr_val_mix(int64_t addr, int64_t val, std::string &sstr) +{ + sstr.clear(); + char str[50]; + for (int i = 0; i < 50; ++i) + { + str[i] = 0; + } + sprintf(str, "%08x%08x", (unsigned int)addr, (unsigned int)val); + sstr = str; +} +bool set_esun_rx_addr_val(iio_context *ctx, int64_t addr, int64_t val) +{ + + if (addr == addr_rx_zd_fc || addr == addr_rx_kd_ddc_fc) + { + } + else + { + // stringstream ss1; + // ss1 << "detail:[" << get_Addr_string(addr) << "]寄存器\taddr:[0x" << std::hex << addr << "]\tval:[" << std::dec << val << "]" << endl; + // MACROS_ERROR_CBK_CALL(ss1.str().c_str()); + } + if (ctx) + { + struct iio_device *phy; + struct iio_channel *chan; + phy = iio_context_find_device(ctx, "adrv9002-phy"); + if (phy == NULL) + { + if (!iio_context_find_err[0]) + { + iio_context_find_err[0] = true; + stringstream ss; + ss << "set_esun_rx_addr_val iio_context_find_device error" << endl; + MACROS_ERROR_CBK_CALL(ss.str().c_str()); + } + return false; + } + chan = iio_device_find_channel(phy, "voltage0", false); + if (chan == NULL) + { + if (!iio_context_find_err[1]) + { + iio_context_find_err[1] = true; + stringstream ss; + ss << "set_esun_rx_addr_val iio_device_find_channel error" << endl; + MACROS_ERROR_CBK_CALL(ss.str().c_str()); + } + return false; + } + + std::string str; + addr_val_mix(addr, val, str); + char vl[20]; + for (int i = 0; i < 20; ++i) + { + vl[i] = 0; + } + strcpy(vl, str.c_str()); + iio_channel_attr_write(chan, "esun_reg", vl); + return true; + } + stringstream ss; + ss << "ctx is nullptr error" << endl; + return false; +} +bool get_esun_rx_addr_val(iio_context *ctx, int64_t addr, int64_t &val) +{ + if (ctx) + { + struct iio_device *phy; + struct iio_channel *chan; + phy = iio_context_find_device(ctx, "adrv9002-phy"); + if (phy == NULL) + { + if (!iio_context_find_err[0]) + { + iio_context_find_err[0] = true; + stringstream ss; + ss << "get_esun_rx_addr_val iio_context_find_device error" << endl; + MACROS_ERROR_CBK_CALL(ss.str().c_str()); + } + return false; + } + chan = iio_device_find_channel(phy, "voltage0", false); + if (chan == NULL) + { + if (!iio_context_find_err[1]) + { + iio_context_find_err[1] = true; + stringstream ss; + ss << "get_esun_rx_addr_val iio_device_find_channel error" << endl; + MACROS_ERROR_CBK_CALL(ss.str().c_str()); + } + return false; + } + char str[20]; + memset(str, 0, 20); + sprintf(str, "%x", addr); + iio_channel_attr_write(chan, "esun_reg", str); + iio_channel_attr_read(chan, "esun_reg", str, 20); + val = atoi(str); + return true; + } + return false; +} +static int stream_channels_get_enable(const struct iio_device *dev, struct iio_channel **chan, bool tx) +{ + int c; + const char *const channels[] = {"voltage0_i", "voltage0_q", "voltage0", "voltage1"}; + for (c = 0; c < 2; c++) + { + const char *str = channels[tx * 2 + c]; + chan[c] = iio_device_find_channel(dev, str, tx); + if (!chan[c]) + { + return -ENODEV; + } + if (!iio_channel_is_enabled(chan[c])) + { + iio_channel_enable(chan[c]); + } + } + return 0; +} +static int stream_channels_get_disenable(const struct iio_device *dev, struct iio_channel **chan, bool tx) +{ + int c; + const char *const channels[] = {"voltage0_i", "voltage0_q", "voltage0", "voltage1"}; + for (c = 0; c < 2; c++) + { + const char *str = channels[tx * 2 + c]; + chan[c] = iio_device_find_channel(dev, str, tx); + if (!chan[c]) + { + return -ENODEV; + } + if (iio_channel_is_enabled(chan[c])) + { + iio_channel_disable(chan[c]); + } + } + return 0; +} +uhd::device_addrs_t Device_UHD::findDevices() +{ + device_addrs_t dev_list; + dev_list.clear(); + device_addr_t t; + t.uri = "ip:172.22.0.2"; + this->bFindedDevice = true; + dev_list.push_back(t); + p_usrp.ctx_isopen = false; + return dev_list; +} +bool Device_UHD::openDevice(uhd::device_addr_t addr) +{ + bool bRet = false; + if (this->bFindedDevice) + { + try + { + this->devAddr = addr; + uhd::usrp::multi_usrp::sptr tmp_URSP; + tmp_URSP.ctx = iio_create_context_from_uri("ip:172.22.0.2"); + // tmp_URSP.ctx = iio_create_context_from_uri("ip:192.168.1.141"); + if (tmp_URSP.ctx != NULL) + { + p_usrp = tmp_URSP; + p_usrp.ctx_isopen = true; + bRet = true; + spThread_Recv[0] = NULL; + spThread_Recv[1] = NULL; + // memset(&rxKDParam, 0, sizeof(rxKDParam)); + for (int i = 0; i < 2; i++) + { + rxKDParam[i].KCH = i; + rxKDParam[i].CenterFreq = 0; + rxKDParam[i].BandWidth = 0; /*getDevParam("RX" + i, UHD_ParamType::BandWidth);*/ + rxKDParam[i].SampleFreq = 0; /* getDevParam("RX" + i, UHD_ParamType::SampleFreq);*/ + for (int y = 0; y < ZDChMax; y++) + { + rxKDParam[i].ZDParam[y].KCH = i; + rxKDParam[i].ZDParam[y].ZCH = i * ZDChMax + y; + } + rxKDParam[i].gain = 0; + rxKDParam[i].Snapshot_Switch = false; + rxKDParam[i].Snapshot_tm_s = 0; + txKDParam[i].gain = -40; + led_val = 0; + } + kd_centerfreq_sw = 0; + fftWin = UHD_FFTWin::blkmc; + fftLen = UHD_FFTLen::_32768; + fftPeriod = 10; + } + } + catch (std::exception ex2) + { + std::cout << ex2.what() << std::endl; + p_usrp.ctx_isopen = false; + bRet = false; + } + } + return bRet; +} +void Device_UHD::closeDevice() +{ + if (p_usrp.ctx != NULL) + { + stopDevRecv(0); + stopDevRecv(1); + stopDevSend(0); + stopDevSend(1); + // 释放前,需把所有引用都赋值NULL,方可释放 + // pTree = NULL; // + iio_context_destroy(p_usrp.ctx); + p_usrp.ctx = NULL; // 内部会自动释放指针 + p_usrp.ctx_isopen = false; + } +} +bool Device_UHD::isDevOpened() const +{ + bool ret = p_usrp.ctx_isopen; + return ret; +} +string GetUHDTree(const uhd::fs_path &path, uhd::property_tree::sptr tree) +{ + return "GetUHDTree\r\n"; +} +string Device_UHD::getDevTree() +{ + return "getDevTree\r\n"; +} +string Device_UHD::findDevInfos() +{ + string ret; + char tmp[200]; + if (p_usrp.ctx != NULL) + { + try + { + { // 查询设备信息 + ret += "ip:172.22.0.2\r\n"; + } + { // 查看设备数量、名称、时钟源 + snprintf(tmp, 200, "get_num_mboards:%d", 0); + ret += string(tmp) + "\r\n"; + ret += "\r\n"; + } + { + } + { // 查询接收通道参数 + // int num = (int)pUSRP->get_rx_num_channels(); + snprintf(tmp, 200, "get_rx_num_channels:%d", 2); + ret += string(tmp) + "\r\n"; + for (int i = 0; i < 2; i++) + { + } + ret += "\r\n"; + } + { // 查询发射通道参数 + snprintf(tmp, 200, "get_tx_num_channels:%d", 2); + ret += string(tmp) + "\r\n"; + for (int i = 0; i < 2; i++) + { + { // 查询发射频率范围 + snprintf(tmp, 200, "get_tx_freq_range(%d):%f~%f", i, 0, 6 * GHz); + ret += string(tmp) + "\r\n"; + } + } + ret += "\r\n"; + } + } + catch (std::exception ex2) + { + std::cout << ex2.what() << std::endl; + } + } + return "findDevInfos\r\n"; +} +string Device_UHD::findDevInfos2() +{ + return "ok"; +} +size_t Device_UHD::getDevRXChCount() +{ + size_t bRet = 0; + try + { + if (p_usrp.ctx != NULL) + { + bRet = 2; + } + } + catch (std::exception ex2) + { + std::cout << ex2.what() << std::endl; + } + return bRet; +} +size_t Device_UHD::getDevTXChCount() +{ + size_t bRet = 0; + try + { + if (p_usrp.ctx != NULL) + { + bRet = 2; + } + } + catch (std::exception ex2) + { + std::cout << ex2.what() << std::endl; + } + return bRet; +} + +bool Device_UHD::setDevClockSource(string sourceStr) +{ + + bool ret = true; + try + { + if (p_usrp.ctx != NULL) + { + if (sourceStr.compare("gpsdo") == 0) + { + set_esun_rx_addr_val(p_usrp.ctx, addr_dev_ref_time, 5); + } + else if (sourceStr.compare("external") == 0) + { + set_esun_rx_addr_val(p_usrp.ctx, addr_dev_ref_time, 10); + } + else if (sourceStr.compare("internal") == 0) + { + set_esun_rx_addr_val(p_usrp.ctx, addr_dev_ref_time, 9); + } + } + } + catch (std::exception ex2) + { + std::cout << ex2.what() << std::endl; + ret = false; + } + return ret; +} +string Device_UHD::getDevClockSource() +{ + string ret = "internal"; + try + { + if (p_usrp.ctx != NULL) + { + int64_t val; + get_esun_rx_addr_val(p_usrp.ctx, (int64_t)addr_dev_ref_time, val); + if (val == 5) + { + ret = string("gpsdo"); + } + else if (val == 9) + { + ret = string("internal"); + } + else if (val == 10) + { + ret = string("external"); + } + } + } + catch (std::exception ex2) + { + std::cout << ex2.what() << std::endl; + } + return ret; +} +bool Device_UHD::setDevInClock(double clockFreq) +{ + bool ret = true; + return ret; +} +void Device_UHD::getDevInClockRange() +{ + try + { + if (p_usrp.ctx != NULL) + { + fParamMin = 10000000; + fParamMax = 10000000; + } + } + catch (std::exception ex2) + { + std::cout << ex2.what() << std::endl; + } +} +double Device_UHD::getDevInClock() +{ + double ret = 0; + try + { + if (p_usrp.ctx != NULL) + { + ret = 10000000; + } + } + catch (std::exception ex2) + { + std::cout << ex2.what() << std::endl; + } + return ret; +} +bool Device_UHD::setDevParam(string chStr, UHD_ParamType paramType, double paramValue) +{ + + stringstream ss; + ss << "ch_str:[" << chStr << "]\tType:[" << get_UHD_ParamType(paramType) << "]\tValue[" << paramValue << "]" << endl; + MACROS_ERROR_CBK_CALL(ss.str().c_str()); + bool ret = true; + try + { + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_data_sw, 0); + if (p_usrp.ctx != NULL) + { + int channel = chStr.find("0") != string::npos ? 0 : 1; + bool bTX = chStr.find("TX") != string::npos; + bool tmp_zd_switch = 0; + + //"频点", "带宽", "采样率", "增益", "校准电平" + + if (!bTX) + { + for (int i = 0; i < 8; ++i) + { + tmp_zd_switch += rxKDParam[channel].ZDParam[i].bSwitch_ZDDC; + } + switch (paramType) + { + case UHD_ParamType::CenterFreq: + // if (tmp_zd_switch) + // { + // return false; + // } + if (!bTX) + { + rxKDParam[channel].old_cf = rxKDParam[channel].CenterFreq; + rxKDParam[channel].CenterFreq = paramValue; + if (rxKDParam[channel].old_cf == 0) + { + rxKDParam[channel].old_cf = rxKDParam[channel].CenterFreq; + } + } + break; + case UHD_ParamType::BandWidth: + // if (tmp_zd_switch) + // { + // return false; + // } + if (!bTX) + { + rxKDParam[channel].old_bw = rxKDParam[channel].BandWidth; + rxKDParam[channel].BandWidth = paramValue; + if (rxKDParam[channel].old_bw == 0) + { + rxKDParam[channel].old_bw = rxKDParam[channel].BandWidth; + } + } + break; + case UHD_ParamType::SampleFreq: + // if (tmp_zd_switch) + // { + // return false; + // } + if (!bTX) + { + if (rxKDParam[channel].bSwitch_KDDC == true) + { + unsigned long long sfcnt = 0; + for (int j = 0; j < 2; ++j) + { + sfcnt += rxKDParam[j].SampleFreq * rxKDParam[j].bSwitch_KDDC; + sfcnt += rxKDParam[j].bSwitch_KFFT * ((double)fftLen / 1024 * 2112 * (1000 / (double)fftPeriod) / 4); + sfcnt += rxKDParam[j].Snapshot_Switch * rx_kz_speed_hz; + for (int i = 0; i < 8; ++i) + { + sfcnt += rxKDParam[j].ZDParam[i].SampleFreq * rxKDParam[j].ZDParam[i].bSwitch_ZDDC; + } + } + // unsigned long long pre_cnt = sfcnt - rxKDParam[channel].SampleFreq + paramValue; + // if (pre_cnt > ach_sf_count_max_hz + 1) + // { + // return false; + // } + // sf_all = pre_cnt; + } + rxKDParam[channel].old_sf = rxKDParam[channel].SampleFreq; + rxKDParam[channel].SampleFreq = paramValue; + if (rxKDParam[channel].old_sf == 0) + { + rxKDParam[channel].old_sf = rxKDParam[channel].SampleFreq; + } + } + break; + case UHD_ParamType::Gain: + if (!bTX) + { + + struct iio_device *phy; + struct iio_channel *chn = nullptr; + phy = iio_context_find_device(this->p_usrp.ctx, "adrv9002-phy"); + if (channel == 0) + { + chn = iio_device_find_channel(phy, "voltage0", false); + } + else if (channel == 1) + { + chn = iio_device_find_channel(phy, "voltage1", false); + } + int retno = iio_channel_attr_write_double(chn, "hardwaregain", paramValue); + if (retno != 0) + { + ret = false; + } + else + { + ret = true; + rxKDParam[channel].gain = paramValue; + } + } + return false; + break; + case UHD_ParamType::PowerRef: + break; + case UHD_ParamType::SnapshotSwitch: + if (!bTX) + { + bool bSwitch = (bool)paramValue; + if (bSwitch == true && rxKDParam[channel].Snapshot_Switch == false) + { + unsigned long long sfcnt = 0; + for (int j = 0; j < 2; ++j) + { + sfcnt += rxKDParam[j].SampleFreq * rxKDParam[j].bSwitch_KDDC; + sfcnt += rxKDParam[j].bSwitch_KFFT * ((double)fftLen / 1024 * 2112 * (1000 / (double)fftPeriod) / 4); + sfcnt += rxKDParam[j].Snapshot_Switch * rx_kz_speed_hz; + for (int i = 0; i < 8; ++i) + { + sfcnt += rxKDParam[j].ZDParam[i].SampleFreq * rxKDParam[j].ZDParam[i].bSwitch_ZDDC; + } + } + // unsigned long long pre_cnt = sfcnt + rx_kz_speed_hz; + // if (pre_cnt > ach_sf_count_max_hz + 1) + // { + // return false; + // } + // sf_all = pre_cnt; + } + rxKDParam[channel].Snapshot_Switch = (bool)paramValue; + // 设置获取本来的宽带 通道开关 并置为0; + unsigned char uSwitch = 0; + if (bSwitch == true) + { + rxKDParam[channel].bSwitch_KDDC = false; + for (int i = 0; i < 2; i++) + { + if (rxKDParam[i].bSwitch_KDDC) + { + uSwitch |= 0x01 << i; + } + } + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_ddc_data_sw, 0); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_ddc_data_sw, uSwitch); + } + set_esun_rx_addr_val(p_usrp.ctx, channel == 0 ? addr_rx_kd_ch0_kz_sw : addr_rx_kd_ch1_kz_sw, 0); + set_esun_rx_addr_val(p_usrp.ctx, channel == 0 ? addr_rx_kd_ch0_kz_sw : addr_rx_kd_ch1_kz_sw, rxKDParam[channel].Snapshot_Switch); + return true; + } + return false; + break; + case UHD_ParamType::Snapshot_tm_s: { + if (!bTX) + { + if (rxKDParam[channel].SampleFreq < 0) + { + return false; + } + int tmp_t_max = (int)(kz_sum / rxKDParam[channel].SampleFreq); + if (paramValue > tmp_t_max || paramValue < 0) + { + // paramValue = tmp_t_max; + rxKDParam[channel].Snapshot_tm_s = tmp_t_max; + } + else + { + rxKDParam[channel].Snapshot_tm_s = paramValue; + } + } + } + break; + defualt: + break; + } + + int kd_cur_indx = channel; + double kddcsamp = rxKDParam[channel].SampleFreq; + int ExtraPer = 0; + unsigned long long CenterFreq = rxKDParam[channel].CenterFreq; + long long BandWidth = rxKDParam[channel].BandWidth; + unsigned long long kd_centerfreq_h16 = CenterFreq & 0xffff00000000; + unsigned long long kd_centerfreq_l32 = CenterFreq & 0xffffffff; + int t = rxKDParam[channel].Snapshot_tm_s; + unsigned long long pack_size = ((unsigned int)((t * rxKDParam[channel].SampleFreq * 32.0) / (2048 * 8.0) / 16)) * 16; + set_esun_rx_addr_val(p_usrp.ctx, channel == 0 ? addr_rx_kd_ch0_kz_pack_size : addr_rx_kd_ch1_kz_pack_size, pack_size); + bool enable_6G_ch = 0; + if (CenterFreq >= 30 * MHz && CenterFreq < 6 * GHz) + { + enable_6G_ch = 1; + } + else if (CenterFreq < 30 * MHz && CenterFreq >= 0) + { + enable_6G_ch = 0; + } + if (channel == 0) + { + if (enable_6G_ch == 1) + kd_centerfreq_sw |= 0x01; + if (enable_6G_ch == 0) + kd_centerfreq_sw &= 0x02; + } + if (channel == 1) + { + if (enable_6G_ch == 1) + kd_centerfreq_sw |= 0x02; + if (enable_6G_ch == 0) + kd_centerfreq_sw &= 0x01; + } + // bool bSwitch = false; + // int kd_ddc_up = 0; + int kd_FilterCoef[128] = {0}; + if (channel == 0) + { + for (int i = KDDCSampIndxMin0; i <= KDDCSampIndxMax0; i++) + { + if (KDDCSampTab0[i][0] == kddcsamp) + { + ExtraPer = i; + break; + } + } + } + else if (channel == 1) + { + for (int i = KDDCSampIndxMin1; i <= KDDCSampIndxMax1; i++) + { + if (KDDCSampTab1[i][0] == kddcsamp) + { + ExtraPer = i; + break; + } + } + } + + if (CenterFreq < 30 * MHz) + { + int kd_30M_ctrword = (int)((double)(CenterFreq - 15000000.0) / define_KDDCSampleMax1 * pow(2, 32)); + if (kd_cur_indx == 0) + { + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_ch0_30Mhz_cw, kd_30M_ctrword); + } + if (kd_cur_indx == 1) + { + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_ch1_30MHz_cw, kd_30M_ctrword); + } + } + int kd_filterLen = SetFIRLpCoef2(kd_FilterCoef, 128, (double)BandWidth / kddcsamp, 18, 1.0); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_ddc_ch_sw, kd_centerfreq_sw); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_ddc_ch, kd_cur_indx); + + // if(rxKDParam[channel].old_bw != BandWidth || rxKDParam[channel].old_sf != kddcsamp) + // { + // if (kd_filterLen > 0) + // { + // for (int i = 0; i < kd_filterLen; i++) + // { + // set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_ddc_fc, kd_FilterCoef[i]); + // } + // } + // } + if (!(rxKDParam[channel].old_cf != CenterFreq && rxKDParam[channel].old_bw == BandWidth && rxKDParam[channel].old_sf == kddcsamp)) + { + if (kd_filterLen > 0) + { + + stringstream ss1; + ss1 << "设置kd滤波器系数" << endl; + MACROS_ERROR_CBK_CALL(ss1.str().c_str()); + for (int i = 0; i < kd_filterLen; i++) + { + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_ddc_fc, kd_FilterCoef[i]); + } + } + } + if (kd_cur_indx == 0) + { + struct iio_channel *chn = nullptr; + struct iio_device *phy; + phy = iio_context_find_device(p_usrp.ctx, "adrv9002-phy"); + chn = iio_device_find_channel(phy, "altvoltage0", true); + bool b1 = (CenterFreq >= (30 * MHz)); + bool b2 = (CenterFreq < (6 * GHz)); + if (b1 && b2) + { + iio_channel_attr_write_longlong(chn, "RX1_LO_frequency", CenterFreq); + } + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_ch0_ddc_df, ExtraPer); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_ch0_ddc_bw, BandWidth); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_ch0_ddc_sf, kddcsamp); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_ch0_ddc_cf_h16, kd_centerfreq_h16); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_ch0_ddc_cf_l32, kd_centerfreq_l32); + } + else if (kd_cur_indx == 1) + { + struct iio_channel *chn = nullptr; + struct iio_device *phy; + phy = iio_context_find_device(p_usrp.ctx, "adrv9002-phy"); + chn = iio_device_find_channel(phy, "altvoltage1", true); + if (CenterFreq >= 30 * MHz && CenterFreq < 6 * GHz) + { + iio_channel_attr_write_longlong(chn, "RX2_LO_frequency", CenterFreq); + } + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_ch1_ddc_df, ExtraPer); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_ch1_ddc_bw, BandWidth); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_ch1_ddc_sf, kddcsamp); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_ch1_ddc_cf_h16, kd_centerfreq_h16); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_ch1_ddc_cf_l32, kd_centerfreq_l32); + } + + struct iio_device *phy; + struct iio_channel *chn = nullptr; + phy = iio_context_find_device(this->p_usrp.ctx, "adrv9002-phy"); + if (channel == 0) + { + chn = iio_device_find_channel(phy, "voltage0", false); + } + else if (channel == 1) + { + chn = iio_device_find_channel(phy, "voltage1", false); + } + // int retno = iio_channel_attr_write_double(chn, "hardwaregain", this->rxKDParam[channel].gain); + // if (retno!=0) + // { + // ret = false; + // } + // else{ + // ret = true; + // rxKDParam[channel].gain = paramValue; + // } + } + + if (bTX) + { + if (paramType == UHD_ParamType::Gain) + { + + struct iio_device *phy; + struct iio_channel *chn = nullptr; + phy = iio_context_find_device(this->p_usrp.ctx, "adrv9002-phy"); + if (channel == 0) + { + chn = iio_device_find_channel(phy, "voltage0", true); + } + else if (channel == 1) + { + chn = iio_device_find_channel(phy, "voltage1", true); + } + int retno = iio_channel_attr_write_double(chn, "hardwaregain", paramValue); + if (retno != 0) + { + ret = false; + } + else + { + ret = true; + txKDParam[channel].gain = paramValue; + } + } + } + } + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_data_sw, 3); + } + catch (std::exception ex2) + { + std::cout << ex2.what() << std::endl; + ret = false; + } + return ret; +} +double Device_UHD::getDevParam(string chStr, UHD_ParamType paramType) +{ + double ret; + try + { + if (p_usrp.ctx != NULL) + { + int channel = chStr.find("0") != string::npos ? 0 : 1; + bool bTX = chStr.find("TX") != string::npos; + //"频点", "带宽", "采样率", "增益", "校准电平" + if (!bTX) + { + switch (paramType) + { + case UHD_ParamType::CenterFreq: + // ret = bTX ? p_usrp->get_tx_freq(channel) : pUSRP->get_rx_freq(channel); + if (!bTX) + { + ret = rxKDParam[channel].CenterFreq; //= ret; + } + break; + case UHD_ParamType::BandWidth: + if (!bTX) + { + ret = rxKDParam[channel].BandWidth; //= ret; + } + break; + case UHD_ParamType::SampleFreq: + if (!bTX) + { + ret = rxKDParam[channel].SampleFreq; // = ret; + } + break; + case UHD_ParamType::Gain: + ret = rxKDParam[channel].gain; + break; + case UHD_ParamType::PowerRef: + ret = 10000000; + break; + case UHD_ParamType::SnapshotSwitch: + ret = rxKDParam[channel].Snapshot_Switch; + break; + case UHD_ParamType::Snapshot_tm_s: + ret = rxKDParam[channel].Snapshot_tm_s; + } + } + if (bTX) + { + if (paramType == UHD_ParamType::Gain) + { + ret = txKDParam[channel].gain; + } + } + } + } + catch (std::exception ex2) + { + std::cout << ex2.what() << std::endl; + } + return ret; +} +bool Device_UHD::setAllAntenna() +{ + bool ret = true; + return ret; +} +void Device_UHD::getDevParamRange(string chStr, UHD_ParamType paramType, double ¶mMin, double ¶mMax) +{ + try + { + if (p_usrp.ctx != NULL) + { + // uhd::meta_range_t range; + int channel = chStr.find("0") != string::npos ? 0 : 1; + bool bTX = chStr.find("TX") != string::npos; + //"频点", "带宽", "采样率", "增益", "校准电平" + switch (paramType) + { + case UHD_ParamType::CenterFreq: + fParamMin = 0; + fParamMax = 6 * GHz; + break; + case UHD_ParamType::BandWidth: + fParamMin = 0; + fParamMax = 40000000; + break; + case UHD_ParamType::SampleFreq: + fParamMin = 0; + fParamMax = define_KDDCSampleMax1; + break; + case UHD_ParamType::Gain: + if (!bTX) + { + fParamMin = 0; + fParamMax = 34; + } + break; + case UHD_ParamType::PowerRef: + fParamMin = 0; + fParamMax = 0; + break; + } + } + } + catch (std::exception ex2) + { + std::cout << ex2.what() << std::endl; + } +} +double Device_UHD::getDevParamMin() const +{ + return fParamMin; +} +double Device_UHD::getDevParamMax() const +{ + return fParamMax; +} +bool Device_UHD::setDevDDCParam_Any(string chStr, unsigned int jcqOffset, unsigned int jcqData) +{ + bool ret = true; + if (p_usrp.ctx != NULL) + { + try + { + int channel = chStr.find("0") != string::npos ? 0 : 1; + set_esun_rx_addr_val(p_usrp.ctx, jcqOffset, jcqData); + } + catch (std::exception ex2) + { + std::cout << ex2.what() << std::endl; + } + } + return ret; +} +bool Device_UHD::getDevDDCParam_Any(string chStr, unsigned int jcqOffset, unsigned int &jcqData) +{ + bool ret = true; + if (p_usrp.ctx != NULL) + { + int64_t va; + try + { + int channel = chStr.find("0") != string::npos ? 0 : 1; + get_esun_rx_addr_val(p_usrp.ctx, jcqOffset, va); + jcqData = va; + } + catch (std::exception ex2) + { + std::cout << ex2.what() << std::endl; + } + } + return ret; +} +bool Device_UHD::setDevDataSwitch(string chStr, UHD_ParamType dataType, unsigned char ZDCh, bool bSwitch) +{ + stringstream ss; + ss << "ch_str:[" << chStr << "]\tType:[" << get_UHD_ParamType(dataType) << "]\tzdch:[" << (int)ZDCh << "]\tsw:[" << bSwitch << "]" << endl; + MACROS_ERROR_CBK_CALL(ss.str().c_str()); + + int xx = bSwitch == true ? 1 : -1; + bool ret = true; + if (p_usrp.ctx != NULL) + { + try + { + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_data_sw, 0); + int channel = chStr.find("0") != string::npos ? 0 : 1; + switch (dataType) + { + case KDDCSwitch: { + if (bSwitch != rxKDParam[channel].bSwitch_KDDC) + { + unsigned long long sfcnt = 0; + for (int j = 0; j < 2; ++j) + { + sfcnt += rxKDParam[j].SampleFreq * rxKDParam[j].bSwitch_KDDC; + sfcnt += rxKDParam[j].bSwitch_KFFT * ((double)fftLen / 1024 * 2112 * (1000 / (double)fftPeriod) / 4); + sfcnt += rxKDParam[j].Snapshot_Switch * rx_kz_speed_hz; + for (int i = 0; i < 8; ++i) + { + sfcnt += rxKDParam[j].ZDParam[i].SampleFreq * rxKDParam[j].ZDParam[i].bSwitch_ZDDC; + } + } + // unsigned long long pre_cnt = sfcnt + (xx * rxKDParam[channel].SampleFreq); + // if (pre_cnt > ach_sf_count_max_hz + 1) + // { + // return false; + // } + // sf_all = pre_cnt; + } + // close zk + if (bSwitch == true) + { + rxKDParam[channel].Snapshot_Switch = false; + // set_esun_rx_addr_val(p_usrp.ctx, channel == 0 ? addr_rx_kd_ch0_kz_sw : addr_rx_kd_ch1_kz_sw, 0); + set_esun_rx_addr_val(p_usrp.ctx, channel == 0 ? addr_rx_kd_ch0_kz_sw : addr_rx_kd_ch1_kz_sw, false); + // rx_kd_ddc_sw |= (1 << channel); + } + else + { + + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_zd_ch, ZDCh); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_zd_ddc_data_sw, 0); + // rx_kd_ddc_sw &= ~(1 << channel); + } + // get old kdsw + unsigned char uSwitch = 0; + for (int i = 0; i < 2; i++) + { + if (rxKDParam[i].bSwitch_KDDC) + { + uSwitch |= (0x01 << i); + } + } + // set kdsw + if (bSwitch) + { + uSwitch |= (1 << channel); + } + else + { + uSwitch &= ~(1 << channel); + } + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_ddc_data_sw, 0); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_ddc_data_sw, uSwitch); + rxKDParam[channel].bSwitch_KDDC = bSwitch; + } + break; + case KFFTSwitch: { + if (bSwitch != rxKDParam[channel].bSwitch_KFFT) + { + unsigned long long sfcnt = 0; + for (int j = 0; j < 2; ++j) + { + sfcnt += rxKDParam[j].SampleFreq * rxKDParam[j].bSwitch_KDDC; + double t_fftlen = (double)fftLen; + sfcnt += rxKDParam[j].bSwitch_KFFT * (t_fftlen / 1024 * 2112 * (1000 / (double)fftPeriod) / 4); + sfcnt += rxKDParam[j].Snapshot_Switch * rx_kz_speed_hz; + for (int i = 0; i < 8; ++i) + { + sfcnt += rxKDParam[j].ZDParam[i].SampleFreq * rxKDParam[j].ZDParam[i].bSwitch_ZDDC; + } + } + // unsigned long long pre_cnt = sfcnt + xx * ((double)fftLen / 1024 * 2112 * (1000 / (double)fftPeriod) / 4); + // if (pre_cnt > ach_sf_count_max_hz + 1) + // { + // return false; + // } + // sf_all = pre_cnt; + } + unsigned char uSwitch = 0; + for (int i = 0; i < 2; i++) + { + if (rxKDParam[i].bSwitch_KFFT) + { + uSwitch |= 0x01 << i; + } + } + if (bSwitch) + { + uSwitch |= (1 << channel); + } + else + { + uSwitch &= ~(1 << channel); + } + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_fft_sw, 0); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_fft_sw, uSwitch); + rxKDParam[channel].bSwitch_KFFT = bSwitch; + } + break; + case ZDDCSwitch: { + if (bSwitch != rxKDParam[channel].ZDParam[ZDCh % ZDChMax].bSwitch_ZDDC) + { + unsigned long long sfcnt = 0; + for (int j = 0; j < 2; ++j) + { + sfcnt += rxKDParam[j].SampleFreq * rxKDParam[j].bSwitch_KDDC; + sfcnt += rxKDParam[j].bSwitch_KFFT * ((double)fftLen / 1024 * 2112 * (1000 / (double)fftPeriod) / 4); + sfcnt += rxKDParam[j].Snapshot_Switch * rx_kz_speed_hz; + for (int i = 0; i < 8; ++i) + { + sfcnt += rxKDParam[j].ZDParam[i].SampleFreq * rxKDParam[j].ZDParam[i].bSwitch_ZDDC; + } + } + // unsigned long long pre_cnt = sfcnt + xx * rxKDParam[channel].ZDParam[ZDCh % ZDChMax].SampleFreq; + // if (pre_cnt > ach_sf_count_max_hz + 1) + // { + // return false; + // } + // sf_all = pre_cnt; + } + if (ZDCh >= 0 && ZDCh <= ZDChMax * 2) + { + rxKDParam[channel].ZDParam[ZDCh % ZDChMax].bSwitch_ZDDC = bSwitch; + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_zd_ch, ZDCh); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_zd_ddc_data_sw, 0); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_zd_ch, ZDCh); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_zd_ddc_data_sw, bSwitch); + } + else + ret = false; + } + break; + default: + ret = false; + break; + } + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_data_sw, 3); + } + catch (std::exception ex2) + { + std::cout << ex2.what() << std::endl; + } + } + return ret; +} +bool Device_UHD::getDevDataSwitch(string chStr, UHD_ParamType dataType, unsigned char ZDCh, bool &bSwitch) +{ + bool ret = true; + if (p_usrp.ctx != NULL) + { + try + { + int channel = chStr.find("0") != string::npos ? 0 : 1; + switch (dataType) + { + case KDDCSwitch: { + bSwitch = rxKDParam[channel].bSwitch_KDDC; + } + break; + case KFFTSwitch: { + bSwitch = rxKDParam[channel].bSwitch_KFFT; + } + break; + case ZDDCSwitch: { + if (ZDCh >= 0 && ZDCh <= ZDChMax * 2) + { + bSwitch = rxKDParam[channel].ZDParam[ZDCh % ZDChMax].bSwitch_ZDDC; + } + } + break; + default: + break; + } + } + catch (std::exception ex2) + { + std::cout << ex2.what() << std::endl; + } + } + return ret; +} +bool Device_UHD::setDevFFTParam(UHD_FFTWin fftWin, UHD_FFTLen fftLen, int fftPeriod_ms) +{ + stringstream ss; + ss << "fftWin:[" << get_UHD_FFTWin(fftWin) << "]\tUHD_FFTLen:[" << (int)fftLen << "]\tfftPeriod_ms:[" << (int)fftPeriod_ms << "]" << endl; + MACROS_ERROR_CBK_CALL(ss.str().c_str()); + double curfftlen = (double)fftLen; + bool ret = false; + if (p_usrp.ctx != NULL) + { + try + { + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_data_sw, 0); + { + unsigned long long d_fft_old = 0; + unsigned long long d_fft_new = 0; + unsigned long long sfcnt = 0; + for (int j = 0; j < 2; ++j) + { + double t_fft_len = (double)this->fftLen; + sfcnt += rxKDParam[j].SampleFreq * rxKDParam[j].bSwitch_KDDC; + d_fft_old += rxKDParam[j].bSwitch_KFFT * ((double)this->fftLen / 1024 * 2112 * (1000 / (double)this->fftPeriod) / 4); + d_fft_new += rxKDParam[j].bSwitch_KFFT * ((double)fftLen / 1024 * 2112 * (1000 / (double)fftPeriod_ms) / 4); + sfcnt += d_fft_old; + sfcnt += rxKDParam[j].Snapshot_Switch * rx_kz_speed_hz; + for (int i = 0; i < 8; ++i) + { + sfcnt += rxKDParam[j].ZDParam[j].SampleFreq * rxKDParam[j].ZDParam[j].bSwitch_ZDDC; + } + } + // unsigned long long pre_cnt = sfcnt - d_fft_old + d_fft_new; + // if (pre_cnt > ach_sf_count_max_hz + 1) + // { + // return -3; + // } + // sf_all = pre_cnt; + } + if (fftPeriod_ms >= 1 && fftPeriod_ms <= 1000) + { + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_fft_type, fftWin); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_fft_len, fftLen); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_fft_preiod, fftPeriod_ms); + this->fftWin = fftWin; + this->fftLen = fftLen; + this->fftPeriod = fftPeriod_ms; + ret = true; + } + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_data_sw, 3); + } + catch (std::exception ex2) + { + std::cout << ex2.what() << std::endl; + } + } + return ret; +} +bool Device_UHD::getDevFFTParam(UHD_FFTWin &fftWin, UHD_FFTLen &fftLen, int &fftPeriod_ms) +{ + bool ret = true; + if (p_usrp.ctx != NULL) + { + fftWin = this->fftWin; + fftLen = this->fftLen; + fftPeriod_ms = this->fftPeriod; + } + return ret; +} +bool Device_UHD::setLedEnable(int led_num, bool bEnable) +{ + int mv_size = 0; + if (led_num == 0) + { + mv_size = 1; + } + if (led_num == 1) + { + mv_size = 4; + } + if (led_num == 2) + { + mv_size = 3; + } + if (led_num == 3) + { + mv_size = 2; + } + if (led_num == 4) + { + mv_size = 0; + } + if (led_num == 5) + { + mv_size = 5; + } + if (p_usrp.ctx != NULL) + { + if (bEnable) + { + this->led_val = led_val | (1 << mv_size); + } + else + { + this->led_val &= ~(1 << mv_size); + } + set_esun_rx_addr_val(p_usrp.ctx, addr_dev_led, led_val); + return true; + } + return false; +} +bool Device_UHD::getLedEnable(int led_num, bool &bEnable) +{ + if (p_usrp.ctx != NULL) + { + int mv_size = 0; + if (led_num == 0) + { + mv_size = 1; + } + if (led_num == 1) + { + mv_size = 4; + } + if (led_num == 2) + { + mv_size = 3; + } + if (led_num == 3) + { + mv_size = 2; + } + if (led_num == 4) + { + mv_size = 0; + } + if (led_num == 5) + { + mv_size = 5; + } + int enable_val = led_val >> mv_size & 0x01; + bEnable = enable_val; + return true; + } + return false; +} +int Device_UHD::setDevZDParam(string chStr, unsigned char ZDCh, long long centerfreq, int bw, int sample) +{ + stringstream ss; + ss << "ch_str:[" << chStr << "]\tzdch:[" << (int)ZDCh << "]\t\tcf:[" << centerfreq << "]\tbw:[" << bw << "]\tsf:[" << sample << "]" << endl; + MACROS_ERROR_CBK_CALL(ss.str().c_str()); + int ret = 0; + if (p_usrp.ctx != NULL) + { + try + { + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_data_sw, 0); + int channel = chStr.find("0") != string::npos ? 0 : 1; + if (sample == 0) + { + rxKDParam[channel].ZDParam[ZDCh % ZDChMax].CenterFreq = 0; + rxKDParam[channel].ZDParam[ZDCh % ZDChMax].BandWidth = 0; + rxKDParam[channel].ZDParam[ZDCh % ZDChMax].SampleFreq = 0; + } + else + { + int kddcSam = rxKDParam[channel].SampleFreq; + long long kddcCenter = rxKDParam[channel].CenterFreq; + int kddcBW = rxKDParam[channel].BandWidth; + int samIndex = ZDExtraMin; + for (int i = ZDExtraMin; i <= ZDExtraMax; i++) + { + if ((int)(kddcSam / pow(2, i + 0)) == sample) + { + samIndex = i; + break; + } + } + int samSum = 0; + for (auto zd : rxKDParam[channel].ZDParam) + { + samSum += zd.ZCH != ZDCh ? zd.SampleFreq : 0; + } + if (samIndex < ZDExtraMin || samSum + sample > ZDSamSum) + { + ret = -3; + } + if (centerfreq < 0 || centerfreq < kddcCenter - kddcBW / 2 || centerfreq > kddcCenter + kddcBW / 2) + { + ret = -1; + } + if (bw < (int)(kddcSam / pow(2, ZDExtraMax + 2) * 0.1) || bw > (int)(kddcSam / pow(2, ZDExtraMin + 2) * 0.8)) + { + ret = -2; + } + { + unsigned long long sfcnt = 0; + for (int j = 0; j < 2; ++j) + { + sfcnt += rxKDParam[j].SampleFreq * rxKDParam[j].bSwitch_KDDC; + sfcnt += rxKDParam[j].bSwitch_KFFT * ((double)fftLen / 1024 * 2112 * (1000 / (double)fftPeriod) / 4); + sfcnt += rxKDParam[j].Snapshot_Switch * rx_kz_speed_hz; + for (int i = 0; i < 8; ++i) + { + sfcnt += rxKDParam[j].ZDParam[i].SampleFreq * rxKDParam[j].ZDParam[i].bSwitch_ZDDC; + } + } + // unsigned long long pre_cnt = sfcnt - rxKDParam[channel].ZDParam[ZDCh % ZDChMax].SampleFreq + sample; + // if (pre_cnt > ach_sf_count_max_hz + 1) + // { + // return -3; + // } + // sf_all = pre_cnt; + } + if (ret == 0) + { + int freqkey = (int)((double)(centerfreq - rxKDParam[channel].CenterFreq) / kddcSam * pow(2, 32)); + long long old_cf = rxKDParam[channel].ZDParam[ZDCh % ZDChMax].CenterFreq; + long long old_bw = rxKDParam[channel].ZDParam[ZDCh % ZDChMax].BandWidth; + long long old_sf = rxKDParam[channel].ZDParam[ZDCh % ZDChMax].SampleFreq; + rxKDParam[channel].ZDParam[ZDCh % ZDChMax].CenterFreq = centerfreq; + rxKDParam[channel].ZDParam[ZDCh % ZDChMax].BandWidth = bw; + rxKDParam[channel].ZDParam[ZDCh % ZDChMax].SampleFreq = sample; + int zd_is_up = rxKDParam[channel].ZDParam[ZDCh % ZDChMax].bSwitch_ZDDC; + { + int CH = ZDCh; + unsigned long long BandWidth = bw; + unsigned long long SampleFreq = sample; + unsigned long long CenterFreq = centerfreq; + int CtrWord = freqkey; + bool bSwitch = zd_is_up; + int chouqvlv_num = samIndex; + int chouqvlv = samIndex; + int zd_FilterCoef[128]; + memset(zd_FilterCoef, 0, 128 * sizeof(int)); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_zd_ch, ZDCh); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_zd_df, chouqvlv); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_zd_bw, BandWidth); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_zd_cw, CtrWord); + if (!(old_cf != CenterFreq && old_bw == BandWidth && old_sf == sample)) + { + int zd_filterLen = SetFIRLpCoef2(zd_FilterCoef, 128, (double)BandWidth / SampleFreq, 18, 1.0); + + stringstream ss1; + ss1 << "设置zd滤波器系数" << endl; + MACROS_ERROR_CBK_CALL(ss1.str().c_str()); + + for (int i = 0; i < zd_filterLen; ++i) + { + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_zd_fc, zd_FilterCoef[i]); + } + } + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_zd_sf, SampleFreq); + // set_esun_rx_addr_val(p_usrp.ctx, addr_rx_zd_ch, ZDCh); + } + ret = 0; + } + } + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_data_sw, 3); + } + catch (std::exception ex2) + { + std::cout << ex2.what() << std::endl; + } + } + return ret; +} +bool Device_UHD::getDevZDParam(string chStr, unsigned char ZDCh, long long ¢erfreq, int &bw, int &sample) +{ + bool ret = true; + try + { + int channel = chStr.find("0") != string::npos ? 0 : 1; + centerfreq = rxKDParam[channel].ZDParam[ZDCh % ZDChMax].CenterFreq; + bw = rxKDParam[channel].ZDParam[ZDCh % ZDChMax].BandWidth; + sample = rxKDParam[channel].ZDParam[ZDCh % ZDChMax].SampleFreq; + } + catch (std::exception ex2) + { + std::cout << ex2.what() << std::endl; + } + return ret; +} +void Device_UHD::getDevZDCenterRange(string chStr, long long &min, long long &max) +{ + int channel = chStr.find("0") != string::npos ? 0 : 1; + min = rxKDParam[channel].CenterFreq - rxKDParam[channel].BandWidth / 2; + min = std::max(min, 0LL); + max = rxKDParam[channel].CenterFreq + rxKDParam[channel].BandWidth / 2; +} +void Device_UHD::getDevZDBandWidthRange(string chStr, int &min, int &max) +{ + int channel = chStr.find("0") != string::npos ? 0 : 1; + min = rxKDParam[channel].SampleFreq / pow(2, ZDExtraMax + 2) * 0.1; + max = rxKDParam[channel].SampleFreq / pow(2, ZDExtraMin + 2) * 0.8; +} +vector Device_UHD::getDevZDSampleFreqRange(string chStr) +{ + vector vecSam; + int channel = chStr.find("0") != string::npos ? 0 : 1; + for (int i = ZDExtraMax; i >= ZDExtraMin; i--) + { + double exSam = rxKDParam[channel].SampleFreq / pow(2, i + 2); + if (exSam > ZDSamSum) + { + continue; + } + vecSam.push_back(exSam); + } + return vecSam; +} +bool old_need_sw; + +// TODO:need del +// typedef struct tmp_cache_t +// { +// void *pcache; +// int len; +// } tmp_cache_t; +// tmp_cache_t m_tmp_cache_arr[2]; + +void ThreadRecv_Func(ThreadRecvParam recvParam) +{ + ofstream ofs_datsrc1; + ofstream ofs_datsrc2; + // if (recvParam.channel == 0) + // { + // ofs_datsrc1.open("DatSrc1.dat", ios::binary); + // m_tmp_cache_arr[0].pcache = malloc(1024 * 1024 * 500); + // } + // else if (recvParam.channel == 1) + // { + // ofs_datsrc2.open("DatSrc2.dat", ios::binary); + // m_tmp_cache_arr[1].pcache = malloc(1024 * 1024 * 500); + // } + + Device_UHD *pThis = (Device_UHD *)recvParam.pThis; + int channel = recvParam.channel; + + if (pThis != NULL && pThis->p_usrp.ctx != NULL) + { + try + { + std::chrono::steady_clock::time_point befTime = std::chrono::steady_clock::now(); + long long iRecvedLen = 0; + struct iio_device *phy; + struct iio_channel *chan; + phy = iio_context_find_device(pThis->p_usrp.ctx, "adrv9002-phy"); + if (pThis->p_usrp.ctx) + { + if (channel == 0) + { + chan = iio_device_find_channel(phy, "voltage0", false); + iio_channel_attr_write(chan, "ensm_mode", "rf_enabled"); + + pThis->p_usrp.iio_tx_arr[channel].tx_dev = iio_context_find_device(pThis->p_usrp.ctx, "axi-adrv9002-tx-lpc"); + stream_channels_get_disenable(pThis->p_usrp.iio_tx_arr[channel].tx_dev, pThis->p_usrp.iio_tx_arr[channel].tx_chan, true); + chan = iio_device_find_channel(phy, "voltage0", true); + iio_channel_attr_write(chan, "ensm_mode", "primed"); + + pThis->p_usrp.iio_rx_arr[channel].rx_dev = iio_context_find_device(pThis->p_usrp.ctx, "axi-adrv9002-rx-lpc"); + stream_channels_get_enable(pThis->p_usrp.iio_rx_arr[channel].rx_dev, pThis->p_usrp.iio_rx_arr[channel].rx_chan, false); + // tmp_block_size[channel] = my_iio_rx_block_point_size_big; + pThis->p_usrp.iio_rx_arr[channel].rx_buf = iio_device_create_buffer(pThis->p_usrp.iio_rx_arr[channel].rx_dev, tmp_block_size[channel], false); + } + else if (channel == 1) + { + chan = iio_device_find_channel(phy, "voltage1", false); + iio_channel_attr_write(chan, "ensm_mode", "rf_enabled"); + + pThis->p_usrp.iio_tx_arr[channel].tx_dev = iio_context_find_device(pThis->p_usrp.ctx, "axi-adrv9002-tx2-lpc"); + stream_channels_get_disenable(pThis->p_usrp.iio_tx_arr[channel].tx_dev, pThis->p_usrp.iio_tx_arr[channel].tx_chan, true); + chan = iio_device_find_channel(phy, "voltage1", true); + iio_channel_attr_write(chan, "ensm_mode", "primed"); + pThis->p_usrp.iio_rx_arr[channel].rx_dev = iio_context_find_device(pThis->p_usrp.ctx, "axi-adrv9002-rx2-lpc"); + stream_channels_get_enable(pThis->p_usrp.iio_rx_arr[channel].rx_dev, pThis->p_usrp.iio_rx_arr[channel].rx_chan, false); + // tmp_block_size[channel]= my_iio_rx_block_point_size_big /8; + pThis->p_usrp.iio_rx_arr[channel].rx_buf = iio_device_create_buffer(pThis->p_usrp.iio_rx_arr[channel].rx_dev, tmp_block_size[channel], false); + } + // int ttret = iio_buffer_set_blocking_mode( pThis->p_usrp.iio_rx_arr[channel].rx_buf,false); + // int b =0; + } + void *buff_ptrs; + + while (pThis->bThread_Recv[channel]) + { + bool need_sleep = false; + + // tmp_sf_all = sf_all; + int nrxbytes = iio_buffer_refill(pThis->p_usrp.iio_rx_arr[channel].rx_buf); + int a = 0; + buff_ptrs = iio_buffer_start(pThis->p_usrp.iio_rx_arr[channel].rx_buf); + size_t recvSize = nrxbytes; // num_rx_samps * iPointSize * iChCount; + if (recvSize > 0 && nrxbytes <= tmp_block_size[channel] * 4) + { + + // if (channel == 0) + // { + // if (ofs_datsrc1.is_open()) + // { + // if (m_tmp_cache_arr[channel].pcache != NULL && m_tmp_cache_arr[channel].len < 300 * 1024 * 1024) + // { + // memcpy(m_tmp_cache_arr[channel].pcache + m_tmp_cache_arr[channel].len, (char *)buff_ptrs, recvSize); + // m_tmp_cache_arr[channel].len += recvSize; + // } + // if (m_tmp_cache_arr[channel].len >= 300 * 1024 * 1024) + // { + // ofs_datsrc1.write((char *)m_tmp_cache_arr[channel].pcache, m_tmp_cache_arr[channel].len); + // ofs_datsrc1.close(); + // free(m_tmp_cache_arr[channel].pcache); + // m_tmp_cache_arr[channel].pcache = NULL; + // } + // } + // } + // else if (channel == 1) + // { + // if (ofs_datsrc2.is_open()) + // { + // if (m_tmp_cache_arr[channel].pcache != NULL && m_tmp_cache_arr[channel].len <= 100 * 1024 * 1024) + // { + // memcpy(m_tmp_cache_arr[channel].pcache + m_tmp_cache_arr[channel].len, (char *)buff_ptrs, recvSize); + // m_tmp_cache_arr[channel].len += recvSize; + // } + // if (m_tmp_cache_arr[channel].len >= (20480000)) + // { + // ofs_datsrc2.write((char *)m_tmp_cache_arr[channel].pcache, m_tmp_cache_arr[channel].len); + // ofs_datsrc2.close(); + // free(m_tmp_cache_arr[channel].pcache); + // m_tmp_cache_arr[channel].pcache = NULL; + // } + // } + // } + + iRecvedLen += recvSize; + bool bCheckHead = pThis->ischeck_head; + if (bCheckHead) + { + int &iRecvBufSize = pThis->iRecvBufSize[channel]; // 缓存总大小 + int &iRecvBufPosi = pThis->iRecvBufPosi[channel]; // 缓存当前大小 + char *pDataBuf = (char *)pThis->pRecvBuf[channel]; // 缓存数据指针 + int length = recvSize; // 网络接收数据大小 + int lengthPosi = 0; // 网络接收数据已处理大小 + char *pData = (char *)buff_ptrs; // 网络数据指针 + char *pCheckData = NULL; // 检测包头的数据指针 + int posi = 0; + if (iRecvBufPosi > 0) + { + int needSize = iRecvBufSize - iRecvBufPosi; // 还需要补充数据量 + needSize = needSize > length ? length : needSize; + lengthPosi = needSize; + memcpy((char *)pDataBuf + iRecvBufPosi, pData, needSize); + iRecvBufPosi = needSize + iRecvBufPosi; // 当前缓存中数据长度 + pCheckData = pDataBuf; + } + else + { + iRecvBufPosi = length; + pCheckData = pData; + } + // 111 + while (pThis->bThread_Recv[channel] && posi < iRecvBufPosi) + { + if (posi + 4 < iRecvBufPosi) + { + if (((unsigned int *)(pCheckData + posi))[0] == 0xf628f6f6) + { + int packLen = (int)2112; + if (posi + packLen <= iRecvBufPosi) + { + if (pThis->callBackData != NULL) + { + pThis->callBackData(channel, pCheckData + posi, packLen); + if (*((char *)pCheckData + posi + 12) == 16) + { + char gps_info[60] = {0}; + strncpy(gps_info, pCheckData + posi + 64, 28); + pThis->gps_info = gps_info; + std::reverse(pThis->gps_info.begin(), pThis->gps_info.end()); + } + } + posi += packLen; + } + else + { + break; + } + } + else + { + posi += 1; + } + } + else + { + break; + } + } + // 如果有剩余数据 + if (posi < iRecvBufPosi) + { + memcpy(pDataBuf, pCheckData + posi, iRecvBufPosi - posi); + iRecvBufPosi = iRecvBufPosi - posi; + } + else + { + iRecvBufPosi = 0; + } + if (pCheckData != pData) + { + if (length - lengthPosi < 2112) + { + memcpy(pDataBuf + iRecvBufPosi, pData + lengthPosi, length - lengthPosi); + iRecvBufPosi += length - lengthPosi; + } + else + { + // 111 + posi = lengthPosi - iRecvBufPosi; + pCheckData = pData; + while (pThis->bThread_Recv[channel] && posi < length) + { + if (posi + 4 < length) + { + if (((unsigned int *)(pCheckData + posi))[0] == 0xf628f6f6) + { + int packLen = (int)2112; + if (posi + packLen <= length) + { + if (pThis->callBackData != NULL) + { + + pThis->callBackData(channel, pCheckData + posi, packLen); + if (*((char *)pCheckData + posi + 12) == 16) + { + char gps_info[60] = {0}; + strncpy(gps_info, pCheckData + posi + 64, 28); + pThis->gps_info = gps_info; + std::reverse(pThis->gps_info.begin(), pThis->gps_info.end()); + } + } + posi += packLen; + } + else + { + break; + } + } + else + { + posi += 1; + } + } + else + { + break; + } + } + // 如果有剩余数据 + if (posi < length) + { + memcpy(pDataBuf, pCheckData + posi, length - posi); + iRecvBufPosi = length - posi; + } + else + { + iRecvBufPosi = 0; + } + // 111 + } + } + } + else + { + pThis->callBackData(channel, buff_ptrs, (int)recvSize); + if (*((char *)buff_ptrs + 12) == 16) + { + char gps_info[60] = {0}; + strncpy(gps_info, (char *)buff_ptrs + 64, 28); + pThis->gps_info = gps_info; + std::reverse(pThis->gps_info.begin(), pThis->gps_info.end()); + } + } + } + else + { + need_sleep = true; + } + // bool need_big = false; + // for (int i = 0; i < 2; ++i) + // { + // if (pThis->rxKDParam[i].bSwitch_KDDC == true) + // { + // need_big = true; + // } + // for (int j = 0; j < 8; ++j) + // { + // if (pThis->rxKDParam[i].ZDParam[j].bSwitch_ZDDC == true) + // { + // need_big = true; + // break; + // } + // } + // if (need_big) + // { + // break; + // } + // } + // if (need_big == true && need_big != old_need_sw) + // { + // iio_buffer_destroy(pThis->p_usrp.iio_rx_arr[channel].rx_buf); + // pThis->p_usrp.iio_rx_arr[channel].rx_buf = iio_device_create_buffer(pThis->p_usrp.iio_rx_arr[channel].rx_dev, tmp_block_size[channel], false); + // old_need_sw = need_big; + // } + // if (need_big == false && need_big != old_need_sw) + // { + // iio_buffer_destroy(pThis->p_usrp.iio_rx_arr[channel].rx_buf); + // pThis->p_usrp.iio_rx_arr[channel].rx_buf = iio_device_create_buffer(pThis->p_usrp.iio_rx_arr[channel].rx_dev, tmp_block_size[channel], false); + // old_need_sw = need_big; + // } + std::chrono::steady_clock::time_point curTime = std::chrono::steady_clock::now(); + auto dur_ms = std::chrono::duration_cast(curTime - befTime); + if (dur_ms.count() > 1000) + { + pThis->fRecvSpeed[channel] = (double)iRecvedLen / dur_ms.count() * 1000; + iRecvedLen = 0; + befTime = curTime; + } + + if (need_sleep) + { + if (channel == 1) + { + usleep(10000); + } + } + } + if (channel == 0) + { + chan = iio_device_find_channel(phy, "voltage0", false); + iio_channel_attr_write(chan, "ensm_mode", "primed"); + pThis->p_usrp.iio_rx_arr[channel].rx_dev = iio_context_find_device(pThis->p_usrp.ctx, "axi-adrv9002-rx-lpc"); + stream_channels_get_disenable(pThis->p_usrp.iio_rx_arr[channel].rx_dev, pThis->p_usrp.iio_rx_arr[channel].rx_chan, false); + iio_buffer_destroy(pThis->p_usrp.iio_rx_arr[channel].rx_buf); + } + else if (channel == 1) + { + chan = iio_device_find_channel(phy, "voltage1", false); + iio_channel_attr_write(chan, "ensm_mode", "primed"); + pThis->p_usrp.iio_rx_arr[channel].rx_dev = iio_context_find_device(pThis->p_usrp.ctx, "axi-adrv9002-rx2-lpc"); + stream_channels_get_disenable(pThis->p_usrp.iio_rx_arr[channel].rx_dev, pThis->p_usrp.iio_rx_arr[channel].rx_chan, false); + iio_buffer_destroy(pThis->p_usrp.iio_rx_arr[channel].rx_buf); + } + } + catch (std::exception ex) + { + std::cout << ex.what() << std::endl; + } + } +} +double Device_UHD::getDevRecvSpeed(int channel) const +{ + return fRecvSpeed[channel]; +} +bool Device_UHD::isDevRecving(int channel) const +{ + return bThread_Recv[channel]; +} +void Device_UHD::startDevRecv(int channel) +{ + if (spThread_Recv[channel] != NULL) + { + bThread_Recv[channel] = false; + if (spThread_Recv[channel]->joinable()) + { + spThread_Recv[channel]->join(); + } + spThread_Recv[channel] = NULL; + if (pRecvBuf[channel] != NULL) + { + free(pRecvBuf[channel]); + pRecvBuf[channel] = NULL; + } + } + else + { + if (channel == 0) + { + tmp_block_size[channel] = my_iio_rx_block_point_size_big; + } + else + { + tmp_block_size[channel] = my_iio_rx_block_point_size_big / 8; + } + iRecvBufSize[channel] = tmp_block_size[channel] * 2; + iRecvBufPosi[channel] = 0; + pRecvBuf[channel] = malloc(iRecvBufSize[channel]); + bThread_Recv[channel] = true; + ThreadRecvParam recvParam; + recvParam.channel = channel; + recvParam.pThis = this; + // rx_kd_ddc_sw |= (1 << channel); + // set_esun_rx_addr_val(p_usrp.ctx, addr_rx_data_sw, rx_kd_ddc_sw); + + send_all_sw &= ~(1 << channel); + set_esun_rx_addr_val(p_usrp.ctx, addr_tx_send_data_cw, send_all_sw); + + long long tmll = time(0); + + set_esun_rx_addr_val(p_usrp.ctx, addr_tm_set_l, tmll & 0xffffffff); + set_esun_rx_addr_val(p_usrp.ctx, addr_tm_set_h, tmll >> 32); + + spThread_Recv[channel] = std::make_shared(ThreadRecv_Func, recvParam); + // // 绑核 + // pthread_t pthread = spThread_Recv[channel]->native_handle(); + // cpu_set_t cpuset; + // CPU_ZERO(&cpuset); + // CPU_SET(channel, &cpuset); + // int ret = pthread_setaffinity_np(pthread, sizeof(cpu_set_t), &cpuset); + // if (0 != ret) + // { + // std::cout << strerror(errno) << std::endl; + // } + } +} +void Device_UHD::stopDevRecv(int channel) +{ + if (spThread_Recv[channel] != NULL) + { + bThread_Recv[channel] = false; + if (spThread_Recv[channel]->joinable()) + { + spThread_Recv[channel]->join(); + } + spThread_Recv[channel] = NULL; + } +} +double Device_UHD::getDevSendSpeed(int channel) const +{ + return fSendSpeed[channel]; +} +bool Device_UHD::isDevSending(int channel) const +{ + return bThread_Send[channel]; +} +void ThreadSend_Func(Device_UHD *pThis, unsigned long long send_cf, unsigned long long data_sf, int channel, char *filename, bool bWhile) +{ + if (pThis != NULL && pThis->p_usrp.ctx_isopen) + { + std::chrono::steady_clock::time_point befTime = std::chrono::steady_clock::now(); + long long iSendedLen0 = 0; + long long iSendedLen1 = 0; + char *pdata0; + char *pdata1; + struct iio_device *phy; + struct iio_channel *chan0; + struct iio_channel *chan1; + phy = iio_context_find_device(pThis->p_usrp.ctx, "adrv9002-phy"); + // 定义缓冲区 + char buffer0[1024]; + char buffer1[1024]; + std::vector content0; + std::vector content1; + size_t read_len0 = 0; + size_t read_len1 = 0; + // set_esun_rx_addr_val(p_usrp.ctx, addr_dev_ref_time, 5); + int insert_num = 0; + int cw_30Mhz = 0; + cw_30Mhz = ((double)send_cf / ((double)122880000) * pow(2, 32)); + for (int i = 0; i <= 10; i++) + { + if (((int)define_KDDCSampleMax1 / pow(2, i)) == data_sf) + { + insert_num = i; + break; + } + } + if (channel == 0) + { + pThis->send_all_sw |= (1 << channel); + } + if (channel == 1) + { + pThis->send_all_sw |= (1 << channel); + } + if (send_cf > 30 * MHz && send_cf < 6 * GHz) + { + pThis->send_chan_sw &= ~(1 << channel); + } + if (send_cf <= 30 * MHz && send_cf > 0) + { + pThis->send_chan_sw |= (1 << channel); + } + int ch_cw = pThis->send_chan_sw; + if (pThis->p_usrp.ctx) + { + + // pThis->rxKDParam[channel].bSwitch_KDDC = false; + // pThis->rxKDParam[channel].bSwitch_KFFT = false; + // for(int i = 0; i <8;++i) + // { + // pThis->rxKDParam[0].ZDParam[i].bSwitch_ZDDC = false; + + // } + + // int kz_val = 0; + // for(int i = 0; i <2;++i) + // { + // if(pThis->rxKDParam[i].Snapshot_Switch == true) + // { + + // kz_val |=1<rxKDParam[i].Snapshot_Switch + + // kz_val &=~(1<p_usrp.ctx, addr_rx_kd_ddc_data_sw, 0); + + // set_esun_rx_addr_val(pThis->p_usrp.ctx, addr_rx_kd_ddc_data_sw, 0); + + if (send_cf > 30 * MHz && send_cf < 6 * GHz) + { + if (channel == 0) + { + + pThis->p_usrp.iio_rx_arr[channel].rx_dev = iio_context_find_device(pThis->p_usrp.ctx, "axi-adrv9002-rx-lpc"); + stream_channels_get_disenable(pThis->p_usrp.iio_rx_arr[channel].rx_dev, pThis->p_usrp.iio_rx_arr[channel].rx_chan, false); + + chan0 = iio_device_find_channel(phy, "voltage0", false); + iio_channel_attr_write(chan0, "ensm_mode", "primed"); + + chan0 = iio_device_find_channel(phy, "voltage0", true); + iio_channel_attr_write(chan0, "ensm_mode", "rf_enabled"); + set_esun_rx_addr_val(pThis->p_usrp.ctx, addr_tx_ch0_insert_rate, insert_num); + set_esun_rx_addr_val(pThis->p_usrp.ctx, addr_tx_send_ch_sw, ch_cw); + chan0 = iio_device_find_channel(phy, "altvoltage2", true); + iio_channel_attr_write_longlong(chan0, "TX1_LO_frequency", send_cf); + pThis->p_usrp.iio_tx_arr[channel].tx_dev = iio_context_find_device(pThis->p_usrp.ctx, "axi-adrv9002-tx-lpc"); + stream_channels_get_enable(pThis->p_usrp.iio_tx_arr[channel].tx_dev, pThis->p_usrp.iio_tx_arr[channel].tx_chan, true); + pThis->p_usrp.iio_tx_arr[channel].tx_buf = iio_device_create_buffer(pThis->p_usrp.iio_tx_arr[channel].tx_dev, my_iio_tx_block_point_size, false); + } + if (channel == 1) + { + + pThis->p_usrp.iio_rx_arr[channel].rx_dev = iio_context_find_device(pThis->p_usrp.ctx, "axi-adrv9002-rx2-lpc"); + stream_channels_get_disenable(pThis->p_usrp.iio_rx_arr[channel].rx_dev, pThis->p_usrp.iio_rx_arr[channel].rx_chan, false); + + chan1 = iio_device_find_channel(phy, "voltage1", false); + iio_channel_attr_write(chan1, "ensm_mode", "primed"); + + chan1 = iio_device_find_channel(phy, "voltage1", true); + iio_channel_attr_write(chan1, "ensm_mode", "rf_enabled"); + set_esun_rx_addr_val(pThis->p_usrp.ctx, addr_tx_ch1_insert_rate, insert_num); + set_esun_rx_addr_val(pThis->p_usrp.ctx, addr_tx_send_ch_sw, ch_cw); + chan1 = iio_device_find_channel(phy, "altvoltage3", true); + iio_channel_attr_write_longlong(chan1, "TX2_LO_frequency", send_cf); + pThis->p_usrp.iio_tx_arr[channel].tx_dev = iio_context_find_device(pThis->p_usrp.ctx, "axi-adrv9002-tx2-lpc"); + stream_channels_get_enable(pThis->p_usrp.iio_tx_arr[channel].tx_dev, pThis->p_usrp.iio_tx_arr[channel].tx_chan, true); + // pThis->p_usrp.iio_tx_arr[channel].tx_chan[1] = iio_device_find_channel(pThis->p_usrp.iio_tx_arr[channel].tx_dev, "voltage0", true); + // if (!iio_channel_is_enabled(pThis->p_usrp.iio_tx_arr[channel].tx_chan[1])) + // { + // iio_channel_enable(pThis->p_usrp.iio_tx_arr[channel].tx_chan[1]); + // } + pThis->p_usrp.iio_tx_arr[channel].tx_buf = iio_device_create_buffer(pThis->p_usrp.iio_tx_arr[channel].tx_dev, my_iio_tx_block_point_size, false); + } + } + else if (send_cf <= 30 * MHz && send_cf > 0) + { + if (channel == 0) + { + chan0 = iio_device_find_channel(phy, "voltage0", true); + iio_channel_attr_write(chan0, "ensm_mode", "primed"); + set_esun_rx_addr_val(pThis->p_usrp.ctx, addr_tx_ch0_insert_rate, insert_num); + set_esun_rx_addr_val(pThis->p_usrp.ctx, addr_tx_ch0_30MHz_cw, cw_30Mhz); + set_esun_rx_addr_val(pThis->p_usrp.ctx, addr_tx_send_ch_sw, ch_cw); + pThis->p_usrp.iio_tx_arr[channel].tx_dev = iio_context_find_device(pThis->p_usrp.ctx, "axi-adrv9002-tx-lpc"); + stream_channels_get_enable(pThis->p_usrp.iio_tx_arr[channel].tx_dev, pThis->p_usrp.iio_tx_arr[channel].tx_chan, true); + pThis->p_usrp.iio_tx_arr[channel].tx_buf = iio_device_create_buffer(pThis->p_usrp.iio_tx_arr[channel].tx_dev, my_iio_tx_block_point_size, false); + } + if (channel == 1) + { + chan1 = iio_device_find_channel(phy, "voltage1", true); + iio_channel_attr_write(chan1, "ensm_mode", "primed"); + set_esun_rx_addr_val(pThis->p_usrp.ctx, addr_tx_ch1_insert_rate, insert_num); + set_esun_rx_addr_val(pThis->p_usrp.ctx, addr_tx_ch1_30MHz_cw, cw_30Mhz); + set_esun_rx_addr_val(pThis->p_usrp.ctx, addr_tx_send_ch_sw, ch_cw); + pThis->p_usrp.iio_tx_arr[channel].tx_dev = iio_context_find_device(pThis->p_usrp.ctx, "axi-adrv9002-tx2-lpc"); + stream_channels_get_enable(pThis->p_usrp.iio_tx_arr[channel].tx_dev, pThis->p_usrp.iio_tx_arr[channel].tx_chan, true); + // pThis->p_usrp.iio_tx_arr[channel].tx_chan[1] = iio_device_find_channel(pThis->p_usrp.iio_tx_arr[channel].tx_dev, "voltage0", true); + // if (!iio_channel_is_enabled(pThis->p_usrp.iio_tx_arr[channel].tx_chan[1])) + // { + // iio_channel_enable(pThis->p_usrp.iio_tx_arr[channel].tx_chan[1]); + // } + pThis->p_usrp.iio_tx_arr[channel].tx_buf = iio_device_create_buffer(pThis->p_usrp.iio_tx_arr[channel].tx_dev, my_iio_tx_block_point_size, false); + } + } + } + + if (channel == 0) + { + std::ifstream file(filename, std::ios::binary); + if (!file.is_open()) + { + std::cerr << "无法打开文件" << std::endl; + return; // 返回错误代码 + } + // 逐块读取文件内容 + while (file.read(buffer0, sizeof(buffer0))) + { + std::streamsize bytesRead = file.gcount(); // 获取实际读取的字节数 + content0.insert(content0.end(), buffer0, buffer0 + bytesRead); + } + // 处理最后一块可能不足1024字节的情况 + if (file) + { + std::streamsize bytesRead = file.gcount(); + content0.insert(content0.end(), buffer0, buffer0 + bytesRead); + } + // 关闭文件 + file.close(); + } + if (channel == 1) + { + std::ifstream file(filename, std::ios::binary); + if (!file.is_open()) + { + std::cerr << "无法打开文件" << std::endl; + return; // 返回错误代码 + } + // 逐块读取文件内容 + while (file.read(buffer1, sizeof(buffer1))) + { + std::streamsize bytesRead = file.gcount(); // 获取实际读取的字节数 + content1.insert(content1.end(), buffer1, buffer1 + bytesRead); + } + // 处理最后一块可能不足1024字节的情况 + if (file) + { + std::streamsize bytesRead = file.gcount(); + content1.insert(content1.end(), buffer1, buffer1 + bytesRead); + } + // 关闭文件 + file.close(); + } + set_esun_rx_addr_val(pThis->p_usrp.ctx, addr_tx_send_data_cw, pThis->send_all_sw); + while (pThis->bThread_Send[channel]) + { + if (channel == 0) + { + size_t num_tx = iio_buffer_push(pThis->p_usrp.iio_tx_arr[channel].tx_buf); + if (num_tx <= 0 || num_tx > my_iio_tx_block_point_size * 4) + { + continue; + } + pdata0 = (char *)iio_buffer_start(pThis->p_usrp.iio_tx_arr[channel].tx_buf); + if (!pdata0) + { + continue; + } + if (content0.size() < num_tx) + { + break; + } + if (content0.size() - read_len0 < num_tx) + { + if (bWhile == true) + { + // read_len0 = 0; + + // 多余数据 + unsigned long long dysj = content0.size() - read_len0; + // 需要切割的头部数据 + unsigned long long need_cut_size = num_tx - dysj; + + ::memcpy(pdata0, content0.data() + read_len0, dysj); + ::memcpy(pdata0 + dysj, content0.data(), need_cut_size); + + read_len0 = need_cut_size; + iSendedLen0 += num_tx; + std::chrono::steady_clock::time_point curTime = std::chrono::steady_clock::now(); + auto dur_ms = std::chrono::duration_cast(curTime - befTime); + if (dur_ms.count() > 1000) + { + pThis->fSendSpeed[channel] = (double)iSendedLen0 / dur_ms.count() * 1000; + iSendedLen0 = 0; + befTime = curTime; + } + + continue; + } + else + { + break; + } + } + ::memcpy(pdata0, content0.data() + read_len0, num_tx); + read_len0 += num_tx; + iSendedLen0 += num_tx; + std::chrono::steady_clock::time_point curTime = std::chrono::steady_clock::now(); + auto dur_ms = std::chrono::duration_cast(curTime - befTime); + if (dur_ms.count() > 1000) + { + pThis->fSendSpeed[channel] = (double)iSendedLen0 / dur_ms.count() * 1000; + iSendedLen0 = 0; + befTime = curTime; + } + } + if (channel == 1) + { + size_t num_tx = iio_buffer_push(pThis->p_usrp.iio_tx_arr[channel].tx_buf); + if (num_tx <= 0 || num_tx > my_iio_tx_block_point_size * 4) + { + continue; + } + pdata1 = (char *)iio_buffer_start(pThis->p_usrp.iio_tx_arr[channel].tx_buf); + if (!pdata1) + { + continue; + } + if (content1.size() < num_tx) + { + break; + } + if (content1.size() - read_len1 < num_tx) + { + if (bWhile == true) + { + // read_len1 = 0; + + // 多余数据 + unsigned long long dysj = content1.size() - read_len1; + // 需要切割的头部数据 + unsigned long long need_cut_size = num_tx - dysj; + + ::memcpy(pdata1, content1.data() + read_len1, dysj); + ::memcpy(pdata1 + dysj, content1.data(), need_cut_size); + + read_len1 = need_cut_size; + iSendedLen1 += num_tx; + std::chrono::steady_clock::time_point curTime = std::chrono::steady_clock::now(); + auto dur_ms = std::chrono::duration_cast(curTime - befTime); + if (dur_ms.count() > 1000) + { + pThis->fSendSpeed[channel] = (double)iSendedLen1 / dur_ms.count() * 1000; + iSendedLen1 = 0; + befTime = curTime; + } + + continue; + } + else + { + break; + } + } + ::memcpy(pdata1, content1.data() + read_len1, num_tx); + read_len1 += num_tx; + iSendedLen1 += num_tx; + std::chrono::steady_clock::time_point curTime = std::chrono::steady_clock::now(); + auto dur_ms = std::chrono::duration_cast(curTime - befTime); + if (dur_ms.count() > 1000) + { + pThis->fSendSpeed[channel] = (double)iSendedLen1 / dur_ms.count() * 1000; + iSendedLen1 = 0; + befTime = curTime; + } + } + } + + //--------------------------------------------- + + pThis->send_chan_sw &= ~(1 << channel); + set_esun_rx_addr_val(pThis->p_usrp.ctx, addr_tx_send_ch_sw, ch_cw); + + pThis->send_all_sw &= ~(1 << channel); + + set_esun_rx_addr_val(pThis->p_usrp.ctx, addr_tx_send_data_cw, pThis->send_all_sw); + if (channel == 0) + { + pThis->p_usrp.iio_tx_arr[channel].tx_dev = iio_context_find_device(pThis->p_usrp.ctx, "axi-adrv9002-tx-lpc"); + stream_channels_get_disenable(pThis->p_usrp.iio_tx_arr[channel].tx_dev, pThis->p_usrp.iio_tx_arr[channel].tx_chan, true); + chan0 = iio_device_find_channel(phy, "voltage0", true); + iio_channel_attr_write(chan0, "ensm_mode", "primed"); + } + if (channel == 1) + { + pThis->p_usrp.iio_tx_arr[channel].tx_dev = iio_context_find_device(pThis->p_usrp.ctx, "axi-adrv9002-tx2-lpc"); + stream_channels_get_disenable(pThis->p_usrp.iio_tx_arr[channel].tx_dev, pThis->p_usrp.iio_tx_arr[channel].tx_chan, true); + chan0 = iio_device_find_channel(phy, "voltage1", true); + iio_channel_attr_write(chan0, "ensm_mode", "primed"); + } + + iio_buffer_destroy(pThis->p_usrp.iio_tx_arr[channel].tx_buf); + } +} +void Device_UHD::startDevSend(int channel, unsigned long long send_cf, unsigned long long data_sf, char *filename, bool bwhile) +{ + if (spThread_Send[channel] != NULL) + { + bThread_Send[channel] = false; + if (spThread_Send[channel]->joinable()) + { + spThread_Send[channel]->join(); + } + spThread_Send[channel] = NULL; + } + else + { + bThread_Send[channel] = true; + rx_kd_ddc_sw &= ~(1 << channel); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_data_sw, rx_kd_ddc_sw); + spThread_Send[channel] = std::make_shared(ThreadSend_Func, this, send_cf, data_sf, channel, filename, bwhile); + } +} +void Device_UHD::stopDevSend(int channel) +{ + if (spThread_Send[channel] != NULL) + { + bThread_Send[channel] = false; + if (spThread_Send[channel]->joinable()) + { + spThread_Send[channel]->join(); + } + spThread_Send[channel] = NULL; + } +} +string Device_UHD::getGPSInfo() +{ + + return this->gps_info; +} diff --git a/module/dll_source_lzy/114/out/lib/device_uhd_cpp.h b/module/dll_source_lzy/114/out/lib/device_uhd_cpp.h new file mode 100644 index 0000000..54febef --- /dev/null +++ b/module/dll_source_lzy/114/out/lib/device_uhd_cpp.h @@ -0,0 +1,144 @@ +#ifndef DEVICE_UHD_H +#define DEVICE_UHD_H + +#include "device_uhd_struct.h" +#include +#include +#include +#include +#include +#include +#include +#include + +#include +using namespace std; +std::string get_UHD_ParamType(UHD_ParamType v); +class Device_UHD +{ + public: + uhd::device_addr_t devAddr; // 设备地址 + bool bFindedDevice; + std::shared_ptr spThread_Recv[2]; + std::shared_ptr spThread_Send[2]; + uhd::property_tree::sptr pTree; + int kd_centerfreq_sw; + double fParamMin; + double fParamMax; + UHD_FFTWin fftWin; // 窗类型 + UHD_FFTLen fftLen; // 窗长度 + int fftPeriod; // 频谱周期 1-1000,单位ms + UHD_KDParam rxKDParam[2]; // rx宽带通道参数 + UHD_KDParam txKDParam[2]; // tx宽带通道参数 + int FilterCoef[256]; // 滤波器系数数组 + public: + std::string gps_info; + int led_val; + + public: + //! Device type, used as a filter in make + // enum device_filter_t { ANY, USRP, CLOCK }; + bool isDevOpened() const; + uhd::device_addrs_t findDevices(); + bool openDevice(uhd::device_addr_t addr); + // 关闭设备 + void closeDevice(); + // 获取设备信息 + string findDevInfos(); + // 获取设备信息2 + string findDevInfos2(); + // 获取设备树 + string getDevTree(); + // 设置时钟源 + bool setDevClockSource(string sourceStr); + // 获取时钟源 + string getDevClockSource(); + bool setDevInClock(double clockFreq); + void getDevInClockRange(); + double getDevInClock(); + size_t getDevRXChCount(); + size_t getDevTXChCount(); + bool setDevParam(string chStr, UHD_ParamType paramType, double paramValue); + double getDevParam(string chStr, UHD_ParamType paramType); + void getDevParamRange(string chStr, UHD_ParamType paramType, double ¶mMin, double ¶mMax); + double getDevParamMin() const; + double getDevParamMax() const; + bool setAllAntenna(); + bool setDevDDCParam_Any(string chStr, unsigned int jcqOffset, unsigned int jcqData); + bool getDevDDCParam_Any(string chStr, unsigned int jcqOffset, unsigned int &jcqData); + bool setDevDataSwitch(string chStr, UHD_ParamType dataType, unsigned char ZDCh, bool bSwitch); + bool getDevDataSwitch(string chStr, UHD_ParamType dataType, unsigned char ZDCh, bool &bSwitch); + // 采样率为0,表示该通道停止使用 + bool ischeck_head = true; + int setDevZDParam(string chStr, unsigned char ZDCh, long long centerfreq, int bw, int sample); + // 采样率为0,表示该通道未使用 + bool getDevZDParam(string chStr, unsigned char ZDCh, long long ¢erfreq, int &bw, int &sample); + void getDevZDCenterRange(string chStr, long long &min, long long &max); + void getDevZDBandWidthRange(string chStr, int &min, int &max); + vector getDevZDSampleFreqRange(string chStr); + bool setDevFFTParam(UHD_FFTWin fftWin, UHD_FFTLen fftLen, int fftPeriod_ms); + bool getDevFFTParam(UHD_FFTWin &fftWin, UHD_FFTLen &fftLen, int &fftPeriod_ms); + + bool bThread_Recv[2] = {0, 0}; + double fRecvSpeed[2] = {0, 0}; + void *pRecvBuf[2] = {0, 0}; + int iRecvBufSize[2] = {0, 0}; + int iRecvBufPosi[2] = {0, 0}; + double getDevRecvSpeed(int channel) const; + bool isDevRecving(int channel) const; + void startDevRecv(int channel); + void stopDevRecv(int channel); + double getDevSendSpeed(int channel) const; + bool isDevSending(int channel) const; + bool bThread_Send[2] = {0, 0}; + double fSendSpeed[2] = {0, 0}; + + int send_chan_sw = 0; + int send_all_sw = 0; + int rx_kd_ddc_sw = 0; + + void startDevSend(int channel, unsigned long long send_cf, unsigned long long data_sf, char *filename, bool bwhile); + void stopDevSend(int channel); + // uhd::usrp::multi_usrp::sptr pUSRP1; + uhd::usrp::multi_usrp::sptr p_usrp; + std::function callBackData; + + std::string getGPSInfo(); + bool setLedEnable(int led_num, bool bEnable); + bool getLedEnable(int led_num, bool &bEnable); + std::string get_UHD_FFTWin(UHD_FFTWin v) + { + /* + jxc =0,// 矩形窗 = 0, + hnc = 1,// 汉宁窗 = 1, + hmc = 2, // 海明窗 = 2, + blkmc = 3,// 布莱克曼窗 = 3, + */ + string tmp; + switch (v) + { + case jxc: { + tmp = "jxc"; + } + break; + case hnc: { + tmp = "hnc"; + } + break; + case hmc: { + tmp = "hmc"; + } + break; + case blkmc: { + tmp = "blkmc"; + } + break; + + default: + break; + } + return tmp; + }; + +}; +#endif // DEVICE_UHD_H diff --git a/module/dll_source_lzy/114/out/lib/device_uhd_struct.h b/module/dll_source_lzy/114/out/lib/device_uhd_struct.h new file mode 100644 index 0000000..800605b --- /dev/null +++ b/module/dll_source_lzy/114/out/lib/device_uhd_struct.h @@ -0,0 +1,319 @@ +#ifndef device_uhd_struct_h +#define device_uhd_struct_h +#include +#include +#include +#ifdef __linux__ +#include "iio.h" +#include +#endif +#ifdef WIN32 +#include +#endif +#include +using namespace std; + +#pragma pack(push) +#pragma pack(1) +namespace uhd +{ +typedef std::string fs_path; +class device_addr_t +{ + public: + std::string uri; + std::string to_string(void) const { return uri; } +}; +typedef std::vector device_addrs_t; +namespace usrp +{ +namespace multi_usrp +{ +typedef struct rx_parm +{ + struct iio_device *rx_dev = nullptr; + struct iio_channel *rx_chan[2]; + struct iio_buffer *rx_buf; + bool rx_chan_is_enable; + bool rx_buf_is_enable; +} rx_parm; +typedef struct tx_parm +{ + struct iio_device *tx_dev = nullptr; + struct iio_channel *tx_chan[2]; + struct iio_buffer *tx_buf; + bool tx_chan_is_enable; + bool tx_buf_is_enable; +} tx_parm; +typedef struct sptr +{ + struct iio_context *ctx = nullptr; + bool ctx_isopen; + struct rx_parm iio_rx_arr[2]; + struct tx_parm iio_tx_arr[2]; + device_addrs_t uri_list; + std::string cur_sourceStr; + double cur_clockFreq; + int rx0_power_reference; + int rx1_power_reference; + int tx0_power_reference; + int tx1_power_reference; +} sptr; +} // namespace multi_usrp +} // namespace usrp +namespace property_tree +{ +typedef std::string sptr; +} +} // namespace uhd +#pragma pack(pop) +#define ZDSamSum 200000000 // 8路窄带采样率之和 +#define ZDChMax 8 // 每路大通道下窄带通道总数 +enum UHD_ParamType : int +{ + CenterFreq = 0, + BandWidth = 1, + SampleFreq = 2, + Gain = 3, + PowerRef = 4, + KDDCSwitch = 5, + KFFTSwitch = 6, + ZDDCSwitch = 7, + ZDDCParam = 8, + KFFTParam = 9, + ClockSource = 10, + SnapshotSwitch = 11, + Snapshot_tm_s = 12, +}; +enum UHD_FFTWin : unsigned char +{ + jxc = 0, // 矩形窗 = 0, + hnc = 1, // 汉宁窗 = 1, + hmc = 2, // 海明窗 = 2, + blkmc = 3, // 布莱克曼窗 = 3, +}; +enum UHD_FFTLen : unsigned int +{ + _1024 = 1024, + _2048 = 2048, + _4096 = 4096, + _8192 = 8192, + _16384 = 16384, + _32768 = 32768, +}; +#pragma pack(push) +#pragma pack(1) +struct UHD_ZDParam +{ + unsigned char KCH = 0; // 宽带通道号 + unsigned short ZCH = 0; // 窄带通道号 + long long CenterFreq = 0; // 中频 + int BandWidth = 0; // 带宽 + int SampleFreq = 0; // 采样率 + int ExtraPer = 1024; // 抽取率 4-4096,2的指数 + bool bSwitch_ZDDC = false; +}; +struct UHD_KDParam +{ + unsigned char KCH = 0; // 宽带通道号 + long long CenterFreq = 10000000; + + int BandWidth = 160000000; + int SampleFreq = 200000000; + + bool bSwitch_6GCH = false; + + bool bSwitch_KDDC = false; + bool bSwitch_KFFT = false; + double gain = 0; + UHD_ZDParam ZDParam[ZDChMax]; + int ExtraPer; + bool Snapshot_Switch = false; + int Snapshot_tm_s = 0; + + unsigned long long old_sf; + unsigned long long old_cf; + unsigned long long old_bw; +}; +#pragma region 枚举/结构体 + +/** @brief TODO: 时码类型枚举 + * @enum LibWZ57_Enum_TimeType + */ +enum Enum_TimeType : uint8_t +{ + Enum_TimeType_Invlid = 0, /**< 无效的*/ + Enum_TimeType_IRIG_B = 1, /**< IRIG-B*/ + Enum_TimeType_RMC = 2, /**< RMC*/ + Enum_TimeType_ABSCNTTM = 3, /**< 绝对计数时间*/ + Enum_TimeType_REFCNTTM = 4, /**< 相对计数时间*/ +}; +typedef struct struct_DateTime +{ + + Enum_TimeType TimeType; /**< 10 时码类型*/ + + /** @brief 10个字节的时码信息 + * @details + * 根据 @ref LibWZ57_Enum_TimeType TimeType,对应不同的 联合体 + */ + union TimeInfo { + ///@brief IRIG-B + ///@struct IRIGB_Head + struct IRIGB_Head + { + uint8_t Year; /**< 年 字节1*/ + uint16_t Day; /**< 日 字节2*/ + uint8_t Hour; /**< 时 字节1*/ + uint8_t Minute; /**< 分 字节1*/ + uint8_t Second; /**< 秒 字节1*/ + uint32_t NanoSec; /**< 纳 字节4*/ + } IRIGB_Head; + + ///@brief RMC + ///@struct RMC_Head + struct RMC_Head + { + uint8_t Year; /**< 年 字节1*/ + uint8_t Month; /**< 月 字节1*/ + uint8_t Day; /**< 日 字节1*/ + uint8_t Hour; /**< 时 字节1*/ + uint8_t Minute; /**< 分 字节1*/ + uint8_t Second; /**< 秒 字节1*/ + uint32_t NanoSec; /**< 纳 字节4*/ + } RMC_Head; + + ///@brief 绝对计数时间 + ///@struct ABSCNTTM_Head + struct ABSCNTTM_Head + { + ///@brief 秒 字节6; 基准秒计数时间+相对秒计数时间 单位:秒 + uint8_t Second[6]; + ///@brief 纳秒 字节4; + uint32_t NanoSec; + } ABSCNTTM_Head; + + ///@brief 相对计数时间 + ///@struct REFCNTTM_Head + struct REFCNTTM_Head + { + ///@brief 秒 字节6; 相对秒计数时间单位:秒 + uint8_t Second[6]; + ///@brief 纳秒 字节4; + uint32_t NanoSec; + } REFCNTTM_Head; + } TimeInfo; + +} struct_DataTime; + +#pragma region 枚举 +/***************************** + *数据类型 + *****************************/ +enum UHD_Enum_DataType : unsigned char +{ + zd_ddc = 1, + kd_ddc = 2, + kd_fft = 3, + GPS_Info = 16, + // 窄带DDC = 0x01, + // 宽带DDC = 0x02, + // 宽带FFT = 0x03, +}; +#pragma endregion +#pragma region 结构体 +#pragma region UHD_Struct_KFFT UHD_Struct_KDDC UHD_Struct_ZDDC +/// +/// 宽带FFT头 +/// +typedef struct +{ + /// + /// 帧标识 6 0x2828F628F6F6 固定值 + /// + unsigned int Head; + /// + /// + /// + unsigned short Head2; + /// + /// 协议版本 1 0x80 + /// + unsigned char DealVersion; + /// + /// 帧头长度 1 64 + /// + unsigned char FrameHeadLen; + /// + /// 数据长度 2 2048 + /// + unsigned short DataLen; + /// + /// 有效数据长度 2 2048 + /// + unsigned short UsefullLen; + /// + /// 数据类型 1 + /// + UHD_Enum_DataType DataType; + unsigned char Other1; + /// + /// 通道号 + /// + unsigned char Channel; + unsigned char Other2; + unsigned short ZDChannel; + /// + /// 帧计数 2 0 ~ 65535 循环递增 + /// + unsigned short FrameIndex; + /// + /// 帧起止标识 1 0x0 + /// + unsigned char FrameBeginFlag; + struct_DateTime DateTm; + /// + /// 采样率 4 单位Hz + /// + unsigned int SampleFreq_Hz; + /// + /// 带宽 4 单位Hz + /// + unsigned int BandWidth_Hz; + /// + /// 中心频点 4 单位Hz,低位 + /// + unsigned int CenterFreq_Hz_Low; + /// + /// 中心频点 2 单位Hz,高位 + /// + unsigned short CenterFreq_Hz_High; + union { + unsigned char other5[18]; + struct + { + unsigned char other4[6]; + /// + /// FFT长度 65536 + /// + int FFTPoint; + unsigned char other5[2]; + float other6; + /// + /// 段内帧号 + /// + unsigned short SubFrame; + } FFT; + } Param; + // 数据 2048 共1024个数据,1个数据2字节。 +} UHD_Struct_KFFT, UHD_Struct_KDDC, UHD_Struct_ZDDC; + + +#pragma endregion +#pragma endregion +#pragma pack(pop) + + +#pragma endregion + +#endif diff --git a/module/dll_source_lzy/114/out/lib/error_callback.cpp b/module/dll_source_lzy/114/out/lib/error_callback.cpp new file mode 100644 index 0000000..b971ff9 --- /dev/null +++ b/module/dll_source_lzy/114/out/lib/error_callback.cpp @@ -0,0 +1,43 @@ +#include "error_callback.h" +#include +#include +#include + +error_cbk_t g_error_callback = nullptr; + +static std::mutex g_error_mutex; + +const char *extract_filename_in_cbk(const char *full_path) +{ + if (!full_path) + return "unknow_file"; +#ifdef _WIN32 + const char *pos = strrchr(full_path, '\\'); +#endif +#ifdef __linux__ + const char *pos = strrchr(full_path, '/'); + +#endif + return (pos) ? (pos + 1) : full_path; +} +void error_callback_call(const char *file_name, const char *func_name, const char *err_msg) +{ + + g_error_mutex.lock(); + if (g_error_callback == nullptr) + { + const char * pure_file = extract_filename_in_cbk(file_name); + std::cout << "[" << func_name << "]==>\t" << err_msg; + //std::cout << "[默认打印]:" << "FILE:[" << pure_file << "]FUNC:[" << func_name << "]==>\t" << err_msg; + } + else + { + g_error_callback(file_name, func_name, err_msg); + } + g_error_mutex.unlock(); +} + +void set_error_cbk(error_cbk_t cbk) +{ + g_error_callback = cbk; +} diff --git a/module/dll_source_lzy/114/out/lib/error_callback.h b/module/dll_source_lzy/114/out/lib/error_callback.h new file mode 100644 index 0000000..4f0a28a --- /dev/null +++ b/module/dll_source_lzy/114/out/lib/error_callback.h @@ -0,0 +1,17 @@ +#ifndef __ERROR_CALLBACK_H__ +#define __ERROR_CALLBACK_H__ + +#include "makelib_common.h" +typedef void (*error_cbk_t)(const char *file_name ,const char *func_name,const char *err_msg); + +extern error_cbk_t g_error_callback; + +ex_declare void error_callback_call( const char *file_name ,const char *func_name,const char *err_msg); +ex_declare const char *extract_filename_in_cbk(const char *full_path); +ex_declare void set_error_cbk(error_cbk_t cbk); + + +#define MACROS_ERROR_CBK_CALL(msg) error_callback_call(__FILE__,__func__,msg) + + +#endif // __ERROR_CALLBACK_H__ \ No newline at end of file diff --git a/module/dll_source_lzy/114/out/lib/hulc/Bit.cpp b/module/dll_source_lzy/114/out/lib/hulc/Bit.cpp new file mode 100644 index 0000000..2965e78 --- /dev/null +++ b/module/dll_source_lzy/114/out/lib/hulc/Bit.cpp @@ -0,0 +1,761 @@ +#include "Bit.h" +#include +#include +#include +#include +#include +// 2025-01-02 05:01:50 [info] 1a480118 9607f81e f020 3a24 67761dbd 1a9ecbf8 5655c75b 00601307 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _USE_GTEST +#include +using namespace yC; +#endif +constexpr std::array make_hex_to_val() { + std::array t{255}; // 初始化为255 + for (uint8_t i = '0'; i <= '9'; ++i) t[i] = i - '0'; + for (uint8_t i = 'A'; i <= 'F'; ++i) t[i] = i - 'A' + 10; + for (uint8_t i = 'a'; i <= 'f'; ++i) t[i] = i - 'a' + 10; + return t; +} +constexpr std::array make_val_to_hex(bool uppercase) { + std::uint8_t s = uppercase ? 'A' : 'a'; + std::array t{}; + for (uint8_t i = 0; i < 10; ++i) { + t[i] = '0' + i; // '0' - '9' + } + for (uint8_t i = 10; i < 16; ++i) { + t[i] = s + (i - 10); // 'a' - 'f' 'A - F' + } + return t; +} +static constexpr std::array val_to_upper_hex = make_val_to_hex(true); +static constexpr std::array val_to_lower_hex = make_val_to_hex(false); +static constexpr std::array hex_to_val = make_hex_to_val(); +constexpr const char* hex_lut_lower = "0123456789abcdef"; +constexpr const char* hex_lut_upper = "0123456789ABCDEF"; +constexpr const char* big_dian_hex_to_bin[16] = { + "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", + "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111" +}; +constexpr const char* small_dian_hex_to_bin[16] = { + "0000", "1000", "0100", "1100", "0010", "1010", "0110", "1110", + "0001", "1001", "0101", "1101", "0011", "1011", "0111", "1111" +}; +constexpr std::array, 256> make_xor_table() { + std::array, 256> t{}; + for (size_t i = 0; i < 256; ++i) { + for (size_t j = 0; j < 256; ++j) { + t[i][j] = 255; + } + } + for (size_t i = 0; i < 16; ++i) { + for (size_t j = 0; j < 16; ++j) { + t[val_to_lower_hex[i]][val_to_lower_hex[j]] = i ^ j; + t[val_to_upper_hex[i]][val_to_upper_hex[j]] = i ^ j; + } + } + return t; +} + +static constexpr std::array, 256> xor_table = make_xor_table(); +inline size_t bin4_to_hex(bool big_byte_order, const char* a) { + static size_t small_base[]{1, 2, 4, 8}; + static size_t big_base[]{8, 4, 2, 1}; + auto cur_dian = big_byte_order ? big_base : small_base; + size_t ret = 0; + for (size_t i = 0; i < 4; ++i) { + auto cur = size_t(a[i] - '0'); + ret += cur_dian[i] * cur; + } + return ret; +} + + + +namespace yC { + const bool is_big_endian = []() { + uint16_t x = 0x0102; // 设置一个已知的 16-bit 值 + auto* p = reinterpret_cast(&x); + return p[0] == 0x01; // 如果 p[0] 为 0x01,说明是大端字节序 + }(); + std::vector split(const std::string& str, const std::string& delimiter) { + std::vector tokens; + size_t start = 0; + size_t end = str.find(delimiter); + if (end == std::string::npos) return {}; + while (end != std::string::npos) { + tokens.push_back(str.substr(start, end - start)); + start = end + 1; + end = str.find(delimiter, start); + } + tokens.push_back(str.substr(start)); // Add the last token + return tokens; + } + std::string bin2mem(const std::string& bin) { + const size_t len = bin.size(); + if (len % 8 != 0) { + throw std::invalid_argument("binary string length must be a multiple of 8"); + } + std::string result; + result.reserve(len / 8); // 提前分配 + for (size_t i = 0; i < len; i += 8) { + uint8_t byte = 0; + for (size_t j = 0; j < 8; ++j) { + char bit = bin[i + j]; + if (bit == '1') { + byte |= (1 << (7 - j)); + } else if (bit != '0') { + std::ostringstream oss; + oss << "Invalid bit character '" << bit << "' at position " << (i + j); + throw std::invalid_argument(oss.str()); + } + } + result.push_back(static_cast(byte)); + } + return result; + } + + void bin2mem(void* dest, const char* data, size_t size) { + if (size % 8 != 0) { + throw std::invalid_argument("Binary string length must be a multiple of 8"); + } + uint8_t* byte_dest = static_cast(dest); // 将 dest 转换为字节指针 + for (size_t i = 0; i < size; i += 8) { + uint8_t byte = 0; + for (size_t j = 0; j < 8; ++j) { + char bit = data[i + j]; + if (bit == '1') { + byte |= (1 << (7 - j)); // 设置相应的位 + } else if (bit != '0') { + std::ostringstream oss; + oss << "Invalid bit character '" << bit << "' at position " << (i + j); + throw std::invalid_argument(oss.str()); + } + } + byte_dest[i / 8] = byte; // 将转换后的字节写入目标内存 + } + } + + void hex2mem_Ex(void* dest, const char* data, size_t size) { + // 判断输入 hex 数据的长度是否为偶数 + if (size % 2 != 0) { + throw std::invalid_argument("hex string length must be even"); + } + // 填充目标数据 + for (size_t i = 0; i < size; i += 2) { + unsigned char hi = data[i]; + unsigned char lo = data[i + 1]; + auto hi_val = hex_to_val[hi]; + auto lo_val = hex_to_val[lo]; + + if (hi_val == 255 || lo_val == 255) { + std::ostringstream oss; + oss << "hex:[" << data << "] Invalid hex: [" << data[i] << data[i + 1] << "] at pos " << i; + throw std::invalid_argument(oss.str()); + } + + // 填充目标内存 + unsigned char byte = (hi_val << 4) | lo_val; + std::memcpy(static_cast(dest) + i / 2, &byte, 1); + } + } + + void mem2hex_Ex2(void* dest, void* mem, size_t num, bool uppercase, const char* middle, size_t middle_len) { + assert(middle != nullptr); + + const char* lut = uppercase ? hex_lut_upper : hex_lut_lower; + if (middle_len == std::numeric_limits::max()) { + middle_len = (middle != nullptr) ? std::strlen(middle) : 0; + } + char* dest_ptr = static_cast(dest); + for (size_t i = 0; i < num; ++i) { + unsigned char c = static_cast(mem)[i]; + *dest_ptr++ = lut[c >> 4]; + *dest_ptr++ = lut[c & 0xF]; + // 添加分隔符 + if (middle_len > 0 && i + 1 < num) { + std::copy(middle, middle + middle_len, dest_ptr); + dest_ptr += middle_len; + } + } + } + + void hex2bin_Ex(void* dest, const char* data, size_t size, bool big_dian) { + auto& dian = big_dian ? big_dian_hex_to_bin : small_dian_hex_to_bin; + for (size_t i = 0; i < size; i++) { + auto str = dian[hex_to_val[(unsigned char)(data[i])]]; + std::memmove(static_cast(dest) + i * 4, str, 4); + } + } + + void + bin2hex_Ex(void* dest, const char* d, size_t size, bool big_dian, bool uppercase) { + const char* lut = uppercase ? hex_lut_upper : hex_lut_lower; + auto tt = get_bin2hex_size(size); + auto n1 = size; + auto n2 = tt * 4; + char cur[4] = {'0', '0', '0', '0'}; + auto r = static_cast(dest); + if (!big_dian) { + // 小端 补充后导0 + for (size_t i = 0; i < n2; i++) { + auto j = i%4; + cur[j] = i >= n1 ? '0' : d[i]; + if (j == 3) { + auto val = bin4_to_hex(false, cur); + r[tt - 1 - i/4] = lut[val]; + } + } + } else { + // 大端模式:补充前导0 + for (size_t i = 0; i < n2; i++) { + // 对应位置 + auto j = i%4; + cur[j] = i >= n1 ? '0' : d[n1 - 1 - i]; + if (j == 3) { + auto val = bin4_to_hex(false, cur); + r[tt - 1 - i/4] = lut[val]; + } + } + } + } +#ifdef _USE_GTEST + TEST(Bit2223, bin2hex_Ex) { + // EXPECT_EQ(bin2hex("01101110"), "6E"); + // + { + // 0110 1110 + // 6 E + std::string it = "1101110"; + auto size = get_bin2hex_size(it.size()); + std::string res; + res.resize(size); + bin2hex_Ex(res.data(), it.c_str(), it.size(), true, true); + EXPECT_STREQ(res.c_str(), "6E"); + } + { + // 1101 1100 + // B 3 + + std::string it = "1101110"; + auto size = get_bin2hex_size(it.size()); + std::string res; + res.resize(size); + bin2hex_Ex(res.data(), it.c_str(), it.size(), false, true); + + // std::cout << res << std::endl; + EXPECT_STREQ(res.c_str(), "3B"); + } + + + } +#endif + + + void xor_bin_Ex(void* dest, const char* s1, size_t n1, const char* s2, size_t n2, bool big_dian) { + if (n1 > n2) { + std::swap(n1, n2); + std::swap(s1, s2); + } + // n1 <= n2 + char* r = static_cast(dest); + if (!big_dian) { + // 小端 补充后导0 + for (size_t i = 0; i < n1; i++) { + r[i] = s1[i] == s2[i] ? '0' : '1'; + } + for (size_t i = n1; i < n2; i++) { + r[i] = '0' == s2[i] ? '0' : '1'; + } + } else { + // 大端模式:补充前导0 + for (size_t i = 0; i < n1; i++) { + // 对应位置 + auto c1 = s1[n1 - 1 - i]; + auto c2 = s2[n2 - 1 - i]; + r[n2 - 1 - i] = c1 == c2 ? '0' : '1'; // 对应位异或 + } + for (size_t i = n1; i < n2; i++) { + auto c1 = '0'; + auto c2 = s2[n2 - 1 - i]; + r[n2 - 1 - i] = c1 == c2 ? '0' : '1'; // 对应位异或 + } + } + } +#ifdef _USE_GTEST + TEST(Bit2223, xor_bin_Ex) { + const char* s1 = "10"; + const char* s2 = "111"; + std::string res; + res.resize(3); + xor_bin_Ex(res.data(), s1, 2, s2, 3, true); + EXPECT_STREQ(res.c_str(), "101"); + xor_bin_Ex(res.data(), s1, 2, s2, 3, false); + EXPECT_STREQ(res.c_str(), "011"); + xor_bin_Ex(res.data(), s2, 3, s1, 2, false); + EXPECT_STREQ(res.c_str(), "011"); + + s2 = "1111"; + res.resize(4); + // 0010 + // 1111 + // 1101 + xor_bin_Ex(res.data(), s1, 2, s2, 4, true); + EXPECT_STREQ(res.c_str(), "1101"); + } +#endif + + + + void xor_hex_Ex(void* dest, const char* s1, size_t n1, const char* s2, size_t n2, bool big_dian, bool uppercase) { + if (n1 > n2) { + std::swap(n1, n2); + std::swap(s1, s2); + } + auto& val_to_hex = uppercase ? val_to_upper_hex : val_to_lower_hex; + // n1 <= n2 + auto r = static_cast(dest); + if (!big_dian) { + // 小端 补充后导0 + for (size_t i = 0; i < n1; i++) { + //r[i] = s1[i] == s2[i] ? '0' : '1'; + auto c1 = s1[i]; + auto c2 = s2[i]; + r[i] = val_to_hex[xor_table[c1][c2]]; + } + for (size_t i = n1; i < n2; i++) { + //r[i] = '0' == s2[i] ? '0' : '1'; + auto c1 = '0'; + auto c2 = s2[i]; + r[i] = val_to_hex[xor_table[c1][c2]]; + } + } else { + // 大端模式:补充前导0 + for (size_t i = 0; i < n1; i++) { + // 对应位置 + auto c1 = s1[n1 - 1 - i]; + auto c2 = s2[n2 - 1 - i]; + //r[n2 - 1 - i] = c1 == c2 ? '0' : '1'; // 对应位异或 + auto idx = xor_table[c1][c2]; + r[n2 - 1 - i] = val_to_hex[idx]; // 对应位异或 + } + for (size_t i = n1; i < n2; i++) { + auto c1 = '0'; + auto c2 = s2[n2 - 1 - i]; + auto idx = xor_table[c1][c2]; + //r[n2 - 1 - i] = c1 == c2 ? '0' : '1'; // 对应位异或 + r[n2 - 1 - i] = val_to_hex[idx]; // 对应位异或 + } + } + } +#ifdef _USE_GTEST + TEST(Bi222, xor_hex_Ex) { + { + const char* s1 = "10"; + const char* s2 = "111"; + std::string res; + res.resize(3); + xor_hex_Ex(res.data(), s1, 2, s2, 3, true, true); + EXPECT_STREQ(res.c_str(), "101"); + xor_hex_Ex(res.data(), s1, 2, s2, 3, false, true); + EXPECT_STREQ(res.c_str(), "011"); + xor_hex_Ex(res.data(), s2, 3, s1, 2, false, true); + EXPECT_STREQ(res.c_str(), "011"); + } + { + const char* s1 = "ab"; + const char* s2 = "111"; + std::string res; + res.resize(3); + // 0ab 0000 0110 0111 + // 111 0001 0001 0001 + // 1ba 0001 0111 0110 + xor_hex_Ex(res.data(), s1, 2, s2, 3, true, true); + EXPECT_STREQ(res.c_str(), "1BA"); + + + + } + } +#endif + + // 将字节序从大端转换到当前平台字节序,并复制到目标内存中 + void big_endian_2_platform(const std::string& big_endian, char* dest) { + // 先复制原始数据 + std::string result = big_endian; + // 如果当前平台是小端,反转数据 + if (!is_big_endian) { + std::reverse(result.begin(), result.end()); + } + // 将转换后的数据拷贝到目标内存中 + std::memcpy(dest, result.data(), result.size()); + } + std::string big_endian_2_platform(const std::string& big_endian) { + std::string result; + result.resize(big_endian.size()); + big_endian_2_platform(big_endian, result.data()); + return result; + } + // 将字节序从小端转换到当前平台字节序,并复制到目标内存中 + void little_endian_2_platform(const std::string& little_endian, char* dest) { + // 先复制原始数据 + std::string result = little_endian; + // 如果当前平台是大端,反转数据 + if (is_big_endian) { + std::reverse(result.begin(), result.end()); + } + // 将转换后的数据拷贝到目标内存中 + std::memcpy(dest, result.data(), result.size()); + } + std::string little_endian_2_platform(const std::string& little_endian) { + std::string result; + result.resize(little_endian.size()); + big_endian_2_platform(little_endian, result.data()); + return result; + } + // 将平台字节序转换为大端字节序 + std::string platform_2_big_endian(void* t, int size) { + char* memory = reinterpret_cast(t); + // for (int i = 0; i < size; ++i) { + // std::cout << (int)memory[i] << std::endl; + // } + std::string result(memory, memory + size); + // 如果当前平台是小端,反转字符串,使其成为大端字节序 + //std::cout << "platform_2_big_endian start " << memory2hex(result) << std::endl; + if (!is_big_endian) { + std::reverse(result.begin(), result.end()); + } + //std::cout << "platform_2_big_endian end " << memory2hex(result) << std::endl; + return result; + } + // 将平台字节序转换为小端字节序 + std::string platform_2_little_endian(void* t, int size) { + char* memory = reinterpret_cast(t); + std::string result(memory, memory + size); + // 如果当前平台是大端,反转字符串,使其成为小端字节序 + if (is_big_endian) { + std::reverse(result.begin(), result.end()); + } + return result; + } +#define GET_BIT(byte, pos) (((byte) >> (pos)) & 1) +#define SET_BIT(byte, pos) ((byte) |= (1 << (pos))) +#define CLR_BIT(byte, pos) ((byte) &= ~(1 << (pos))) +#define WRITE_BIT(byte, pos, val) \ + ((byte) = ((byte) & ~(1 << (pos))) | (((val) & 1) << (pos))) + template + void bit_op(void* dest, size_t d_offset, const void* src, size_t s_offset, size_t num, BitOp op) { + auto* d = (uint8_t*)dest; + const auto* s = (const uint8_t*)src; + for (size_t i = 0; i < num; ++i) { + size_t src_pos = s_offset + i; + size_t dst_pos = d_offset + i; + uint8_t src_bit = GET_BIT(s[src_pos / 8], src_pos % 8); + uint8_t dst_bit = GET_BIT(d[dst_pos / 8], dst_pos % 8); + uint8_t res_bit = op(dst_bit, src_bit); + WRITE_BIT(d[dst_pos / 8], dst_pos % 8, res_bit); + } + } + void bit_move(void* d, size_t doff, const void* s, size_t soff, size_t n) { + bit_op(d, doff, s, soff, n, [](uint8_t, uint8_t s) { return s; }); + } + void bit_xor(void* d, size_t doff, const void* s, size_t soff, size_t n) { + bit_op(d, doff, s, soff, n, [](uint8_t d, uint8_t s) { return d ^ s; }); + } + void bit_or(void* d, size_t doff, const void* s, size_t soff, size_t n) { + bit_op(d, doff, s, soff, n, [](uint8_t d, uint8_t s) { return d | s; }); + } + void bit_and(void* d, size_t doff, const void* s, size_t soff, size_t n) { + bit_op(d, doff, s, soff, n, [](uint8_t d, uint8_t s) { return d & s; }); + } +} +constexpr uint8_t reverse8(uint8_t b) { + b = (b & 0xF0) >> 4 | (b & 0x0F) << 4; + b = (b & 0xCC) >> 2 | (b & 0x33) << 2; + b = (b & 0xAA) >> 1 | (b & 0x55) << 1; + return b; +} +constexpr std::array make_reverse8_table() { + std::array arr = {}; + for (uint16_t i = 0; i < 256; ++i) arr[i] = reverse8(static_cast(i)); + return arr; +} +constexpr auto reserve8 = make_reverse8_table(); +#define BYTE(b) reserve8[0b##b] +#ifdef _USE_GTEST +#include +using namespace yC; +// 辅助函数:字节数组转十六进制字符串(方便调试) +std::string bytes_to_hex(const std::vector& v) { + std::ostringstream oss; + for (auto b : v) { + oss << std::hex << std::setw(2) << std::setfill('0') << (int)b; + } + return oss.str(); +} +// case 2:dest 偏移,src 对齐 +TEST(BitMoveTest, DestBitOffset) { + struct Data { + std::vector dest; + size_t dest_offset; + std::vector src; + size_t src_offset; + size_t num; + std::vector expected_move; + std::vector expected_xor; + std::vector expected_or; + std::vector expected_and; + std::string msg; + }; + std::vector list; + // 1. 目标偏移2位,拷贝6位 + // 00 00000000 + // dest 000000 + // src 111100 + // xor: 111100 + // or: 111100 + // and: 000000 + Data d1{ + {BYTE(00000000), BYTE(00000000)}, + 2, + {BYTE(11110000), BYTE(00001111)}, + 0, + 6, + {BYTE(00111100), BYTE(00000000)}, + // move + {BYTE(00111100), BYTE(00000000)}, + // xor (0x3C, 0x00) + {BYTE(00111100), BYTE(00000000)}, + // or (0x3C, 0x00) + {BYTE(00000000), BYTE(00000000)}, + // and (0x00, 0x00) + "目标偏移2位,拷贝6位" + }; + + char arr[100]; + size_t a = get_mem2hex_size(2, 0); + mem2hex_Ex2(arr, d1.expected_move.data(), 2, false, ""); + + + + EXPECT_STREQ(hex2bin(std::string(arr, a)).c_str(), "0011110000000000"); + + + // 2. 目标偏移1位,拷贝9位,跨越目标字节 + // 1 000001 + // dest 000000000 + // src 011111111 + // xor: 011111111 + // or: 011111111 + // and: 000000000 + list.push_back({ + {BYTE(10000000), BYTE(00000001)}, + 1, + {BYTE(01111111), BYTE(10000000)}, + 0, + 9, + {BYTE(10111111), BYTE(11000001)}, + // move + {BYTE(10111111), BYTE(11000001)}, + // xor (0xFE, 0x83) + {BYTE(10111111), BYTE(11000001)}, + // or (0xFE, 0x83) + {BYTE(10000000), BYTE(00000001)}, + // and (0x01, 0x03) + "目标偏移1位,拷贝9位,跨字节" + }); + // 3. 目标偏移4,源偏移3,拷贝8位 + // 1100 1010 + // dest 00111010 + // src 10000000 + // xor 10111010 + // or 10111010 + // and 00000000 + list.push_back({ + {BYTE(11000011), BYTE(10101010)}, + 4, + {BYTE(11110000), BYTE(00001111)}, + 3, + 8, + {BYTE(11001000), BYTE(00001010)}, + // move + {BYTE(11001011), BYTE(10101010)}, + // xor + {BYTE(11001011), BYTE(10101010)}, + // or + {BYTE(11000000), BYTE(00001010)}, + // and + "目标偏移4,源偏移3,拷贝8位" + }); + // 4. 全1拷贝部分,全0目标 + // 00000 0000 + // dest 0000000 + // src 1111111 + // xor 1111111 + // or 1111111 + // and 0000000 + list.push_back({ + {BYTE(00000000), BYTE(00000000)}, + 5, + {BYTE(11111111), BYTE(11111111)}, + 2, + 7, + {BYTE(00000111), BYTE(11110000)}, + // move + {BYTE(00000111), BYTE(11110000)}, + // xor + {BYTE(00000111), BYTE(11110000)}, + // or + {BYTE(00000000), BYTE(00000000)}, + // and + "全1源,拷贝7位到目标末尾" + }); + // 5. 源目标均有内容(交错) + // 110 10011 + // dest 01100001 + // src 10100101 + // xor 11000100 + // or 11100101 + // and 00100001 + list.push_back({ + {BYTE(11001100), BYTE(00110011)}, + 3, + {BYTE(10101010), BYTE(01010101)}, + 4, + 8, + {BYTE(11010100), BYTE(10110011)}, + // move + {BYTE(11011000), BYTE(10010011)}, + // xor + {BYTE(11011100), BYTE(10110011)}, + // or + {BYTE(11000100), BYTE(00110011)}, + // and + "目标有内容,源偏移4,拷贝8位" + }); + // 6. 源目标完全重叠 + // 1011 01 + // dest 1001110100 + // src 1101111010 + // move 1101111010 + // xor 0100001110 + // or 1101111110 + // and 1001110000 + list.push_back({ + {BYTE(10111001), BYTE(11010001)}, + 4, + {BYTE(10110111), BYTE(10100101)}, + 2, + 10, + {BYTE(10111101), BYTE(11101001)}, + // move + {BYTE(10110100), BYTE(00111001)}, + // xor + {BYTE(10111101), BYTE(11111001)}, + // or + {BYTE(10111001), BYTE(11000001)}, + // and + "目标/源重叠,偏移不同" + }); + for (auto& d : list) { + auto dest_move = d.dest; + auto dest_xor = d.dest; + auto dest_or = d.dest; + auto dest_and = d.dest; + bit_move(dest_move.data(), d.dest_offset, d.src.data(), d.src_offset, d.num); + bit_xor(dest_xor.data(), d.dest_offset, d.src.data(), d.src_offset, d.num); + bit_or(dest_or.data(), d.dest_offset, d.src.data(), d.src_offset, d.num); + bit_and(dest_and.data(), d.dest_offset, d.src.data(), d.src_offset, d.num); + EXPECT_EQ(dest_move, d.expected_move) << "move 结果: " << hex2bin(bytes_to_hex(dest_move)) << "\n期望: " << + hex2bin(bytes_to_hex(d.expected_move)) << "\n" + d.msg; + EXPECT_EQ(dest_xor, d.expected_xor) << "xor 结果: " << bytes_to_hex(dest_xor) << "\n期望: " << + bytes_to_hex(d.expected_xor) << "\n" + d.msg; + EXPECT_EQ(dest_or, d.expected_or) << "or 结果: " << bytes_to_hex(dest_or) << "\n期望: " << + bytes_to_hex(d.expected_or) << "\n" + d.msg; + EXPECT_EQ(dest_and, d.expected_and) << "and 结果: " << bytes_to_hex(dest_and) << "\n期望: " << + bytes_to_hex(d.expected_and) << "\n" + d.msg; + } + +} + + +TEST(Bit222, WriteAndReadFullByte223) { + + + + + std::pmr::string s("11101110"); + std::string s2("11101110"); + std::cout << bin2hex(s) << std::endl; + std::cout << bin2hex(s2) << std::endl; + std::cout << bin2hex("11101110") << std::endl; + + + std::cout << "111:" << hex2bin("01") << std::endl; + std::cout << "big_dian:" << bin4_to_hex(true, "0011") << std::endl; + std::cout << "small_dian:" << bin4_to_hex(false, "0011") << std::endl; +} + +TEST(BitOpsLE, WriteAndReadFullByte) { + uint8_t buf[8] = {0}; + set_bits(buf, 0, 8, 0xAB); // 小端模式:低位在低bit + EXPECT_EQ(buf[0], 0xAB); + EXPECT_EQ(get_bits(buf, 0, 8), 0xAB); +} +TEST(BitOpsLE, CrossByteWriteAndRead) { + uint8_t buf[8] = {0}; + set_bits(buf, 4, 12, 0xF0F); // 写12位,偏移4 + EXPECT_EQ(get_bits(buf, 4, 12), 0xF0F); +} +TEST(BitOpsLE, UnalignedBitWriteAndRead) { + uint8_t buf[8] = {0}; + set_bits(buf, 5, 10, 0x2AA); // 偏移5位,写10位 + EXPECT_EQ(get_bits(buf, 5, 10), 0x2AA); +} +TEST(BitOpsLE, SingleBitWriteAndRead) { + uint8_t buf[8] = {0}; + set_bits(buf, 10, 1, 1); + EXPECT_EQ(get_bits(buf, 10, 1), 1); + set_bits(buf, 10, 1, 0); + EXPECT_EQ(get_bits(buf, 10, 1), 0); +} +TEST(BitOpsLE, WriteAndReadFullUint64) { + uint8_t buf[8] = {0}; + set_bits(buf, 0, 64, 0x123456789ABCDEF0ULL); + EXPECT_EQ(get_bits(buf, 0, 64), 0x123456789ABCDEF0ULL); +} +TEST(BitOpsLE, OverwriteZeroBits) { + uint8_t buf[8]; + std::memset(buf, 0xFF, sizeof(buf)); + set_bits(buf, 16, 16, 0x0000); + EXPECT_EQ(get_bits(buf, 16, 16), 0x0000); + // 其它位应保持原值 + for (size_t i = 0; i < 2; ++i) + EXPECT_EQ(buf[i], 0xFF); + for (size_t i = 4; i < 8; ++i) + EXPECT_EQ(buf[i], 0xFF); +} +TEST(BitOpsLE, AllZeroAndAllOne) { + uint8_t buf[8] = {0}; + set_bits(buf, 0, 64, 0xFFFFFFFFFFFFFFFFULL); + EXPECT_EQ(get_bits(buf, 0, 64), 0xFFFFFFFFFFFFFFFFULL); + set_bits(buf, 0, 64, 0x0ULL); + EXPECT_EQ(get_bits(buf, 0, 64), 0x0ULL); +} +#else +#endif diff --git a/module/dll_source_lzy/114/out/lib/hulc/Bit.h b/module/dll_source_lzy/114/out/lib/hulc/Bit.h new file mode 100644 index 0000000..59e8c58 --- /dev/null +++ b/module/dll_source_lzy/114/out/lib/hulc/Bit.h @@ -0,0 +1,309 @@ +#ifndef BitSet_H +#define BitSet_H +#include +#ifdef __linux__ +#include +#endif +#include +#include +#include +#include + +namespace yC { + template + typename std::enable_if::value, T>::type + create_string(size_t size, std::pmr::memory_resource* resource = nullptr) { + std::pmr::memory_resource* r = resource ? resource : std::pmr::get_default_resource(); + std::pmr::string ret(r); + ret.resize(size); + return ret; // 返回 std::pmr::string + } + + template + typename std::enable_if::value, T>::type + create_string(size_t size, std::pmr::memory_resource* resource = nullptr) { + std::string ret; + ret.resize(size); + return ret; // 返回 std::string + } + + template + struct cacl_type { + using type = T; + size_t size(T& a) { + return a.size(); + } + static void* data(T& a) { + return (void*)a.data(); + } + static size_t size(const T& a) { + return a.size(); + } + static void* data(const T& a) { + return (void*)a.data(); + } + }; + template <> + struct cacl_type { + using type = std::string; + static size_t size(const char* a) {return strlen(a);} + static void* data(const char* a) {return (void*)a;} + }; + + template + struct cacl_type { + using type = std::string; + static size_t size(const char (&a)[N]) { return N - 1; } + static void* data(const char (&a)[N]) { return (void*)a; } + }; + + template + struct cacl_type { + using type = std::string; + static size_t size(const char (&a)[N]) { return N - 1; } + static void* data(const char (&a)[N]) { return (void*)a; } + }; +} + + + +#define Base template , \ +typename STR_Type = std::basic_string, allocator_type>, \ +typename ret_type = typename cacl_type::type \ +> +// #define Base template <\ +// typename STR_Type, \ +// typename ret_type = typename cacl_type::type \ +// > + + +namespace yC { + // 检查当前机器是否是大端字节序 + extern const bool is_big_endian; + void big_endian_2_platform(void* dest, const char* d, size_t size); + void little_endian_2_platform(void* dest, const char* d, size_t size); + + + + void big_endian_2_platform(const std::string& big_endian, char* dest); + void little_endian_2_platform(const std::string& little_endian, char* dest); + + + std::string big_endian_2_platform(const std::string& big_endian); + std::string little_endian_2_platform(const std::string& little_endian); + std::string platform_2_big_endian(void* memory, int size); + std::string platform_2_little_endian(void* memory, int size); + + + + + inline size_t get_xor_hex_size(size_t n1, size_t n2){return std::max(n1, n2);} + void xor_hex_Ex(void* dest, const char* s1, size_t n1, const char* s2, size_t n2, bool big_dian, bool is_upper); + Base + ret_type xorHex(const STR_Type& s1, const STR_Type& s2, std::pmr::memory_resource* resource = nullptr) { + auto n1 = cacl_type::size(s1); + auto n2 = cacl_type::size(s2); + auto size = get_xor_hex_size(n1, n2); + auto ret = create_string(size, resource); + xor_hex_Ex((void*)ret.data(), (const char*)cacl_type::data(s1), n1, (const char*)cacl_type::data(s2), n2, true, true); + return ret; + } + + + inline size_t get_xor_bin_size(size_t n1, size_t n2){return std::max(n1, n2);} + void xor_bin_Ex(void* dest, const char* s1, size_t n1, const char* s2, size_t n2, bool big_dian); + Base + ret_type xorBin(const STR_Type& s1, const STR_Type& s2, std::pmr::memory_resource* resource = nullptr) { + auto n1 = cacl_type::size(s1); + auto n2 = cacl_type::size(s2); + auto size = get_xor_bin_size(n1, n2); + auto ret = create_string(size, resource); + xor_bin_Ex((void*)ret.data(), (const char*)cacl_type::data(s1), n1, (const char*)cacl_type::data(s2), n2, true); + return ret; + } + + + + + inline size_t get_bin2hex_size(size_t num) {return (num + 3) / 4;} + void bin2hex_Ex(void* dest, const char* data, size_t size, bool big_dian, bool isupper); + Base + ret_type bin2hex(const STR_Type& mem, std::pmr::memory_resource* resource = nullptr) { + auto size = cacl_type::size(mem); + auto ret = create_string(get_bin2hex_size(size), resource); + bin2hex_Ex((void*)ret.data(), (const char*)cacl_type::data(mem), size, true, true); + return ret; + } + + + + inline size_t get_hex2bin_size(size_t num) {return num * 4;} + void hex2bin_Ex(void* dest, const char* data, size_t size, bool big_dian); + Base + ret_type hex2bin(const STR_Type& mem, std::pmr::memory_resource* resource = nullptr) { + auto size = cacl_type::size(mem); + auto ret = create_string(get_hex2bin_size(size), resource); + hex2bin_Ex((void*)ret.data(), (const char*)cacl_type::data(mem), size, true); + return ret; + } + + inline size_t get_bin2mem_size(size_t num) {return num/8;}; + void bin2mem(void* dest, const char* data, size_t size); + Base + STR_Type bin2mem(const STR_Type& mem, std::pmr::memory_resource* resource = nullptr) { + auto size = cacl_type::size(mem); + auto ret = create_string(get_bin2mem_size(size), resource); + bin2mem((void*)ret.data(), (const char*)cacl_type::data(mem), size); + return ret; + } + + // inline ret_str bin2mem(param_str mem, std::pmr::memory_resource* resource = nullptr) { + // auto size = mem.size(); + // auto ret = ret_str(); + // ret.resize(get_bin2mem_size(size)); + // bin2mem((void*)ret.data(), (const char*)mem.data(), size); + // return ret; + // } + + + inline size_t get_hex2mem_size(size_t hex_hum) {return hex_hum/2;}; + void hex2mem_Ex(void* dest, const char* data, size_t size); + Base + STR_Type hex2mem(const STR_Type& mem, std::pmr::memory_resource* resource = nullptr) { + auto size = cacl_type::size(mem); + auto ret = create_string(get_hex2mem_size(size), resource); + hex2mem_Ex((void*)ret.data(), (const char*)cacl_type::data(mem), size); + return ret; + } + + // inline ret_str hex2mem(param_str hex, std::pmr::memory_resource* resource = nullptr) { + // auto size = hex.size(); + // auto ret = ret_str(); + // ret.resize(get_hex2mem_size(size)); + // hex2mem_Ex((void*)ret.data(), (const char*)hex.data(), size); + // return ret; + // } + + + inline size_t get_mem2hex_size(size_t num, size_t middle_len) { return num * 2 + (num - 1) * middle_len;} + void mem2hex_Ex2(void* dest, void* mem, size_t num, bool uppercase, const char* middle, size_t middle_len = std::numeric_limits::max()); + Base + STR_Type mem2hex(const STR_Type& mem, bool uppercase = true, const std::string& middle = "", std::pmr::memory_resource* resource = nullptr) { + auto size = cacl_type::size(mem); + auto ret = create_string(get_mem2hex_size(size, middle.size()), resource); + mem2hex_Ex2(ret.data(), cacl_type::data(mem), size, uppercase, middle.data(), middle.size()); + return ret; + } + + // inline ret_str mem2hex(param_str& mem, bool uppercase = true, const std::string& middle = "", std::pmr::memory_resource* resource = nullptr) { + // auto size = get_mem2hex_size(mem.size(), middle.size()); + // auto ret = ret_str(); + // mem2hex_Ex2(ret.data(), (void*)mem.data(), size, uppercase, middle.data(), middle.size()); + // return ret; + // } + + + template + void get_bin(std::string& msg, int& n) { + n = std::bitset(msg.substr(start, len)).to_ullong(); + } + template + void get_bin(std::string& msg, Enum& n) { + n = static_cast(std::bitset(msg.substr(start, len)).to_ullong()); + } + template + Enum get_bin(std::string& msg) { + return static_cast(std::bitset(msg.substr(start, len)).to_ullong()); + } + template + int get_bin(const std::string& msg) { + return std::bitset(msg.substr(start, len)).to_ullong(); + } + template + void set_bin(std::string& msg, unsigned long long n) { + msg.replace(start, len, std::bitset(n).to_string()); + } + template + void set_bin(std::string& msg, const std::string& value) { + if (value.size() != len) { + std::cout << "len == " << len << " bits.size() == " << value.size() << std::endl; + throw std::out_of_range("Start position and length exceed bit string size"); + } + msg.replace(start, len, value); + } + template + std::string to_bin(unsigned long long n) { + return std::bitset(n).to_string(); + } + template + std::string to_bin(double n) { + return std::bitset(static_cast(n)).to_string(); + } + template + T bin2(const std::string& binstr) { + return std::stoull(binstr, nullptr, 2); + } + template + unsigned long long hex2(const std::string& hexstr) { + return std::stoull(hexstr, nullptr, 16); + } + template <> + inline int bin2(const std::string& binstr) { + int bit_limit = sizeof(int) * 8; + if (binstr.size() > bit_limit) { + std::cout << "Bitset.h inline int bin2 error! Binary string exceeds int bit limit" << std::endl; + } + return std::stoi(binstr, nullptr, 2); + } + // 设置dest的从off位起n位,写入value的低n位 + template + void set_bits(void* dest, size_t off, size_t n, T value) { + auto d = static_cast(dest); + size_t bit_pos = off; + size_t val_pos = 0; + while (n > 0) { + size_t byte_idx = bit_pos / 8; + size_t bit_in_byte = bit_pos % 8; + size_t bits_in_this_byte = std::min(n, 8 - bit_in_byte); + // 为当前字节构建掩码 + uint8_t mask = ((1u << bits_in_this_byte) - 1) << bit_in_byte; + // 取value对应的低bits_in_this_byte位 + uint8_t v = (value >> val_pos) & ((1u << bits_in_this_byte) - 1); + // 清除目标字节对应位置后设置 + d[byte_idx] = (d[byte_idx] & ~mask) | ((v << bit_in_byte) & mask); + bit_pos += bits_in_this_byte; + val_pos += bits_in_this_byte; + n -= bits_in_this_byte; + } + } + + + + // 大批量位处理性能不好 但是通常也没有这样的场景 + void bit_move(void* d, size_t doff, const void* s, size_t soff, size_t n); + void bit_xor(void* d, size_t doff, const void* s, size_t soff, size_t n); + void bit_or(void* d, size_t doff, const void* s, size_t soff, size_t n); + void bit_and(void* d, size_t doff, const void* s, size_t soff, size_t n); + template + T get_bits(void* src, size_t off, size_t n) { + auto s = static_cast(src); + size_t bit_pos = off; + size_t val_pos = 0; + T result = 0; + while (n > 0) { + size_t byte_idx = bit_pos / 8; + size_t bit_in_byte = bit_pos % 8; + size_t bits_in_this_byte = std::min(n, 8 - bit_in_byte); + uint8_t mask = ((1u << bits_in_this_byte) - 1) << bit_in_byte; + uint8_t bits = (s[byte_idx] & mask) >> bit_in_byte; + result |= (T(bits) << val_pos); + bit_pos += bits_in_this_byte; + val_pos += bits_in_this_byte; + n -= bits_in_this_byte; + } + return result; + } +} + +#undef Base +#endif diff --git a/module/dll_source_lzy/114/out/lib/hulc/DataOutputFormats.cpp b/module/dll_source_lzy/114/out/lib/hulc/DataOutputFormats.cpp new file mode 100644 index 0000000..33c3fa0 --- /dev/null +++ b/module/dll_source_lzy/114/out/lib/hulc/DataOutputFormats.cpp @@ -0,0 +1,106 @@ +#include "DataOutputFormats.h" + +#include +#include + +using namespace yC; + +MLAT_timestamp::MLAT_timestamp() { + std::chrono::time_point t = std::chrono::high_resolution_clock::now(); + // 获取当前的系统时间(秒) + std::chrono::duration duration_since_epoch = t.time_since_epoch(); + // 获取秒数和纳秒数 + auto seconds = std::chrono::duration_cast(duration_since_epoch); + auto nanoseconds = std::chrono::duration_cast(duration_since_epoch); + // 获取当天的秒数和纳秒数 + this->daysec = seconds.count() % 86400; // 86400 = 24 * 60 * 60 (一天的秒数) + this->nanosec = nanoseconds.count() % 86400000000000; // 1秒 = 10^9纳秒 + memory = bin2mem(to_bin_string()); + parse_hhmmss(); +} + + +MLAT_timestamp::MLAT_timestamp(const std::string& memory_6) : memory(memory_6) { + assert(memory_6.size() == 6); + auto msg_bin = hex2bin(mem2hex(memory)); + daysec = std::bitset<18>(msg_bin.substr(0, 18)).to_ulong(); + nanosec = std::bitset<30>(msg_bin.substr(18, 30)).to_ulong(); + parse_hhmmss(); + + //assert(memory_6 == bin2mem(to_bin_string()), "MLAT_timestamp,内存转换错误!"); +} + +MLAT_timestamp::MLAT_timestamp(std::uint32_t daysec, std::uint32_t nanosec) : daysec(daysec), nanosec(nanosec) { + parse_hhmmss(); +} + + +std::string MLAT_timestamp::to_bin_string() const { + std::bitset<18> daysec_bits = daysec; + std::bitset<30> nanosec_bits = nanosec; + return daysec_bits.to_string() + nanosec_bits.to_string(); +} + +// std::string MLAT_timestamp::to_memory() { +// return bin2memory(to_bin_string()); +// } + +std::string MLAT_timestamp::to_memory() const { + return memory; +} + +void MLAT_timestamp::parse_hhmmss() { + hh = (daysec/3600) % 24; + mm = (daysec/60) % 60; + ss = daysec % 60; +} +std::string packet_to_escape_format(std::string t) { + std::string result = "\x1a"; + for (size_t i = 1; i < t.size(); ++i) { + result.push_back(t[i]); // 插入当前字符 + if (t[i] == '\x1a') { + result.push_back('\x1a'); // 如果是 0x1a,插入另一个 0x1a + } + } + return result; +} +void Binary_Format_handle_buffer(std::string& buffer, const std::string& data, const std::function& callback) { + size_t i = 0; + while (i < data.size()) { + if (data[i] == 0x1A) { + // 如果遇到起始标记 0x1A + if (i + 1 < data.size() && data[i + 1] == 0x1A) { + // 如果是转义的 0x1A 0x1A,继续处理 + buffer.push_back(0x1A); // 添加一个正常的 0x1A 字节 + i += 2; // 跳过这两个字节 + } else { + // 检测到起始标记 0x1A,认为是新消息的开始 + if (!buffer.empty()) { + // 如果当前消息 buffer 中已有数据,调用回调函数处理当前消息 + callback(buffer); + buffer.clear(); // 清空当前消息的缓存 + } + buffer.push_back(0x1A); + // 跳过当前的 SOP 标记 (0x1A) + i++; + } + } else + { + // 如果不是 0x1A,直接将数据添加到 buffer 中 + buffer.push_back(data[i]); + i++; + } + } +} + + + +// 9 + 2 +// 9 + 7 +// 9 + 14 +std::string mode_s_msg_packet_to_server_packet(std::uint32_t id, std::string packet) { + std::string id_code = yC::platform_2_big_endian((char*)&id, sizeof(id)); + //assert(id_code.size() == 4, "id.size != 4"); + packet.insert(1, id_code.c_str(), 4); + return packet; +} \ No newline at end of file diff --git a/module/dll_source_lzy/114/out/lib/hulc/DataOutputFormats.h b/module/dll_source_lzy/114/out/lib/hulc/DataOutputFormats.h new file mode 100644 index 0000000..aab359e --- /dev/null +++ b/module/dll_source_lzy/114/out/lib/hulc/DataOutputFormats.h @@ -0,0 +1,531 @@ +#ifndef DATAOUTPUTFORMATS_H +#define DATAOUTPUTFORMATS_H +#include "base_format.h" +using namespace yC; + +// AVR format +// *02E99619FACDAE; +// *8D3C5EE69901BD9540078D37335F; +// *7700; +inline std::string create_AVR_format(const std::string& msg_hex) { + return "*" + msg_hex + ";"; +} + +// @016CE3671C7423FFE7AB7BFCAB; +// @016CE3671AA8A800199A8BB80030A8000628F400; +// @016CE3671C747700; + +// @5500068BA46CB402c18d34fc8000; +inline std::string create_MLAT_AVR_format(const std::string& msg_hex, MLAT_timestamp* timestamp) { + //std::string signal_level_str = bin2hex(std::bitset<8>(signal_level).to_string()); + //std::cout << "signal:" << signal_level_str << std::endl; + return "@" + bin2hex(timestamp->to_bin_string()) + msg_hex + ";"; +} + + +// Binary Format +// "1" : 6 byte MLAT timestamp, 1 byte signal level, 2 byte Mode-AC +// "2" : 6 byte MLAT timestamp, 1 byte signal level, 7 byte Mode-S short frame +// "3" : 6 byte MLAT timestamp, 1 byte signal level, 14 byte Mode-S long frame +// "4" : 6 byte MLAT timestamp, 1 byte unused, DIP switch configuration settings, time stamp error ticks as int8_t (1 tick is 15ns) (message "4" not on Mode-S Beast classic) +// : true 0x1a +// is 0x1a, and "1", "2" and "3" are 0x31, 0x32 and 0x33 +inline std::string create_Binary_Format_memory(const std::string& msg_hex, char signal_level, MLAT_timestamp* timestamp) { + std::string type; + switch (msg_hex.size()) { + case 4: type = '1'; + break; + case 14: type = '2'; + break; + case 28: type = '3'; + break; + default: std::cerr << msg_hex << "create_Binary_Format error is not a valid binary format." << std::endl; + throw std::runtime_error("create_Binary_Format error!"); + } + + + std::string t = timestamp->to_memory() + signal_level + yC::hex2mem(msg_hex); + + // std::cout << "msg_hex.size():" << msg_hex.size() << std::endl; + // std::cout << "hex2memory(msg_hex):" << hex2memory(msg_hex).size() << std::endl; + // std::cout << t.size() << std::endl; + std::string result; + + // 遍历原始字符串 + for (size_t i = 0; i < t.size(); ++i) { + result.push_back(t[i]); // 插入当前字符 + if (t[i] == '\x1a') { + result.push_back('\x1a'); // 如果是 0x1a,插入另一个 0x1a + } + } + + return char(0x1a) + type + result; +} + +// 把要传递的信息转化成转义字符 二进制==>转义二进制 +std::string packet_to_escape_format(std::string t); + +inline std::string unescape_packet(std::string t) { + std::string result; + for (size_t i = 0; i < t.size(); ++i) { + if (t[i] == '\x1a' && i + 1 < t.size() && t[i + 1] == '\x1a') { + result.push_back('\x1a'); // 如果是连续的两个 \x1a,只添加一个 + ++i; // 跳过下一个 \x1a + } else { + result.push_back(t[i]); // 否则,直接添加当前字符 + } + } + return result; +} + + +// 用于dip_setting +// FPGA switch settings +// Bit 0: Data output mode(port 10002 only) Binary AVR hexdump +// Bit 1: Raw data frame types DF11, DF17 and DF18 only no pre-filtering +// Bit 2: Timestamps within AVR format enabled disabled +// Bit 3: not used +// Bit 4: Timestamp mode GPS legacy 12MHz +// Bit 5: FPGA/USB handshake disabled enabled +// Bit 6: 1 bit forward error correction (FEC) disabled enabled +// Bit 7: Mode-A/C decoding enabled disabled +// GPS status information +// Bit 0: Antenna status good fail +// Bit 1: Tracking at least 1 satellite true false +// Bit 2: Tracking at least 3 satellites true false +// Bit 3: Time value base UTC time GPS time (8sec offset) +// Bit 4: unused +// Bit 5: unused +// Bit 6: unused +// Bit 7: Daysec value range 0 ... 86399 1 ... 86400 +inline std::string create_Binary_Format_4(MLAT_timestamp timestamp, char signal_level, char dip_setting, char time_stamp_error_ticks) { + return char(0x1a) + "4" + timestamp.to_bin_string() + char(0xaa) + dip_setting + time_stamp_error_ticks; +} + +//相对时间戳(无 GPS):在没有连接 GPS 接收器的情况下,时间戳是一个 48 位无符号数字, +//计数 12 MHz 周期。时间戳大约每 271 天换行一次。 +struct TCXO_Clock { + unsigned long long times; + + explicit TCXO_Clock(const std::string& hex) { + times = std::bitset<48>(hex2bin(hex)).to_ullong(); + } + + [[nodiscard]] std::string to_string() const { + // 每个周期的时间是 1 / 12,000,000 秒 + double seconds = static_cast(times) / 12000000.0; + // 计算小时、分钟、秒 + int hours = static_cast(seconds / 3600); + seconds -= hours * 3600; + int minutes = static_cast(seconds / 60); + seconds -= minutes * 60; + int secs = static_cast(seconds); + // 格式化为时分秒字符串 + std::ostringstream oss; + oss.fill('0'); + oss << hours << ":"; + oss.width(2); + oss << minutes << ":"; + oss.width(2); + oss << secs; + return oss.str(); + } +}; + +/* +Periodic status message which is emitted every second +0x1A 0x48 0x01 0x18 SerNum Flags I.U. xTime Lat Lon Alt Sat HDOP +Fields: + SerNum 32-bit(1) Device Serial Number + Flags 16-bit(1) Status Flags* + I.U. 16-bit Internal Use + xTime 32-bit(1) Unix-Timestamp (Seconds since midnight 1970-01-01, UTC) + Lat 32-bit(1) Latitude as 32-bit BAM 2, thus 232 ≡ 360° + Lon 32-bit(1) Latitude as 32-bit BAM 2 + Alt 16-bit(1) Signed altitude meters + Sat 8-bit Number of satellites used in fix + HDOP 8-bit HDOP * 10, thus a value of 12 is HDOP 1.2 +1) MSB-first +2) https://en.wikipedia.org/wiki/Binary_scaling#Binary_angles + Status Flags: + 1xxx xxxx xxxx xxxx - GPS device detected -> Using absolute timestamp + x1xx xxxx xxxx xxxx - GPS valid (GGA, RMC present) + xx1x xxxx xxxx xxxx - GPS currently has a valid fix + xxx1 xxxx xxxx xxxx - High accuracy absolute time is available via PPS + xxxx xxxx 1xxx xxxx - TX-Queue overflow since start-up (normal if HW-handshaking is used) + xxxx xxxx x1xx xxxx - TX-Queue overflow during last second (probably due to HW-handshaking) + xxxx xxxx xx1x xxxx - Excessive NMEA found (other than GGA/RMC) +*/ +// +// All HULC messages (Type 0x48) have the following structure: +// 0x1A 0x48 ID LEN +// Fields: +// ID: HULC Message ID +// LEN: Number of bytes following +struct HULC_Message { + std::uint8_t head; + std::uint8_t id; + std::uint8_t len; // 指示下面的长度 +}; + + + + +struct HULC_Status_Message : HULC_Message { + std::uint32_t SerNum{}; + std::uint16_t Flags{}; // MSB大端字节序 + std::uint16_t I_U_{}; // Internal Use + std::uint32_t xTime{}; // Unix-Timestamp (Seconds since midnight 1970-01-01, UTC) + std::int32_t Lat{}; + std::int32_t Lon{}; + std::int16_t Alt{}; + std::uint8_t Sat{}; // Sat字段记录了定位过程中使用的卫星数量 + std::uint8_t HDOP{}; + + [[nodiscard]] double get_HDOP() const { + // HDOP(Horizontal Dilution of Precision) 描述的是 水平精度的衰减,即 GPS 系统的水平定位精度与卫星的几何布局有关。HDOP 数值越低,说明卫星的几何布局越好,定位精度越高。 + // 较低的 HDOP 值(例如 1-2)表示卫星信号较强,且卫星的分布较为理想,因此定位精度较高。 + // 较高的 HDOP 值(例如 5 或更高)表示卫星信号较弱,或卫星的分布较差,可能导致较差的定位精度。 + return double(HDOP) / 10.0; + } + + void set_latitude(double latitude) { + // 根据经纬度设置 Lat 值 + Lat = static_cast((latitude / 360.0) * pow(2, 32)); + } + + void set_longitude(double longitude) { + // 根据经纬度设置 Lon 值 + Lon = static_cast((longitude / 360.0) * pow(2, 32)); + } + + [[nodiscard]] double get_latitude() const { + return (static_cast(Lat) / pow(2, 32)) * 360.0; + } + + [[nodiscard]] double get_longitude() const { + return (static_cast(Lon) / pow(2, 32)) * 360.0; + } + + [[nodiscard]] std::string get_latitude_d_m_s() const{ + return decimalToDMS(get_latitude()); + } + + [[nodiscard]] std::string get_longitude_d_m_s() const{ + return decimalToDMS(get_longitude()); + } + + [[nodiscard]] std::string get_timestamp_string() const{ + return convert_timestamp_to_string(xTime); + } + + static std::string convert_timestamp_to_string(std::uint32_t time32) { + std::time_t time = time32; + std::stringstream ss; + ss << std::put_time(std::gmtime(&time), "%Y-%m-%d %H:%M:%S"); // 使用 std::put_time 格式化日期 + return ss.str( + + ); + // 返回格式化后的字符串 + // std::time_t time = time32; + // std::stringstream ss; + // // 将时间戳转换为本地时间 + // ss << std::put_time(std::localtime(&time), "%Y-%m-%d %H:%M:%S"); // 使用 std::localtime 格式化日期 + // return ss.str(); // 返回格式化后的字符串 + // // Unix Timestamp + // std::time_t timestamp = xTime; + // + // std::tm* ptm = std::gmtime(×tamp); + // + // return std::asctime(ptm); + } + + + // 转化经纬度变成 度 分 秒 + static std::string decimalToDMS(double decimalDegree) { + int degrees = static_cast(decimalDegree); + double minutesDouble = (decimalDegree - degrees) * 60; + int minutes = static_cast(minutesDouble); + int seconds = static_cast((minutesDouble - minutes) * 60.0); + return "(" + std::to_string(degrees) + "°" + std::to_string(minutes) + "'" + std::to_string(seconds) + "\")"; + } + /* + Status Flags: + 1xxx xxxx xxxx xxxx - GPS device detected -> Using absolute timestamp + x1xx xxxx xxxx xxxx - GPS valid (GGA, RMC present) + xx1x xxxx xxxx xxxx - GPS currently has a valid fix + xxx1 xxxx xxxx xxxx - High accuracy absolute time is available via PPS + xxxx xxxx 1xxx xxxx - TX-Queue overflow since start-up (normal if HW-handshaking is used) + xxxx xxxx x1xx xxxx - TX-Queue overflow during last second (probably due to HW-handshaking) + xxxx xxxx xx1x xxxx - Excessive NMEA found (other than GGA/RMC) + */ + [[nodiscard]] bool GPS_device_detected() const { + return Flags & (1 << 15); // 检查第 15 位,GPS 设备是否检测到 + } + + [[nodiscard]] bool GPS_valid() const { + return Flags & (1 << 14); // 检查第 14 位,GPS 数据是否有效 + } + + [[nodiscard]] bool GPS_has_valid_fix() const { + return Flags & (1 << 13); // 检查第 13 位,GPS 是否有有效定位 + } + + [[nodiscard]] bool GPS_high_accuracy_time() const { + return Flags & (1 << 12); // 检查第 12 位,是否通过 PPS 提供高精度绝对时间 + } + + [[nodiscard]] bool TX_queue_overflow_since_startup() const { + return Flags & (1 << 7); // 检查第 7 位,自启动以来是否发生 TX 队列溢出 + } + + [[nodiscard]] bool TX_queue_overflow_last_second() const { + return Flags & (1 << 6); // 检查第 6 位,过去一秒内是否发生 TX 队列溢出 + } + + [[nodiscard]] bool excessive_NMEA_found() const { + return Flags & (1 << 5); // 检查第 5 位,是否发现过多的 NMEA 数据(非 GGA/RMC) + } + + [[nodiscard]] Json toJson() const { + Json ret = Json::object(); + ret.append({"序列号", SerNum}); + ret.append({"状态标志", Flags}); + ret.append({"内部使用", I_U_}); + ret.append({"时间戳", get_timestamp_string()}); + ret.append({"纬度", std::to_string(get_latitude()) + " " + get_latitude_d_m_s()}); + ret.append({"经度", std::to_string(get_longitude()) + " " + get_longitude_d_m_s()}); + ret.append({"高度", Alt}); + ret.append({"卫星数量", Sat}); + ret.append({"HDOP", get_HDOP()}); + ret.append({"GPS设备检测到", GPS_device_detected()}); + ret.append({"GPS有效", GPS_valid()}); + ret.append({"GPS有效定位", GPS_has_valid_fix()}); + ret.append({"GPS高精度时间", GPS_high_accuracy_time()}); + ret.append({"启动以来TX队列溢出", TX_queue_overflow_since_startup()}); + ret.append({"过去一秒TX队列溢出", TX_queue_overflow_last_second()}); + ret.append({"发现过多NMEA数据", excessive_NMEA_found()}); + return ret; + } + + + static double decodeLatitudeFromBAM(const std::string& bigdian4) { + std::uint32_t value; + yC::big_endian_2_platform(bigdian4, (char*)&value); + // BAM 格式解码公式 + // return (static_cast(value) / pow(2, 32)) * 360.0; + return (static_cast(value) / pow(2, 32)) * 360.0; + } + std::string toBinary() { + std::string binary = {0x1a, 0x48, 0x01, 0x18}; + binary.append(yC::platform_2_big_endian(&SerNum, 4)); + binary.append(yC::platform_2_big_endian(&Flags, 2)); + binary.append(std::string((char*)&I_U_, 2)); // 内部使用没说什么序 默认大端序 + binary.append(yC::platform_2_big_endian(&xTime, 4)); + binary.append(yC::platform_2_big_endian(&Lat, 4)); + binary.append(yC::platform_2_big_endian(&Lon, 4)); + binary.append(yC::platform_2_big_endian(&Alt, 2)); + // 没说什么序 一字节 大端小端 等同 + binary.append({(char)Sat}); + binary.append({(char)HDOP}); + return binary; + } +}; + + + +static void hulc_big_endian_set(const std::string& msg, void* field, int start, int len) { + auto str = msg.substr(start, len); + yC::big_endian_2_platform(str, (char*)field); +} + +static void hulc_set2(const std::string& msg, void* field, int start, int len) { + auto it = msg.substr(start, len); + std::memcpy(field, it.data(), len); +} +// msg 是文本二进制字符串 转义后的 1a34 +static HULC_Status_Message create_HULC_Status_Message(const std::string& msg) { + HULC_Status_Message ret{}; + hulc_big_endian_set(msg, &ret.SerNum, 4, 4); + hulc_big_endian_set(msg, &ret.Flags, 8, 2); + hulc_set2(msg, &ret.I_U_, 10, 2); + hulc_big_endian_set(msg, &ret.xTime, 12, 4); + hulc_big_endian_set(msg, &ret.Lat, 16, 4); + hulc_big_endian_set(msg, &ret.Lon, 20, 4); + hulc_big_endian_set(msg, &ret.Alt, 24, 2); + hulc_set2(msg, &ret.Sat, 26, 1); + hulc_set2(msg, &ret.HDOP, 27, 1); + return ret; +} + + +struct HULC_Reply_to_command : HULC_Message { + std::uint8_t CMD; + std::uint8_t POO_14; +}; + +// 0x1A 0x48 0x01 0x18 SerNum Flags I.U. xTime Lat Lon Alt Sat HDOP +inline std::uint8_t get_id(const std::string& msg) { + return msg[2]; +} + +inline std::uint8_t get_len(const std::string& msg) { + return msg[3]; +} + +// Type Payload Size Description +// 0x31 4 bytes Mode-A/C raw data +// 0x32 7 bytes Mode-S Short Squitter raw data +// 0x33 14 bytes Mode-S Extended Squitter raw data +// 0x48 variable HULC Message, see below for details +// HULC Protocol uses the byte 0x1A as start-of-packet (SOP) marker. In order to avoid misinterpretation +// of normal data bytes with value 0x1A as SOP, each occurrence of data byte 0x1A is doubled in the +// data stream during transmission ('escaping'). It is thus necessary during reception to detect every +// 0x1A not followed by another 0x1A as an SOP marker and to reduce every occurrence of a double +// 0x1A to a single 0x1A data byte ('un-escaping'). +// Example of a 4-byte long packet including SOP marker and 0x1A data bytes: +// Before Escaping: 1A 32 27 1A E8 57 F0 1A 6C +// During Transmission: 1A 32 27 1A 1A E8 57 F0 1A 1A 6C +// After Un-Escaping: 1A 32 27 1A E8 57 F0 1A 6C +void Binary_Format_handle_buffer(std::string& buffer, const std::string& data, const std::function& callback); +/* Command Message (Host ==> Device) +The command-message has a simple ASCII based structure. Each message starts with a ‘#’ (0x23) and +ends with ‘’ (0x0D, 0x0A). In-between are one to 16 bytes in 2-digit hexadecimal representation +using upper-case letters, separated by ‘-’ (0x2D). +For example: + ‘#00’ or hexadecimal 0x23 0x30 0x30 0x0D 0x0A + ‘#43-02’ or hexadecimal 0x23 0x34 0x33 0x2D 0x30 0x32 0x0D 0x0A + The first byte is mandatory and holds the command while the remaining bytes are parameters. + Available commands depend on the selected protocol and are discussed in the respective protocol + section. +*/ + +std::string mode_s_msg_packet_to_server_packet(std::uint32_t id, std::string packet); + + + +// 1a34 radarcape 状态帧消息 +// https://wiki.jetvision.de/wiki/Radarcape:Version_History#Status_Frame_0x34_contents_were_extended_with_GPS_and_UTC_information +// 状态帧0x34内容已扩展为 GPS 和 UTC 信息 +// 当选择 GPS 时间戳时,状态帧由 1PPS 脉冲触发,在传统 12MHz 时间戳的情况下随机触发。 +// 状态帧包含有效的时间戳 +// 信号电平值为零/保留 + + +#define SETGET(name, pos) void set_##name(bool value) { set(pos, value); } \ +bool get_##name() { return get(pos); } + +#define SETGET2(Type, name, pos) void set_##name(Type value) { set(pos, (uint8_t)value); } \ +Type get_##name() { return (Type)get(pos); } + +struct BYTE_Settings { +protected: + uint8_t settings{}; // 8 位的字段,存储所有设置 + void set(uint8_t pos, bool value) { + if (value) { + // 设置指定位置的位为 1 + settings |= (1 << pos); + } else { + // 设置指定位置的位为 0 + settings &= ~(1 << pos); + } + } + [[nodiscard]] bool get(uint8_t pos) const { + // 获取指定位置的位值 + return (settings >> pos) & 0x01; + } +}; +struct FPGA_Setting : BYTE_Settings { + enum class Data_Output_Mode { AVR_hexdump, Binary }; + enum class Raw_Data_Frame_Type { No_Pre_Filtering, DF11_17_18_only }; + enum class Timestamp_Mode { Legacy_12MHz, GPS }; + SETGET2(Data_Output_Mode, data_output_mode, 0) + SETGET2(Raw_Data_Frame_Type, raw_data_frame_type, 1) + SETGET(timestamps_within_AVR_format, 2) + SETGET2(Timestamp_Mode, timestamp_mode, 4) + SETGET(serial_flow_control, 5) + SETGET(FEC, 6) // 1位转发错误校正 + SETGET(mode_ac_decoding , 7) + Json toJson() { + Json ret = Json::object(); + ret.append({"Data_Output_Mode", to_string(get_data_output_mode())}); + ret.append({"Raw_Data_Frame_Type", to_string(get_raw_data_frame_type())}); + ret.append({"timestamps_within_AVR_format", get_timestamps_within_AVR_format()}); + ret.append({"timestamps_mode", to_string(get_timestamp_mode())}); + ret.append({"serial_flow_control", get_serial_flow_control()}); + ret.append({"1位转发错误校正", get_FEC()}); + ret.append({"mode_ac_decoding", get_mode_ac_decoding()}); + return ret; + } + +}; + +struct GPS_Setting : BYTE_Settings { + enum class Time_Value_Base { UTC, GPS }; + enum class Daysec_Range { R_0_86399, R_1_86400 }; + SETGET(antenna_status, 0) // 位 0: 天线状态 + SETGET(tracking_at_least_1_satellite, 1) // 位 1: 至少跟踪 1 颗卫星 + SETGET(tracking_at_least_3_satellites, 2) // 位 2: 至少跟踪 3 颗卫星 + SETGET2(Time_Value_Base, time_value_base, 3) // 位 3: 时间值基数 (UTC/GPS) + SETGET(unused4, 4) // 位 4: 保留 + SETGET(unused5, 5) // 位 5: 保留 + SETGET(unused6, 6) // 位 6: 保留 + SETGET2(Daysec_Range, daysec_range, 7) // 位 7: Daysec 值范围 + Json toJson() { + Json ret = Json::object(); // 创建 JSON 对象 + ret.append({"antenna_status", get_antenna_status()}); + ret.append({"至少跟踪 1 颗卫星", get_tracking_at_least_1_satellite()}); + ret.append({"至少跟踪 3 颗卫星", get_tracking_at_least_3_satellites()}); + ret.append({"timestamps_mode", to_string(get_time_value_base())}); + ret.append({"daysec_range", to_string(get_daysec_range())}); + return ret; + } +}; + +struct Radarcape_STATUS_Message { + FPGA_Setting fpga_settings; + std::uint8_t pps_nanosecond_offset{}; // 包含 1PPS 事件时纳秒计时器的偏移量,单位为 15.625ns。正常值范围为 -3 ... +3。 + GPS_Setting gps_settings; + void set_pps_nanosecond(double value) { + if (value < 0.0 || value > 4000) { + std::cerr << "Invalid value. Must be in range [0.0, 4000.0]." << std::endl; + return; + } + pps_nanosecond_offset = static_cast((value)/15.625); + } + [[nodiscard]] double get_pps_nanosecond() const { + return (double)pps_nanosecond_offset * 15.625; + } + std::string toBinary() { + std::string binary = {0x1a, 0x34}; + binary.append(reinterpret_cast(&fpga_settings), 1); + binary.append(reinterpret_cast(&pps_nanosecond_offset), 1); + binary.append(reinterpret_cast(&gps_settings), 1); + return binary; + } + + Json toJson() { + Json ret = Json::object(); + ret.append({"pps_nanosecond_offset", get_pps_nanosecond()}); + ret.append({"fpga_settings", fpga_settings.toJson()}); + ret.append({"gps_settings", gps_settings.toJson()}); + return ret; + } + +}; + +// 消息5字节 +// +static Radarcape_STATUS_Message create_Radarcape_STATUS_Message(const std::string& msg_5) { + std::string msg = yC::big_endian_2_platform(msg_5.substr(2)); + Radarcape_STATUS_Message ret{}; + std::memcpy(&ret, (void*)(msg.data()), 3); + return ret; +} + + + +#undef SETGET +#undef SETGET2 + +#endif diff --git a/module/dll_source_lzy/114/out/lib/hulc/Json.cpp b/module/dll_source_lzy/114/out/lib/hulc/Json.cpp new file mode 100644 index 0000000..8949c43 --- /dev/null +++ b/module/dll_source_lzy/114/out/lib/hulc/Json.cpp @@ -0,0 +1,420 @@ +#include +#include +#include "Json.h" +#include +#include +std::function Json::handle_error = [](const char* function_name, const std::string& reason, const char* file, int line) { + std::ostringstream oss; + oss << "Json::" << function_name << " 原因:" << reason << std::endl; + oss << "位置:" << file << ":" << line << std::endl; + //throw std::runtime_error(oss.str().c_str()); + std::cout << oss.str(); + exit(-1); +}; + +#define HANDLE_ERROR(reason) Json::handle_error(__func__, reason, __FILE__, __LINE__); +void skip_whitespace(std::string& s, size_t& i); +std::string parse_string(std::string& s, size_t& i); +std::string parse_number(std::string& s, size_t& i); +std::optional parse_object(std::string& s, size_t& i); +std::optional parse_array(std::string& s, size_t& i); + +std::ostream& operator<<(std::ostream& os, const Json& obj) { + os << const_cast(obj).to_json_string(); + return os; +} + +Json::operator std::string() const { + return const_cast(this)->to_json_string(); +} + +std::string Json::get_string(const std::string& key) const { + const Json* that = get(key); + if (!that) { + HANDLE_ERROR(key + " not found! " + to_json_string()) + return ""; + } + return that->val; +} + +bool Json::bool_val() const { + if (val != "true" && val != "false") { + HANDLE_ERROR("Invalid bool argument: " + val) + } + return (val == "true"); +} + +const std::string& Json::get_inside_string(const std::string& key) const { + const Json* that = get(key); + if (!that) { + HANDLE_ERROR(key + " not found!") + return that->val; + } + return that->val; +} + +Json::Json(std::string key, const char* val) : key(std::move(key)), val(std::string(val)), valueType(String) { +} + +Json::Json(std::string key, std::string val) : key(std::move(key)), val(std::move(val)), valueType(String) { +} + +Json::Json(std::string key, bool val) : key(std::move(key)), val(val ? "true" : "false"), valueType(Bool) { +} + +Json::Json(std::string key, const Json& children) : + key(std::move(key)), val(children.val), valueType(children.valueType), children(children.children) {} + + +void Json::append_list(const std::vector& arr) { +#ifdef _DEBUG + if(valueType != JsonType::Object && valueType != JsonType::Array){ + HANDLE_ERROR("append_list error! key:" + key + " not array or object " + to_json_string()) + } +#else + +#endif + for (const Json& j : arr) { + children.push_back(j); + } +} + +void Json::append(const Json& json) { +#ifdef _DEBUG + if (valueType != JsonType::Object && valueType != JsonType::Array) + { + HANDLE_ERROR("append_list error! key:" + key + " not array or object " + to_json_string()) + } +#else +#endif + children.push_back(json); +} +void Json::prepend(const Json& json) { +#ifdef _DEBUG + if (valueType != JsonType::Object && valueType != JsonType::Array) + { + HANDLE_ERROR("append_list error! key:" + key + " not array or object " + to_json_string()) + } +#else +#endif + children.insert(children.begin(), json); +} +Json::Json(const char* val) : val(std::string(val)), valueType(String) { +} + +Json::Json(std::string val) : val(std::move(val)), valueType(String) { +} + +Json::Json(const int& val) : val(std::to_string(val)), valueType(Number) { +} + +Json::Json(const double& val) : val(std::to_string(val)), valueType(Number) { +} + +Json::Json(const bool& val) : val(val ? "true" : "false"), valueType(Bool) { +} + +const Json* Json::get(const std::string& key) const { + for (const Json& child : children) { + if (child.key == key) { + return &child; + } + } + HANDLE_ERROR(key + " not found!" + to_json_string()) + return nullptr; +} + +Json Json::array(const std::vector& children) { + return array("", children); +} + +Json Json::object(const std::vector& children) { + return object("", children); +} + +Json Json::array(std::string key, const std::vector& children) { + Json ret; + ret.key = std::move(key); + ret.valueType = Array; + ret.children = children; + return ret; +} + +Json Json::object(std::string key, const std::vector& children) { + Json ret; + ret.key = std::move(key); + ret.valueType = Object; + ret.children = children; + return ret; +} + +std::string Json::get_indent(const int& indent, const std::string& indentStr) { + std::string ret; + for (int i = 0; i < indent; ++i) { + ret.append(indentStr); + } + return ret; +} + +void Json::append_value_string(std::string& ret, const int& indent, bool isEnd, const std::string& object_split, + const std::string& array_split, const std::string& indentStr, JsonType fatherType) const { + ret.append(get_indent(indent, indentStr)); + if (fatherType == Object) ret.append("\"" + key + "\"" + ": "); + const std::string split = fatherType == Array ? array_split : object_split; + if (valueType == String) { + ret.append("\"" + val + "\""); + goto end; + } + if (valueType == Null) { + ret.append("null"); + goto end; + } + if (valueType == Number || valueType == Bool) { + ret.append(val); + goto end; + } + if (valueType == Object) { + ret.append("{" + object_split); + size_t n = children.size(); + if (n) { + for (size_t i = 0; i < n - 1; ++i) { + children[i].append_value_string(ret, indent + 2, false, object_split, array_split, indentStr, Object); + } + children[n - 1].append_value_string(ret, indent + 2, true, object_split, array_split, indentStr, Object); + } + ret.append(get_indent(indent, indentStr) + "}"); + goto end; + } + if (valueType == Array) { + ret.append("[" + array_split); + size_t n = children.size(); + if (n) { + for (size_t i = 0; i < n - 1; ++i) { + children[i].append_value_string(ret, indent + 1, false, object_split, array_split, indentStr, Array); + } + children[n - 1].append_value_string(ret, indent + 1, true, object_split, array_split, indentStr, Array); + } + ret.append(get_indent(indent, indentStr) + "]"); + goto end; + } +end: if (!isEnd) ret.append(","); + ret.append(split); +} + + +void handleBlank(std::string& s) { + int n = static_cast(s.length()); + bool isInStr = false; + for (int i = n - 1; i >= 0; --i) { + const char& c = s[i]; + if (c == '\"') isInStr = !isInStr; + if (isInStr) continue; + if (c == '\n' || c == '\t' || c == ' ') { + s.erase(i, 1); + } + } +} + +std::string Json::to_json_string(const std::string& object_split, const std::string& array_split, + const std::string& indentStr, const int& indent) const { + if (valueType == Bool) return val; + if (valueType == String) return '\"' + val + '\"'; + if (valueType == Number) return val; + if (valueType == Null) { + if (children.size() != 0) { + HANDLE_ERROR( "null 带有children 转成了字符串 (" + key + "," + val + ")" + to_json_string()) + } + return "null"; + } + std::string ret; + //ret.append(split); + append_value_string(ret, indent, true, object_split, array_split, indentStr, Null); + return ret; +} + +Json::Json(std::nullptr_t) : valueType(Null), val("null") { +} + +Json::Json(std::string key, std::nullptr_t) : key(std::move(key)), valueType(Null), val("null") { +} + +Json::Json() = default; +// 解析的分割线---------------------------- + + +// 如果未找到非空白字符,将 i 更新为 std::string::npos +void skip_whitespace(std::string& s, size_t& i) { + i = s.find_first_not_of(" \t\n\r\f\v", i); +} + +// 传入的 i 是 "所在的index +std::string parse_string(std::string& s, size_t& i) { + i++; //skip '"' + if (s[i] == '"') { + i++; + return ""; + } + std::string ret; + while (true) { + if (s[i] == '"' && s[i - 1] != '\\') { + break; + } + ret += s[i]; + i++; + } + i++; + return ret; +} + +std::string parse_number(std::string& s, size_t& i) { + std::string num; + while (isdigit(s[i])) { + num += s[i++]; + } + if (s[i] == '.') { + i++; + num += '.'; + while (isdigit(s[i])) { + num += s[i++]; + } + } + return num; +} + + +std::optional parse_json_EX(std::string& s, size_t& i); +std::optional parse_json(const std::string& s) { + auto& t = const_cast(s); + size_t i = 0; + return parse_json_EX(t, i); +} + +std::optional parse_json_EX(std::string& s, size_t& i) { + skip_whitespace(s, i); + switch (s[i]) { + case 'n': i += 4; + return nullptr; + case 't': i += 4; + return true; + case 'f': i += 5; + return false; + case '{': return parse_object(s, i); + case '[': return parse_array(s, i); + case '"': return parse_string(s, i); + case '-': { + i++; //skip - + Json ret(nullptr); + ret.valueType = Json::Number; + ret.val = '-' + parse_number(s, i); + return ret; + } + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': { + Json ret(nullptr); + ret.valueType = Json::Number; + ret.val = parse_number(s, i); + return ret; + } + default: { + HANDLE_ERROR("json 解析错误! s:【" + s + "】\n") + return std::nullopt; + } + } +} + +std::optional parse_object(std::string& s, size_t& i) { + i++; // skip '{' + skip_whitespace(s, i); + Json ret = Json::object(); + if (s[i] == '}') { + i++; + return ret; + } + while (true) { + skip_whitespace(s, i); + std::string key = parse_string(s, i); + skip_whitespace(s, i); + if (s[i] != ':') { + HANDLE_ERROR("格式错误!") + return std::nullopt; + } + i++; + skip_whitespace(s, i); + std::optional o_kv = parse_json_EX(s, i); + if(!o_kv.has_value()){ + return std::nullopt; + } + auto& kv = o_kv.value(); + skip_whitespace(s, i); + kv.key = key; + ret.children.push_back(kv); + if (s[i] == '}') { + i++; + break; + } + if (s[i] == ',') { + i++; + } + } + return ret; +} + +std::optional parse_array(std::string& s, size_t& i) { + i++; // skip '[' + skip_whitespace(s, i); + Json ret = Json::array(); + if (s[i] == ']') { + i++; + return ret; + } + while (true) { + skip_whitespace(s, i); + // parseJson(s, i) + std::optional o_kv = parse_json_EX(s, i); + if(!o_kv.has_value()){ + return std::nullopt; + } + auto& kv = o_kv.value(); + ret.children.push_back(kv); + skip_whitespace(s, i); + if (s[i] == ']') { + i++; + break; + } + if (s[i] == ',') { + i++; + } + } + return ret; +} +std::optional parse_json_file(std::string& fileName) { + static auto readFile = [](const std::string& path) -> std::string { + std::ifstream infile(path, std::ios::binary | std::ios::ate); + if (!infile.is_open()) { + HANDLE_ERROR("找不到文件路径!" + path) + return ""; + } + std::streampos fileSize = infile.tellg(); + infile.seekg(0, std::ios::beg); // 将文件指针移回文件开始位置 + std::string content(fileSize, '\0'); // 预分配足够的空间 + infile.read(&content[0], fileSize); // 读取文件到字符串中 + infile.close(); + return content; + }; + return parse_json(readFile(fileName)); +} + +std::optional parse_json_file(std::string&& fileName){ + return parse_json_file(fileName); +} + +#undef HANDLE_ERROR + diff --git a/module/dll_source_lzy/114/out/lib/hulc/Json.h b/module/dll_source_lzy/114/out/lib/hulc/Json.h new file mode 100644 index 0000000..01b44a7 --- /dev/null +++ b/module/dll_source_lzy/114/out/lib/hulc/Json.h @@ -0,0 +1,142 @@ +#ifndef Json_H +#define Json_H +#include +#include +#include +#include +#include +#include +#include +#define Json_GET(type, name) [[nodiscard]] type get_##name(const std::string &key) const { \ + const Json* that = get(key); \ + if (!that) { \ + std::cout << "get" #type " error json not found! key:" << key << " json: " << to_json_string() << std::endl; \ + return false; \ + } \ + return that-> name##_val(); \ +} + + +template +T_Number to_number(const std::string& val) { + if constexpr (std::is_integral::value) { + if constexpr (std::is_unsigned::value) { + return static_cast(std::stoull(val)); + } else if constexpr (std::is_signed::value) { + return static_cast(std::stoll(val)); + } + } else if constexpr (std::is_floating_point::value) { + return static_cast(std::stold(val)); + } + return T_Number(); +} + + +class Json { +public: + static std::function handle_error; + explicit operator std::string() const; + friend std::ostream& operator<<(std::ostream& os, const Json& obj); + [[nodiscard]] const Json* get(const std::string& key) const; + [[nodiscard]] std::string get_string(const std::string& key) const; + [[nodiscard]] const std::string& get_inside_string(const std::string& key) const; + //键值对 + Json(std::string key, const char* charArrayVal); + Json(std::string key, std::nullptr_t); + Json(std::string key, std::string stringVal); + Json(std::string key, bool boolVal); + Json(std::string key, const Json& body); + + [[nodiscard]] bool bool_val() const; + Json_GET(bool, bool) + template + T_Number get_number(const std::string& key) const { + const Json* that = get(key); + if (!that) { + std::cout << "json not found! key:" << key << " json: " << to_json_string() << std::endl; + return false; + } + return that->number_val(); + } + template + T_Number number_val() const { + return to_number(val); + } + // template + // Json(std::string key, const T_Number& intVal) : key(std::move(key)), + // val(std::to_string(intVal)), valueType(Number) { + // } + + template + Json(std::string key, const T_Number& intVal, typename std::enable_if< + !std::is_same::value && + !std::is_same>::value + >::type* = nullptr) + : key(std::move(key)), val(std::to_string(intVal)), valueType(Number) { + } + + + void append_list(const std::vector& arr); + void append(const Json& json); + void prepend(const Json& json); + static Json array(std::string key, const std::vector& arr); + static Json object(std::string key, const std::vector& children); + static Json array(const std::vector& arr = {}); + static Json object(const std::vector& children = {}); + //不加explicit 让他允许隐式类型转换 + Json(std::nullptr_t); //只能填写 nullptr + Json(const char* charArrayVal); + Json(std::string stringVal); + Json(const int& intVal); + Json(const double& doubleVal); + Json(const bool& boolVal); + + enum JsonType { + String, + Object, + Array, + Null, + Number, + Bool + } valueType = Null; + + std::string key, val; + std::vector children; + [[nodiscard]] std::string to_json_string(const std::string& object_split = "\n", const std::string& array_split = "\n", const std::string& indentStr = " ", const int& indent = 0) const; + Json(); +private: + static std::string get_indent(const int& indent, const std::string& indentStr); + void append_value_string(std::string& ret, const int& indent, bool isEnd, const std::string& object_split, + const std::string& array_split, const std::string& indentStr, JsonType fatherType) const; +}; + +std::optional parse_json(const std::string& s); +std::optional parse_json_file(std::string& fileName); +std::optional parse_json_file(std::string&& fileName); + + + +#undef Json_GET + +// #define J(FIELD) Json(#FIELD, this->FIELD) +// #define JEnum(FIELD) Json(#FIELD, to_string(this->FIELD)) + +#define Ret_J(FIELD) ret.append(Json(#FIELD, this->FIELD)); +#define Ret_JEnum(FIELD) ret.append(Json(#FIELD, to_string(this->FIELD))); + +#define ORet_J(FIELD) if(FIELD.has_value()) ret.append(Json(#FIELD, FIELD.value())); \ +else ret.append(Json(#FIELD, nullptr)); + +#define ORet_JEnum(FIELD) if(FIELD.has_value()) ret.append(Json(#FIELD, to_string(FIELD.value()))); \ +else ret.append(Json(#FIELD, nullptr)); + +#define ORet_J2(FIELD) if(FIELD.has_value()) ret.append(Json(#FIELD, FIELD.value())); + + +#define ORet_JEnum2(FIELD) if(FIELD.has_value()) ret.append(Json(#FIELD, to_string(FIELD.value()))); + + +#define J_Get_Number(FIELD) FIELD = that_json->get_number(#FIELD); + +#define JA_Get_Number(FIELD) FIELD.store(that_json->get_number(#FIELD)); +#endif diff --git a/module/dll_source_lzy/114/out/lib/hulc/base_format.h b/module/dll_source_lzy/114/out/lib/hulc/base_format.h new file mode 100644 index 0000000..6708353 --- /dev/null +++ b/module/dll_source_lzy/114/out/lib/hulc/base_format.h @@ -0,0 +1,74 @@ + +#ifndef BASE_FORMAT_H +#define BASE_FORMAT_H +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Bit.h" +#include "Json.h" +#include "magic_enum/export.h" + + +// 1纳秒是 10 -9次方秒 +struct MLAT_timestamp { + explicit MLAT_timestamp(); + explicit MLAT_timestamp(const std::string& memory_6); + MLAT_timestamp(std::uint32_t daysec, std::uint32_t nanosec); + std::uint32_t daysec{}; // 当天的秒数 高18位 + std::uint32_t nanosec{}; // 当天的纳秒数 低30位 + std::string to_bin_string() const; + std::string to_memory() const; + unsigned long hh{}; + unsigned long mm{}; + unsigned long ss{}; + std::string memory{}; + bool operator<(const MLAT_timestamp& other) const { + // 比较 daysec(高18位) + if (daysec != other.daysec) { + return daysec < other.daysec; + } + // 如果 daysec 相等,比较 nanosec(低30位) + return nanosec < other.nanosec; + } + + + [[nodiscard]] Json toJson() const { + Json ret = Json::object(); + ret.append({"秒", daysec}); + ret.append({"纳秒", nanosec}); + ret.append({"时间", std::to_string(hh) + ":" + std::to_string(mm) + ":" + std::to_string(ss)}); + return ret; + } + + [[nodiscard]] std::string to_string() const { + return + "{" + std::to_string(daysec) + "," + std::to_string(nanosec) + "}_" + + "[" + + std::to_string(hh) + "时:" + + std::to_string(mm) + "分:" + + std::to_string(ss) + "秒" + "]"; + } + + void parse_hhmmss(); +}; + +#endif diff --git a/module/dll_source_lzy/114/out/lib/hulc/magic_enum/export.h b/module/dll_source_lzy/114/out/lib/hulc/magic_enum/export.h new file mode 100644 index 0000000..a6c579c --- /dev/null +++ b/module/dll_source_lzy/114/out/lib/hulc/magic_enum/export.h @@ -0,0 +1,114 @@ +#ifndef yc_magic_enum_H +#define yc_magic_enum_H +#include "magic_enum/magic_enum.hpp" +#include +#include + +template +EnumType to_enum(const std::string& str) { + auto opt = magic_enum::enum_cast(str); + if (opt.has_value()) { + return opt.value(); // 返回枚举值 + } + std::cerr << std::string(magic_enum::enum_type_name()) +"字符串转换枚举值错误!str:" + str + "\n"; + exit(-1); +} + +template +std::optional to_enum2(const std::string& str) { + auto opt = magic_enum::enum_cast(str); + if (opt.has_value()) { + return opt.value(); // 返回枚举值 + } + return std::nullopt; +} + +template +std::string to_string(EnumType type) { + return std::string(magic_enum::enum_name(type)); +} + +template +std::optional int_to_enum(int enum_value) { + // 静态断言,确保 EnumType 是枚举类型 + static_assert(std::is_enum_v, "EnumType must be an enum type"); + // 使用 magic_enum 获取所有的枚举值 + auto enum_values = magic_enum::enum_values(); + // 检查是否存在匹配的枚举值 + for (auto value : enum_values) { + if (static_cast(value) == enum_value) { + return value; // 返回匹配的枚举值 + } + } + // 如果没有匹配的枚举值,返回 std::nullopt + return std::nullopt; +} + +template +std::optional enum_int_to_string(int enum_value) { + auto tmp = int_to_enum(enum_value); + if (!tmp.has_value()) return std::nullopt; + return to_string(tmp.value()); +} + +template +std::vector split_flags(Enum flags) +{ + static_assert(std::is_enum_v, "Template parameter must be an enum type"); + std::vector setFlags; + for (auto flag : magic_enum::enum_values()) + { + if ((flags & flag) == flag) + { + setFlags.push_back(flag); + } + } + return setFlags; +} + + +inline std::string to_string(const char* val) { + return std::string(val); +} + +template <> +inline std::string to_string(std::string val) { + return val; +} +template <> +inline std::string to_string(bool val) { + return val ? "true" : "false"; +} +template <> +inline std::string to_string(void* val) { + std::ostringstream oss; + oss << "0x" << std::hex << std::showbase << reinterpret_cast(val); + return oss.str(); +} + +#define IMPL_to_string_from_std(Type) template <> \ +inline std::string to_string(Type val) { \ + return std::to_string(val); \ +} \ + +IMPL_to_string_from_std(signed char) +IMPL_to_string_from_std(short) +IMPL_to_string_from_std(int) +IMPL_to_string_from_std(long) +IMPL_to_string_from_std(long long) +IMPL_to_string_from_std(unsigned char) +IMPL_to_string_from_std(unsigned short) +IMPL_to_string_from_std(unsigned int) +IMPL_to_string_from_std(unsigned long) +IMPL_to_string_from_std(unsigned long long) +IMPL_to_string_from_std(float) +IMPL_to_string_from_std(double) +IMPL_to_string_from_std(long double) +#undef IMPL_to_string_from_std + + + + + + +#endif \ No newline at end of file diff --git a/module/dll_source_lzy/114/out/lib/hulc/magic_enum/magic_enum/LICENSE b/module/dll_source_lzy/114/out/lib/hulc/magic_enum/magic_enum/LICENSE new file mode 100644 index 0000000..20acf2f --- /dev/null +++ b/module/dll_source_lzy/114/out/lib/hulc/magic_enum/magic_enum/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 - 2024 Daniil Goncharov + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/module/dll_source_lzy/114/out/lib/hulc/magic_enum/magic_enum/magic_enum.hpp b/module/dll_source_lzy/114/out/lib/hulc/magic_enum/magic_enum/magic_enum.hpp new file mode 100644 index 0000000..158207e --- /dev/null +++ b/module/dll_source_lzy/114/out/lib/hulc/magic_enum/magic_enum/magic_enum.hpp @@ -0,0 +1,1508 @@ +// __ __ _ ______ _____ +// | \/ | (_) | ____| / ____|_ _ +// | \ / | __ _ __ _ _ ___ | |__ _ __ _ _ _ __ ___ | | _| |_ _| |_ +// | |\/| |/ _` |/ _` | |/ __| | __| | '_ \| | | | '_ ` _ \ | | |_ _|_ _| +// | | | | (_| | (_| | | (__ | |____| | | | |_| | | | | | | | |____|_| |_| +// |_| |_|\__,_|\__, |_|\___| |______|_| |_|\__,_|_| |_| |_| \_____| +// __/ | https://github.com/Neargye/magic_enum +// |___/ version 0.9.7 +// +// Licensed under the MIT License . +// SPDX-License-Identifier: MIT +// Copyright (c) 2019 - 2024 Daniil Goncharov . +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#ifndef NEARGYE_MAGIC_ENUM_HPP +#define NEARGYE_MAGIC_ENUM_HPP + +#define MAGIC_ENUM_VERSION_MAJOR 0 +#define MAGIC_ENUM_VERSION_MINOR 9 +#define MAGIC_ENUM_VERSION_PATCH 7 + +#ifndef MAGIC_ENUM_USE_STD_MODULE +#include +#include +#include +#include +#include +#include +#include +#endif + +#if defined(MAGIC_ENUM_CONFIG_FILE) +# include MAGIC_ENUM_CONFIG_FILE +#endif + +#ifndef MAGIC_ENUM_USE_STD_MODULE +#if !defined(MAGIC_ENUM_USING_ALIAS_OPTIONAL) +# include +#endif +#if !defined(MAGIC_ENUM_USING_ALIAS_STRING) +# include +#endif +#if !defined(MAGIC_ENUM_USING_ALIAS_STRING_VIEW) +# include +#endif +#endif + +#if defined(MAGIC_ENUM_NO_ASSERT) +# define MAGIC_ENUM_ASSERT(...) static_cast(0) +#elif !defined(MAGIC_ENUM_ASSERT) +# include +# define MAGIC_ENUM_ASSERT(...) assert((__VA_ARGS__)) +#endif + +#if defined(__clang__) +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Wunknown-warning-option" +# pragma clang diagnostic ignored "-Wenum-constexpr-conversion" +# pragma clang diagnostic ignored "-Wuseless-cast" // suppresses 'static_cast('\0')' for char_type = char (common on Linux). +#elif defined(__GNUC__) +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wmaybe-uninitialized" // May be used uninitialized 'return {};'. +# pragma GCC diagnostic ignored "-Wuseless-cast" // suppresses 'static_cast('\0')' for char_type = char (common on Linux). +#elif defined(_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 26495) // Variable 'static_str::chars_' is uninitialized. +# pragma warning(disable : 28020) // Arithmetic overflow: Using operator '-' on a 4 byte value and then casting the result to a 8 byte value. +# pragma warning(disable : 26451) // The expression '0<=_Param_(1)&&_Param_(1)<=1-1' is not true at this call. +# pragma warning(disable : 4514) // Unreferenced inline function has been removed. +#endif + +// Checks magic_enum compiler compatibility. +#if defined(__clang__) && __clang_major__ >= 5 || defined(__GNUC__) && __GNUC__ >= 9 || defined(_MSC_VER) && _MSC_VER >= 1910 || defined(__RESHARPER__) +# undef MAGIC_ENUM_SUPPORTED +# define MAGIC_ENUM_SUPPORTED 1 +#endif + +// Checks magic_enum compiler aliases compatibility. +#if defined(__clang__) && __clang_major__ >= 5 || defined(__GNUC__) && __GNUC__ >= 9 || defined(_MSC_VER) && _MSC_VER >= 1920 +# undef MAGIC_ENUM_SUPPORTED_ALIASES +# define MAGIC_ENUM_SUPPORTED_ALIASES 1 +#endif + +// Enum value must be greater or equals than MAGIC_ENUM_RANGE_MIN. By default MAGIC_ENUM_RANGE_MIN = -128. +// If need another min range for all enum types by default, redefine the macro MAGIC_ENUM_RANGE_MIN. +#if !defined(MAGIC_ENUM_RANGE_MIN) +# define MAGIC_ENUM_RANGE_MIN -128 +#endif + +// Enum value must be less or equals than MAGIC_ENUM_RANGE_MAX. By default MAGIC_ENUM_RANGE_MAX = 127. +// If need another max range for all enum types by default, redefine the macro MAGIC_ENUM_RANGE_MAX. +#if !defined(MAGIC_ENUM_RANGE_MAX) +# define MAGIC_ENUM_RANGE_MAX 127 +#endif + +// Improve ReSharper C++ intellisense performance with builtins, avoiding unnecessary template instantiations. +#if defined(__RESHARPER__) +# undef MAGIC_ENUM_GET_ENUM_NAME_BUILTIN +# undef MAGIC_ENUM_GET_TYPE_NAME_BUILTIN +# if __RESHARPER__ >= 20230100 +# define MAGIC_ENUM_GET_ENUM_NAME_BUILTIN(V) __rscpp_enumerator_name(V) +# define MAGIC_ENUM_GET_TYPE_NAME_BUILTIN(T) __rscpp_type_name() +# else +# define MAGIC_ENUM_GET_ENUM_NAME_BUILTIN(V) nullptr +# define MAGIC_ENUM_GET_TYPE_NAME_BUILTIN(T) nullptr +# endif +#endif + +namespace magic_enum { + +// If need another optional type, define the macro MAGIC_ENUM_USING_ALIAS_OPTIONAL. +#if defined(MAGIC_ENUM_USING_ALIAS_OPTIONAL) +MAGIC_ENUM_USING_ALIAS_OPTIONAL +#else +using std::optional; +#endif + +// If need another string_view type, define the macro MAGIC_ENUM_USING_ALIAS_STRING_VIEW. +#if defined(MAGIC_ENUM_USING_ALIAS_STRING_VIEW) +MAGIC_ENUM_USING_ALIAS_STRING_VIEW +#else +using std::string_view; +#endif + +// If need another string type, define the macro MAGIC_ENUM_USING_ALIAS_STRING. +#if defined(MAGIC_ENUM_USING_ALIAS_STRING) +MAGIC_ENUM_USING_ALIAS_STRING +#else +using std::string; +#endif + +using char_type = string_view::value_type; +static_assert(std::is_same_v, "magic_enum::customize requires same string_view::value_type and string::value_type"); +static_assert([] { + if constexpr (std::is_same_v) { + constexpr const char c[] = "abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789|"; + constexpr const wchar_t wc[] = L"abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789|"; + static_assert(std::size(c) == std::size(wc), "magic_enum::customize identifier characters are multichars in wchar_t."); + + for (std::size_t i = 0; i < std::size(c); ++i) { + if (c[i] != wc[i]) { + return false; + } + } + } + return true; +} (), "magic_enum::customize wchar_t is not compatible with ASCII."); + +namespace customize { + +// Enum value must be in range [MAGIC_ENUM_RANGE_MIN, MAGIC_ENUM_RANGE_MAX]. By default MAGIC_ENUM_RANGE_MIN = -128, MAGIC_ENUM_RANGE_MAX = 127. +// If need another range for all enum types by default, redefine the macro MAGIC_ENUM_RANGE_MIN and MAGIC_ENUM_RANGE_MAX. +// If need another range for specific enum type, add specialization enum_range for necessary enum type. +template +struct enum_range { + static constexpr int min = MAGIC_ENUM_RANGE_MIN; + static constexpr int max = MAGIC_ENUM_RANGE_MAX; +}; + +static_assert(MAGIC_ENUM_RANGE_MAX > MAGIC_ENUM_RANGE_MIN, "MAGIC_ENUM_RANGE_MAX must be greater than MAGIC_ENUM_RANGE_MIN."); + +namespace detail { + +enum class customize_tag { + default_tag, + invalid_tag, + custom_tag +}; + +} // namespace magic_enum::customize::detail + +class customize_t : public std::pair { + public: + constexpr customize_t(string_view srt) : std::pair{detail::customize_tag::custom_tag, srt} {} + constexpr customize_t(const char_type* srt) : customize_t{string_view{srt}} {} + constexpr customize_t(detail::customize_tag tag) : std::pair{tag, string_view{}} { + MAGIC_ENUM_ASSERT(tag != detail::customize_tag::custom_tag); + } +}; + +// Default customize. +inline constexpr auto default_tag = customize_t{detail::customize_tag::default_tag}; +// Invalid customize. +inline constexpr auto invalid_tag = customize_t{detail::customize_tag::invalid_tag}; + +// If need custom names for enum, add specialization enum_name for necessary enum type. +template +constexpr customize_t enum_name(E) noexcept { + return default_tag; +} + +// If need custom type name for enum, add specialization enum_type_name for necessary enum type. +template +constexpr customize_t enum_type_name() noexcept { + return default_tag; +} + +} // namespace magic_enum::customize + +namespace detail { + +template +struct supported +#if defined(MAGIC_ENUM_SUPPORTED) && MAGIC_ENUM_SUPPORTED || defined(MAGIC_ENUM_NO_CHECK_SUPPORT) + : std::true_type {}; +#else + : std::false_type {}; +#endif + +template , std::enable_if_t, int> = 0> +using enum_constant = std::integral_constant; + +template +inline constexpr bool always_false_v = false; + +template +struct has_is_flags : std::false_type {}; + +template +struct has_is_flags::is_flags)>> : std::bool_constant::is_flags)>>> {}; + +template +struct range_min : std::integral_constant {}; + +template +struct range_min::min)>> : std::integral_constant::min), customize::enum_range::min> {}; + +template +struct range_max : std::integral_constant {}; + +template +struct range_max::max)>> : std::integral_constant::max), customize::enum_range::max> {}; + +struct str_view { + const char* str_ = nullptr; + std::size_t size_ = 0; +}; + +template +class static_str { + public: + constexpr explicit static_str(str_view str) noexcept : static_str{str.str_, std::make_integer_sequence{}} { + MAGIC_ENUM_ASSERT(str.size_ == N); + } + + constexpr explicit static_str(string_view str) noexcept : static_str{str.data(), std::make_integer_sequence{}} { + MAGIC_ENUM_ASSERT(str.size() == N); + } + + constexpr const char_type* data() const noexcept { return chars_; } + + constexpr std::uint16_t size() const noexcept { return N; } + + constexpr operator string_view() const noexcept { return {data(), size()}; } + + private: + template + constexpr static_str(const char* str, std::integer_sequence) noexcept : chars_{static_cast(str[I])..., static_cast('\0')} {} + + template + constexpr static_str(string_view str, std::integer_sequence) noexcept : chars_{str[I]..., static_cast('\0')} {} + + char_type chars_[static_cast(N) + 1]; +}; + +template <> +class static_str<0> { + public: + constexpr explicit static_str() = default; + + constexpr explicit static_str(str_view) noexcept {} + + constexpr explicit static_str(string_view) noexcept {} + + constexpr const char_type* data() const noexcept { return nullptr; } + + constexpr std::uint16_t size() const noexcept { return 0; } + + constexpr operator string_view() const noexcept { return {}; } +}; + +template > +class case_insensitive { + static constexpr char_type to_lower(char_type c) noexcept { + return (c >= static_cast('A') && c <= static_cast('Z')) ? static_cast(c + (static_cast('a') - static_cast('A'))) : c; + } + + public: + template + constexpr auto operator()(L lhs, R rhs) const noexcept -> std::enable_if_t, char_type> && std::is_same_v, char_type>, bool> { + return Op{}(to_lower(lhs), to_lower(rhs)); + } +}; + +constexpr std::size_t find(string_view str, char_type c) noexcept { +#if defined(__clang__) && __clang_major__ < 9 && defined(__GLIBCXX__) || defined(_MSC_VER) && _MSC_VER < 1920 && !defined(__clang__) +// https://stackoverflow.com/questions/56484834/constexpr-stdstring-viewfind-last-of-doesnt-work-on-clang-8-with-libstdc +// https://developercommunity.visualstudio.com/content/problem/360432/vs20178-regression-c-failed-in-test.html + constexpr bool workaround = true; +#else + constexpr bool workaround = false; +#endif + + if constexpr (workaround) { + for (std::size_t i = 0; i < str.size(); ++i) { + if (str[i] == c) { + return i; + } + } + + return string_view::npos; + } else { + return str.find(c); + } +} + +template +constexpr bool is_default_predicate() noexcept { + return std::is_same_v, std::equal_to> || + std::is_same_v, std::equal_to<>>; +} + +template +constexpr bool is_nothrow_invocable() { + return is_default_predicate() || + std::is_nothrow_invocable_r_v; +} + +template +constexpr bool cmp_equal(string_view lhs, string_view rhs, [[maybe_unused]] BinaryPredicate&& p) noexcept(is_nothrow_invocable()) { +#if defined(_MSC_VER) && _MSC_VER < 1920 && !defined(__clang__) + // https://developercommunity.visualstudio.com/content/problem/360432/vs20178-regression-c-failed-in-test.html + // https://developercommunity.visualstudio.com/content/problem/232218/c-constexpr-string-view.html + constexpr bool workaround = true; +#else + constexpr bool workaround = false; +#endif + + if constexpr (!is_default_predicate() || workaround) { + if (lhs.size() != rhs.size()) { + return false; + } + + const auto size = lhs.size(); + for (std::size_t i = 0; i < size; ++i) { + if (!p(lhs[i], rhs[i])) { + return false; + } + } + + return true; + } else { + return lhs == rhs; + } +} + +template +constexpr bool cmp_less(L lhs, R rhs) noexcept { + static_assert(std::is_integral_v && std::is_integral_v, "magic_enum::detail::cmp_less requires integral type."); + + if constexpr (std::is_signed_v == std::is_signed_v) { + // If same signedness (both signed or both unsigned). + return lhs < rhs; + } else if constexpr (std::is_same_v) { // bool special case + return static_cast(lhs) < rhs; + } else if constexpr (std::is_same_v) { // bool special case + return lhs < static_cast(rhs); + } else if constexpr (std::is_signed_v) { + // If 'right' is negative, then result is 'false', otherwise cast & compare. + return rhs > 0 && lhs < static_cast>(rhs); + } else { + // If 'left' is negative, then result is 'true', otherwise cast & compare. + return lhs < 0 || static_cast>(lhs) < rhs; + } +} + +template +constexpr I log2(I value) noexcept { + static_assert(std::is_integral_v, "magic_enum::detail::log2 requires integral type."); + + if constexpr (std::is_same_v) { // bool special case + return MAGIC_ENUM_ASSERT(false), value; + } else { + auto ret = I{0}; + for (; value > I{1}; value >>= I{1}, ++ret) {} + + return ret; + } +} + +#if defined(__cpp_lib_array_constexpr) && __cpp_lib_array_constexpr >= 201603L +# define MAGIC_ENUM_ARRAY_CONSTEXPR 1 +#else +template +constexpr std::array, N> to_array(T (&a)[N], std::index_sequence) noexcept { + return {{a[I]...}}; +} +#endif + +template +inline constexpr bool is_enum_v = std::is_enum_v && std::is_same_v>; + +template +constexpr auto n() noexcept { + static_assert(is_enum_v, "magic_enum::detail::n requires enum type."); + + if constexpr (supported::value) { +#if defined(MAGIC_ENUM_GET_TYPE_NAME_BUILTIN) + constexpr auto name_ptr = MAGIC_ENUM_GET_TYPE_NAME_BUILTIN(E); + constexpr auto name = name_ptr ? str_view{name_ptr, std::char_traits::length(name_ptr)} : str_view{}; +#elif defined(__clang__) + str_view name; + if constexpr (sizeof(__PRETTY_FUNCTION__) == sizeof(__FUNCTION__)) { + static_assert(always_false_v, "magic_enum::detail::n requires __PRETTY_FUNCTION__."); + return str_view{}; + } else { + name.size_ = sizeof(__PRETTY_FUNCTION__) - 36; + name.str_ = __PRETTY_FUNCTION__ + 34; + } +#elif defined(__GNUC__) + auto name = str_view{__PRETTY_FUNCTION__, sizeof(__PRETTY_FUNCTION__) - 1}; + if constexpr (sizeof(__PRETTY_FUNCTION__) == sizeof(__FUNCTION__)) { + static_assert(always_false_v, "magic_enum::detail::n requires __PRETTY_FUNCTION__."); + return str_view{}; + } else if (name.str_[name.size_ - 1] == ']') { + name.size_ -= 50; + name.str_ += 49; + } else { + name.size_ -= 40; + name.str_ += 37; + } +#elif defined(_MSC_VER) + // CLI/C++ workaround (see https://github.com/Neargye/magic_enum/issues/284). + str_view name; + name.str_ = __FUNCSIG__; + name.str_ += 40; + name.size_ += sizeof(__FUNCSIG__) - 57; +#else + auto name = str_view{}; +#endif + std::size_t p = 0; + for (std::size_t i = name.size_; i > 0; --i) { + if (name.str_[i] == ':') { + p = i + 1; + break; + } + } + if (p > 0) { + name.size_ -= p; + name.str_ += p; + } + return name; + } else { + return str_view{}; // Unsupported compiler or Invalid customize. + } +} + +template +constexpr auto type_name() noexcept { + [[maybe_unused]] constexpr auto custom = customize::enum_type_name(); + static_assert(std::is_same_v, customize::customize_t>, "magic_enum::customize requires customize_t type."); + if constexpr (custom.first == customize::detail::customize_tag::custom_tag) { + constexpr auto name = custom.second; + static_assert(!name.empty(), "magic_enum::customize requires not empty string."); + return static_str{name}; + } else if constexpr (custom.first == customize::detail::customize_tag::invalid_tag) { + return static_str<0>{}; + } else if constexpr (custom.first == customize::detail::customize_tag::default_tag) { + constexpr auto name = n(); + return static_str{name}; + } else { + static_assert(always_false_v, "magic_enum::customize invalid."); + } +} + +template +inline constexpr auto type_name_v = type_name(); + +template +constexpr auto n() noexcept { + static_assert(is_enum_v, "magic_enum::detail::n requires enum type."); + + if constexpr (supported::value) { +#if defined(MAGIC_ENUM_GET_ENUM_NAME_BUILTIN) + constexpr auto name_ptr = MAGIC_ENUM_GET_ENUM_NAME_BUILTIN(V); + auto name = name_ptr ? str_view{name_ptr, std::char_traits::length(name_ptr)} : str_view{}; +#elif defined(__clang__) + str_view name; + if constexpr (sizeof(__PRETTY_FUNCTION__) == sizeof(__FUNCTION__)) { + static_assert(always_false_v, "magic_enum::detail::n requires __PRETTY_FUNCTION__."); + return str_view{}; + } else { + name.size_ = sizeof(__PRETTY_FUNCTION__) - 36; + name.str_ = __PRETTY_FUNCTION__ + 34; + } + if (name.size_ > 22 && name.str_[0] == '(' && name.str_[1] == 'a' && name.str_[10] == ' ' && name.str_[22] == ':') { + name.size_ -= 23; + name.str_ += 23; + } + if (name.str_[0] == '(' || name.str_[0] == '-' || (name.str_[0] >= '0' && name.str_[0] <= '9')) { + name = str_view{}; + } +#elif defined(__GNUC__) + auto name = str_view{__PRETTY_FUNCTION__, sizeof(__PRETTY_FUNCTION__) - 1}; + if constexpr (sizeof(__PRETTY_FUNCTION__) == sizeof(__FUNCTION__)) { + static_assert(always_false_v, "magic_enum::detail::n requires __PRETTY_FUNCTION__."); + return str_view{}; + } else if (name.str_[name.size_ - 1] == ']') { + name.size_ -= 55; + name.str_ += 54; + } else { + name.size_ -= 40; + name.str_ += 37; + } + if (name.str_[0] == '(') { + name = str_view{}; + } +#elif defined(_MSC_VER) + str_view name; + if ((__FUNCSIG__[5] == '_' && __FUNCSIG__[35] != '(') || (__FUNCSIG__[5] == 'c' && __FUNCSIG__[41] != '(')) { + // CLI/C++ workaround (see https://github.com/Neargye/magic_enum/issues/284). + name.str_ = __FUNCSIG__; + name.str_ += 35; + name.size_ = sizeof(__FUNCSIG__) - 52; + } +#else + auto name = str_view{}; +#endif + std::size_t p = 0; + for (std::size_t i = name.size_; i > 0; --i) { + if (name.str_[i] == ':') { + p = i + 1; + break; + } + } + if (p > 0) { + name.size_ -= p; + name.str_ += p; + } + return name; + } else { + return str_view{}; // Unsupported compiler or Invalid customize. + } +} + +#if defined(_MSC_VER) && !defined(__clang__) && _MSC_VER < 1920 +# define MAGIC_ENUM_VS_2017_WORKAROUND 1 +#endif + +#if defined(MAGIC_ENUM_VS_2017_WORKAROUND) +template +constexpr auto n() noexcept { + static_assert(is_enum_v, "magic_enum::detail::n requires enum type."); + +# if defined(MAGIC_ENUM_GET_ENUM_NAME_BUILTIN) + constexpr auto name_ptr = MAGIC_ENUM_GET_ENUM_NAME_BUILTIN(V); + auto name = name_ptr ? str_view{name_ptr, std::char_traits::length(name_ptr)} : str_view{}; +# else + // CLI/C++ workaround (see https://github.com/Neargye/magic_enum/issues/284). + str_view name; + name.str_ = __FUNCSIG__; + name.size_ = sizeof(__FUNCSIG__) - 17; + std::size_t p = 0; + for (std::size_t i = name.size_; i > 0; --i) { + if (name.str_[i] == ',' || name.str_[i] == ':') { + p = i + 1; + break; + } + } + if (p > 0) { + name.size_ -= p; + name.str_ += p; + } + if (name.str_[0] == '(' || name.str_[0] == '-' || (name.str_[0] >= '0' && name.str_[0] <= '9')) { + name = str_view{}; + } + return name; +# endif +} +#endif + +template +constexpr auto enum_name() noexcept { + [[maybe_unused]] constexpr auto custom = customize::enum_name(V); + static_assert(std::is_same_v, customize::customize_t>, "magic_enum::customize requires customize_t type."); + if constexpr (custom.first == customize::detail::customize_tag::custom_tag) { + constexpr auto name = custom.second; + static_assert(!name.empty(), "magic_enum::customize requires not empty string."); + return static_str{name}; + } else if constexpr (custom.first == customize::detail::customize_tag::invalid_tag) { + return static_str<0>{}; + } else if constexpr (custom.first == customize::detail::customize_tag::default_tag) { +#if defined(MAGIC_ENUM_VS_2017_WORKAROUND) + constexpr auto name = n(); +#else + constexpr auto name = n(); +#endif + return static_str{name}; + } else { + static_assert(always_false_v, "magic_enum::customize invalid."); + } +} + +template +inline constexpr auto enum_name_v = enum_name(); + +template +constexpr bool is_valid() noexcept { +#if defined(__clang__) && __clang_major__ >= 16 + // https://reviews.llvm.org/D130058, https://reviews.llvm.org/D131307 + constexpr E v = __builtin_bit_cast(E, V); +#else + constexpr E v = static_cast(V); +#endif + [[maybe_unused]] constexpr auto custom = customize::enum_name(v); + static_assert(std::is_same_v, customize::customize_t>, "magic_enum::customize requires customize_t type."); + if constexpr (custom.first == customize::detail::customize_tag::custom_tag) { + constexpr auto name = custom.second; + static_assert(!name.empty(), "magic_enum::customize requires not empty string."); + return name.size() != 0; + } else if constexpr (custom.first == customize::detail::customize_tag::default_tag) { +#if defined(MAGIC_ENUM_VS_2017_WORKAROUND) + return n().size_ != 0; +#else + return n().size_ != 0; +#endif + } else { + return false; + } +} + +enum class enum_subtype { + common, + flags +}; + +template > +constexpr U ualue(std::size_t i) noexcept { + if constexpr (std::is_same_v) { // bool special case + static_assert(O == 0, "magic_enum::detail::ualue requires valid offset."); + + return static_cast(i); + } else if constexpr (S == enum_subtype::flags) { + return static_cast(U{1} << static_cast(static_cast(i) + O)); + } else { + return static_cast(static_cast(i) + O); + } +} + +template > +constexpr E value(std::size_t i) noexcept { + return static_cast(ualue(i)); +} + +template > +constexpr int reflected_min() noexcept { + if constexpr (S == enum_subtype::flags) { + return 0; + } else { + constexpr auto lhs = range_min::value; + constexpr auto rhs = (std::numeric_limits::min)(); + + if constexpr (cmp_less(rhs, lhs)) { + return lhs; + } else { + return rhs; + } + } +} + +template > +constexpr int reflected_max() noexcept { + if constexpr (S == enum_subtype::flags) { + return std::numeric_limits::digits - 1; + } else { + constexpr auto lhs = range_max::value; + constexpr auto rhs = (std::numeric_limits::max)(); + + if constexpr (cmp_less(lhs, rhs)) { + return lhs; + } else { + return rhs; + } + } +} + +#define MAGIC_ENUM_FOR_EACH_256(T) \ + T( 0)T( 1)T( 2)T( 3)T( 4)T( 5)T( 6)T( 7)T( 8)T( 9)T( 10)T( 11)T( 12)T( 13)T( 14)T( 15)T( 16)T( 17)T( 18)T( 19)T( 20)T( 21)T( 22)T( 23)T( 24)T( 25)T( 26)T( 27)T( 28)T( 29)T( 30)T( 31) \ + T( 32)T( 33)T( 34)T( 35)T( 36)T( 37)T( 38)T( 39)T( 40)T( 41)T( 42)T( 43)T( 44)T( 45)T( 46)T( 47)T( 48)T( 49)T( 50)T( 51)T( 52)T( 53)T( 54)T( 55)T( 56)T( 57)T( 58)T( 59)T( 60)T( 61)T( 62)T( 63) \ + T( 64)T( 65)T( 66)T( 67)T( 68)T( 69)T( 70)T( 71)T( 72)T( 73)T( 74)T( 75)T( 76)T( 77)T( 78)T( 79)T( 80)T( 81)T( 82)T( 83)T( 84)T( 85)T( 86)T( 87)T( 88)T( 89)T( 90)T( 91)T( 92)T( 93)T( 94)T( 95) \ + T( 96)T( 97)T( 98)T( 99)T(100)T(101)T(102)T(103)T(104)T(105)T(106)T(107)T(108)T(109)T(110)T(111)T(112)T(113)T(114)T(115)T(116)T(117)T(118)T(119)T(120)T(121)T(122)T(123)T(124)T(125)T(126)T(127) \ + T(128)T(129)T(130)T(131)T(132)T(133)T(134)T(135)T(136)T(137)T(138)T(139)T(140)T(141)T(142)T(143)T(144)T(145)T(146)T(147)T(148)T(149)T(150)T(151)T(152)T(153)T(154)T(155)T(156)T(157)T(158)T(159) \ + T(160)T(161)T(162)T(163)T(164)T(165)T(166)T(167)T(168)T(169)T(170)T(171)T(172)T(173)T(174)T(175)T(176)T(177)T(178)T(179)T(180)T(181)T(182)T(183)T(184)T(185)T(186)T(187)T(188)T(189)T(190)T(191) \ + T(192)T(193)T(194)T(195)T(196)T(197)T(198)T(199)T(200)T(201)T(202)T(203)T(204)T(205)T(206)T(207)T(208)T(209)T(210)T(211)T(212)T(213)T(214)T(215)T(216)T(217)T(218)T(219)T(220)T(221)T(222)T(223) \ + T(224)T(225)T(226)T(227)T(228)T(229)T(230)T(231)T(232)T(233)T(234)T(235)T(236)T(237)T(238)T(239)T(240)T(241)T(242)T(243)T(244)T(245)T(246)T(247)T(248)T(249)T(250)T(251)T(252)T(253)T(254)T(255) + +template +constexpr void valid_count(bool* valid, std::size_t& count) noexcept { +#define MAGIC_ENUM_V(O) \ + if constexpr ((I + O) < Size) { \ + if constexpr (is_valid(I + O)>()) { \ + valid[I + O] = true; \ + ++count; \ + } \ + } + + MAGIC_ENUM_FOR_EACH_256(MAGIC_ENUM_V) + + if constexpr ((I + 256) < Size) { + valid_count(valid, count); + } +#undef MAGIC_ENUM_V +} + +template +struct valid_count_t { + std::size_t count = 0; + bool valid[N] = {}; +}; + +template +constexpr auto valid_count() noexcept { + valid_count_t vc; + valid_count(vc.valid, vc.count); + return vc; +} + +template +constexpr auto values() noexcept { + constexpr auto vc = valid_count(); + + if constexpr (vc.count > 0) { +#if defined(MAGIC_ENUM_ARRAY_CONSTEXPR) + std::array values = {}; +#else + E values[vc.count] = {}; +#endif + for (std::size_t i = 0, v = 0; v < vc.count; ++i) { + if (vc.valid[i]) { + values[v++] = value(i); + } + } +#if defined(MAGIC_ENUM_ARRAY_CONSTEXPR) + return values; +#else + return to_array(values, std::make_index_sequence{}); +#endif + } else { + return std::array{}; + } +} + +template > +constexpr auto values() noexcept { + constexpr auto min = reflected_min(); + constexpr auto max = reflected_max(); + constexpr auto range_size = max - min + 1; + static_assert(range_size > 0, "magic_enum::enum_range requires valid size."); + + return values(); +} + +template > +constexpr enum_subtype subtype(std::true_type) noexcept { + if constexpr (std::is_same_v) { // bool special case + return enum_subtype::common; + } else if constexpr (has_is_flags::value) { + return customize::enum_range::is_flags ? enum_subtype::flags : enum_subtype::common; + } else { +#if defined(MAGIC_ENUM_AUTO_IS_FLAGS) + constexpr auto flags_values = values(); + constexpr auto default_values = values(); + if (flags_values.size() == 0 || default_values.size() > flags_values.size()) { + return enum_subtype::common; + } + for (std::size_t i = 0; i < default_values.size(); ++i) { + const auto v = static_cast(default_values[i]); + if (v != 0 && (v & (v - 1)) != 0) { + return enum_subtype::common; + } + } + return enum_subtype::flags; +#else + return enum_subtype::common; +#endif + } +} + +template +constexpr enum_subtype subtype(std::false_type) noexcept { + // For non-enum type return default common subtype. + return enum_subtype::common; +} + +template > +inline constexpr auto subtype_v = subtype(std::is_enum{}); + +template +inline constexpr auto values_v = values(); + +template > +using values_t = decltype((values_v)); + +template +inline constexpr auto count_v = values_v.size(); + +template > +inline constexpr auto min_v = (count_v > 0) ? static_cast(values_v.front()) : U{0}; + +template > +inline constexpr auto max_v = (count_v > 0) ? static_cast(values_v.back()) : U{0}; + +template +constexpr auto names(std::index_sequence) noexcept { + constexpr auto names = std::array{{enum_name_v[I]>...}}; + return names; +} + +template +inline constexpr auto names_v = names(std::make_index_sequence>{}); + +template > +using names_t = decltype((names_v)); + +template +constexpr auto entries(std::index_sequence) noexcept { + constexpr auto entries = std::array, sizeof...(I)>{{{values_v[I], enum_name_v[I]>}...}}; + return entries; +} + +template +inline constexpr auto entries_v = entries(std::make_index_sequence>{}); + +template > +using entries_t = decltype((entries_v)); + +template > +constexpr bool is_sparse() noexcept { + if constexpr (count_v == 0) { + return false; + } else if constexpr (std::is_same_v) { // bool special case + return false; + } else { + constexpr auto max = (S == enum_subtype::flags) ? log2(max_v) : max_v; + constexpr auto min = (S == enum_subtype::flags) ? log2(min_v) : min_v; + constexpr auto range_size = max - min + 1; + + return range_size != count_v; + } +} + +template > +inline constexpr bool is_sparse_v = is_sparse(); + +template +struct is_reflected +#if defined(MAGIC_ENUM_NO_CHECK_REFLECTED_ENUM) + : std::true_type {}; +#else + : std::bool_constant && (count_v != 0)> {}; +#endif + +template +inline constexpr bool is_reflected_v = is_reflected, S>{}; + +template +struct enable_if_enum {}; + +template +struct enable_if_enum { + using type = R; + static_assert(supported::value, "magic_enum unsupported compiler (https://github.com/Neargye/magic_enum#compiler-compatibility)."); +}; + +template , typename D = std::decay_t> +using enable_if_t = typename enable_if_enum && std::is_invocable_r_v, R>::type; + +template >, int> = 0> +using enum_concept = T; + +template > +struct is_scoped_enum : std::false_type {}; + +template +struct is_scoped_enum : std::bool_constant>> {}; + +template > +struct is_unscoped_enum : std::false_type {}; + +template +struct is_unscoped_enum : std::bool_constant>> {}; + +template >> +struct underlying_type {}; + +template +struct underlying_type : std::underlying_type> {}; + +#if defined(MAGIC_ENUM_ENABLE_HASH) || defined(MAGIC_ENUM_ENABLE_HASH_SWITCH) + +template +struct constexpr_hash_t; + +template +struct constexpr_hash_t>> { + constexpr auto operator()(Value value) const noexcept { + using U = typename underlying_type::type; + if constexpr (std::is_same_v) { // bool special case + return static_cast(value); + } else { + return static_cast(value); + } + } + using secondary_hash = constexpr_hash_t; +}; + +template +struct constexpr_hash_t>> { + static constexpr std::uint32_t crc_table[256] { + 0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x076dc419L, 0x706af48fL, 0xe963a535L, 0x9e6495a3L, + 0x0edb8832L, 0x79dcb8a4L, 0xe0d5e91eL, 0x97d2d988L, 0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L, 0x90bf1d91L, + 0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL, 0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L, + 0x136c9856L, 0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L, 0xfa0f3d63L, 0x8d080df5L, + 0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L, 0xa2677172L, 0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL, + 0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L, 0x32d86ce3L, 0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L, + 0x26d930acL, 0x51de003aL, 0xc8d75180L, 0xbfd06116L, 0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L, 0xb8bda50fL, + 0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L, 0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL, + 0x76dc4190L, 0x01db7106L, 0x98d220bcL, 0xefd5102aL, 0x71b18589L, 0x06b6b51fL, 0x9fbfe4a5L, 0xe8b8d433L, + 0x7807c9a2L, 0x0f00f934L, 0x9609a88eL, 0xe10e9818L, 0x7f6a0dbbL, 0x086d3d2dL, 0x91646c97L, 0xe6635c01L, + 0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL, 0x6c0695edL, 0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L, + 0x65b0d9c6L, 0x12b7e950L, 0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L, 0xfbd44c65L, + 0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L, 0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL, + 0x4369e96aL, 0x346ed9fcL, 0xad678846L, 0xda60b8d0L, 0x44042d73L, 0x33031de5L, 0xaa0a4c5fL, 0xdd0d7cc9L, + 0x5005713cL, 0x270241aaL, 0xbe0b1010L, 0xc90c2086L, 0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL, + 0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L, 0x59b33d17L, 0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL, + 0xedb88320L, 0x9abfb3b6L, 0x03b6e20cL, 0x74b1d29aL, 0xead54739L, 0x9dd277afL, 0x04db2615L, 0x73dc1683L, + 0xe3630b12L, 0x94643b84L, 0x0d6d6a3eL, 0x7a6a5aa8L, 0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L, 0x7d079eb1L, + 0xf00f9344L, 0x8708a3d2L, 0x1e01f268L, 0x6906c2feL, 0xf762575dL, 0x806567cbL, 0x196c3671L, 0x6e6b06e7L, + 0xfed41b76L, 0x89d32be0L, 0x10da7a5aL, 0x67dd4accL, 0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L, + 0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L, 0xd1bb67f1L, 0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL, + 0xd80d2bdaL, 0xaf0a1b4cL, 0x36034af6L, 0x41047a60L, 0xdf60efc3L, 0xa867df55L, 0x316e8eefL, 0x4669be79L, + 0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L, 0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL, + 0xc5ba3bbeL, 0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L, 0xc2d7ffa7L, 0xb5d0cf31L, 0x2cd99e8bL, 0x5bdeae1dL, + 0x9b64c2b0L, 0xec63f226L, 0x756aa39cL, 0x026d930aL, 0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x05005713L, + 0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0x0cb61b38L, 0x92d28e9bL, 0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L, + 0x86d3d2d4L, 0xf1d4e242L, 0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L, 0x18b74777L, + 0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL, 0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L, + 0xa00ae278L, 0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L, 0xa7672661L, 0xd06016f7L, 0x4969474dL, 0x3e6e77dbL, + 0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L, 0x37d83bf0L, 0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L, + 0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L, 0xbad03605L, 0xcdd70693L, 0x54de5729L, 0x23d967bfL, + 0xb3667a2eL, 0xc4614ab8L, 0x5d681b02L, 0x2a6f2b94L, 0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL, 0x2d02ef8dL + }; + constexpr std::uint32_t operator()(string_view value) const noexcept { + auto crc = static_cast(0xffffffffL); + for (const auto c : value) { + crc = (crc >> 8) ^ crc_table[(crc ^ static_cast(c)) & 0xff]; + } + return crc ^ 0xffffffffL; + } + + struct secondary_hash { + constexpr std::uint32_t operator()(string_view value) const noexcept { + auto acc = static_cast(2166136261ULL); + for (const auto c : value) { + acc = ((acc ^ static_cast(c)) * static_cast(16777619ULL)) & (std::numeric_limits::max)(); + } + return static_cast(acc); + } + }; +}; + +template +inline constexpr Hash hash_v{}; + +template +constexpr auto calculate_cases(std::size_t Page) noexcept { + constexpr std::array values = *GlobValues; + constexpr std::size_t size = values.size(); + + using switch_t = std::invoke_result_t; + static_assert(std::is_integral_v && !std::is_same_v); + const std::size_t values_to = (std::min)(static_cast(256), size - Page); + + std::array result{}; + auto fill = result.begin(); + { + auto first = values.begin() + static_cast(Page); + auto last = values.begin() + static_cast(Page + values_to); + while (first != last) { + *fill++ = hash_v(*first++); + } + } + + // dead cases, try to avoid case collisions + for (switch_t last_value = result[values_to - 1]; fill != result.end() && last_value != (std::numeric_limits::max)(); *fill++ = ++last_value) { + } + + { + auto it = result.begin(); + auto last_value = (std::numeric_limits::min)(); + for (; fill != result.end(); *fill++ = last_value++) { + while (last_value == *it) { + ++last_value, ++it; + } + } + } + + return result; +} + +template +constexpr R invoke_r(F&& f, Args&&... args) noexcept(std::is_nothrow_invocable_r_v) { + if constexpr (std::is_void_v) { + std::forward(f)(std::forward(args)...); + } else { + return static_cast(std::forward(f)(std::forward(args)...)); + } +} + +enum class case_call_t { + index, + value +}; + +template +inline constexpr auto default_result_type_lambda = []() noexcept(std::is_nothrow_default_constructible_v) { return T{}; }; + +template <> +inline constexpr auto default_result_type_lambda = []() noexcept {}; + +template +constexpr bool has_duplicate() noexcept { + using value_t = std::decay_t; + using hash_value_t = std::invoke_result_t; + std::arraysize()> hashes{}; + std::size_t size = 0; + for (auto elem : *Arr) { + hashes[size] = hash_v(elem); + for (auto i = size++; i > 0; --i) { + if (hashes[i] < hashes[i - 1]) { + auto tmp = hashes[i]; + hashes[i] = hashes[i - 1]; + hashes[i - 1] = tmp; + } else if (hashes[i] == hashes[i - 1]) { + return false; + } else { + break; + } + } + } + return true; +} + +#define MAGIC_ENUM_CASE(val) \ + case cases[val]: \ + if constexpr ((val) + Page < size) { \ + if (!pred(values[val + Page], searched)) { \ + break; \ + } \ + if constexpr (CallValue == case_call_t::index) { \ + if constexpr (std::is_invocable_r_v>) { \ + return detail::invoke_r(std::forward(lambda), std::integral_constant{}); \ + } else if constexpr (std::is_invocable_v>) { \ + MAGIC_ENUM_ASSERT(false && "magic_enum::detail::constexpr_switch wrong result type."); \ + } \ + } else if constexpr (CallValue == case_call_t::value) { \ + if constexpr (std::is_invocable_r_v>) { \ + return detail::invoke_r(std::forward(lambda), enum_constant{}); \ + } else if constexpr (std::is_invocable_r_v>) { \ + MAGIC_ENUM_ASSERT(false && "magic_enum::detail::constexpr_switch wrong result type."); \ + } \ + } \ + break; \ + } else [[fallthrough]]; + +template ::value_type>, + typename BinaryPredicate = std::equal_to<>, + typename Lambda, + typename ResultGetterType> +constexpr decltype(auto) constexpr_switch( + Lambda&& lambda, + typename std::decay_t::value_type searched, + ResultGetterType&& def, + BinaryPredicate&& pred = {}) { + using result_t = std::invoke_result_t; + using hash_t = std::conditional_t(), Hash, typename Hash::secondary_hash>; + static_assert(has_duplicate(), "magic_enum::detail::constexpr_switch duplicated hash found, please report it: https://github.com/Neargye/magic_enum/issues."); + constexpr std::array values = *GlobValues; + constexpr std::size_t size = values.size(); + constexpr std::array cases = calculate_cases(Page); + + switch (hash_v(searched)) { + MAGIC_ENUM_FOR_EACH_256(MAGIC_ENUM_CASE) + default: + if constexpr (size > 256 + Page) { + return constexpr_switch(std::forward(lambda), searched, std::forward(def)); + } + break; + } + return def(); +} + +#undef MAGIC_ENUM_CASE + +#endif + +} // namespace magic_enum::detail + +// Checks is magic_enum supported compiler. +inline constexpr bool is_magic_enum_supported = detail::supported::value; + +template +using Enum = detail::enum_concept; + +// Checks whether T is an Unscoped enumeration type. +// Provides the member constant value which is equal to true, if T is an [Unscoped enumeration](https://en.cppreference.com/w/cpp/language/enum#Unscoped_enumeration) type. Otherwise, value is equal to false. +template +struct is_unscoped_enum : detail::is_unscoped_enum {}; + +template +inline constexpr bool is_unscoped_enum_v = is_unscoped_enum::value; + +// Checks whether T is an Scoped enumeration type. +// Provides the member constant value which is equal to true, if T is an [Scoped enumeration](https://en.cppreference.com/w/cpp/language/enum#Scoped_enumerations) type. Otherwise, value is equal to false. +template +struct is_scoped_enum : detail::is_scoped_enum {}; + +template +inline constexpr bool is_scoped_enum_v = is_scoped_enum::value; + +// If T is a complete enumeration type, provides a member typedef type that names the underlying type of T. +// Otherwise, if T is not an enumeration type, there is no member type. Otherwise (T is an incomplete enumeration type), the program is ill-formed. +template +struct underlying_type : detail::underlying_type {}; + +template +using underlying_type_t = typename underlying_type::type; + +template +using enum_constant = detail::enum_constant; + +// Returns type name of enum. +template +[[nodiscard]] constexpr auto enum_type_name() noexcept -> detail::enable_if_t { + constexpr string_view name = detail::type_name_v>; + static_assert(!name.empty(), "magic_enum::enum_type_name enum type does not have a name."); + + return name; +} + +// Returns number of enum values. +template > +[[nodiscard]] constexpr auto enum_count() noexcept -> detail::enable_if_t { + return detail::count_v, S>; +} + +// Returns enum value at specified index. +// No bounds checking is performed: the behavior is undefined if index >= number of enum values. +template > +[[nodiscard]] constexpr auto enum_value(std::size_t index) noexcept -> detail::enable_if_t> { + using D = std::decay_t; + static_assert(detail::is_reflected_v, "magic_enum requires enum implementation and valid max and min."); + + if constexpr (detail::is_sparse_v) { + return MAGIC_ENUM_ASSERT(index < detail::count_v), detail::values_v[index]; + } else { + constexpr auto min = (S == detail::enum_subtype::flags) ? detail::log2(detail::min_v) : detail::min_v; + + return MAGIC_ENUM_ASSERT(index < detail::count_v), detail::value(index); + } +} + +// Returns enum value at specified index. +template > +[[nodiscard]] constexpr auto enum_value() noexcept -> detail::enable_if_t> { + using D = std::decay_t; + static_assert(detail::is_reflected_v, "magic_enum requires enum implementation and valid max and min."); + static_assert(I < detail::count_v, "magic_enum::enum_value out of range."); + + return enum_value(I); +} + +// Returns std::array with enum values, sorted by enum value. +template > +[[nodiscard]] constexpr auto enum_values() noexcept -> detail::enable_if_t> { + using D = std::decay_t; + static_assert(detail::is_reflected_v, "magic_enum requires enum implementation and valid max and min."); + + return detail::values_v; +} + +// Returns integer value from enum value. +template +[[nodiscard]] constexpr auto enum_integer(E value) noexcept -> detail::enable_if_t> { + return static_cast>(value); +} + +// Returns underlying value from enum value. +template +[[nodiscard]] constexpr auto enum_underlying(E value) noexcept -> detail::enable_if_t> { + return static_cast>(value); +} + +// Obtains index in enum values from enum value. +// Returns optional with index. +template > +[[nodiscard]] constexpr auto enum_index(E value) noexcept -> detail::enable_if_t> { + using D = std::decay_t; + using U = underlying_type_t; + static_assert(detail::is_reflected_v, "magic_enum requires enum implementation and valid max and min."); + + if constexpr (detail::is_sparse_v || (S == detail::enum_subtype::flags)) { +#if defined(MAGIC_ENUM_ENABLE_HASH) + return detail::constexpr_switch<&detail::values_v, detail::case_call_t::index>( + [](std::size_t i) { return optional{i}; }, + value, + detail::default_result_type_lambda>); +#else + for (std::size_t i = 0; i < detail::count_v; ++i) { + if (enum_value(i) == value) { + return i; + } + } + return {}; // Invalid value or out of range. +#endif + } else { + const auto v = static_cast(value); + if (v >= detail::min_v && v <= detail::max_v) { + return static_cast(v - detail::min_v); + } + return {}; // Invalid value or out of range. + } +} + +// Obtains index in enum values from enum value. +// Returns optional with index. +template +[[nodiscard]] constexpr auto enum_index(E value) noexcept -> detail::enable_if_t> { + using D = std::decay_t; + static_assert(detail::is_reflected_v, "magic_enum requires enum implementation and valid max and min."); + + return enum_index(value); +} + +// Obtains index in enum values from static storage enum variable. +template >> +[[nodiscard]] constexpr auto enum_index() noexcept -> detail::enable_if_t {\ + using D = std::decay_t; + static_assert(detail::is_reflected_v, "magic_enum requires enum implementation and valid max and min."); + constexpr auto index = enum_index(V); + static_assert(index, "magic_enum::enum_index enum value does not have a index."); + + return *index; +} + +// Returns name from static storage enum variable. +// This version is much lighter on the compile times and is not restricted to the enum_range limitation. +template +[[nodiscard]] constexpr auto enum_name() noexcept -> detail::enable_if_t { + constexpr string_view name = detail::enum_name_v, V>; + static_assert(!name.empty(), "magic_enum::enum_name enum value does not have a name."); + + return name; +} + +// Returns name from enum value. +// If enum value does not have name or value out of range, returns empty string. +template > +[[nodiscard]] constexpr auto enum_name(E value) noexcept -> detail::enable_if_t { + using D = std::decay_t; + static_assert(detail::is_reflected_v, "magic_enum requires enum implementation and valid max and min."); + + if (const auto i = enum_index(value)) { + return detail::names_v[*i]; + } + return {}; +} + +// Returns name from enum value. +// If enum value does not have name or value out of range, returns empty string. +template +[[nodiscard]] constexpr auto enum_name(E value) -> detail::enable_if_t { + using D = std::decay_t; + static_assert(detail::is_reflected_v, "magic_enum requires enum implementation and valid max and min."); + + return enum_name(value); +} + +// Returns std::array with names, sorted by enum value. +template > +[[nodiscard]] constexpr auto enum_names() noexcept -> detail::enable_if_t> { + using D = std::decay_t; + static_assert(detail::is_reflected_v, "magic_enum requires enum implementation and valid max and min."); + + return detail::names_v; +} + +// Returns std::array with pairs (value, name), sorted by enum value. +template > +[[nodiscard]] constexpr auto enum_entries() noexcept -> detail::enable_if_t> { + using D = std::decay_t; + static_assert(detail::is_reflected_v, "magic_enum requires enum implementation and valid max and min."); + + return detail::entries_v; +} + +// Allows you to write magic_enum::enum_cast("bar", magic_enum::case_insensitive); +inline constexpr auto case_insensitive = detail::case_insensitive<>{}; + +// Obtains enum value from integer value. +// Returns optional with enum value. +template > +[[nodiscard]] constexpr auto enum_cast(underlying_type_t value) noexcept -> detail::enable_if_t>> { + using D = std::decay_t; + static_assert(detail::is_reflected_v, "magic_enum requires enum implementation and valid max and min."); + + if constexpr (detail::is_sparse_v || (S == detail::enum_subtype::flags)) { +#if defined(MAGIC_ENUM_ENABLE_HASH) + return detail::constexpr_switch<&detail::values_v, detail::case_call_t::value>( + [](D v) { return optional{v}; }, + static_cast(value), + detail::default_result_type_lambda>); +#else + for (std::size_t i = 0; i < detail::count_v; ++i) { + if (value == static_cast>(enum_value(i))) { + return static_cast(value); + } + } + return {}; // Invalid value or out of range. +#endif + } else { + if (value >= detail::min_v && value <= detail::max_v) { + return static_cast(value); + } + return {}; // Invalid value or out of range. + } +} + +// Obtains enum value from name. +// Returns optional with enum value. +template , typename BinaryPredicate = std::equal_to<>> +[[nodiscard]] constexpr auto enum_cast(string_view value, [[maybe_unused]] BinaryPredicate p = {}) noexcept(detail::is_nothrow_invocable()) -> detail::enable_if_t>, BinaryPredicate> { + using D = std::decay_t; + static_assert(detail::is_reflected_v, "magic_enum requires enum implementation and valid max and min."); + +#if defined(MAGIC_ENUM_ENABLE_HASH) + if constexpr (detail::is_default_predicate()) { + return detail::constexpr_switch<&detail::names_v, detail::case_call_t::index>( + [](std::size_t i) { return optional{detail::values_v[i]}; }, + value, + detail::default_result_type_lambda>, + [&p](string_view lhs, string_view rhs) { return detail::cmp_equal(lhs, rhs, p); }); + } +#endif + for (std::size_t i = 0; i < detail::count_v; ++i) { + if (detail::cmp_equal(value, detail::names_v[i], p)) { + return enum_value(i); + } + } + return {}; // Invalid value or out of range. +} + +// Checks whether enum contains value with such value. +template > +[[nodiscard]] constexpr auto enum_contains(E value) noexcept -> detail::enable_if_t { + using D = std::decay_t; + using U = underlying_type_t; + + return static_cast(enum_cast(static_cast(value))); +} + +// Checks whether enum contains value with such value. +template +[[nodiscard]] constexpr auto enum_contains(E value) noexcept -> detail::enable_if_t { + using D = std::decay_t; + using U = underlying_type_t; + + return static_cast(enum_cast(static_cast(value))); +} + +// Checks whether enum contains value with such integer value. +template > +[[nodiscard]] constexpr auto enum_contains(underlying_type_t value) noexcept -> detail::enable_if_t { + using D = std::decay_t; + + return static_cast(enum_cast(value)); +} + +// Checks whether enum contains enumerator with such name. +template , typename BinaryPredicate = std::equal_to<>> +[[nodiscard]] constexpr auto enum_contains(string_view value, BinaryPredicate p = {}) noexcept(detail::is_nothrow_invocable()) -> detail::enable_if_t { + using D = std::decay_t; + + return static_cast(enum_cast(value, std::move(p))); +} + +// Returns true if the enum integer value is in the range of values that can be reflected. +template > +[[nodiscard]] constexpr auto enum_reflected(underlying_type_t value) noexcept -> detail::enable_if_t { + using D = std::decay_t; + + if constexpr (detail::is_reflected_v) { + constexpr auto min = detail::reflected_min(); + constexpr auto max = detail::reflected_max(); + return value >= min && value <= max; + } else { + return false; + } +} + +// Returns true if the enum value is in the range of values that can be reflected. +template > +[[nodiscard]] constexpr auto enum_reflected(E value) noexcept -> detail::enable_if_t { + using D = std::decay_t; + + return enum_reflected(static_cast>(value)); +} + +// Returns true if the enum value is in the range of values that can be reflected. +template +[[nodiscard]] constexpr auto enum_reflected(E value) noexcept -> detail::enable_if_t { + using D = std::decay_t; + + return enum_reflected(value); +} + +template +inline constexpr auto as_flags = AsFlags ? detail::enum_subtype::flags : detail::enum_subtype::common; + +template +inline constexpr auto as_common = AsFlags ? detail::enum_subtype::common : detail::enum_subtype::flags; + +namespace bitwise_operators { + +template = 0> +constexpr E operator~(E rhs) noexcept { + return static_cast(~static_cast>(rhs)); +} + +template = 0> +constexpr E operator|(E lhs, E rhs) noexcept { + return static_cast(static_cast>(lhs) | static_cast>(rhs)); +} + +template = 0> +constexpr E operator&(E lhs, E rhs) noexcept { + return static_cast(static_cast>(lhs) & static_cast>(rhs)); +} + +template = 0> +constexpr E operator^(E lhs, E rhs) noexcept { + return static_cast(static_cast>(lhs) ^ static_cast>(rhs)); +} + +template = 0> +constexpr E& operator|=(E& lhs, E rhs) noexcept { + return lhs = (lhs | rhs); +} + +template = 0> +constexpr E& operator&=(E& lhs, E rhs) noexcept { + return lhs = (lhs & rhs); +} + +template = 0> +constexpr E& operator^=(E& lhs, E rhs) noexcept { + return lhs = (lhs ^ rhs); +} + +} // namespace magic_enum::bitwise_operators + +} // namespace magic_enum + +#if defined(__clang__) +# pragma clang diagnostic pop +#elif defined(__GNUC__) +# pragma GCC diagnostic pop +#elif defined(_MSC_VER) +# pragma warning(pop) +#endif + +#undef MAGIC_ENUM_GET_ENUM_NAME_BUILTIN +#undef MAGIC_ENUM_GET_TYPE_NAME_BUILTIN +#undef MAGIC_ENUM_VS_2017_WORKAROUND +#undef MAGIC_ENUM_ARRAY_CONSTEXPR +#undef MAGIC_ENUM_FOR_EACH_256 + +#endif // NEARGYE_MAGIC_ENUM_HPP diff --git a/module/dll_source_lzy/114/out/lib/hulc/magic_enum/magic_enum/magic_enum_all.hpp b/module/dll_source_lzy/114/out/lib/hulc/magic_enum/magic_enum/magic_enum_all.hpp new file mode 100644 index 0000000..7a05281 --- /dev/null +++ b/module/dll_source_lzy/114/out/lib/hulc/magic_enum/magic_enum/magic_enum_all.hpp @@ -0,0 +1,44 @@ +// __ __ _ ______ _____ +// | \/ | (_) | ____| / ____|_ _ +// | \ / | __ _ __ _ _ ___ | |__ _ __ _ _ _ __ ___ | | _| |_ _| |_ +// | |\/| |/ _` |/ _` | |/ __| | __| | '_ \| | | | '_ ` _ \ | | |_ _|_ _| +// | | | | (_| | (_| | | (__ | |____| | | | |_| | | | | | | | |____|_| |_| +// |_| |_|\__,_|\__, |_|\___| |______|_| |_|\__,_|_| |_| |_| \_____| +// __/ | https://github.com/Neargye/magic_enum +// |___/ version 0.9.7 +// +// Licensed under the MIT License . +// SPDX-License-Identifier: MIT +// Copyright (c) 2019 - 2024 Daniil Goncharov . +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#ifndef NEARGYE_MAGIC_ENUM_ALL_HPP +#define NEARGYE_MAGIC_ENUM_ALL_HPP + +#include "magic_enum.hpp" +#include "../magic_enum_containers.hpp" +#include "../magic_enum_flags.hpp" +#include "../magic_enum_format.hpp" +#include "../magic_enum_fuse.hpp" +#include "../magic_enum_iostream.hpp" +#include "../magic_enum_switch.hpp" +#include "../magic_enum_utility.hpp" + +#endif // NEARGYE_MAGIC_ENUM_ALL_HPP diff --git a/module/dll_source_lzy/114/out/lib/hulc/magic_enum/magic_enum/magic_enum_containers.hpp b/module/dll_source_lzy/114/out/lib/hulc/magic_enum/magic_enum/magic_enum_containers.hpp new file mode 100644 index 0000000..f817306 --- /dev/null +++ b/module/dll_source_lzy/114/out/lib/hulc/magic_enum/magic_enum/magic_enum_containers.hpp @@ -0,0 +1,1174 @@ +// __ __ _ ______ _____ +// | \/ | (_) | ____| / ____|_ _ +// | \ / | __ _ __ _ _ ___ | |__ _ __ _ _ _ __ ___ | | _| |_ _| |_ +// | |\/| |/ _` |/ _` | |/ __| | __| | '_ \| | | | '_ ` _ \ | | |_ _|_ _| +// | | | | (_| | (_| | | (__ | |____| | | | |_| | | | | | | | |____|_| |_| +// |_| |_|\__,_|\__, |_|\___| |______|_| |_|\__,_|_| |_| |_| \_____| +// __/ | https://github.com/Neargye/magic_enum +// |___/ version 0.9.7 +// +// Licensed under the MIT License . +// SPDX-License-Identifier: MIT +// Copyright (c) 2019 - 2024 Daniil Goncharov . +// Copyright (c) 2022 - 2023 Bela Schaum . +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#ifndef NEARGYE_MAGIC_ENUM_CONTAINERS_HPP +#define NEARGYE_MAGIC_ENUM_CONTAINERS_HPP + +#include "magic_enum.hpp" + +#if !defined(MAGIC_ENUM_NO_EXCEPTION) && (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) +#ifndef MAGIC_ENUM_USE_STD_MODULE +# include +#endif +# define MAGIC_ENUM_THROW(...) throw (__VA_ARGS__) +#else +#ifndef MAGIC_ENUM_USE_STD_MODULE +# include +#endif +# define MAGIC_ENUM_THROW(...) std::abort() +#endif + +namespace magic_enum::containers { + +namespace detail { + +template +static constexpr bool is_transparent_v{}; + +template +static constexpr bool is_transparent_v>{true}; + +template , typename T1, typename T2> +constexpr bool equal(T1&& t1, T2&& t2, Eq&& eq = {}) { + auto first1 = t1.begin(); + auto last1 = t1.end(); + auto first2 = t2.begin(); + auto last2 = t2.end(); + + for (; first1 != last1; ++first1, ++first2) { + if (first2 == last2 || !eq(*first1, *first2)) { + return false; + } + } + return first2 == last2; +} + +template , typename T1, typename T2> +constexpr bool lexicographical_compare(T1&& t1, T2&& t2, Cmp&& cmp = {}) noexcept { + auto first1 = t1.begin(); + auto last1 = t1.end(); + auto first2 = t2.begin(); + auto last2 = t2.end(); + + // copied from std::lexicographical_compare + for (; (first1 != last1) && (first2 != last2); ++first1, (void)++first2) { + if (cmp(*first1, *first2)) { + return true; + } + if (cmp(*first2, *first1)) { + return false; + } + } + return (first1 == last1) && (first2 != last2); +} + +template +constexpr std::size_t popcount(T x) noexcept { + std::size_t c = 0; + while (x > 0) { + c += x & 1; + x >>= 1; + } + return c; +} + +template , typename ForwardIt, typename E> +constexpr ForwardIt lower_bound(ForwardIt first, ForwardIt last, E&& e, Cmp&& comp = {}) { + auto count = std::distance(first, last); + for (auto it = first; count > 0;) { + auto step = count / 2; + std::advance(it, step); + if (comp(*it, e)) { + first = ++it; + count -= step + 1; + } else { + count = step; + } + } + return first; +} + +template , typename BidirIt, typename E> +constexpr auto equal_range(BidirIt begin, BidirIt end, E&& e, Cmp&& comp = {}) { + const auto first = lower_bound(begin, end, e, comp); + return std::pair{first, lower_bound(std::make_reverse_iterator(end), std::make_reverse_iterator(first), e, [&comp](auto&& lhs, auto&& rhs) { return comp(rhs, lhs); }).base()}; +} + +template , typename = void> +class indexing { + [[nodiscard]] static constexpr auto get_indices() noexcept { + // reverse result index mapping + std::array()> rev_res{}; + + // std::iota + for (std::size_t i = 0; i < enum_count(); ++i) { + rev_res[i] = i; + } + + constexpr auto orig_values = enum_values(); + constexpr Cmp cmp{}; + + // ~std::sort + for (std::size_t i = 0; i < enum_count(); ++i) { + for (std::size_t j = i + 1; j < enum_count(); ++j) { + if (cmp(orig_values[rev_res[j]], orig_values[rev_res[i]])) { + auto tmp = rev_res[i]; + rev_res[i] = rev_res[j]; + rev_res[j] = tmp; + } + } + } + + std::array()> sorted_values{}; + // reverse the sorted indices + std::array()> res{}; + for (std::size_t i = 0; i < enum_count(); ++i) { + res[rev_res[i]] = i; + sorted_values[i] = orig_values[rev_res[i]]; + } + + return std::pair{sorted_values, res}; + } + + static constexpr auto indices = get_indices(); + + public: + [[nodiscard]] static constexpr const E* begin() noexcept { return indices.first.data(); } + + [[nodiscard]] static constexpr const E* end() noexcept { return indices.first.data() + indices.first.size(); } + + [[nodiscard]] static constexpr const E* it(std::size_t i) noexcept { return indices.first.data() + i; } + + [[nodiscard]] static constexpr optional at(E val) noexcept { + if (auto i = enum_index(val)) { + return indices.second[*i]; + } + return {}; + } +}; + +template +class indexing> && (std::is_same_v> || std::is_same_v>)>> { + static constexpr auto& values = enum_values(); + + public: + [[nodiscard]] static constexpr const E* begin() noexcept { return values.data(); } + + [[nodiscard]] static constexpr const E* end() noexcept { return values.data() + values.size(); } + + [[nodiscard]] static constexpr const E* it(std::size_t i) noexcept { return values.data() + i; } + + [[nodiscard]] static constexpr optional at(E val) noexcept { return enum_index(val); } +}; + +template +struct indexing { + using is_transparent = std::true_type; + + template + [[nodiscard]] static constexpr optional at(E val) noexcept { + return indexing::at(val); + } +}; + +template , typename = void> +struct name_sort_impl { + [[nodiscard]] constexpr bool operator()(E e1, E e2) const noexcept { return Cmp{}(enum_name(e1), enum_name(e2)); } +}; + +template +struct name_sort_impl { + using is_transparent = std::true_type; + + template + struct FullCmp : C {}; + + template + struct FullCmp && std::is_invocable_v>> { + [[nodiscard]] constexpr bool operator()(string_view s1, string_view s2) const noexcept { return lexicographical_compare(s1, s2); } + }; + + template + [[nodiscard]] constexpr std::enable_if_t< + // at least one of need to be an enum type + (std::is_enum_v> || std::is_enum_v>) && + // if both is enum, only accept if the same enum + (!std::is_enum_v> || !std::is_enum_v> || std::is_same_v) && + // is invocable with comparator + (std::is_invocable_r_v, std::conditional_t>, string_view, E1>, std::conditional_t>, string_view, E2>>), + bool> + operator()(E1 e1, E2 e2) const noexcept { + using D1 = std::decay_t; + using D2 = std::decay_t; + constexpr FullCmp<> cmp{}; + + if constexpr (std::is_enum_v && std::is_enum_v) { + return cmp(enum_name(e1), enum_name(e2)); + } else if constexpr (std::is_enum_v) { + return cmp(enum_name(e1), e2); + } else /* if constexpr (std::is_enum_v) */ { + return cmp(e1, enum_name(e2)); + } + } +}; + +struct raw_access_t {}; + +template +struct FilteredIterator { + Parent parent; + Iterator first; + Iterator last; + Iterator current; + Getter getter; + Predicate predicate; + + using iterator_category = std::bidirectional_iterator_tag; + using value_type = std::remove_reference_t>; + using difference_type = std::ptrdiff_t; + using pointer = value_type*; + using reference = value_type&; + + constexpr FilteredIterator() noexcept = default; + constexpr FilteredIterator(const FilteredIterator&) = default; + constexpr FilteredIterator& operator=(const FilteredIterator&) = default; + constexpr FilteredIterator(FilteredIterator&&) noexcept = default; + constexpr FilteredIterator& operator=(FilteredIterator&&) noexcept = default; + + template && std::is_convertible_v>*> + constexpr explicit FilteredIterator(const FilteredIterator& other) + : parent(other.parent), first(other.first), last(other.last), current(other.current), getter(other.getter), predicate(other.predicate) {} + + constexpr FilteredIterator(Parent p, Iterator begin, Iterator end, Iterator curr, Getter get = {}, Predicate pred = {}) + : parent(p), first(std::move(begin)), last(std::move(end)), current(std::move(curr)), getter{std::move(get)}, predicate{std::move(pred)} { + if (current == first && !predicate(parent, current)) { + ++*this; + } + } + + [[nodiscard]] constexpr reference operator*() const { return getter(parent, current); } + + [[nodiscard]] constexpr pointer operator->() const { return std::addressof(**this); } + + constexpr FilteredIterator& operator++() { + do { + ++current; + } while (current != last && !predicate(parent, current)); + return *this; + } + + [[nodiscard]] constexpr FilteredIterator operator++(int) { + FilteredIterator cp = *this; + ++*this; + return cp; + } + + constexpr FilteredIterator& operator--() { + do { + --current; + } while (current != first && !predicate(parent, current)); + return *this; + } + + [[nodiscard]] constexpr FilteredIterator operator--(int) { + FilteredIterator cp = *this; + --*this; + return cp; + } + + [[nodiscard]] friend constexpr bool operator==(const FilteredIterator& lhs, const FilteredIterator& rhs) { return lhs.current == rhs.current; } + + [[nodiscard]] friend constexpr bool operator!=(const FilteredIterator& lhs, const FilteredIterator& rhs) { return lhs.current != rhs.current; } +}; + +} // namespace detail + +template +using name_less = detail::name_sort_impl; + +template +using name_greater = detail::name_sort_impl>; + +using name_less_case_insensitive = detail::name_sort_impl>>; + +using name_greater_case_insensitive = detail::name_sort_impl>>; + +template +using default_indexing = detail::indexing; + +template > +using comparator_indexing = detail::indexing; + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// ARRAY // +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +template > +struct array { + static_assert(std::is_enum_v); + static_assert(std::is_trivially_constructible_v); + static_assert(enum_count() > 0 && Index::at(enum_values().front())); + + using index_type = Index; + using container_type = std::array()>; + + using value_type = typename container_type::value_type; + using size_type = typename container_type::size_type; + using difference_type = typename container_type::difference_type; + using reference = typename container_type::reference; + using const_reference = typename container_type::const_reference; + using pointer = typename container_type::pointer; + using const_pointer = typename container_type::const_pointer; + using iterator = typename container_type::iterator; + using const_iterator = typename container_type::const_iterator; + using reverse_iterator = typename container_type::reverse_iterator; + using const_reverse_iterator = typename container_type::const_reverse_iterator; + + constexpr reference at(E pos) { + if (auto index = index_type::at(pos)) { + return a[*index]; + } + MAGIC_ENUM_THROW(std::out_of_range("magic_enum::containers::array::at Unrecognized position")); + } + + constexpr const_reference at(E pos) const { + if (auto index = index_type::at(pos)) { + return a[*index]; + } + MAGIC_ENUM_THROW(std::out_of_range("magic_enum::containers::array::at: Unrecognized position")); + } + + [[nodiscard]] constexpr reference operator[](E pos) { + auto i = index_type::at(pos); + return MAGIC_ENUM_ASSERT(i), a[*i]; + } + + [[nodiscard]] constexpr const_reference operator[](E pos) const { + auto i = index_type::at(pos); + return MAGIC_ENUM_ASSERT(i), a[*i]; + } + + [[nodiscard]] constexpr reference front() noexcept { return a.front(); } + + [[nodiscard]] constexpr const_reference front() const noexcept { return a.front(); } + + [[nodiscard]] constexpr reference back() noexcept { return a.back(); } + + [[nodiscard]] constexpr const_reference back() const noexcept { return a.back(); } + + [[nodiscard]] constexpr pointer data() noexcept { return a.data(); } + + [[nodiscard]] constexpr const_pointer data() const noexcept { return a.data(); } + + [[nodiscard]] constexpr iterator begin() noexcept { return a.begin(); } + + [[nodiscard]] constexpr const_iterator begin() const noexcept { return a.begin(); } + + [[nodiscard]] constexpr const_iterator cbegin() const noexcept { return a.cbegin(); } + + [[nodiscard]] constexpr iterator end() noexcept { return a.end(); } + + [[nodiscard]] constexpr const_iterator end() const noexcept { return a.end(); } + + [[nodiscard]] constexpr const_iterator cend() const noexcept { return a.cend(); } + + [[nodiscard]] constexpr iterator rbegin() noexcept { return a.rbegin(); } + + [[nodiscard]] constexpr const_iterator rbegin() const noexcept { return a.rbegin(); } + + [[nodiscard]] constexpr const_iterator crbegin() const noexcept { return a.crbegin(); } + + [[nodiscard]] constexpr iterator rend() noexcept { return a.rend(); } + + [[nodiscard]] constexpr const_iterator rend() const noexcept { return a.rend(); } + + [[nodiscard]] constexpr const_iterator crend() const noexcept { return a.crend(); } + + [[nodiscard]] constexpr bool empty() const noexcept { return a.empty(); } + + [[nodiscard]] constexpr size_type size() const noexcept { return a.size(); } + + [[nodiscard]] constexpr size_type max_size() const noexcept { return a.max_size(); } + + constexpr void fill(const V& value) { + for (auto& v : a) { + v = value; + } + } + + constexpr void swap(array& other) noexcept(std::is_nothrow_swappable_v) { + for (std::size_t i = 0; i < a.size(); ++i) { + auto v = std::move(other.a[i]); + other.a[i] = std::move(a[i]); + a[i] = std::move(v); + } + } + + [[nodiscard]] friend constexpr bool operator==(const array& a1, const array& a2) { return detail::equal(a1, a2); } + + [[nodiscard]] friend constexpr bool operator!=(const array& a1, const array& a2) { return !detail::equal(a1, a2); } + + [[nodiscard]] friend constexpr bool operator<(const array& a1, const array& a2) { return detail::lexicographical_compare(a1, a2); } + + [[nodiscard]] friend constexpr bool operator<=(const array& a1, const array& a2) { return !detail::lexicographical_compare(a2, a1); } + + [[nodiscard]] friend constexpr bool operator>(const array& a1, const array& a2) { return detail::lexicographical_compare(a2, a1); } + + [[nodiscard]] friend constexpr bool operator>=(const array& a1, const array& a2) { return !detail::lexicographical_compare(a1, a2); } + + container_type a; +}; + +namespace detail { + +template +constexpr array> to_array_impl(T (&a)[N], std::index_sequence) { + return {{a[I]...}}; +} + +template +constexpr array> to_array_impl(T(&&a)[N], std::index_sequence) { + return {{std::move(a[I])...}}; +} + +} // namespace detail + +template +constexpr std::enable_if_t<(enum_count() == N), array>> to_array(T (&a)[N]) { + return detail::to_array_impl(a, std::make_index_sequence{}); +} + +template +constexpr std::enable_if_t<(enum_count() == N), array>> to_array(T(&&a)[N]) { + return detail::to_array_impl(std::move(a), std::make_index_sequence{}); +} + +template +constexpr std::enable_if_t<(enum_count() == sizeof...(Ts)), array>>> make_array(Ts&&... ts) { + return {{std::forward(ts)...}}; +} + +inline constexpr detail::raw_access_t raw_access{}; + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// BITSET // +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +template > +class bitset { + static_assert(std::is_enum_v); + static_assert(std::is_trivially_constructible_v); + static_assert(enum_count() > 0 && Index::at(enum_values().front())); + + using base_type = std::conditional_t() <= 8, std::uint_least8_t, + std::conditional_t() <= 16, std::uint_least16_t, + std::conditional_t() <= 32, std::uint_least32_t, + std::uint_least64_t>>>; + + static constexpr std::size_t bits_per_base = sizeof(base_type) * 8; + static constexpr std::size_t base_type_count = (enum_count() > 0 ? (enum_count() - 1) / bits_per_base + 1 : 0); + static constexpr std::size_t not_interested = base_type_count * bits_per_base - enum_count(); + static constexpr base_type last_value_max = (base_type{1} << (bits_per_base - not_interested)) - 1; + + template + class reference_impl { + friend class bitset; + + parent_t parent; + std::size_t num_index; + base_type bit_index; + + constexpr reference_impl(parent_t p, std::size_t i) noexcept : reference_impl(p, std::pair{i / bits_per_base, base_type{1} << (i % bits_per_base)}) {} + + constexpr reference_impl(parent_t p, std::pair i) noexcept : parent(p), num_index(std::get<0>(i)), bit_index(std::get<1>(i)) {} + + public: + constexpr reference_impl& operator=(bool v) noexcept { + if (v) { + parent->a[num_index] |= bit_index; + } else { + parent->a[num_index] &= ~bit_index; + } + return *this; + } + + constexpr reference_impl& operator=(const reference_impl& v) noexcept { + if (this == &v) { + return *this; + } + *this = static_cast(v); + return *this; + } + + [[nodiscard]] constexpr operator bool() const noexcept { return (parent->a[num_index] & bit_index) > 0; } + + [[nodiscard]] constexpr bool operator~() const noexcept { return !static_cast(*this); } + + constexpr reference_impl& flip() noexcept { + *this = ~*this; + return *this; + } + }; + + template + [[nodiscard]] constexpr T to_(detail::raw_access_t) const { + T res{}; + T flag{1}; + for (std::size_t i = 0; i < size(); ++i, flag <<= 1) { + if (const_reference{this, i}) { + if (i >= sizeof(T) * 8) { + MAGIC_ENUM_THROW(std::overflow_error("magic_enum::containers::bitset::to: Cannot represent enum in this type")); + } + res |= flag; + } + } + return res; + } + + public: + using index_type = Index; + using container_type = std::array; + using reference = reference_impl<>; + using const_reference = reference_impl; + + constexpr explicit bitset(detail::raw_access_t = raw_access) noexcept : a{{}} {} + + constexpr explicit bitset(detail::raw_access_t, unsigned long long val) : a{{}} { + unsigned long long bit{1}; + for (std::size_t i = 0; i < (sizeof(val) * 8); ++i, bit <<= 1) { + if ((val & bit) > 0) { + if (i >= enum_count()) { + MAGIC_ENUM_THROW(std::out_of_range("magic_enum::containers::bitset::constructor: Upper bit set in raw number")); + } + + reference{this, i} = true; + } + } + } + + constexpr explicit bitset(detail::raw_access_t, string_view sv, string_view::size_type pos = 0, string_view::size_type n = string_view::npos, char_type zero = static_cast('0'), char_type one = static_cast('1')) + : a{{}} { + std::size_t i = 0; + for (auto c : sv.substr(pos, n)) { + if (c == one) { + if (i >= enum_count()) { + MAGIC_ENUM_THROW(std::out_of_range("magic_enum::containers::bitset::constructor: Upper bit set in raw string")); + } + reference{this, i} = true; + } else if (c != zero) { + MAGIC_ENUM_THROW(std::invalid_argument("magic_enum::containers::bitset::constructor: Unrecognized character in raw string")); + } + ++i; + } + } + + constexpr explicit bitset(detail::raw_access_t, const char_type* str, std::size_t n = ~std::size_t{0}, char_type zero = static_cast('0'), char_type one = static_cast('1')) + : bitset(string_view{str, (std::min)(std::char_traits::length(str), n)}, 0, n, zero, one) {} + + constexpr bitset(std::initializer_list starters) : a{{}} { + if constexpr (magic_enum::detail::subtype_v == magic_enum::detail::enum_subtype::flags) { + for (auto& f : starters) { + *this |= bitset(f); + } + } else { + for (auto& f : starters) { + set(f); + } + } + } + template && magic_enum::detail::subtype_v == magic_enum::detail::enum_subtype::flags, int> = 0> + constexpr explicit bitset(V starter) : a{{}} { + auto u = enum_underlying(starter); + for (E v : enum_values()) { + if (auto ul = enum_underlying(v); (ul & u) != 0) { + u &= ~ul; + (*this)[v] = true; + } + } + if (u != 0) { + MAGIC_ENUM_THROW(std::invalid_argument("magic_enum::containers::bitset::constructor: Unrecognized enum value in flag")); + } + } + + template > + constexpr explicit bitset(string_view sv, Cmp&& cmp = {}, char_type sep = static_cast('|')) { + for (std::size_t to = 0; (to = magic_enum::detail::find(sv, sep)) != string_view::npos; sv.remove_prefix(to + 1)) { + if (auto v = enum_cast(sv.substr(0, to), cmp)) { + set(*v); + } else { + MAGIC_ENUM_THROW(std::invalid_argument("magic_enum::containers::bitset::constructor: Unrecognized enum value in string")); + } + } + if (!sv.empty()) { + if (auto v = enum_cast(sv, cmp)) { + set(*v); + } else { + MAGIC_ENUM_THROW(std::invalid_argument("magic_enum::containers::bitset::constructor: Unrecognized enum value in string")); + } + } + } + + [[nodiscard]] friend constexpr bool operator==(const bitset& lhs, const bitset& rhs) noexcept { return detail::equal(lhs.a, rhs.a); } + + [[nodiscard]] friend constexpr bool operator!=(const bitset& lhs, const bitset& rhs) noexcept { return !detail::equal(lhs.a, rhs.a); } + + [[nodiscard]] constexpr bool operator[](E pos) const { + auto i = index_type::at(pos); + return MAGIC_ENUM_ASSERT(i), static_cast(const_reference(this, *i)); + } + + [[nodiscard]] constexpr reference operator[](E pos) { + auto i = index_type::at(pos); + return MAGIC_ENUM_ASSERT(i), reference{this, *i}; + } + + constexpr bool test(E pos) const { + if (auto i = index_type::at(pos)) { + return static_cast(const_reference(this, *i)); + } + MAGIC_ENUM_THROW(std::out_of_range("magic_enum::containers::bitset::test: Unrecognized position")); + } + + [[nodiscard]] constexpr bool all() const noexcept { + if constexpr (base_type_count == 0) { + return true; + } + + for (std::size_t i = 0; i < base_type_count - (not_interested > 0); ++i) { + auto check = ~a[i]; + if (check) { + return false; + } + } + + if constexpr (not_interested > 0) { + return a[base_type_count - 1] == last_value_max; + } + } + + [[nodiscard]] constexpr bool any() const noexcept { + for (auto& v : a) { + if (v > 0) { + return true; + } + } + return false; + } + + [[nodiscard]] constexpr bool none() const noexcept { return !any(); } + + [[nodiscard]] constexpr std::size_t count() const noexcept { + std::size_t c = 0; + for (auto& v : a) { + c += detail::popcount(v); + } + return c; + } + + [[nodiscard]] constexpr std::size_t size() const noexcept { return enum_count(); } + + [[nodiscard]] constexpr std::size_t max_size() const noexcept { return enum_count(); } + + constexpr bitset& operator&=(const bitset& other) noexcept { + for (std::size_t i = 0; i < base_type_count; ++i) { + a[i] &= other.a[i]; + } + return *this; + } + + constexpr bitset& operator|=(const bitset& other) noexcept { + for (std::size_t i = 0; i < base_type_count; ++i) { + a[i] |= other.a[i]; + } + return *this; + } + + constexpr bitset& operator^=(const bitset& other) noexcept { + for (std::size_t i = 0; i < base_type_count; ++i) { + a[i] ^= other.a[i]; + } + return *this; + } + + [[nodiscard]] constexpr bitset operator~() const noexcept { + bitset res; + for (std::size_t i = 0; i < base_type_count - (not_interested > 0); ++i) { + res.a[i] = ~a[i]; + } + + if constexpr (not_interested > 0) { + res.a[base_type_count - 1] = ~a[base_type_count - 1] & last_value_max; + } + return res; + } + + constexpr bitset& set() noexcept { + for (std::size_t i = 0; i < base_type_count - (not_interested > 0); ++i) { + a[i] = ~base_type{0}; + } + + if constexpr (not_interested > 0) { + a[base_type_count - 1] = last_value_max; + } + return *this; + } + + constexpr bitset& set(E pos, bool value = true) { + if (auto i = index_type::at(pos)) { + reference{this, *i} = value; + return *this; + } + MAGIC_ENUM_THROW(std::out_of_range("magic_enum::containers::bitset::set: Unrecognized position")); + } + + constexpr bitset& reset() noexcept { return *this = bitset{}; } + + constexpr bitset& reset(E pos) { + if (auto i = index_type::at(pos)) { + reference{this, *i} = false; + return *this; + } + MAGIC_ENUM_THROW(std::out_of_range("magic_enum::containers::bitset::reset: Unrecognized position")); + } + + constexpr bitset& flip() noexcept { return *this = ~*this; } + + [[nodiscard]] friend constexpr bitset operator&(const bitset& lhs, const bitset& rhs) noexcept { + bitset cp = lhs; + cp &= rhs; + return cp; + } + + [[nodiscard]] friend constexpr bitset operator|(const bitset& lhs, const bitset& rhs) noexcept { + bitset cp = lhs; + cp |= rhs; + return cp; + } + + [[nodiscard]] friend constexpr bitset operator^(const bitset& lhs, const bitset& rhs) noexcept { + bitset cp = lhs; + cp ^= rhs; + return cp; + } + + template + [[nodiscard]] constexpr explicit operator std::enable_if_t == magic_enum::detail::enum_subtype::flags, E>() const { + E res{}; + for (const auto& e : enum_values()) { + if (test(e)) { + res |= e; + } + } + return res; + } + + [[nodiscard]] string to_string(char_type sep = static_cast('|')) const { + string name; + + for (const auto& e : enum_values()) { + if (test(e)) { + if (!name.empty()) { + name.append(1, sep); + } + auto n = enum_name(e); + name.append(n.data(), n.size()); + } + } + return name; + } + + [[nodiscard]] string to_string(detail::raw_access_t, char_type zero = static_cast('0'), char_type one = static_cast('1')) const { + string name; + name.reserve(size()); + for (std::size_t i = 0; i < size(); ++i) { + name.append(1, const_reference{this, i} ? one : zero); + } + return name; + } + + [[nodiscard]] constexpr unsigned long long to_ullong(detail::raw_access_t raw) const { return to_(raw); } + + [[nodiscard]] constexpr unsigned long long to_ulong(detail::raw_access_t raw) const { return to_(raw); } + + friend std::ostream& operator<<(std::ostream& o, const bitset& bs) { return o << bs.to_string(); } + + friend std::istream& operator>>(std::istream& i, bitset& bs) { + string s; + if (i >> s; !s.empty()) { + bs = bitset(string_view{s}); + } + return i; + } + + private: + container_type a; +}; + +template +explicit bitset(V starter) -> bitset; + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// SET // +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +template > +class set { + using index_type = detail::indexing; + struct Getter { + constexpr const E& operator()(const set*, const E* p) const noexcept { return *p; } + }; + struct Predicate { + constexpr bool operator()(const set* h, const E* e) const noexcept { return h->a[*e]; } + }; + + public: + using container_type = bitset; + using key_type = E; + using value_type = E; + using size_type = std::size_t; + using difference_type = std::ptrdiff_t; + using key_compare = Cmp; + using value_compare = Cmp; + using reference = value_type&; + using const_reference = const value_type&; + using pointer = value_type*; + using const_pointer = const value_type*; + using iterator = detail::FilteredIterator; + using const_iterator = detail::FilteredIterator; + using reverse_iterator = std::reverse_iterator; + using const_reverse_iterator = std::reverse_iterator; + + constexpr set() noexcept = default; + + template + constexpr set(InputIt first, InputIt last) { + while (first != last) { + insert(*first++); + } + } + + constexpr set(std::initializer_list ilist) { + for (auto e : ilist) { + insert(e); + } + } + template && magic_enum::detail::subtype_v == magic_enum::detail::enum_subtype::flags, int> = 0> + constexpr explicit set(V starter) { + auto u = enum_underlying(starter); + for (E v : enum_values()) { + if ((enum_underlying(v) & u) != 0) { + insert(v); + } + } + } + + constexpr set(const set&) noexcept = default; + constexpr set(set&&) noexcept = default; + + constexpr set& operator=(const set&) noexcept = default; + constexpr set& operator=(set&&) noexcept = default; + constexpr set& operator=(std::initializer_list ilist) { + for (auto e : ilist) { + insert(e); + } + } + + constexpr const_iterator begin() const noexcept { + return const_iterator{this, index_type::begin(), index_type::end(), index_type::begin()}; + } + + constexpr const_iterator end() const noexcept { + return const_iterator{this, index_type::begin(), index_type::end(), index_type::end()}; + } + + constexpr const_iterator cbegin() const noexcept { return begin(); } + + constexpr const_iterator cend() const noexcept { return end(); } + + constexpr const_reverse_iterator rbegin() const noexcept { return {end()}; } + + constexpr const_reverse_iterator rend() const noexcept { return {begin()}; } + + constexpr const_reverse_iterator crbegin() const noexcept { return rbegin(); } + + constexpr const_reverse_iterator crend() const noexcept { return rend(); } + + [[nodiscard]] constexpr bool empty() const noexcept { return s == 0; } + + [[nodiscard]] constexpr size_type size() const noexcept { return s; } + + [[nodiscard]] constexpr size_type max_size() const noexcept { return a.max_size(); } + + constexpr void clear() noexcept { + a.reset(); + s = 0; + } + + constexpr std::pair insert(const value_type& value) noexcept { + if (auto i = index_type::at(value)) { + typename container_type::reference ref = a[value]; + bool r = !ref; + if (r) { + ref = true; + ++s; + } + + return {iterator{this, index_type::begin(), index_type::end(), index_type::it(*i)}, r}; + } + return {end(), false}; + } + + constexpr std::pair insert(value_type&& value) noexcept { return insert(value); } + + constexpr iterator insert(const_iterator, const value_type& value) noexcept { return insert(value).first; } + + constexpr iterator insert(const_iterator hint, value_type&& value) noexcept { return insert(hint, value); } + + template + constexpr void insert(InputIt first, InputIt last) noexcept { + while (first != last) { + insert(*first++); + } + } + + constexpr void insert(std::initializer_list ilist) noexcept { + for (auto v : ilist) { + insert(v); + } + } + + template + constexpr std::pair emplace(Args&&... args) noexcept { + return insert({std::forward(args)...}); + } + + template + constexpr iterator emplace_hint(const_iterator, Args&&... args) noexcept { + return emplace(std::forward(args)...).first; + } + + constexpr iterator erase(const_iterator pos) noexcept { + erase(*pos++); + return pos; + } + + constexpr iterator erase(const_iterator first, const_iterator last) noexcept { + while ((first = erase(first)) != last) { + } + return first; + } + + constexpr size_type erase(const key_type& key) noexcept { + typename container_type::reference ref = a[key]; + bool res = ref; + if (res) { + --s; + } + ref = false; + return res; + } + + template + constexpr std::enable_if_t, size_type> erase(K&& x) noexcept { + size_type c = 0; + for (auto [first, last] = detail::equal_range(index_type::begin(), index_type::end(), x, key_compare{}); first != last;) { + c += erase(*first++); + } + return c; + } + + void swap(set& other) noexcept { + set cp = *this; + *this = other; + other = cp; + } + + [[nodiscard]] constexpr size_type count(const key_type& key) const noexcept { return index_type::at(key) && a[key]; } + + template + [[nodiscard]] constexpr std::enable_if_t, size_type> count(const K& x) const { + size_type c = 0; + for (auto [first, last] = detail::equal_range(index_type::begin(), index_type::end(), x, key_compare{}); first != last; ++first) { + c += count(*first); + } + return c; + } + + [[nodiscard]] constexpr const_iterator find(const key_type& key) const noexcept { + if (auto i = index_type::at(key); i && a.test(key)) { + return const_iterator{this, index_type::begin(), index_type::end(), index_type::it(*i)}; + } + return end(); + } + + template + [[nodiscard]] constexpr std::enable_if_t, const_iterator> find(const K& x) const { + for (auto [first, last] = detail::equal_range(index_type::begin(), index_type::end(), x, key_compare{}); first != last; ++first) { + if (a.test(*first)) { + return find(*first); + } + } + return end(); + } + + [[nodiscard]] constexpr bool contains(const key_type& key) const noexcept { return count(key); } + + template + [[nodiscard]] constexpr std::enable_if_t, bool> contains(const K& x) const noexcept { + return count(x) > 0; + } + + [[nodiscard]] constexpr std::pair equal_range(const key_type& key) const noexcept { return {lower_bound(key), upper_bound(key)}; } + + template + [[nodiscard]] constexpr std::enable_if_t, std::pair> equal_range(const K& x) const noexcept { + return {lower_bound(x), upper_bound(x)}; + } + + [[nodiscard]] constexpr const_iterator lower_bound(const key_type& key) const noexcept { + if (auto i = index_type::at(key)) { + auto it = const_iterator{this, index_type::begin(), index_type::end(), index_type::it(*i)}; + return a.test(key) ? it : std::next(it); + } + return end(); + } + + template + [[nodiscard]] constexpr std::enable_if_t, const_iterator> lower_bound(const K& x) const noexcept { + auto [first, last] = detail::equal_range(index_type::begin(), index_type::end(), x, key_compare{}); + return first != last ? lower_bound(*first) : end(); + } + + [[nodiscard]] constexpr const_iterator upper_bound(const key_type& key) const noexcept { + if (auto i = index_type::at(key)) { + return std::next(const_iterator{this, index_type::begin(), index_type::end(), index_type::it(*i)}); + } + return end(); + } + + template + [[nodiscard]] constexpr std::enable_if_t, const_iterator> upper_bound(const K& x) const noexcept { + auto [first, last] = detail::equal_range(index_type::begin(), index_type::end(), x, key_compare{}); + return first != last ? upper_bound(*std::prev(last)) : end(); + } + + [[nodiscard]] constexpr key_compare key_comp() const { return {}; } + + [[nodiscard]] constexpr value_compare value_comp() const { return {}; } + + [[nodiscard]] constexpr friend bool operator==(const set& lhs, const set& rhs) noexcept { return lhs.a == rhs.a; } + + [[nodiscard]] constexpr friend bool operator!=(const set& lhs, const set& rhs) noexcept { return lhs.a != rhs.a; } + + [[nodiscard]] constexpr friend bool operator<(const set& lhs, const set& rhs) noexcept { + if (lhs.s < rhs.s) { + return true; + } + if (rhs.s < lhs.s) { + return false; + } + + for (auto it = index_type::begin(); it != index_type::end(); ++it) { + if (auto c = rhs.contains(*it); c != lhs.contains(*it)) { + return c; + } + } + return false; + } + + [[nodiscard]] constexpr friend bool operator<=(const set& lhs, const set& rhs) noexcept { return !(rhs < lhs); } + + [[nodiscard]] constexpr friend bool operator>(const set& lhs, const set& rhs) noexcept { return rhs < lhs; } + + [[nodiscard]] constexpr friend bool operator>=(const set& lhs, const set& rhs) noexcept { return !(lhs < rhs); } + + template + size_type erase_if(Pred pred) { + auto old_size = size(); + for (auto i = begin(), last = end(); i != last;) { + if (pred(*i)) { + i = erase(i); + } else { + ++i; + } + } + return old_size - size(); + } + + private: + container_type a; + std::size_t s = 0; +}; + +template +explicit set(V starter) -> set; + +template +constexpr std::enable_if_t<(std::is_integral_v && I < enum_count()), V&> get(array& a) noexcept { + return a.a[I]; +} + +template +constexpr std::enable_if_t<(std::is_integral_v && I < enum_count()), V&&> get(array&& a) noexcept { + return std::move(a.a[I]); +} + +template +constexpr std::enable_if_t<(std::is_integral_v && I < enum_count()), const V&> get(const array& a) noexcept { + return a.a[I]; +} + +template +constexpr std::enable_if_t<(std::is_integral_v && I < enum_count()), const V&&> get(const array&& a) noexcept { + return std::move(a.a[I]); +} + +template +constexpr std::enable_if_t && enum_contains(Enum), V&> get(array& a) { + return a[Enum]; +} + +template +constexpr std::enable_if_t && enum_contains(Enum), V&&> get(array&& a) { + return std::move(a[Enum]); +} + +template +constexpr std::enable_if_t && enum_contains(Enum), const V&> get(const array& a) { + return a[Enum]; +} + +template +constexpr std::enable_if_t && enum_contains(Enum), const V&&> get(const array&& a) { + return std::move(a[Enum]); +} + +} // namespace magic_enum::containers + +#endif // NEARGYE_MAGIC_ENUM_CONTAINERS_HPP diff --git a/module/dll_source_lzy/114/out/lib/hulc/magic_enum/magic_enum/magic_enum_flags.hpp b/module/dll_source_lzy/114/out/lib/hulc/magic_enum/magic_enum/magic_enum_flags.hpp new file mode 100644 index 0000000..f2d81b5 --- /dev/null +++ b/module/dll_source_lzy/114/out/lib/hulc/magic_enum/magic_enum/magic_enum_flags.hpp @@ -0,0 +1,222 @@ +// __ __ _ ______ _____ +// | \/ | (_) | ____| / ____|_ _ +// | \ / | __ _ __ _ _ ___ | |__ _ __ _ _ _ __ ___ | | _| |_ _| |_ +// | |\/| |/ _` |/ _` | |/ __| | __| | '_ \| | | | '_ ` _ \ | | |_ _|_ _| +// | | | | (_| | (_| | | (__ | |____| | | | |_| | | | | | | | |____|_| |_| +// |_| |_|\__,_|\__, |_|\___| |______|_| |_|\__,_|_| |_| |_| \_____| +// __/ | https://github.com/Neargye/magic_enum +// |___/ version 0.9.7 +// +// Licensed under the MIT License . +// SPDX-License-Identifier: MIT +// Copyright (c) 2019 - 2024 Daniil Goncharov . +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#ifndef NEARGYE_MAGIC_ENUM_FLAGS_HPP +#define NEARGYE_MAGIC_ENUM_FLAGS_HPP + +#include "magic_enum.hpp" + +#if defined(__clang__) +# pragma clang diagnostic push +#elif defined(__GNUC__) +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wmaybe-uninitialized" // May be used uninitialized 'return {};'. +#elif defined(_MSC_VER) +# pragma warning(push) +#endif + +namespace magic_enum { + +namespace detail { + +template > +constexpr U values_ors() noexcept { + static_assert(S == enum_subtype::flags, "magic_enum::detail::values_ors requires valid subtype."); + + auto ors = U{0}; + for (std::size_t i = 0; i < count_v; ++i) { + ors |= static_cast(values_v[i]); + } + + return ors; +} + +} // namespace magic_enum::detail + +// Returns name from enum-flags value. +// If enum-flags value does not have name or value out of range, returns empty string. +template +[[nodiscard]] auto enum_flags_name(E value, char_type sep = static_cast('|')) -> detail::enable_if_t { + using D = std::decay_t; + using U = underlying_type_t; + constexpr auto S = detail::enum_subtype::flags; + static_assert(detail::is_reflected_v, "magic_enum requires enum implementation and valid max and min."); + + string name; + auto check_value = U{0}; + for (std::size_t i = 0; i < detail::count_v; ++i) { + if (const auto v = static_cast(enum_value(i)); (static_cast(value) & v) != 0) { + if (const auto n = detail::names_v[i]; !n.empty()) { + check_value |= v; + if (!name.empty()) { + name.append(1, sep); + } + name.append(n.data(), n.size()); + } else { + return {}; // Value out of range. + } + } + } + + if (check_value != 0 && check_value == static_cast(value)) { + return name; + } + return {}; // Invalid value or out of range. +} + +// Obtains enum-flags value from integer value. +// Returns optional with enum-flags value. +template +[[nodiscard]] constexpr auto enum_flags_cast(underlying_type_t value) noexcept -> detail::enable_if_t>> { + using D = std::decay_t; + using U = underlying_type_t; + constexpr auto S = detail::enum_subtype::flags; + static_assert(detail::is_reflected_v, "magic_enum requires enum implementation and valid max and min."); + + if constexpr (detail::count_v == 0) { + static_cast(value); + return {}; // Empty enum. + } else { + if constexpr (detail::is_sparse_v) { + auto check_value = U{0}; + for (std::size_t i = 0; i < detail::count_v; ++i) { + if (const auto v = static_cast(enum_value(i)); (value & v) != 0) { + check_value |= v; + } + } + + if (check_value != 0 && check_value == value) { + return static_cast(value); + } + } else { + constexpr auto min = detail::min_v; + constexpr auto max = detail::values_ors(); + + if (value >= min && value <= max) { + return static_cast(value); + } + } + return {}; // Invalid value or out of range. + } +} + +// Obtains enum-flags value from name. +// Returns optional with enum-flags value. +template > +[[nodiscard]] constexpr auto enum_flags_cast(string_view value, [[maybe_unused]] BinaryPredicate p = {}) noexcept(detail::is_nothrow_invocable()) -> detail::enable_if_t>, BinaryPredicate> { + using D = std::decay_t; + using U = underlying_type_t; + constexpr auto S = detail::enum_subtype::flags; + static_assert(detail::is_reflected_v, "magic_enum requires enum implementation and valid max and min."); + + if constexpr (detail::count_v == 0) { + static_cast(value); + return {}; // Empty enum. + } else { + auto result = U{0}; + while (!value.empty()) { + const auto d = detail::find(value, '|'); + const auto s = (d == string_view::npos) ? value : value.substr(0, d); + auto f = U{0}; + for (std::size_t i = 0; i < detail::count_v; ++i) { + if (detail::cmp_equal(s, detail::names_v[i], p)) { + f = static_cast(enum_value(i)); + result |= f; + break; + } + } + if (f == U{0}) { + return {}; // Invalid value or out of range. + } + value.remove_prefix((d == string_view::npos) ? value.size() : d + 1); + } + + if (result != U{0}) { + return static_cast(result); + } + return {}; // Invalid value or out of range. + } +} + +// Checks whether enum-flags contains value with such value. +template +[[nodiscard]] constexpr auto enum_flags_contains(E value) noexcept -> detail::enable_if_t { + using D = std::decay_t; + using U = underlying_type_t; + + return static_cast(enum_flags_cast(static_cast(value))); +} + +// Checks whether enum-flags contains value with such integer value. +template +[[nodiscard]] constexpr auto enum_flags_contains(underlying_type_t value) noexcept -> detail::enable_if_t { + using D = std::decay_t; + + return static_cast(enum_flags_cast(value)); +} + +// Checks whether enum-flags contains enumerator with such name. +template > +[[nodiscard]] constexpr auto enum_flags_contains(string_view value, BinaryPredicate p = {}) noexcept(detail::is_nothrow_invocable()) -> detail::enable_if_t { + using D = std::decay_t; + + return static_cast(enum_flags_cast(value, std::move(p))); +} + +// Checks whether `flags set` contains `flag`. +// Note: If `flag` equals 0, it returns false, as 0 is not a flag. +template +constexpr auto enum_flags_test(E flags, E flag) noexcept -> detail::enable_if_t { + using U = underlying_type_t; + + return static_cast(flag) && ((static_cast(flags) & static_cast(flag)) == static_cast(flag)); +} + +// Checks whether `lhs flags set` and `rhs flags set` have common flags. +// Note: If `lhs flags set` or `rhs flags set` equals 0, it returns false, as 0 is not a flag, and therfore cannot have any matching flag. +template +constexpr auto enum_flags_test_any(E lhs, E rhs) noexcept -> detail::enable_if_t { + using U = underlying_type_t; + + return (static_cast(lhs) & static_cast(rhs)) != 0; +} + +} // namespace magic_enum + +#if defined(__clang__) +# pragma clang diagnostic pop +#elif defined(__GNUC__) +# pragma GCC diagnostic pop +#elif defined(_MSC_VER) +# pragma warning(pop) +#endif + +#endif // NEARGYE_MAGIC_ENUM_FLAGS_HPP diff --git a/module/dll_source_lzy/114/out/lib/hulc/magic_enum/magic_enum/magic_enum_format.hpp b/module/dll_source_lzy/114/out/lib/hulc/magic_enum/magic_enum/magic_enum_format.hpp new file mode 100644 index 0000000..f10371f --- /dev/null +++ b/module/dll_source_lzy/114/out/lib/hulc/magic_enum/magic_enum/magic_enum_format.hpp @@ -0,0 +1,114 @@ +// __ __ _ ______ _____ +// | \/ | (_) | ____| / ____|_ _ +// | \ / | __ _ __ _ _ ___ | |__ _ __ _ _ _ __ ___ | | _| |_ _| |_ +// | |\/| |/ _` |/ _` | |/ __| | __| | '_ \| | | | '_ ` _ \ | | |_ _|_ _| +// | | | | (_| | (_| | | (__ | |____| | | | |_| | | | | | | | |____|_| |_| +// |_| |_|\__,_|\__, |_|\___| |______|_| |_|\__,_|_| |_| |_| \_____| +// __/ | https://github.com/Neargye/magic_enum +// |___/ version 0.9.7 +// +// Licensed under the MIT License . +// SPDX-License-Identifier: MIT +// Copyright (c) 2019 - 2024 Daniil Goncharov . +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#ifndef NEARGYE_MAGIC_ENUM_FORMAT_HPP +#define NEARGYE_MAGIC_ENUM_FORMAT_HPP + +#include "magic_enum.hpp" +#include "magic_enum_flags.hpp" + +#if !defined(MAGIC_ENUM_DEFAULT_ENABLE_ENUM_FORMAT) +# define MAGIC_ENUM_DEFAULT_ENABLE_ENUM_FORMAT 1 +# define MAGIC_ENUM_DEFAULT_ENABLE_ENUM_FORMAT_AUTO_DEFINE +#endif + +namespace magic_enum::customize { + // customize enum to enable/disable automatic std::format + template + constexpr bool enum_format_enabled() noexcept { + return MAGIC_ENUM_DEFAULT_ENABLE_ENUM_FORMAT; + } +} // magic_enum::customize + +#if defined(__cpp_lib_format) + +#ifndef MAGIC_ENUM_USE_STD_MODULE +#include +#endif + +template +struct std::formatter> && magic_enum::customize::enum_format_enabled(), char>> : std::formatter { + template + auto format(E e, FormatContext& ctx) const { + static_assert(std::is_same_v, "formatter requires string_view::value_type type same as char."); + using D = std::decay_t; + + if constexpr (magic_enum::detail::supported::value) { + if constexpr (magic_enum::detail::subtype_v == magic_enum::detail::enum_subtype::flags) { + if (const auto name = magic_enum::enum_flags_name(e); !name.empty()) { + return formatter::format(std::string_view{name.data(), name.size()}, ctx); + } + } else { + if (const auto name = magic_enum::enum_name(e); !name.empty()) { + return formatter::format(std::string_view{name.data(), name.size()}, ctx); + } + } + } + return formatter::format(std::to_string(magic_enum::enum_integer(e)), ctx); + } +}; + +#endif + +#if defined(FMT_VERSION) + +#include +struct fmt::formatter> && magic_enum::customize::enum_format_enabled(), char>> : fmt::formatter { + template + auto format(E e, FormatContext& ctx) const { + static_assert(std::is_same_v, "formatter requires string_view::value_type type same as char."); + using D = std::decay_t; + + if constexpr (magic_enum::detail::supported::value) { + if constexpr (magic_enum::detail::subtype_v == magic_enum::detail::enum_subtype::flags) { + if (const auto name = magic_enum::enum_flags_name(e); !name.empty()) { + return formatter::format(std::string_view{name.data(), name.size()}, ctx); + } + } else { + if (const auto name = magic_enum::enum_name(e); !name.empty()) { + return formatter::format(std::string_view{name.data(), name.size()}, ctx); + } + } + } + return formatter::format(std::to_string(magic_enum::enum_integer(e)), ctx); + } +}; + +#endif + +#if defined(MAGIC_ENUM_DEFAULT_ENABLE_ENUM_FORMAT_AUTO_DEFINE) +# undef MAGIC_ENUM_DEFAULT_ENABLE_ENUM_FORMAT +# undef MAGIC_ENUM_DEFAULT_ENABLE_ENUM_FORMAT_AUTO_DEFINE +#endif + +#endif // NEARGYE_MAGIC_ENUM_FORMAT_HPP diff --git a/module/dll_source_lzy/114/out/lib/hulc/magic_enum/magic_enum/magic_enum_fuse.hpp b/module/dll_source_lzy/114/out/lib/hulc/magic_enum/magic_enum/magic_enum_fuse.hpp new file mode 100644 index 0000000..6b2a3ef --- /dev/null +++ b/module/dll_source_lzy/114/out/lib/hulc/magic_enum/magic_enum/magic_enum_fuse.hpp @@ -0,0 +1,89 @@ +// __ __ _ ______ _____ +// | \/ | (_) | ____| / ____|_ _ +// | \ / | __ _ __ _ _ ___ | |__ _ __ _ _ _ __ ___ | | _| |_ _| |_ +// | |\/| |/ _` |/ _` | |/ __| | __| | '_ \| | | | '_ ` _ \ | | |_ _|_ _| +// | | | | (_| | (_| | | (__ | |____| | | | |_| | | | | | | | |____|_| |_| +// |_| |_|\__,_|\__, |_|\___| |______|_| |_|\__,_|_| |_| |_| \_____| +// __/ | https://github.com/Neargye/magic_enum +// |___/ version 0.9.7 +// +// Licensed under the MIT License . +// SPDX-License-Identifier: MIT +// Copyright (c) 2019 - 2024 Daniil Goncharov . +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#ifndef NEARGYE_MAGIC_ENUM_FUSE_HPP +#define NEARGYE_MAGIC_ENUM_FUSE_HPP + +#include "magic_enum.hpp" + +namespace magic_enum { + +namespace detail { + +template +constexpr optional fuse_one_enum(optional hash, E value) noexcept { + if (hash) { + if (const auto index = enum_index(value)) { + return (*hash << log2((enum_count() << 1) - 1)) | *index; + } + } + return {}; +} + +template +constexpr optional fuse_enum(E value) noexcept { + return fuse_one_enum(0, value); +} + +template +constexpr optional fuse_enum(E head, Es... tail) noexcept { + return fuse_one_enum(fuse_enum(tail...), head); +} + +template +constexpr auto typesafe_fuse_enum(Es... values) noexcept { + enum class enum_fuse_t : std::uintmax_t; + const auto fuse = fuse_enum(values...); + if (fuse) { + return optional{static_cast(*fuse)}; + } + return optional{}; +} + +} // namespace magic_enum::detail + +// Returns a bijective mix of several enum values. This can be used to emulate 2D switch/case statements. +template +[[nodiscard]] constexpr auto enum_fuse(Es... values) noexcept { + static_assert((std::is_enum_v> && ...), "magic_enum::enum_fuse requires enum type."); + static_assert(sizeof...(Es) >= 2, "magic_enum::enum_fuse requires at least 2 values."); + static_assert((detail::log2(enum_count>() + 1) + ...) <= (sizeof(std::uintmax_t) * 8), "magic_enum::enum_fuse does not work for large enums"); +#if defined(MAGIC_ENUM_NO_TYPESAFE_ENUM_FUSE) + const auto fuse = detail::fuse_enum...>(values...); +#else + const auto fuse = detail::typesafe_fuse_enum...>(values...); +#endif + return MAGIC_ENUM_ASSERT(fuse), fuse; +} + +} // namespace magic_enum + +#endif // NEARGYE_MAGIC_ENUM_FUSE_HPP diff --git a/module/dll_source_lzy/114/out/lib/hulc/magic_enum/magic_enum/magic_enum_iostream.hpp b/module/dll_source_lzy/114/out/lib/hulc/magic_enum/magic_enum/magic_enum_iostream.hpp new file mode 100644 index 0000000..6130dcb --- /dev/null +++ b/module/dll_source_lzy/114/out/lib/hulc/magic_enum/magic_enum/magic_enum_iostream.hpp @@ -0,0 +1,117 @@ +// __ __ _ ______ _____ +// | \/ | (_) | ____| / ____|_ _ +// | \ / | __ _ __ _ _ ___ | |__ _ __ _ _ _ __ ___ | | _| |_ _| |_ +// | |\/| |/ _` |/ _` | |/ __| | __| | '_ \| | | | '_ ` _ \ | | |_ _|_ _| +// | | | | (_| | (_| | | (__ | |____| | | | |_| | | | | | | | |____|_| |_| +// |_| |_|\__,_|\__, |_|\___| |______|_| |_|\__,_|_| |_| |_| \_____| +// __/ | https://github.com/Neargye/magic_enum +// |___/ version 0.9.7 +// +// Licensed under the MIT License . +// SPDX-License-Identifier: MIT +// Copyright (c) 2019 - 2024 Daniil Goncharov . +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#ifndef NEARGYE_MAGIC_ENUM_IOSTREAM_HPP +#define NEARGYE_MAGIC_ENUM_IOSTREAM_HPP + +#include "magic_enum.hpp" +#include "magic_enum_flags.hpp" + +#ifndef MAGIC_ENUM_USE_STD_MODULE +#include +#endif + +namespace magic_enum { + +namespace ostream_operators { + +template = 0> +std::basic_ostream& operator<<(std::basic_ostream& os, E value) { + using D = std::decay_t; + using U = underlying_type_t; + + if constexpr (detail::supported::value) { + if constexpr (detail::subtype_v == detail::enum_subtype::flags) { + if (const auto name = enum_flags_name(value); !name.empty()) { + for (const auto c : name) { + os.put(c); + } + return os; + } + } else { + if (const auto name = enum_name(value); !name.empty()) { + for (const auto c : name) { + os.put(c); + } + return os; + } + } + } + return (os << static_cast(value)); +} + +template = 0> +std::basic_ostream& operator<<(std::basic_ostream& os, optional value) { + return value ? (os << *value) : os; +} + +} // namespace magic_enum::ostream_operators + +namespace istream_operators { + +template = 0> +std::basic_istream& operator>>(std::basic_istream& is, E& value) { + using D = std::decay_t; + + std::basic_string s; + is >> s; + if constexpr (detail::supported::value) { + if constexpr (detail::subtype_v == detail::enum_subtype::flags) { + if (const auto v = enum_flags_cast(s)) { + value = *v; + } else { + is.setstate(std::basic_ios::failbit); + } + } else { + if (const auto v = enum_cast(s)) { + value = *v; + } else { + is.setstate(std::basic_ios::failbit); + } + } + } else { + is.setstate(std::basic_ios::failbit); + } + return is; +} + +} // namespace magic_enum::istream_operators + +namespace iostream_operators { + +using magic_enum::ostream_operators::operator<<; +using magic_enum::istream_operators::operator>>; + +} // namespace magic_enum::iostream_operators + +} // namespace magic_enum + +#endif // NEARGYE_MAGIC_ENUM_IOSTREAM_HPP diff --git a/module/dll_source_lzy/114/out/lib/hulc/magic_enum/magic_enum/magic_enum_switch.hpp b/module/dll_source_lzy/114/out/lib/hulc/magic_enum/magic_enum/magic_enum_switch.hpp new file mode 100644 index 0000000..63fc19a --- /dev/null +++ b/module/dll_source_lzy/114/out/lib/hulc/magic_enum/magic_enum/magic_enum_switch.hpp @@ -0,0 +1,195 @@ +// __ __ _ ______ _____ +// | \/ | (_) | ____| / ____|_ _ +// | \ / | __ _ __ _ _ ___ | |__ _ __ _ _ _ __ ___ | | _| |_ _| |_ +// | |\/| |/ _` |/ _` | |/ __| | __| | '_ \| | | | '_ ` _ \ | | |_ _|_ _| +// | | | | (_| | (_| | | (__ | |____| | | | |_| | | | | | | | |____|_| |_| +// |_| |_|\__,_|\__, |_|\___| |______|_| |_|\__,_|_| |_| |_| \_____| +// __/ | https://github.com/Neargye/magic_enum +// |___/ version 0.9.7 +// +// Licensed under the MIT License . +// SPDX-License-Identifier: MIT +// Copyright (c) 2019 - 2024 Daniil Goncharov . +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#ifndef NEARGYE_MAGIC_ENUM_SWITCH_HPP +#define NEARGYE_MAGIC_ENUM_SWITCH_HPP + +#include "magic_enum.hpp" + +namespace magic_enum { + +namespace detail { + +struct default_result_type {}; + +template +struct identity { + using type = T; +}; + +struct nonesuch {}; + +template > +struct invoke_result : identity {}; + +template +struct invoke_result : std::invoke_result {}; + +template +using invoke_result_t = typename invoke_result::type; + +template +constexpr auto common_invocable(std::index_sequence) noexcept { + static_assert(std::is_enum_v, "magic_enum::detail::invocable_index requires enum type."); + + if constexpr (count_v == 0) { + return identity{}; + } else { + return std::common_type[I]>>...>{}; + } +} + +template +constexpr auto result_type() noexcept { + static_assert(std::is_enum_v, "magic_enum::detail::result_type requires enum type."); + + constexpr auto seq = std::make_index_sequence>{}; + using R = typename decltype(common_invocable(seq))::type; + if constexpr (std::is_same_v) { + if constexpr (std::is_same_v) { + return identity{}; + } else { + return identity{}; + } + } else { + if constexpr (std::is_convertible_v) { + return identity{}; + } else if constexpr (std::is_convertible_v) { + return identity{}; + } else { + return identity{}; + } + } +} + +template , typename R = typename decltype(result_type())::type> +using result_t = std::enable_if_t && !std::is_same_v, R>; + +#if !defined(MAGIC_ENUM_ENABLE_HASH) && !defined(MAGIC_ENUM_ENABLE_HASH_SWITCH) + +template +inline constexpr auto default_result_type_lambda = []() noexcept(std::is_nothrow_default_constructible_v) { return T{}; }; + +template <> +inline constexpr auto default_result_type_lambda = []() noexcept {}; + +template +constexpr decltype(auto) constexpr_switch_impl(F&& f, E value, Def&& def) { + if constexpr(I < End) { + constexpr auto v = enum_constant()>{}; + if (value == v) { + if constexpr (std::is_invocable_r_v) { + return static_cast(std::forward(f)(v)); + } else { + return def(); + } + } else { + return constexpr_switch_impl(std::forward(f), value, std::forward(def)); + } + } else { + return def(); + } +} + +template +constexpr decltype(auto) constexpr_switch(F&& f, E value, Def&& def) { + static_assert(is_enum_v, "magic_enum::detail::constexpr_switch requires enum type."); + + if constexpr (count_v == 0) { + return def(); + } else { + return constexpr_switch_impl<0, count_v, R, E, S>(std::forward(f), value, std::forward(def)); + } +} +#endif + +} // namespace magic_enum::detail + +template , typename F, typename R = detail::result_t> +constexpr decltype(auto) enum_switch(F&& f, E value) { + using D = std::decay_t; + static_assert(std::is_enum_v, "magic_enum::enum_switch requires enum type."); + static_assert(detail::is_reflected_v, "magic_enum requires enum implementation and valid max and min."); + +#if defined(MAGIC_ENUM_ENABLE_HASH) || defined(MAGIC_ENUM_ENABLE_HASH_SWITCH) + return detail::constexpr_switch<&detail::values_v, detail::case_call_t::value>( + std::forward(f), + value, + detail::default_result_type_lambda); +#else + return detail::constexpr_switch( + std::forward(f), + value, + detail::default_result_type_lambda); +#endif +} + +template > +constexpr decltype(auto) enum_switch(F&& f, E value) { + return enum_switch(std::forward(f), value); +} + +template , typename F, typename R = detail::result_t> +constexpr decltype(auto) enum_switch(F&& f, E value, Result&& result) { + using D = std::decay_t; + static_assert(std::is_enum_v, "magic_enum::enum_switch requires enum type."); + static_assert(detail::is_reflected_v, "magic_enum requires enum implementation and valid max and min."); + +#if defined(MAGIC_ENUM_ENABLE_HASH) || defined(MAGIC_ENUM_ENABLE_HASH_SWITCH) + return detail::constexpr_switch<&detail::values_v, detail::case_call_t::value>( + std::forward(f), + value, + [&result]() -> R { return std::forward(result); }); +#else + return detail::constexpr_switch( + std::forward(f), + value, + [&result]() -> R { return std::forward(result); }); +#endif +} + +template > +constexpr decltype(auto) enum_switch(F&& f, E value, Result&& result) { + return enum_switch(std::forward(f), value, std::forward(result)); +} + +} // namespace magic_enum + +template <> +struct std::common_type : magic_enum::detail::identity {}; + +template +struct std::common_type : magic_enum::detail::identity {}; + +template +struct std::common_type : magic_enum::detail::identity {}; + +#endif // NEARGYE_MAGIC_ENUM_SWITCH_HPP diff --git a/module/dll_source_lzy/114/out/lib/hulc/magic_enum/magic_enum/magic_enum_utility.hpp b/module/dll_source_lzy/114/out/lib/hulc/magic_enum/magic_enum/magic_enum_utility.hpp new file mode 100644 index 0000000..5368b02 --- /dev/null +++ b/module/dll_source_lzy/114/out/lib/hulc/magic_enum/magic_enum/magic_enum_utility.hpp @@ -0,0 +1,138 @@ +// __ __ _ ______ _____ +// | \/ | (_) | ____| / ____|_ _ +// | \ / | __ _ __ _ _ ___ | |__ _ __ _ _ _ __ ___ | | _| |_ _| |_ +// | |\/| |/ _` |/ _` | |/ __| | __| | '_ \| | | | '_ ` _ \ | | |_ _|_ _| +// | | | | (_| | (_| | | (__ | |____| | | | |_| | | | | | | | |____|_| |_| +// |_| |_|\__,_|\__, |_|\___| |______|_| |_|\__,_|_| |_| |_| \_____| +// __/ | https://github.com/Neargye/magic_enum +// |___/ version 0.9.7 +// +// Licensed under the MIT License . +// SPDX-License-Identifier: MIT +// Copyright (c) 2019 - 2024 Daniil Goncharov . +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#ifndef NEARGYE_MAGIC_ENUM_UTILITY_HPP +#define NEARGYE_MAGIC_ENUM_UTILITY_HPP + +#include "magic_enum.hpp" + +namespace magic_enum { + +namespace detail { + +template +constexpr auto for_each(F&& f, std::index_sequence) { + constexpr bool has_void_return = (std::is_void_v[I]>>> || ...); + constexpr bool all_same_return = (std::is_same_v[0]>>, std::invoke_result_t[I]>>> && ...); + + if constexpr (has_void_return) { + (f(enum_constant[I]>{}), ...); + } else if constexpr (all_same_return) { + return std::array{f(enum_constant[I]>{})...}; + } else { + return std::tuple{f(enum_constant[I]>{})...}; + } +} + +template +constexpr bool all_invocable(std::index_sequence) { + if constexpr (count_v == 0) { + return false; + } else { + return (std::is_invocable_v[I]>> && ...); + } +} + +} // namespace magic_enum::detail + +template , typename F, detail::enable_if_t = 0> +constexpr auto enum_for_each(F&& f) { + using D = std::decay_t; + static_assert(std::is_enum_v, "magic_enum::enum_for_each requires enum type."); + static_assert(detail::is_reflected_v, "magic_enum requires enum implementation and valid max and min."); + constexpr auto sep = std::make_index_sequence>{}; + + if constexpr (detail::all_invocable(sep)) { + return detail::for_each(std::forward(f), sep); + } else { + static_assert(detail::always_false_v, "magic_enum::enum_for_each requires invocable of all enum value."); + } +} + +template > +[[nodiscard]] constexpr auto enum_next_value(E value, std::ptrdiff_t n = 1) noexcept -> detail::enable_if_t>> { + using D = std::decay_t; + constexpr std::ptrdiff_t count = detail::count_v; + + if (const auto i = enum_index(value)) { + const std::ptrdiff_t index = (static_cast(*i) + n); + if (index >= 0 && index < count) { + return enum_value(static_cast(index)); + } + } + return {}; +} + +template > +[[nodiscard]] constexpr auto enum_next_value_circular(E value, std::ptrdiff_t n = 1) noexcept -> detail::enable_if_t> { + using D = std::decay_t; + constexpr std::ptrdiff_t count = detail::count_v; + + if (const auto i = enum_index(value)) { + const std::ptrdiff_t index = ((((static_cast(*i) + n) % count) + count) % count); + if (index >= 0 && index < count) { + return enum_value(static_cast(index)); + } + } + return MAGIC_ENUM_ASSERT(false), value; +} + +template > +[[nodiscard]] constexpr auto enum_prev_value(E value, std::ptrdiff_t n = 1) noexcept -> detail::enable_if_t>> { + using D = std::decay_t; + constexpr std::ptrdiff_t count = detail::count_v; + + if (const auto i = enum_index(value)) { + const std::ptrdiff_t index = (static_cast(*i) - n); + if (index >= 0 && index < count) { + return enum_value(static_cast(index)); + } + } + return {}; +} + +template > +[[nodiscard]] constexpr auto enum_prev_value_circular(E value, std::ptrdiff_t n = 1) noexcept -> detail::enable_if_t> { + using D = std::decay_t; + constexpr std::ptrdiff_t count = detail::count_v; + + if (const auto i = enum_index(value)) { + const std::ptrdiff_t index = ((((static_cast(*i) - n) % count) + count) % count); + if (index >= 0 && index < count) { + return enum_value(static_cast(index)); + } + } + return MAGIC_ENUM_ASSERT(false), value; +} + +} // namespace magic_enum + +#endif // NEARGYE_MAGIC_ENUM_UTILITY_HPP diff --git a/module/dll_source_lzy/114/out/lib/log.txt b/module/dll_source_lzy/114/out/lib/log.txt new file mode 100644 index 0000000..b310560 --- /dev/null +++ b/module/dll_source_lzy/114/out/lib/log.txt @@ -0,0 +1,1443 @@ +findDevices success! +openDevice success! + addr = 0x42c0val = 0 +[func~] Server_Socket:[0.0.0.0:10003] 添加了连接 [fd:12:[192.168.1.110:49424]] + addr = 0x42e4val = 1762950288 + addr = 0x42e0val = 0 +startDevRecv success! + addr = 0x42c0val = 0 + addr = 0x42e4val = 1762950288 + addr = 0x42e0val = 0 +startDevRecv success! +chstrRX0 dataType:7 ZDCh0 bSwitch0 + addr = 0x4210val = 0 + addr = 0x4280val = 0 + addr = 0x4284val = 0 + addr = 0x4280val = 0 + addr = 0x4284val = 0 + addr = 0x4210val = 3 +chstrRX0 dataType:6 ZDCh0 bSwitch0 + addr = 0x4210val = 0 + addr = 0x4220val = 0 + addr = 0x4220val = 0 + addr = 0x4210val = 3 +chstrRX0 dataType:5 ZDCh0 bSwitch0 + addr = 0x4210val = 0 + addr = 0x4280val = 0 + addr = 0x4284val = 0 + addr = 0x4240val = 0 + addr = 0x4240val = 0 + addr = 0x4210val = 3 +chstrRX1 dataType:7 ZDCh8 bSwitch0 + addr = 0x4210val = 0 + addr = 0x4280val = 8 + addr = 0x4284val = 0 + addr = 0x4280val = 8 + addr = 0x4284val = 0 + addr = 0x4210val = 3 +chstrRX1 dataType:6 ZDCh0 bSwitch0 + addr = 0x4210val = 0 + addr = 0x4220val = 0 + addr = 0x4220val = 0 + addr = 0x4210val = 3 +chstrRX1 dataType:5 ZDCh0 bSwitch0 + addr = 0x4210val = 0 + addr = 0x4280val = 0 + addr = 0x4284val = 0 + addr = 0x4240val = 0 + addr = 0x4240val = 0 + addr = 0x4210val = 3 +chstrRX0 paramType:0 paramValue1.089e+09 + addr = 0x4210val = 0 + addr = 0x4234val = 0 + addr = 0x4208val = 1 + addr = 0x4264val = 0 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4268val = 0 + addr = 0x4248val = 0 + addr = 0x4244val = 0 + addr = 0x424cval = 0 + addr = 0x4250val = 1089000000 + addr = 0x4210val = 3 +chstrRX0 paramType:1 paramValue6e+06 + addr = 0x4210val = 0 + addr = 0x4234val = 0 + addr = 0x4208val = 1 + addr = 0x4264val = 0 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4268val = 0 + addr = 0x4248val = 6000000 + addr = 0x4244val = 0 + addr = 0x424cval = 0 + addr = 0x4250val = 1089000000 + addr = 0x4210val = 3 +chstrRX0 paramType:2 paramValue2.4e+07 + addr = 0x4210val = 0 + addr = 0x4234val = 0 + addr = 0x4208val = 1 + addr = 0x4264val = 0 + addr = 0x4270val = -20 + addr = 0x4270val = -50 + addr = 0x4270val = -52 + addr = 0x4270val = -22 + addr = 0x4270val = 24 + addr = 0x4270val = 62 + addr = 0x4270val = 67 + addr = 0x4270val = 30 + addr = 0x4270val = -33 + addr = 0x4270val = -88 + addr = 0x4270val = -97 + addr = 0x4270val = -45 + addr = 0x4270val = 49 + addr = 0x4270val = 131 + addr = 0x4270val = 145 + addr = 0x4270val = 66 + addr = 0x4270val = -73 + addr = 0x4270val = -194 + addr = 0x4270val = -213 + addr = 0x4270val = -97 + addr = 0x4270val = 106 + addr = 0x4270val = 278 + addr = 0x4270val = 304 + addr = 0x4270val = 137 + addr = 0x4270val = -149 + addr = 0x4270val = -390 + addr = 0x4270val = -423 + addr = 0x4270val = -190 + addr = 0x4270val = 205 + addr = 0x4270val = 534 + addr = 0x4270val = 576 + addr = 0x4270val = 257 + addr = 0x4270val = -277 + addr = 0x4270val = -719 + addr = 0x4270val = -773 + addr = 0x4270val = -344 + addr = 0x4270val = 370 + addr = 0x4270val = 958 + addr = 0x4270val = 1029 + addr = 0x4270val = 458 + addr = 0x4270val = -491 + addr = 0x4270val = -1275 + addr = 0x4270val = -1370 + addr = 0x4270val = -610 + addr = 0x4270val = 657 + addr = 0x4270val = 1711 + addr = 0x4270val = 1848 + addr = 0x4270val = 828 + addr = 0x4270val = -898 + addr = 0x4270val = -2359 + addr = 0x4270val = -2576 + addr = 0x4270val = -1170 + addr = 0x4270val = 1289 + addr = 0x4270val = 3452 + addr = 0x4270val = 3859 + addr = 0x4270val = 1805 + addr = 0x4270val = -2064 + addr = 0x4270val = -5796 + addr = 0x4270val = -6897 + addr = 0x4270val = -3511 + addr = 0x4270val = 4535 + addr = 0x4270val = 15380 + addr = 0x4270val = 25691 + addr = 0x4270val = 31960 + addr = 0x4270val = 31960 + addr = 0x4270val = 25691 + addr = 0x4270val = 15380 + addr = 0x4270val = 4535 + addr = 0x4270val = -3511 + addr = 0x4270val = -6897 + addr = 0x4270val = -5796 + addr = 0x4270val = -2064 + addr = 0x4270val = 1805 + addr = 0x4270val = 3859 + addr = 0x4270val = 3452 + addr = 0x4270val = 1289 + addr = 0x4270val = -1170 + addr = 0x4270val = -2576 + addr = 0x4270val = -2359 + addr = 0x4270val = -898 + addr = 0x4270val = 828 + addr = 0x4270val = 1848 + addr = 0x4270val = 1711 + addr = 0x4270val = 657 + addr = 0x4270val = -610 + addr = 0x4270val = -1370 + addr = 0x4270val = -1275 + addr = 0x4270val = -491 + addr = 0x4270val = 458 + addr = 0x4270val = 1029 + addr = 0x4270val = 958 + addr = 0x4270val = 370 + addr = 0x4270val = -344 + addr = 0x4270val = -773 + addr = 0x4270val = -719 + addr = 0x4270val = -277 + addr = 0x4270val = 257 + addr = 0x4270val = 576 + addr = 0x4270val = 534 + addr = 0x4270val = 205 + addr = 0x4270val = -190 + addr = 0x4270val = -423 + addr = 0x4270val = -390 + addr = 0x4270val = -149 + addr = 0x4270val = 137 + addr = 0x4270val = 304 + addr = 0x4270val = 278 + addr = 0x4270val = 106 + addr = 0x4270val = -97 + addr = 0x4270val = -213 + addr = 0x4270val = -194 + addr = 0x4270val = -73 + addr = 0x4270val = 66 + addr = 0x4270val = 145 + addr = 0x4270val = 131 + addr = 0x4270val = 49 + addr = 0x4270val = -45 + addr = 0x4270val = -97 + addr = 0x4270val = -88 + addr = 0x4270val = -33 + addr = 0x4270val = 30 + addr = 0x4270val = 67 + addr = 0x4270val = 62 + addr = 0x4270val = 24 + addr = 0x4270val = -22 + addr = 0x4270val = -52 + addr = 0x4270val = -50 + addr = 0x4270val = -20 + addr = 0x4268val = 0 + addr = 0x4248val = 6000000 + addr = 0x4244val = 24000000 + addr = 0x424cval = 0 + addr = 0x4250val = 1089000000 + addr = 0x4210val = 3 +chstrRX0 paramType:3 paramValue30 + addr = 0x4210val = 0 +chstrRX1 paramType:0 paramValue1.5e+07 + addr = 0x4210val = 0 + addr = 0x423cval = 0 + addr = 0x427cval = 0 + addr = 0x4208val = 1 + addr = 0x4264val = 1 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x426cval = 0 + addr = 0x4258val = 0 + addr = 0x4254val = 0 + addr = 0x425cval = 0 + addr = 0x4260val = 15000000 + addr = 0x4210val = 3 +chstrRX1 paramType:1 paramValue3e+07 + addr = 0x4210val = 0 + addr = 0x423cval = 0 + addr = 0x427cval = 0 + addr = 0x4208val = 1 + addr = 0x4264val = 1 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x4270val = -2147483648 + addr = 0x426cval = 0 + addr = 0x4258val = 30000000 + addr = 0x4254val = 0 + addr = 0x425cval = 0 + addr = 0x4260val = 15000000 + addr = 0x4210val = 3 +chstrRX1 paramType:2 paramValue6.144e+07 + addr = 0x4210val = 0 + addr = 0x423cval = 0 + addr = 0x427cval = 0 + addr = 0x4208val = 1 + addr = 0x4264val = 1 + addr = 0x4270val = -1 + addr = 0x4270val = 54 + addr = 0x4270val = 5 + addr = 0x4270val = -58 + addr = 0x4270val = -10 + addr = 0x4270val = 66 + addr = 0x4270val = 17 + addr = 0x4270val = -76 + addr = 0x4270val = -27 + addr = 0x4270val = 90 + addr = 0x4270val = 40 + addr = 0x4270val = -106 + addr = 0x4270val = -57 + addr = 0x4270val = 125 + addr = 0x4270val = 80 + addr = 0x4270val = -145 + addr = 0x4270val = -109 + addr = 0x4270val = 167 + addr = 0x4270val = 145 + addr = 0x4270val = -190 + addr = 0x4270val = -189 + addr = 0x4270val = 212 + addr = 0x4270val = 242 + addr = 0x4270val = -232 + addr = 0x4270val = -305 + addr = 0x4270val = 249 + addr = 0x4270val = 378 + addr = 0x4270val = -262 + addr = 0x4270val = -464 + addr = 0x4270val = 269 + addr = 0x4270val = 561 + addr = 0x4270val = -268 + addr = 0x4270val = -672 + addr = 0x4270val = 257 + addr = 0x4270val = 798 + addr = 0x4270val = -234 + addr = 0x4270val = -940 + addr = 0x4270val = 196 + addr = 0x4270val = 1099 + addr = 0x4270val = -139 + addr = 0x4270val = -1278 + addr = 0x4270val = 59 + addr = 0x4270val = 1481 + addr = 0x4270val = 49 + addr = 0x4270val = -1711 + addr = 0x4270val = -193 + addr = 0x4270val = 1977 + addr = 0x4270val = 383 + addr = 0x4270val = -2290 + addr = 0x4270val = -635 + addr = 0x4270val = 2669 + addr = 0x4270val = 975 + addr = 0x4270val = -3146 + addr = 0x4270val = -1449 + addr = 0x4270val = 3781 + addr = 0x4270val = 2143 + addr = 0x4270val = -4703 + addr = 0x4270val = -3254 + addr = 0x4270val = 6223 + addr = 0x4270val = 5322 + addr = 0x4270val = -9373 + addr = 0x4270val = -10624 + addr = 0x4270val = 20689 + addr = 0x4270val = 57875 + addr = 0x4270val = 57875 + addr = 0x4270val = 20689 + addr = 0x4270val = -10624 + addr = 0x4270val = -9373 + addr = 0x4270val = 5322 + addr = 0x4270val = 6223 + addr = 0x4270val = -3254 + addr = 0x4270val = -4703 + addr = 0x4270val = 2143 + addr = 0x4270val = 3781 + addr = 0x4270val = -1449 + addr = 0x4270val = -3146 + addr = 0x4270val = 975 + addr = 0x4270val = 2669 + addr = 0x4270val = -635 + addr = 0x4270val = -2290 + addr = 0x4270val = 383 + addr = 0x4270val = 1977 + addr = 0x4270val = -193 + addr = 0x4270val = -1711 + addr = 0x4270val = 49 + addr = 0x4270val = 1481 + addr = 0x4270val = 59 + addr = 0x4270val = -1278 + addr = 0x4270val = -139 + addr = 0x4270val = 1099 + addr = 0x4270val = 196 + addr = 0x4270val = -940 + addr = 0x4270val = -234 + addr = 0x4270val = 798 + addr = 0x4270val = 257 + addr = 0x4270val = -672 + addr = 0x4270val = -268 + addr = 0x4270val = 561 + addr = 0x4270val = 269 + addr = 0x4270val = -464 + addr = 0x4270val = -262 + addr = 0x4270val = 378 + addr = 0x4270val = 249 + addr = 0x4270val = -305 + addr = 0x4270val = -232 + addr = 0x4270val = 242 + addr = 0x4270val = 212 + addr = 0x4270val = -189 + addr = 0x4270val = -190 + addr = 0x4270val = 145 + addr = 0x4270val = 167 + addr = 0x4270val = -109 + addr = 0x4270val = -145 + addr = 0x4270val = 80 + addr = 0x4270val = 125 + addr = 0x4270val = -57 + addr = 0x4270val = -106 + addr = 0x4270val = 40 + addr = 0x4270val = 90 + addr = 0x4270val = -27 + addr = 0x4270val = -76 + addr = 0x4270val = 17 + addr = 0x4270val = 66 + addr = 0x4270val = -10 + addr = 0x4270val = -58 + addr = 0x4270val = 5 + addr = 0x4270val = 54 + addr = 0x4270val = -1 + addr = 0x426cval = 0 + addr = 0x4258val = 30000000 + addr = 0x4254val = 61440000 + addr = 0x425cval = 0 + addr = 0x4260val = 15000000 + addr = 0x4210val = 3 +chstrRX1 paramType:3 paramValue30 + addr = 0x4210val = 0 +chstr:RX0 centerfreq:1090000000 bw:3000000 sample:12000000 + addr = 0x4280val = 0 + addr = 0x4288val = 1 + addr = 0x428cval = 3000000 + addr = 0x4290val = 178956970 + addr = 0x4294val = -20 + addr = 0x4294val = -50 + addr = 0x4294val = -52 + addr = 0x4294val = -22 + addr = 0x4294val = 24 + addr = 0x4294val = 62 + addr = 0x4294val = 67 + addr = 0x4294val = 30 + addr = 0x4294val = -33 + addr = 0x4294val = -88 + addr = 0x4294val = -97 + addr = 0x4294val = -45 + addr = 0x4294val = 49 + addr = 0x4294val = 131 + addr = 0x4294val = 145 + addr = 0x4294val = 66 + addr = 0x4294val = -73 + addr = 0x4294val = -194 + addr = 0x4294val = -213 + addr = 0x4294val = -97 + addr = 0x4294val = 106 + addr = 0x4294val = 278 + addr = 0x4294val = 304 + addr = 0x4294val = 137 + addr = 0x4294val = -149 + addr = 0x4294val = -390 + addr = 0x4294val = -423 + addr = 0x4294val = -190 + addr = 0x4294val = 205 + addr = 0x4294val = 534 + addr = 0x4294val = 576 + addr = 0x4294val = 257 + addr = 0x4294val = -277 + addr = 0x4294val = -719 + addr = 0x4294val = -773 + addr = 0x4294val = -344 + addr = 0x4294val = 370 + addr = 0x4294val = 958 + addr = 0x4294val = 1029 + addr = 0x4294val = 458 + addr = 0x4294val = -491 + addr = 0x4294val = -1275 + addr = 0x4294val = -1370 + addr = 0x4294val = -610 + addr = 0x4294val = 657 + addr = 0x4294val = 1711 + addr = 0x4294val = 1848 + addr = 0x4294val = 828 + addr = 0x4294val = -898 + addr = 0x4294val = -2359 + addr = 0x4294val = -2576 + addr = 0x4294val = -1170 + addr = 0x4294val = 1289 + addr = 0x4294val = 3452 + addr = 0x4294val = 3859 + addr = 0x4294val = 1805 + addr = 0x4294val = -2064 + addr = 0x4294val = -5796 + addr = 0x4294val = -6897 + addr = 0x4294val = -3511 + addr = 0x4294val = 4535 + addr = 0x4294val = 15380 + addr = 0x4294val = 25691 + addr = 0x4294val = 31960 + addr = 0x4294val = 31960 + addr = 0x4294val = 25691 + addr = 0x4294val = 15380 + addr = 0x4294val = 4535 + addr = 0x4294val = -3511 + addr = 0x4294val = -6897 + addr = 0x4294val = -5796 + addr = 0x4294val = -2064 + addr = 0x4294val = 1805 + addr = 0x4294val = 3859 + addr = 0x4294val = 3452 + addr = 0x4294val = 1289 + addr = 0x4294val = -1170 + addr = 0x4294val = -2576 + addr = 0x4294val = -2359 + addr = 0x4294val = -898 + addr = 0x4294val = 828 + addr = 0x4294val = 1848 + addr = 0x4294val = 1711 + addr = 0x4294val = 657 + addr = 0x4294val = -610 + addr = 0x4294val = -1370 + addr = 0x4294val = -1275 + addr = 0x4294val = -491 + addr = 0x4294val = 458 + addr = 0x4294val = 1029 + addr = 0x4294val = 958 + addr = 0x4294val = 370 + addr = 0x4294val = -344 + addr = 0x4294val = -773 + addr = 0x4294val = -719 + addr = 0x4294val = -277 + addr = 0x4294val = 257 + addr = 0x4294val = 576 + addr = 0x4294val = 534 + addr = 0x4294val = 205 + addr = 0x4294val = -190 + addr = 0x4294val = -423 + addr = 0x4294val = -390 + addr = 0x4294val = -149 + addr = 0x4294val = 137 + addr = 0x4294val = 304 + addr = 0x4294val = 278 + addr = 0x4294val = 106 + addr = 0x4294val = -97 + addr = 0x4294val = -213 + addr = 0x4294val = -194 + addr = 0x4294val = -73 + addr = 0x4294val = 66 + addr = 0x4294val = 145 + addr = 0x4294val = 131 + addr = 0x4294val = 49 + addr = 0x4294val = -45 + addr = 0x4294val = -97 + addr = 0x4294val = -88 + addr = 0x4294val = -33 + addr = 0x4294val = 30 + addr = 0x4294val = 67 + addr = 0x4294val = 62 + addr = 0x4294val = 24 + addr = 0x4294val = -22 + addr = 0x4294val = -52 + addr = 0x4294val = -50 + addr = 0x4294val = -20 + addr = 0x4298val = 12000000 +external + addr = 0x4200val = 10 + REF = external +chstrRX0 dataType:7 ZDCh0 bSwitch1 + addr = 0x4210val = 0 + addr = 0x4280val = 0 + addr = 0x4284val = 0 + addr = 0x4280val = 0 + addr = 0x4284val = 1 + addr = 0x4210val = 3 + set 9002 genneric success! +adsb_set_less_30Mhz_ddc_param 15000000 30000 20000 +chstrRX1 dataType:7 ZDCh8 bSwitch0 + addr = 0x4210val = 0 + addr = 0x4280val = 8 + addr = 0x4284val = 0 + addr = 0x4280val = 8 + addr = 0x4284val = 0 + addr = 0x4210val = 3 +chstr:RX1 centerfreq:15000000 bw:20000 sample:30000 + addr = 0x4280val = 8 + addr = 0x4288val = 11 + addr = 0x428cval = 20000 + addr = 0x4290val = 0 + addr = 0x4294val = 46 + addr = 0x4294val = -47 + addr = 0x4294val = 0 + addr = 0x4294val = 51 + addr = 0x4294val = -54 + addr = 0x4294val = 0 + addr = 0x4294val = 63 + addr = 0x4294val = -69 + addr = 0x4294val = 0 + addr = 0x4294val = 83 + addr = 0x4294val = -91 + addr = 0x4294val = 0 + addr = 0x4294val = 111 + addr = 0x4294val = -123 + addr = 0x4294val = 0 + addr = 0x4294val = 150 + addr = 0x4294val = -165 + addr = 0x4294val = 0 + addr = 0x4294val = 199 + addr = 0x4294val = -218 + addr = 0x4294val = 0 + addr = 0x4294val = 261 + addr = 0x4294val = -284 + addr = 0x4294val = 0 + addr = 0x4294val = 336 + addr = 0x4294val = -365 + addr = 0x4294val = 0 + addr = 0x4294val = 428 + addr = 0x4294val = -463 + addr = 0x4294val = 0 + addr = 0x4294val = 539 + addr = 0x4294val = -581 + addr = 0x4294val = 0 + addr = 0x4294val = 673 + addr = 0x4294val = -724 + addr = 0x4294val = 0 + addr = 0x4294val = 835 + addr = 0x4294val = -897 + addr = 0x4294val = 0 + addr = 0x4294val = 1034 + addr = 0x4294val = -1111 + addr = 0x4294val = 0 + addr = 0x4294val = 1283 + addr = 0x4294val = -1380 + addr = 0x4294val = 0 + addr = 0x4294val = 1602 + addr = 0x4294val = -1730 + addr = 0x4294val = 0 + addr = 0x4294val = 2030 + addr = 0x4294val = -2209 + addr = 0x4294val = 0 + addr = 0x4294val = 2644 + addr = 0x4294val = -2914 + addr = 0x4294val = 0 + addr = 0x4294val = 3613 + addr = 0x4294val = -4079 + addr = 0x4294val = 0 + addr = 0x4294val = 5426 + addr = 0x4294val = -6457 + addr = 0x4294val = 0 + addr = 0x4294val = 10250 + addr = 0x4294val = -14399 + addr = 0x4294val = 0 + addr = 0x4294val = 72237 + addr = 0x4294val = 72237 + addr = 0x4294val = 0 + addr = 0x4294val = -14399 + addr = 0x4294val = 10250 + addr = 0x4294val = 0 + addr = 0x4294val = -6457 + addr = 0x4294val = 5426 + addr = 0x4294val = 0 + addr = 0x4294val = -4079 + addr = 0x4294val = 3613 + addr = 0x4294val = 0 + addr = 0x4294val = -2914 + addr = 0x4294val = 2644 + addr = 0x4294val = 0 + addr = 0x4294val = -2209 + addr = 0x4294val = 2030 + addr = 0x4294val = 0 + addr = 0x4294val = -1730 + addr = 0x4294val = 1602 + addr = 0x4294val = 0 + addr = 0x4294val = -1380 + addr = 0x4294val = 1283 + addr = 0x4294val = 0 + addr = 0x4294val = -1111 + addr = 0x4294val = 1034 + addr = 0x4294val = 0 + addr = 0x4294val = -897 + lose frame current_index0 lastframindex_ch0_zdddc0 + addr = 0x4294val = 835 + addr = 0x4294val = 0 + addr = 0x4294val = -724 + addr = 0x4294val = 673 + addr = 0x4294val = 0 + addr = 0x4294val = -581 + addr = 0x4294val = 539 + addr = 0x4294val = 0 + addr = 0x4294val = -463 + addr = 0x4294val = 428 + addr = 0x4294val = 0 + addr = 0x4294val = -365 + addr = 0x4294val = 336 + addr = 0x4294val = 0 + addr = 0x4294val = -284 + addr = 0x4294val = 261 + addr = 0x4294val = 0 + addr = 0x4294val = -218 + addr = 0x4294val = 199 + addr = 0x4294val = 0 + addr = 0x4294val = -165 + addr = 0x4294val = 150 + addr = 0x4294val = 0 + addr = 0x4294val = -123 + addr = 0x4294val = 111 + addr = 0x4294val = 0 + addr = 0x4294val = -91 + addr = 0x4294val = 83 + addr = 0x4294val = 0 + addr = 0x4294val = -69 + addr = 0x4294val = 63 + addr = 0x4294val = 0 + addr = 0x4294val = -54 + addr = 0x4294val = 51 + addr = 0x4294val = 0 + addr = 0x4294val = -47 + addr = 0x4294val = 46 + addr = 0x4298val = 30000 +chstrRX1 dataType:7 ZDCh8 bSwitch1 + addr = 0x4210val = 0 + addr = 0x4280val = 8 + addr = 0x4284val = 0 + addr = 0x4280val = 8 + addr = 0x4284val = 1 + addr = 0x4210val = 3 +adsb_set_less_30Mhz_fft_param 3 1024 100 +chstrRX1 dataType:6 ZDCh8 bSwitch0 + addr = 0x4210val = 0 + addr = 0x4220val = 0 + addr = 0x4220val = 0 + addr = 0x4210val = 3 + addr = 0x4210val = 0 + addr = 0x4228val = 3 + addr = 0x4224val = 1024 + addr = 0x422cval = 100 + addr = 0x4210val = 3 +chstrRX1 dataType:6 ZDCh8 bSwitch1 + addr = 0x4210val = 0 + addr = 0x4220val = 0 + addr = 0x4220val = 2 + addr = 0x4210val = 3 +adsb_set_iq_cbk 0x55c27c214cc0 1 + lose frame current_index6288 lastframindex_ch0_zdddc2047 + lose frame current_index0 lastframindex_ch0_zdddc7340 + + + lose frame current_index0 lastframindex_ch1_zdddc0 + lose frame current_index0 lastframindex_ch1_fft0 + + + +adsb_set_less_30Mhz_ddc_param 15000000 30000 15000 +chstrRX1 dataType:7 ZDCh8 bSwitch0 + addr = 0x4210val = 0 + addr = 0x4280val = 8 + addr = 0x4284val = 0 + addr = 0x4280val = 8 + addr = 0x4284val = 0 + addr = 0x4210val = 3 +chstr:RX1 centerfreq:15000000 bw:15000 sample:30000 + addr = 0x4280val = 8 + addr = 0x4288val = 11 + addr = 0x428cval = 15000 + addr = 0x4290val = 0 + addr = 0x4294val = -37 + addr = 0x4294val = -38 + addr = 0x4294val = 39 + addr = 0x4294val = 41 + addr = 0x4294val = -44 + addr = 0x4294val = -47 + addr = 0x4294val = 51 + addr = 0x4294val = 56 + addr = 0x4294val = -61 + addr = 0x4294val = -68 + addr = 0x4294val = 75 + addr = 0x4294val = 82 + addr = 0x4294val = -91 + addr = 0x4294val = -100 + addr = 0x4294val = 111 + addr = 0x4294val = 122 + addr = 0x4294val = -135 + addr = 0x4294val = -148 + addr = 0x4294val = 163 + addr = 0x4294val = 178 + addr = 0x4294val = -195 + addr = 0x4294val = -213 + addr = 0x4294val = 232 + addr = 0x4294val = 253 + addr = 0x4294val = -275 + addr = 0x4294val = -298 + addr = 0x4294val = 323 + addr = 0x4294val = 350 + addr = 0x4294val = -378 + addr = 0x4294val = -409 + addr = 0x4294val = 441 + addr = 0x4294val = 475 + addr = 0x4294val = -511 + addr = 0x4294val = -550 + addr = 0x4294val = 591 + addr = 0x4294val = 636 + addr = 0x4294val = -683 + addr = 0x4294val = -733 + addr = 0x4294val = 787 + addr = 0x4294val = 845 + addr = 0x4294val = -908 + addr = 0x4294val = -975 + addr = 0x4294val = 1048 + addr = 0x4294val = 1127 + addr = 0x4294val = -1214 + addr = 0x4294val = -1309 + addr = 0x4294val = 1414 + addr = 0x4294val = 1530 + addr = 0x4294val = -1659 + addr = 0x4294val = -1805 + addr = 0x4294val = 1970 + addr = 0x4294val = 2160 + addr = 0x4294val = -2381 + addr = 0x4294val = -2641 + addr = 0x4294val = 2952 + addr = 0x4294val = 3334 + addr = 0x4294val = -3813 + addr = 0x4294val = -4434 + addr = 0x4294val = 5276 + addr = 0x4294val = 6485 + addr = 0x4294val = -8376 + addr = 0x4294val = -11766 + addr = 0x4294val = 19654 + addr = 0x4294val = 59027 + addr = 0x4294val = 59027 + addr = 0x4294val = 19654 + addr = 0x4294val = -11766 + addr = 0x4294val = -8376 + addr = 0x4294val = 6485 + addr = 0x4294val = 5276 + addr = 0x4294val = -4434 + addr = 0x4294val = -3813 + addr = 0x4294val = 3334 + addr = 0x4294val = 2952 + addr = 0x4294val = -2641 + addr = 0x4294val = -2381 + addr = 0x4294val = 2160 + addr = 0x4294val = 1970 + addr = 0x4294val = -1805 + addr = 0x4294val = -1659 + addr = 0x4294val = 1530 + addr = 0x4294val = 1414 + addr = 0x4294val = -1309 + addr = 0x4294val = -1214 + lose frame current_index0 lastframindex_ch0_zdddc16084 + addr = 0x4294val = 1127 + addr = 0x4294val = 1048 + addr = 0x4294val = -975 + addr = 0x4294val = -908 + addr = 0x4294val = 845 + addr = 0x4294val = 787 + addr = 0x4294val = -733 + addr = 0x4294val = -683 + addr = 0x4294val = 636 + addr = 0x4294val = 591 + addr = 0x4294val = -550 + addr = 0x4294val = -511 + addr = 0x4294val = 475 + addr = 0x4294val = 441 + addr = 0x4294val = -409 + addr = 0x4294val = -378 + addr = 0x4294val = 350 + addr = 0x4294val = 323 + addr = 0x4294val = -298 + addr = 0x4294val = -275 + addr = 0x4294val = 253 + addr = 0x4294val = 232 + addr = 0x4294val = -213 + addr = 0x4294val = -195 + addr = 0x4294val = 178 + addr = 0x4294val = 163 + addr = 0x4294val = -148 + addr = 0x4294val = -135 + addr = 0x4294val = 122 + addr = 0x4294val = 111 + addr = 0x4294val = -100 + addr = 0x4294val = -91 + addr = 0x4294val = 82 + addr = 0x4294val = 75 + addr = 0x4294val = -68 addr = 0x4280val = 8 + addr = 0x4284val = 0 + addr = 0x4280val = 8 + addr = 0x4284val = 0 + addr = 0x4294val = -61 + addr = 0x4294val = 56 + addr = 0x4294val = 51 + addr = 0x4294val = -47 + addr = 0x4294val = -44 + addr = 0x4294val = 41 + addr = 0x4294val = 39 + addr = 0x4294val = -38 + addr = 0x4294val = -37 + addr = 0x4298val = 30000 +chstrRX1 dataType:7 ZDCh8 bSwitch1 + addr = 0x4210val = 0 + addr = 0x4280val = 8 + addr = 0x4284val = 0 + addr = 0x4280val = 8 + addr = 0x4284val = 1 + addr = 0x4210val = 3 + lose frame current_index0 lastframindex_ch0_zdddc7128 + lose frame current_index0 lastframindex_ch1_zdddc4469 +^A + lose frame current_index12621 lastframindex_ch0_zdddc12596 + lose frame current_index14850 lastframindex_ch0_zdddc14668 + lose frame current_index17153 lastframindex_ch0_zdddc16897 + lose frame current_index19326 lastframindex_ch0_zdddc19200 + lose frame current_index21441 lastframindex_ch0_zdddc21373 + lose frame current_index23565 lastframindex_ch0_zdddc23488 + lose frame current_index25652 lastframindex_ch0_zdddc25612 + lose frame current_index27887 lastframindex_ch0_zdddc27698 + lose frame current_index30061 lastframindex_ch0_zdddc29933 + lose frame current_index38279 lastframindex_ch0_zdddc38252 + lose frame current_index40404 lastframindex_ch0_zdddc40326 + lose frame current_index44538 lastframindex_ch0_zdddc44499 + lose frame current_index46791 lastframindex_ch0_zdddc46584 + lose frame current_index48851 lastframindex_ch0_zdddc48838 + lose frame current_index51321 lastframindex_ch0_zdddc50898 + lose frame current_index53483 lastframindex_ch0_zdddc53368 + lose frame current_index63789 lastframindex_ch0_zdddc63722 + lose frame current_index366 lastframindex_ch0_zdddc300 + lose frame current_index2509 lastframindex_ch0_zdddc2413 + lose frame current_index5149 lastframindex_ch0_zdddc4555 + lose frame current_index7454 lastframindex_ch0_zdddc7195 + lose frame current_index9548 lastframindex_ch0_zdddc9501 + lose frame current_index11749 lastframindex_ch0_zdddc11595 + lose frame current_index13821 lastframindex_ch0_zdddc13796 + lose frame current_index15940 lastframindex_ch0_zdddc15868 + lose frame current_index18058 lastframindex_ch0_zdddc17987 + lose frame current_index20596 lastframindex_ch0_zdddc20104 + lose frame current_index22755 lastframindex_ch0_zdddc22643 +^C[SIGINT (Ctrl+C)] + lose frame current_index24879 lastframindex_ch0_zdddc24802 + lose frame current_index26999 lastframindex_ch0_zdddc26926 + lose frame current_index29568 lastframindex_ch0_zdddc29046 + lose frame current_index31761 lastframindex_ch0_zdddc31614 + lose frame current_index33927 lastframindex_ch0_zdddc33808 + lose frame current_index36041 lastframindex_ch0_zdddc35974 + lose frame current_index38389 lastframindex_ch0_zdddc38088 + lose frame current_index40441 lastframindex_ch0_zdddc40436 + lose frame current_index42725 lastframindex_ch0_zdddc42487 + lose frame current_index44902 lastframindex_ch0_zdddc44771 + lose frame current_index49028 lastframindex_ch0_zdddc48997 + lose frame current_index51431 lastframindex_ch0_zdddc51075 + lose frame current_index53722 lastframindex_ch0_zdddc53477 +耗时: 14 毫秒 Data_Source_Handle_Thread:[dll]退出! +耗时: 8 毫秒 Data_Source_Handle_Thread:[radarcape]退出! +耗时: 0 毫秒 data_feed_thread退出! +耗时: 0 毫秒 web服务器线程退出! +chstrRX0 dataType:7 ZDCh0 bSwitch0 + addr = 0x4210val = 0 + addr = 0x4280val = 0 + addr = 0x4284val = 0 + addr = 0x4280val = 0 + addr = 0x4284val = 0 + addr = 0x4210val = 3 +chstrRX0 dataType:5 ZDCh0 bSwitch0 + addr = 0x4210val = 0 + addr = 0x4280val = 0 + addr = 0x4284val = 0 + addr = 0x4240val = 0 + addr = 0x4240val = 0 + addr = 0x4210val = 3 +^C[SIGINT (Ctrl+C)] +malloc_consolidate(): invalid chunk size +Stack trace written to stack_trace_2025-11-12_20-27-16.txt +SIGSEGV (Segmentation Fault) 意料之外的信号捕捉到! +Stack trace: +#0 ./rls(+0x1a8534) [0x55c27bf45534] +#1 signal_handler(int) ??:? ./rls(+0x53061) [0x55c27bdf0061] +#2 yC::serial::set_baud_rate(termios&, int, unsigned int) [clone .cold] Serial_linux.cpp:? /lib/x86_64-linux-gnu/libc.so.6(+0x43090) [0x7f5c8fa47090] +#3 get_current_time[abi:cxx11]() ??:? /lib/x86_64-linux-gnu/libc.so.6(+0x168915) [0x7f5c8fb6c915] +#4 ?? ??:0 /home/heco/ys_ecap_server/x86_linux_Release_lib9002so/lib9002.so(_Z15ThreadRecv_Func15ThreadRecvParam+0xfc5) [0x7f5c847c8895] +#5 ADS_B_T::BDS09_Airspeed::toJson() ??:? /lib/x86_64-linux-gnu/libstdc++.so.6(+0xd6df4) [0x7f5c8fe5bdf4] +#6 ?? ??:0 /lib/x86_64-linux-gnu/libpthread.so.0(+0x8609) [0x7f5c8fbfe609] +#7 ?? ??:0 /lib/x86_64-linux-gnu/libc.so.6(clone+0x43) [0x7f5c8fb23353] +Segmentation fault (core dumped) +heco@heco:~/ys_ecap_server$ + diff --git a/module/dll_source_lzy/114/out/lib/makelib_common.h b/module/dll_source_lzy/114/out/lib/makelib_common.h new file mode 100644 index 0000000..7205625 --- /dev/null +++ b/module/dll_source_lzy/114/out/lib/makelib_common.h @@ -0,0 +1,14 @@ +#pragma once +#define export 1 +#if defined(_MSC_VER) || defined(WIN64) || defined(WIN32) || defined(__NT__) +#define ex_export __declspec(dllexport) +#define ex_emport __declspec(dllimport) +#else // linux or mac +#define ex_export __attribute__((visibility("default"))) +#define ex_emport __attribute__((visibility("default"))) +#endif +#if defined(export) +#define ex_declare ex_export +#else +#define ex_declare ex_emport +#endif \ No newline at end of file diff --git a/module/dll_source_lzy/114/out/lib9002.so b/module/dll_source_lzy/114/out/lib9002.so new file mode 100644 index 0000000..408323b Binary files /dev/null and b/module/dll_source_lzy/114/out/lib9002.so differ diff --git a/module/dll_source_lzy/114/丢包测试记录.txt b/module/dll_source_lzy/114/丢包测试记录.txt new file mode 100644 index 0000000..65800af --- /dev/null +++ b/module/dll_source_lzy/114/丢包测试记录.txt @@ -0,0 +1,70 @@ +测试流程: +一 关闭自启动 + 1 远程到设备(192.168.1.102) + ssh heco@192.168.1.102 #输入密码 123465 + 2 关闭设备自启动 (将 目录 /home/heco/ys_ecap_server/protect.bash 内容中的最后一行注释掉) + vi /home/heco/ys_ecap_server/protect.bash + 命令模式下(j 往下一直 定位到 ${DIR}/pt > ${DIR}/pt.log) + 定位好之后 (I 由命令模式切换到 插入模式) ,此时输入 '#' 号,注释调该行 + 按esc键 (由插入模式转换为命令模式), 输入 :wq 此时强制保存退出 + 3 重启设备9002rm, 和本测试机器 + ssh root@172.22.0.2 /sbin/reboot #重启设备9002rm + sudo reboot #重启本机器 + 4 待重启好之后,查看线程中是否还存在 ecap_server + ssh heco@192.168.1.102 #输入密码 123465 , 重新登陆 + ps aux |grep ecap_server + 若发现 只有一个--color == xxxxecap_server , 说明只剩下查询时候有关ecap_server在运行,没有自启动线程在运行了 +二 测试丢包情况 + + +[testsever]:FILE:[device_uhd_cpp.cpp]FUNC:[set_esun_rx_addr_val]==> addr:[0x4210] val:[0] +[testsever]:FILE:[device_uhd_cpp.cpp]FUNC:[set_esun_rx_addr_val]==> addr:[0x4220] val:[0] +[testsever]:FILE:[device_uhd_cpp.cpp]FUNC:[set_esun_rx_addr_val]==> addr:[0x4220] val:[0] +[testsever]:FILE:[device_uhd_cpp.cpp]FUNC:[set_esun_rx_addr_val]==> addr:[0x4210] val:[3] +[testsever]:FILE:[device_uhd_cpp.cpp]FUNC:[set_esun_rx_addr_val]==> addr:[0x4210] val:[0] +[testsever]:FILE:[device_uhd_cpp.cpp]FUNC:[set_esun_rx_addr_val]==> addr:[0x4228] val:[3] +[testsever]:FILE:[device_uhd_cpp.cpp]FUNC:[set_esun_rx_addr_val]==> addr:[0x4224] val:[1024] +[testsever]:FILE:[device_uhd_cpp.cpp]FUNC:[set_esun_rx_addr_val]==> addr:[0x422c] val:[10] +[testsever]:FILE:[device_uhd_cpp.cpp]FUNC:[set_esun_rx_addr_val]==> addr:[0x4210] val:[3] +[testsever]:FILE:[device_uhd_cpp.cpp]FUNC:[set_esun_rx_addr_val]==> addr:[0x4210] val:[0] +[testsever]:FILE:[device_uhd_cpp.cpp]FUNC:[set_esun_rx_addr_val]==> addr:[0x4220] val:[0] +[testsever]:FILE:[device_uhd_cpp.cpp]FUNC:[set_esun_rx_addr_val]==> addr:[0x4220] val:[2] +[testsever]:FILE:[device_uhd_cpp.cpp]FUNC:[set_esun_rx_addr_val]==> addr:[0x4210] val:[3] +[testsever]:FILE:[test_s_main.cpp]FUNC:[main]==> changed_ch2_times:[14] +[testsever]:FILE:[test_s_main.cpp]FUNC:[main]==> loop 2:end +[testsever]:FILE:[test_s_main.cpp]FUNC:[main]==> loop flag 2:begin +[testsever]:FILE:[device_uhd_cpp.cpp]FUNC:[set_esun_rx_addr_val]==> addr:[0x4210] val:[0] +[testsever]:FILE:[device_uhd_cpp.cpp]FUNC:[set_esun_rx_addr_val]==> addr:[0x4220] val:[0] +[testsever]:FILE:[device_uhd_cpp.cpp]FUNC:[set_esun_rx_addr_val]==> addr:[0x4220] val:[0] +[testsever]:FILE:[device_uhd_cpp.cpp]FUNC:[set_esun_rx_addr_val]==> addr:[0x4210] val:[3] +[testsever]:FILE:[device_uhd_cpp.cpp]FUNC:[set_esun_rx_addr_val]==> addr:[0x4210] val:[0] +[testsever]:FILE:[device_uhd_cpp.cpp]FUNC:[set_esun_rx_addr_val]==> addr:[0x4228] val:[3] +[testsever]:FILE:[device_uhd_cpp.cpp]FUNC:[set_esun_rx_addr_val]==> addr:[0x4224] val:[1024] +[testsever]:FILE:[device_uhd_cpp.cpp]FUNC:[set_esun_rx_addr_val]==> addr:[0x422c] val:[10] +[testsever]:FILE:[device_uhd_cpp.cpp]FUNC:[set_esun_rx_addr_val]==> addr:[0x4210] val:[3] +[testsever]:FILE:[device_uhd_cpp.cpp]FUNC:[set_esun_rx_addr_val]==> addr:[0x4210] val:[0] +[testsever]:FILE:[device_uhd_cpp.cpp]FUNC:[set_esun_rx_addr_val]==> addr:[0x4220] val:[0] +[testsever]:FILE:[device_uhd_cpp.cpp]FUNC:[set_esun_rx_addr_val]==> addr:[0x4220] val:[2] +[testsever]:FILE:[device_uhd_cpp.cpp]FUNC:[set_esun_rx_addr_val]==> addr:[0x4210] val:[3] +[testsever]:FILE:[test_s_main.cpp]FUNC:[main]==> changed_ch2_times:[15] +[testsever]:FILE:[test_s_main.cpp]FUNC:[main]==> loop 2:end +[testsever]:FILE:[device_uhd_c.cpp]FUNC:[_rx_data_cbk_t]==> loseframe!!!=> channel:[1] current_index:[153] last_index:[23169] +[testsever]:FILE:[device_uhd_c.cpp]FUNC:[_rx_data_cbk_t]==> loseframe!!!=> channel:[1] current_index:[6] last_index:[229] +[testsever]:FILE:[test_s_main.cpp]FUNC:[main]==> loop flag 2:begin +[testsever]:FILE:[device_uhd_cpp.cpp]FUNC:[set_esun_rx_addr_val]==> addr:[0x4210] val:[0] +[testsever]:FILE:[device_uhd_cpp.cpp]FUNC:[set_esun_rx_addr_val]==> addr:[0x4220] val:[0] +[testsever]:FILE:[device_uhd_cpp.cpp]FUNC:[set_esun_rx_addr_val]==> addr:[0x4220] val:[0] +[testsever]:FILE:[device_uhd_cpp.cpp]FUNC:[set_esun_rx_addr_val]==> addr:[0x4210] val:[3] +[testsever]:FILE:[device_uhd_cpp.cpp]FUNC:[set_esun_rx_addr_val]==> addr:[0x4210] val:[0] +[testsever]:FILE:[device_uhd_cpp.cpp]FUNC:[set_esun_rx_addr_val]==> addr:[0x4228] val:[3] +[testsever]:FILE:[device_uhd_cpp.cpp]FUNC:[set_esun_rx_addr_val]==> addr:[0x4224] val:[1024] +[testsever]:FILE:[device_uhd_cpp.cpp]FUNC:[set_esun_rx_addr_val]==> addr:[0x422c] val:[10] +[testsever]:FILE:[device_uhd_cpp.cpp]FUNC:[set_esun_rx_addr_val]==> addr:[0x4210] val:[3] +[testsever]:FILE:[device_uhd_cpp.cpp]FUNC:[set_esun_rx_addr_val]==> addr:[0x4210] val:[0] +[testsever]:FILE:[device_uhd_cpp.cpp]FUNC:[set_esun_rx_addr_val]==> addr:[0x4220] val:[0] +[testsever]:FILE:[device_uhd_cpp.cpp]FUNC:[set_esun_rx_addr_val]==> addr:[0x4220] val:[2] +[testsever]:FILE:[device_uhd_cpp.cpp]FUNC:[set_esun_rx_addr_val]==> addr:[0x4210] val:[3] +[testsever]:FILE:[test_s_main.cpp]FUNC:[main]==> changed_ch2_times:[16] +[testsever]:FILE:[test_s_main.cpp]FUNC:[main]==> loop 2:end +^C +第15次循环的时候,出现 丢包现象 \ No newline at end of file diff --git a/module/dll_source_lzy/ecap/lib/.device_uhd_c.cpp.swp b/module/dll_source_lzy/ecap/lib/.device_uhd_c.cpp.swp new file mode 100644 index 0000000..c2b24d4 Binary files /dev/null and b/module/dll_source_lzy/ecap/lib/.device_uhd_c.cpp.swp differ diff --git a/module/dll_source_lzy/ecap/lib/DDCSampTable.h b/module/dll_source_lzy/ecap/lib/DDCSampTable.h new file mode 100644 index 0000000..c9a8fbf --- /dev/null +++ b/module/dll_source_lzy/ecap/lib/DDCSampTable.h @@ -0,0 +1,28 @@ +#ifndef DDCSAMPTABLE_H +#define DDCSAMPTABLE_H +#include + +// adsb +const double KDDCSampTab0[11][2] = {{24000000, 1}, {12000000, 2}, {6000000, 4}, {3000000, 8}, {1500000, 16}, {750000, 32}, {375000, 64}, {187500, 128}, {93750, 256}, {46875, 512}, {23437, 1024}}; +const string KDDCSampTabStr0[11] = {"24000000 ", "12000000 ", "6000000 ", "3000000 ", "1500000 ", "750000 ", "375000 ", "187500 ", "93750 ", "46875 ", "23437 "}; +const int KDDCSampIndxMin0 = 0; +const int KDDCSampIndxMax0 = 10; +const double define_KDDCSampleMax0 = 24000000; +const double X0 = 0.8; +const int ZDDCSampIndxMin0 = 0; +const int ZDDCSampIndxMax0 = 12; +const double ZDDCSampTab0[13] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; +const double TXSFTab0[11] = {24000000, 12000000, 6000000, 3000000, 1500000, 750000, 375000, 187500, 93750, 46875, 23437}; + +// less 30 mhz +const double KDDCSampTab1[11][2] = {{61440000, 1}, {30720000, 2}, {15360000, 4}, {7680000, 8}, {3840000, 16}, {1920000, 32}, {960000, 64}, {480000, 128}, {240000, 256}, {120000, 512}, {60000, 1024}}; +const string KDDCSampTabStr1[11] = {"61440000", "30720000", "15360000", "7680000", "3840000", "1920000", "960000", "480000", "240000", "120000", "60000"}; +const int KDDCSampIndxMin1 = 0; +const int KDDCSampIndxMax1 = 10; +const double define_KDDCSampleMax1 = 61440000; +const double X1 = 0.8; +const int ZDDCSampIndxMin1 = 0; +const int ZDDCSampIndxMax1 = 12; +const double ZDDCSampTab1[13] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; +const double TXSFTab1[11] = {61440000, 30720000, 15360000, 7680000, 3840000, 1920000, 960000, 480000, 240000, 120000, 60000}; +#endif // DDCSAMPTABLE_H diff --git a/module/dll_source_lzy/ecap/lib/FIRGenLowpass_no_ipp.h b/module/dll_source_lzy/ecap/lib/FIRGenLowpass_no_ipp.h new file mode 100644 index 0000000..717bd54 --- /dev/null +++ b/module/dll_source_lzy/ecap/lib/FIRGenLowpass_no_ipp.h @@ -0,0 +1,105 @@ +#ifndef _FIRGenLowpass_H_ +#define _FIRGenLowpass_H_ +// #include "ipp/ipps.h" +#include +#include +#define FIRGenLowpassLen 256 //滤波器长度 +#define FIRGenLowpassLen2 192 //滤波器长度 + double m_dFilterCoef[FIRGenLowpassLen]; //滤波器系数 +unsigned char m_dFilterBuff[FIRGenLowpassLen*2]; +#define PI (3.1415926) +#define POINT_SIZE (1024) +//int m_nFIRPnt; //????? +double m_dFIRCoef_ptr[POINT_SIZE]; //????? +float m_fFIRCoef_ptr[POINT_SIZE]; //????? +bool GenLowpass(double rFreq, double **coef, int point,float mult) +{ + if (NULL == *coef) + { + *coef =(double *) m_fFIRCoef_ptr; + } + int nFIRPnt0 = point - 1; + float fFIRPnt0D2 = nFIRPnt0 / 2.0f; + for (int i = 0; i < point; i++) + { + m_dFIRCoef_ptr[i] = 0.54 - 0.46 * cos((2 * PI * i) / nFIRPnt0); + } + double dTheta = 2 * PI * rFreq, dCoefSum = 0; + + for (int i = 0; i < point; i++) + { + if (fFIRPnt0D2 == i) + { + m_dFIRCoef_ptr[i] *= (dTheta / PI); + } + else + { + m_dFIRCoef_ptr[i] *= (sin((i - fFIRPnt0D2) * dTheta) / ((i - fFIRPnt0D2) * PI)); + } + dCoefSum += m_dFIRCoef_ptr[i]; + } + mult /= dCoefSum; + for(int i = 0; i < point; ++i) + { + (*coef)[i] = m_dFIRCoef_ptr[i] * mult; + } + return true; +} +/***************************** +*函数名:SetFIRLpCoef +*功能描述:设置滤波器参数 +*参数名称:coef 滤波器系数 + length 滤波器系数长度 + rate 带宽采样率之比 = 带宽 / 采样率 + bitLen 量化位宽 + mult 带宽放大系数 +*返回:成功有效滤波器长度, 失败返回0 +*****************************/ +int SetFIRLpCoef2(int *coef, int length, double rate, int bitLen, double mult = 1.0) +{ + int ret = 0; + if (NULL == coef) + { + return ret; + } + double* dFIRCoef = new double[length]; + std::fill(dFIRCoef, dFIRCoef + length, 0); + if (!GenLowpass(rate * 0.5 * mult, &dFIRCoef, length, (float ) pow(2.0, bitLen - 1) - 1)) + { + ret = 0; + } + if (bitLen <= 16) + { + for (int i = 0; i < length; ++i) { + if (dFIRCoef[i] >= 0) + { + ((short *)coef)[i] = (short)(dFIRCoef[i] + 0.5); + } + else + { + ((short *)coef)[i] = (short)(dFIRCoef[i] - 0.5); + } + } + ret = length / 2; + } + else + { + for (int i = 0; i < length; ++i) { + if (dFIRCoef[i] >= 0) + { + coef[i] = (int)(dFIRCoef[i] + 0.5); + } + else + { + coef[i] = (int)(dFIRCoef[i] - 0.5); + } + } + ret = length; + } + if (dFIRCoef != nullptr) + { + delete[] dFIRCoef; + } + return ret; +} +#endif //_FIRGenLowpass_H_ diff --git a/module/dll_source_lzy/ecap/lib/cJSON.c b/module/dll_source_lzy/ecap/lib/cJSON.c new file mode 100644 index 0000000..d7c7236 --- /dev/null +++ b/module/dll_source_lzy/ecap/lib/cJSON.c @@ -0,0 +1,3164 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +/* cJSON */ +/* JSON parser in C. */ + +/* disable warnings about old C89 functions in MSVC */ +#if !defined(_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) +#define _CRT_SECURE_NO_DEPRECATE +#endif + +#ifdef __GNUC__ +#pragma GCC visibility push(default) +#endif +#if defined(_MSC_VER) +#pragma warning (push) +/* disable warning about single line comments in system headers */ +#pragma warning (disable : 4001) +#endif + +#include +#include +#include +#include +#include +#include +#include + +#ifdef ENABLE_LOCALES +#include +#endif + +#if defined(_MSC_VER) +#pragma warning (pop) +#endif +#ifdef __GNUC__ +#pragma GCC visibility pop +#endif + +#include "cJSON.h" + +/* define our own boolean type */ +#ifdef true +#undef true +#endif +#define true ((cJSON_bool)1) + +#ifdef false +#undef false +#endif +#define false ((cJSON_bool)0) + +/* define isnan and isinf for ANSI C, if in C99 or above, isnan and isinf has been defined in math.h */ +#ifndef isinf +#define isinf(d) (isnan((d - d)) && !isnan(d)) +#endif +#ifndef isnan +#define isnan(d) (d != d) +#endif + +#ifndef NAN +#ifdef _WIN32 +#define NAN sqrt(-1.0) +#else +#define NAN 0.0/0.0 +#endif +#endif + +typedef struct { + const unsigned char *json; + size_t position; +} error; +static error global_error = { NULL, 0 }; + +CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void) +{ + return (const char*) (global_error.json + global_error.position); +} + +CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item) +{ + if (!cJSON_IsString(item)) + { + return NULL; + } + + return item->valuestring; +} + +CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item) +{ + if (!cJSON_IsNumber(item)) + { + return (double) NAN; + } + + return item->valuedouble; +} + +/* This is a safeguard to prevent copy-pasters from using incompatible C and header files */ +#if (CJSON_VERSION_MAJOR != 1) || (CJSON_VERSION_MINOR != 7) || (CJSON_VERSION_PATCH != 18) + #error cJSON.h and cJSON.c have different versions. Make sure that both have the same. +#endif + +CJSON_PUBLIC(const char*) cJSON_Version(void) +{ + static char version[15]; + sprintf(version, "%i.%i.%i", CJSON_VERSION_MAJOR, CJSON_VERSION_MINOR, CJSON_VERSION_PATCH); + + return version; +} + +/* Case insensitive string comparison, doesn't consider two NULL pointers equal though */ +static int case_insensitive_strcmp(const unsigned char *string1, const unsigned char *string2) +{ + if ((string1 == NULL) || (string2 == NULL)) + { + return 1; + } + + if (string1 == string2) + { + return 0; + } + + for(; tolower(*string1) == tolower(*string2); (void)string1++, string2++) + { + if (*string1 == '\0') + { + return 0; + } + } + + return tolower(*string1) - tolower(*string2); +} + +typedef struct internal_hooks +{ + void *(CJSON_CDECL *allocate)(size_t size); + void (CJSON_CDECL *deallocate)(void *pointer); + void *(CJSON_CDECL *reallocate)(void *pointer, size_t size); +} internal_hooks; + +#if defined(_MSC_VER) +/* work around MSVC error C2322: '...' address of dllimport '...' is not static */ +static void * CJSON_CDECL internal_malloc(size_t size) +{ + return malloc(size); +} +static void CJSON_CDECL internal_free(void *pointer) +{ + free(pointer); +} +static void * CJSON_CDECL internal_realloc(void *pointer, size_t size) +{ + return realloc(pointer, size); +} +#else +#define internal_malloc malloc +#define internal_free free +#define internal_realloc realloc +#endif + +/* strlen of character literals resolved at compile time */ +#define static_strlen(string_literal) (sizeof(string_literal) - sizeof("")) + +static internal_hooks global_hooks = { internal_malloc, internal_free, internal_realloc }; + +static unsigned char* cJSON_strdup(const unsigned char* string, const internal_hooks * const hooks) +{ + size_t length = 0; + unsigned char *copy = NULL; + + if (string == NULL) + { + return NULL; + } + + length = strlen((const char*)string) + sizeof(""); + copy = (unsigned char*)hooks->allocate(length); + if (copy == NULL) + { + return NULL; + } + memcpy(copy, string, length); + + return copy; +} + +CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks) +{ + if (hooks == NULL) + { + /* Reset hooks */ + global_hooks.allocate = malloc; + global_hooks.deallocate = free; + global_hooks.reallocate = realloc; + return; + } + + global_hooks.allocate = malloc; + if (hooks->malloc_fn != NULL) + { + global_hooks.allocate = hooks->malloc_fn; + } + + global_hooks.deallocate = free; + if (hooks->free_fn != NULL) + { + global_hooks.deallocate = hooks->free_fn; + } + + /* use realloc only if both free and malloc are used */ + global_hooks.reallocate = NULL; + if ((global_hooks.allocate == malloc) && (global_hooks.deallocate == free)) + { + global_hooks.reallocate = realloc; + } +} + +/* Internal constructor. */ +static cJSON *cJSON_New_Item(const internal_hooks * const hooks) +{ + cJSON* node = (cJSON*)hooks->allocate(sizeof(cJSON)); + if (node) + { + memset(node, '\0', sizeof(cJSON)); + } + + return node; +} + +/* Delete a cJSON structure. */ +CJSON_PUBLIC(void) cJSON_Delete(cJSON *item) +{ + cJSON *next = NULL; + while (item != NULL) + { + next = item->next; + if (!(item->type & cJSON_IsReference) && (item->child != NULL)) + { + cJSON_Delete(item->child); + } + if (!(item->type & cJSON_IsReference) && (item->valuestring != NULL)) + { + global_hooks.deallocate(item->valuestring); + item->valuestring = NULL; + } + if (!(item->type & cJSON_StringIsConst) && (item->string != NULL)) + { + global_hooks.deallocate(item->string); + item->string = NULL; + } + global_hooks.deallocate(item); + item = next; + } +} + +/* get the decimal point character of the current locale */ +static unsigned char get_decimal_point(void) +{ +#ifdef ENABLE_LOCALES + struct lconv *lconv = localeconv(); + return (unsigned char) lconv->decimal_point[0]; +#else + return '.'; +#endif +} + +typedef struct +{ + const unsigned char *content; + size_t length; + size_t offset; + size_t depth; /* How deeply nested (in arrays/objects) is the input at the current offset. */ + internal_hooks hooks; +} parse_buffer; + +/* check if the given size is left to read in a given parse buffer (starting with 1) */ +#define can_read(buffer, size) ((buffer != NULL) && (((buffer)->offset + size) <= (buffer)->length)) +/* check if the buffer can be accessed at the given index (starting with 0) */ +#define can_access_at_index(buffer, index) ((buffer != NULL) && (((buffer)->offset + index) < (buffer)->length)) +#define cannot_access_at_index(buffer, index) (!can_access_at_index(buffer, index)) +/* get a pointer to the buffer at the position */ +#define buffer_at_offset(buffer) ((buffer)->content + (buffer)->offset) + +/* Parse the input text to generate a number, and populate the result into item. */ +static cJSON_bool parse_number(cJSON * const item, parse_buffer * const input_buffer) +{ + double number = 0; + unsigned char *after_end = NULL; + unsigned char number_c_string[64]; + unsigned char decimal_point = get_decimal_point(); + size_t i = 0; + + if ((input_buffer == NULL) || (input_buffer->content == NULL)) + { + return false; + } + + /* copy the number into a temporary buffer and replace '.' with the decimal point + * of the current locale (for strtod) + * This also takes care of '\0' not necessarily being available for marking the end of the input */ + for (i = 0; (i < (sizeof(number_c_string) - 1)) && can_access_at_index(input_buffer, i); i++) + { + switch (buffer_at_offset(input_buffer)[i]) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + case '+': + case '-': + case 'e': + case 'E': + number_c_string[i] = buffer_at_offset(input_buffer)[i]; + break; + + case '.': + number_c_string[i] = decimal_point; + break; + + default: + goto loop_end; + } + } +loop_end: + number_c_string[i] = '\0'; + + number = strtod((const char*)number_c_string, (char**)&after_end); + if (number_c_string == after_end) + { + return false; /* parse_error */ + } + + item->valuedouble = number; + + /* use saturation in case of overflow */ + if (number >= INT_MAX) + { + item->valueint = INT_MAX; + } + else if (number <= (double)INT_MIN) + { + item->valueint = INT_MIN; + } + else + { + item->valueint = (int)number; + } + + item->type = cJSON_Number; + + input_buffer->offset += (size_t)(after_end - number_c_string); + return true; +} + +/* don't ask me, but the original cJSON_SetNumberValue returns an integer or double */ +CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number) +{ + if (number >= INT_MAX) + { + object->valueint = INT_MAX; + } + else if (number <= (double)INT_MIN) + { + object->valueint = INT_MIN; + } + else + { + object->valueint = (int)number; + } + + return object->valuedouble = number; +} + +/* Note: when passing a NULL valuestring, cJSON_SetValuestring treats this as an error and return NULL */ +CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring) +{ + char *copy = NULL; + size_t v1_len; + size_t v2_len; + /* if object's type is not cJSON_String or is cJSON_IsReference, it should not set valuestring */ + if ((object == NULL) || !(object->type & cJSON_String) || (object->type & cJSON_IsReference)) + { + return NULL; + } + /* return NULL if the object is corrupted or valuestring is NULL */ + if (object->valuestring == NULL || valuestring == NULL) + { + return NULL; + } + + v1_len = strlen(valuestring); + v2_len = strlen(object->valuestring); + + if (v1_len <= v2_len) + { + /* strcpy does not handle overlapping string: [X1, X2] [Y1, Y2] => X2 < Y1 or Y2 < X1 */ + if (!( valuestring + v1_len < object->valuestring || object->valuestring + v2_len < valuestring )) + { + return NULL; + } + strcpy(object->valuestring, valuestring); + return object->valuestring; + } + copy = (char*) cJSON_strdup((const unsigned char*)valuestring, &global_hooks); + if (copy == NULL) + { + return NULL; + } + if (object->valuestring != NULL) + { + cJSON_free(object->valuestring); + } + object->valuestring = copy; + + return copy; +} + +typedef struct +{ + unsigned char *buffer; + size_t length; + size_t offset; + size_t depth; /* current nesting depth (for formatted printing) */ + cJSON_bool noalloc; + cJSON_bool format; /* is this print a formatted print */ + internal_hooks hooks; +} printbuffer; + +/* realloc printbuffer if necessary to have at least "needed" bytes more */ +static unsigned char* ensure(printbuffer * const p, size_t needed) +{ + unsigned char *newbuffer = NULL; + size_t newsize = 0; + + if ((p == NULL) || (p->buffer == NULL)) + { + return NULL; + } + + if ((p->length > 0) && (p->offset >= p->length)) + { + /* make sure that offset is valid */ + return NULL; + } + + if (needed > INT_MAX) + { + /* sizes bigger than INT_MAX are currently not supported */ + return NULL; + } + + needed += p->offset + 1; + if (needed <= p->length) + { + return p->buffer + p->offset; + } + + if (p->noalloc) { + return NULL; + } + + /* calculate new buffer size */ + if (needed > (INT_MAX / 2)) + { + /* overflow of int, use INT_MAX if possible */ + if (needed <= INT_MAX) + { + newsize = INT_MAX; + } + else + { + return NULL; + } + } + else + { + newsize = needed * 2; + } + + if (p->hooks.reallocate != NULL) + { + /* reallocate with realloc if available */ + newbuffer = (unsigned char*)p->hooks.reallocate(p->buffer, newsize); + if (newbuffer == NULL) + { + p->hooks.deallocate(p->buffer); + p->length = 0; + p->buffer = NULL; + + return NULL; + } + } + else + { + /* otherwise reallocate manually */ + newbuffer = (unsigned char*)p->hooks.allocate(newsize); + if (!newbuffer) + { + p->hooks.deallocate(p->buffer); + p->length = 0; + p->buffer = NULL; + + return NULL; + } + + memcpy(newbuffer, p->buffer, p->offset + 1); + p->hooks.deallocate(p->buffer); + } + p->length = newsize; + p->buffer = newbuffer; + + return newbuffer + p->offset; +} + +/* calculate the new length of the string in a printbuffer and update the offset */ +static void update_offset(printbuffer * const buffer) +{ + const unsigned char *buffer_pointer = NULL; + if ((buffer == NULL) || (buffer->buffer == NULL)) + { + return; + } + buffer_pointer = buffer->buffer + buffer->offset; + + buffer->offset += strlen((const char*)buffer_pointer); +} + +/* securely comparison of floating-point variables */ +static cJSON_bool compare_double(double a, double b) +{ + double maxVal = fabs(a) > fabs(b) ? fabs(a) : fabs(b); + return (fabs(a - b) <= maxVal * DBL_EPSILON); +} + +/* Render the number nicely from the given item into a string. */ +static cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output_pointer = NULL; + double d = item->valuedouble; + int length = 0; + size_t i = 0; + unsigned char number_buffer[26] = {0}; /* temporary buffer to print the number into */ + unsigned char decimal_point = get_decimal_point(); + double test = 0.0; + + if (output_buffer == NULL) + { + return false; + } + + /* This checks for NaN and Infinity */ + if (isnan(d) || isinf(d)) + { + length = sprintf((char*)number_buffer, "null"); + } + else if(d == (double)item->valueint) + { + length = sprintf((char*)number_buffer, "%d", item->valueint); + } + else + { + /* Try 15 decimal places of precision to avoid nonsignificant nonzero digits */ + length = sprintf((char*)number_buffer, "%1.15g", d); + + /* Check whether the original double can be recovered */ + if ((sscanf((char*)number_buffer, "%lg", &test) != 1) || !compare_double((double)test, d)) + { + /* If not, print with 17 decimal places of precision */ + length = sprintf((char*)number_buffer, "%1.17g", d); + } + } + + /* sprintf failed or buffer overrun occurred */ + if ((length < 0) || (length > (int)(sizeof(number_buffer) - 1))) + { + return false; + } + + /* reserve appropriate space in the output */ + output_pointer = ensure(output_buffer, (size_t)length + sizeof("")); + if (output_pointer == NULL) + { + return false; + } + + /* copy the printed number to the output and replace locale + * dependent decimal point with '.' */ + for (i = 0; i < ((size_t)length); i++) + { + if (number_buffer[i] == decimal_point) + { + output_pointer[i] = '.'; + continue; + } + + output_pointer[i] = number_buffer[i]; + } + output_pointer[i] = '\0'; + + output_buffer->offset += (size_t)length; + + return true; +} + +/* parse 4 digit hexadecimal number */ +static unsigned parse_hex4(const unsigned char * const input) +{ + unsigned int h = 0; + size_t i = 0; + + for (i = 0; i < 4; i++) + { + /* parse digit */ + if ((input[i] >= '0') && (input[i] <= '9')) + { + h += (unsigned int) input[i] - '0'; + } + else if ((input[i] >= 'A') && (input[i] <= 'F')) + { + h += (unsigned int) 10 + input[i] - 'A'; + } + else if ((input[i] >= 'a') && (input[i] <= 'f')) + { + h += (unsigned int) 10 + input[i] - 'a'; + } + else /* invalid */ + { + return 0; + } + + if (i < 3) + { + /* shift left to make place for the next nibble */ + h = h << 4; + } + } + + return h; +} + +/* converts a UTF-16 literal to UTF-8 + * A literal can be one or two sequences of the form \uXXXX */ +static unsigned char utf16_literal_to_utf8(const unsigned char * const input_pointer, const unsigned char * const input_end, unsigned char **output_pointer) +{ + long unsigned int codepoint = 0; + unsigned int first_code = 0; + const unsigned char *first_sequence = input_pointer; + unsigned char utf8_length = 0; + unsigned char utf8_position = 0; + unsigned char sequence_length = 0; + unsigned char first_byte_mark = 0; + + if ((input_end - first_sequence) < 6) + { + /* input ends unexpectedly */ + goto fail; + } + + /* get the first utf16 sequence */ + first_code = parse_hex4(first_sequence + 2); + + /* check that the code is valid */ + if (((first_code >= 0xDC00) && (first_code <= 0xDFFF))) + { + goto fail; + } + + /* UTF16 surrogate pair */ + if ((first_code >= 0xD800) && (first_code <= 0xDBFF)) + { + const unsigned char *second_sequence = first_sequence + 6; + unsigned int second_code = 0; + sequence_length = 12; /* \uXXXX\uXXXX */ + + if ((input_end - second_sequence) < 6) + { + /* input ends unexpectedly */ + goto fail; + } + + if ((second_sequence[0] != '\\') || (second_sequence[1] != 'u')) + { + /* missing second half of the surrogate pair */ + goto fail; + } + + /* get the second utf16 sequence */ + second_code = parse_hex4(second_sequence + 2); + /* check that the code is valid */ + if ((second_code < 0xDC00) || (second_code > 0xDFFF)) + { + /* invalid second half of the surrogate pair */ + goto fail; + } + + + /* calculate the unicode codepoint from the surrogate pair */ + codepoint = 0x10000 + (((first_code & 0x3FF) << 10) | (second_code & 0x3FF)); + } + else + { + sequence_length = 6; /* \uXXXX */ + codepoint = first_code; + } + + /* encode as UTF-8 + * takes at maximum 4 bytes to encode: + * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */ + if (codepoint < 0x80) + { + /* normal ascii, encoding 0xxxxxxx */ + utf8_length = 1; + } + else if (codepoint < 0x800) + { + /* two bytes, encoding 110xxxxx 10xxxxxx */ + utf8_length = 2; + first_byte_mark = 0xC0; /* 11000000 */ + } + else if (codepoint < 0x10000) + { + /* three bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx */ + utf8_length = 3; + first_byte_mark = 0xE0; /* 11100000 */ + } + else if (codepoint <= 0x10FFFF) + { + /* four bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx */ + utf8_length = 4; + first_byte_mark = 0xF0; /* 11110000 */ + } + else + { + /* invalid unicode codepoint */ + goto fail; + } + + /* encode as utf8 */ + for (utf8_position = (unsigned char)(utf8_length - 1); utf8_position > 0; utf8_position--) + { + /* 10xxxxxx */ + (*output_pointer)[utf8_position] = (unsigned char)((codepoint | 0x80) & 0xBF); + codepoint >>= 6; + } + /* encode first byte */ + if (utf8_length > 1) + { + (*output_pointer)[0] = (unsigned char)((codepoint | first_byte_mark) & 0xFF); + } + else + { + (*output_pointer)[0] = (unsigned char)(codepoint & 0x7F); + } + + *output_pointer += utf8_length; + + return sequence_length; + +fail: + return 0; +} + +/* Parse the input text into an unescaped cinput, and populate item. */ +static cJSON_bool parse_string(cJSON * const item, parse_buffer * const input_buffer) +{ + const unsigned char *input_pointer = buffer_at_offset(input_buffer) + 1; + const unsigned char *input_end = buffer_at_offset(input_buffer) + 1; + unsigned char *output_pointer = NULL; + unsigned char *output = NULL; + + /* not a string */ + if (buffer_at_offset(input_buffer)[0] != '\"') + { + goto fail; + } + + { + /* calculate approximate size of the output (overestimate) */ + size_t allocation_length = 0; + size_t skipped_bytes = 0; + while (((size_t)(input_end - input_buffer->content) < input_buffer->length) && (*input_end != '\"')) + { + /* is escape sequence */ + if (input_end[0] == '\\') + { + if ((size_t)(input_end + 1 - input_buffer->content) >= input_buffer->length) + { + /* prevent buffer overflow when last input character is a backslash */ + goto fail; + } + skipped_bytes++; + input_end++; + } + input_end++; + } + if (((size_t)(input_end - input_buffer->content) >= input_buffer->length) || (*input_end != '\"')) + { + goto fail; /* string ended unexpectedly */ + } + + /* This is at most how much we need for the output */ + allocation_length = (size_t) (input_end - buffer_at_offset(input_buffer)) - skipped_bytes; + output = (unsigned char*)input_buffer->hooks.allocate(allocation_length + sizeof("")); + if (output == NULL) + { + goto fail; /* allocation failure */ + } + } + + output_pointer = output; + /* loop through the string literal */ + while (input_pointer < input_end) + { + if (*input_pointer != '\\') + { + *output_pointer++ = *input_pointer++; + } + /* escape sequence */ + else + { + unsigned char sequence_length = 2; + if ((input_end - input_pointer) < 1) + { + goto fail; + } + + switch (input_pointer[1]) + { + case 'b': + *output_pointer++ = '\b'; + break; + case 'f': + *output_pointer++ = '\f'; + break; + case 'n': + *output_pointer++ = '\n'; + break; + case 'r': + *output_pointer++ = '\r'; + break; + case 't': + *output_pointer++ = '\t'; + break; + case '\"': + case '\\': + case '/': + *output_pointer++ = input_pointer[1]; + break; + + /* UTF-16 literal */ + case 'u': + sequence_length = utf16_literal_to_utf8(input_pointer, input_end, &output_pointer); + if (sequence_length == 0) + { + /* failed to convert UTF16-literal to UTF-8 */ + goto fail; + } + break; + + default: + goto fail; + } + input_pointer += sequence_length; + } + } + + /* zero terminate the output */ + *output_pointer = '\0'; + + item->type = cJSON_String; + item->valuestring = (char*)output; + + input_buffer->offset = (size_t) (input_end - input_buffer->content); + input_buffer->offset++; + + return true; + +fail: + if (output != NULL) + { + input_buffer->hooks.deallocate(output); + output = NULL; + } + + if (input_pointer != NULL) + { + input_buffer->offset = (size_t)(input_pointer - input_buffer->content); + } + + return false; +} + +/* Render the cstring provided to an escaped version that can be printed. */ +static cJSON_bool print_string_ptr(const unsigned char * const input, printbuffer * const output_buffer) +{ + const unsigned char *input_pointer = NULL; + unsigned char *output = NULL; + unsigned char *output_pointer = NULL; + size_t output_length = 0; + /* numbers of additional characters needed for escaping */ + size_t escape_characters = 0; + + if (output_buffer == NULL) + { + return false; + } + + /* empty string */ + if (input == NULL) + { + output = ensure(output_buffer, sizeof("\"\"")); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "\"\""); + + return true; + } + + /* set "flag" to 1 if something needs to be escaped */ + for (input_pointer = input; *input_pointer; input_pointer++) + { + switch (*input_pointer) + { + case '\"': + case '\\': + case '\b': + case '\f': + case '\n': + case '\r': + case '\t': + /* one character escape sequence */ + escape_characters++; + break; + default: + if (*input_pointer < 32) + { + /* UTF-16 escape sequence uXXXX */ + escape_characters += 5; + } + break; + } + } + output_length = (size_t)(input_pointer - input) + escape_characters; + + output = ensure(output_buffer, output_length + sizeof("\"\"")); + if (output == NULL) + { + return false; + } + + /* no characters have to be escaped */ + if (escape_characters == 0) + { + output[0] = '\"'; + memcpy(output + 1, input, output_length); + output[output_length + 1] = '\"'; + output[output_length + 2] = '\0'; + + return true; + } + + output[0] = '\"'; + output_pointer = output + 1; + /* copy the string */ + for (input_pointer = input; *input_pointer != '\0'; (void)input_pointer++, output_pointer++) + { + if ((*input_pointer > 31) && (*input_pointer != '\"') && (*input_pointer != '\\')) + { + /* normal character, copy */ + *output_pointer = *input_pointer; + } + else + { + /* character needs to be escaped */ + *output_pointer++ = '\\'; + switch (*input_pointer) + { + case '\\': + *output_pointer = '\\'; + break; + case '\"': + *output_pointer = '\"'; + break; + case '\b': + *output_pointer = 'b'; + break; + case '\f': + *output_pointer = 'f'; + break; + case '\n': + *output_pointer = 'n'; + break; + case '\r': + *output_pointer = 'r'; + break; + case '\t': + *output_pointer = 't'; + break; + default: + /* escape and print as unicode codepoint */ + sprintf((char*)output_pointer, "u%04x", *input_pointer); + output_pointer += 4; + break; + } + } + } + output[output_length + 1] = '\"'; + output[output_length + 2] = '\0'; + + return true; +} + +/* Invoke print_string_ptr (which is useful) on an item. */ +static cJSON_bool print_string(const cJSON * const item, printbuffer * const p) +{ + return print_string_ptr((unsigned char*)item->valuestring, p); +} + +/* Predeclare these prototypes. */ +static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer); +static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer); +static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer); +static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer); +static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer); +static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer); + +/* Utility to jump whitespace and cr/lf */ +static parse_buffer *buffer_skip_whitespace(parse_buffer * const buffer) +{ + if ((buffer == NULL) || (buffer->content == NULL)) + { + return NULL; + } + + if (cannot_access_at_index(buffer, 0)) + { + return buffer; + } + + while (can_access_at_index(buffer, 0) && (buffer_at_offset(buffer)[0] <= 32)) + { + buffer->offset++; + } + + if (buffer->offset == buffer->length) + { + buffer->offset--; + } + + return buffer; +} + +/* skip the UTF-8 BOM (byte order mark) if it is at the beginning of a buffer */ +static parse_buffer *skip_utf8_bom(parse_buffer * const buffer) +{ + if ((buffer == NULL) || (buffer->content == NULL) || (buffer->offset != 0)) + { + return NULL; + } + + if (can_access_at_index(buffer, 4) && (strncmp((const char*)buffer_at_offset(buffer), "\xEF\xBB\xBF", 3) == 0)) + { + buffer->offset += 3; + } + + return buffer; +} + +CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated) +{ + size_t buffer_length; + + if (NULL == value) + { + return NULL; + } + + /* Adding null character size due to require_null_terminated. */ + buffer_length = strlen(value) + sizeof(""); + + return cJSON_ParseWithLengthOpts(value, buffer_length, return_parse_end, require_null_terminated); +} + +/* Parse an object - create a new root, and populate. */ +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated) +{ + parse_buffer buffer = { 0, 0, 0, 0, { 0, 0, 0 } }; + cJSON *item = NULL; + + /* reset error position */ + global_error.json = NULL; + global_error.position = 0; + + if (value == NULL || 0 == buffer_length) + { + goto fail; + } + + buffer.content = (const unsigned char*)value; + buffer.length = buffer_length; + buffer.offset = 0; + buffer.hooks = global_hooks; + + item = cJSON_New_Item(&global_hooks); + if (item == NULL) /* memory fail */ + { + goto fail; + } + + if (!parse_value(item, buffer_skip_whitespace(skip_utf8_bom(&buffer)))) + { + /* parse failure. ep is set. */ + goto fail; + } + + /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */ + if (require_null_terminated) + { + buffer_skip_whitespace(&buffer); + if ((buffer.offset >= buffer.length) || buffer_at_offset(&buffer)[0] != '\0') + { + goto fail; + } + } + if (return_parse_end) + { + *return_parse_end = (const char*)buffer_at_offset(&buffer); + } + + return item; + +fail: + if (item != NULL) + { + cJSON_Delete(item); + } + + if (value != NULL) + { + error local_error; + local_error.json = (const unsigned char*)value; + local_error.position = 0; + + if (buffer.offset < buffer.length) + { + local_error.position = buffer.offset; + } + else if (buffer.length > 0) + { + local_error.position = buffer.length - 1; + } + + if (return_parse_end != NULL) + { + *return_parse_end = (const char*)local_error.json + local_error.position; + } + + global_error = local_error; + } + + return NULL; +} + +/* Default options for cJSON_Parse */ +CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value) +{ + return cJSON_ParseWithOpts(value, 0, 0); +} + +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length) +{ + return cJSON_ParseWithLengthOpts(value, buffer_length, 0, 0); +} + +#define cjson_min(a, b) (((a) < (b)) ? (a) : (b)) + +static unsigned char *print(const cJSON * const item, cJSON_bool format, const internal_hooks * const hooks) +{ + static const size_t default_buffer_size = 256; + printbuffer buffer[1]; + unsigned char *printed = NULL; + + memset(buffer, 0, sizeof(buffer)); + + /* create buffer */ + buffer->buffer = (unsigned char*) hooks->allocate(default_buffer_size); + buffer->length = default_buffer_size; + buffer->format = format; + buffer->hooks = *hooks; + if (buffer->buffer == NULL) + { + goto fail; + } + + /* print the value */ + if (!print_value(item, buffer)) + { + goto fail; + } + update_offset(buffer); + + /* check if reallocate is available */ + if (hooks->reallocate != NULL) + { + printed = (unsigned char*) hooks->reallocate(buffer->buffer, buffer->offset + 1); + if (printed == NULL) { + goto fail; + } + buffer->buffer = NULL; + } + else /* otherwise copy the JSON over to a new buffer */ + { + printed = (unsigned char*) hooks->allocate(buffer->offset + 1); + if (printed == NULL) + { + goto fail; + } + memcpy(printed, buffer->buffer, cjson_min(buffer->length, buffer->offset + 1)); + printed[buffer->offset] = '\0'; /* just to be sure */ + + /* free the buffer */ + hooks->deallocate(buffer->buffer); + buffer->buffer = NULL; + } + + return printed; + +fail: + if (buffer->buffer != NULL) + { + hooks->deallocate(buffer->buffer); + buffer->buffer = NULL; + } + + if (printed != NULL) + { + hooks->deallocate(printed); + printed = NULL; + } + + return NULL; +} + +/* Render a cJSON item/entity/structure to text. */ +CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item) +{ + return (char*)print(item, true, &global_hooks); +} + +CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item) +{ + return (char*)print(item, false, &global_hooks); +} + +CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt) +{ + printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; + + if (prebuffer < 0) + { + return NULL; + } + + p.buffer = (unsigned char*)global_hooks.allocate((size_t)prebuffer); + if (!p.buffer) + { + return NULL; + } + + p.length = (size_t)prebuffer; + p.offset = 0; + p.noalloc = false; + p.format = fmt; + p.hooks = global_hooks; + + if (!print_value(item, &p)) + { + global_hooks.deallocate(p.buffer); + p.buffer = NULL; + return NULL; + } + + return (char*)p.buffer; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format) +{ + printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; + + if ((length < 0) || (buffer == NULL)) + { + return false; + } + + p.buffer = (unsigned char*)buffer; + p.length = (size_t)length; + p.offset = 0; + p.noalloc = true; + p.format = format; + p.hooks = global_hooks; + + return print_value(item, &p); +} + +/* Parser core - when encountering text, process appropriately. */ +static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer) +{ + if ((input_buffer == NULL) || (input_buffer->content == NULL)) + { + return false; /* no input */ + } + + /* parse the different types of values */ + /* null */ + if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "null", 4) == 0)) + { + item->type = cJSON_NULL; + input_buffer->offset += 4; + return true; + } + /* false */ + if (can_read(input_buffer, 5) && (strncmp((const char*)buffer_at_offset(input_buffer), "false", 5) == 0)) + { + item->type = cJSON_False; + input_buffer->offset += 5; + return true; + } + /* true */ + if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "true", 4) == 0)) + { + item->type = cJSON_True; + item->valueint = 1; + input_buffer->offset += 4; + return true; + } + /* string */ + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '\"')) + { + return parse_string(item, input_buffer); + } + /* number */ + if (can_access_at_index(input_buffer, 0) && ((buffer_at_offset(input_buffer)[0] == '-') || ((buffer_at_offset(input_buffer)[0] >= '0') && (buffer_at_offset(input_buffer)[0] <= '9')))) + { + return parse_number(item, input_buffer); + } + /* array */ + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '[')) + { + return parse_array(item, input_buffer); + } + /* object */ + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '{')) + { + return parse_object(item, input_buffer); + } + + return false; +} + +/* Render a value to text. */ +static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output = NULL; + + if ((item == NULL) || (output_buffer == NULL)) + { + return false; + } + + switch ((item->type) & 0xFF) + { + case cJSON_NULL: + output = ensure(output_buffer, 5); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "null"); + return true; + + case cJSON_False: + output = ensure(output_buffer, 6); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "false"); + return true; + + case cJSON_True: + output = ensure(output_buffer, 5); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "true"); + return true; + + case cJSON_Number: + return print_number(item, output_buffer); + + case cJSON_Raw: + { + size_t raw_length = 0; + if (item->valuestring == NULL) + { + return false; + } + + raw_length = strlen(item->valuestring) + sizeof(""); + output = ensure(output_buffer, raw_length); + if (output == NULL) + { + return false; + } + memcpy(output, item->valuestring, raw_length); + return true; + } + + case cJSON_String: + return print_string(item, output_buffer); + + case cJSON_Array: + return print_array(item, output_buffer); + + case cJSON_Object: + return print_object(item, output_buffer); + + default: + return false; + } +} + +/* Build an array from input text. */ +static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer) +{ + cJSON *head = NULL; /* head of the linked list */ + cJSON *current_item = NULL; + + if (input_buffer->depth >= CJSON_NESTING_LIMIT) + { + return false; /* to deeply nested */ + } + input_buffer->depth++; + + if (buffer_at_offset(input_buffer)[0] != '[') + { + /* not an array */ + goto fail; + } + + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ']')) + { + /* empty array */ + goto success; + } + + /* check if we skipped to the end of the buffer */ + if (cannot_access_at_index(input_buffer, 0)) + { + input_buffer->offset--; + goto fail; + } + + /* step back to character in front of the first element */ + input_buffer->offset--; + /* loop through the comma separated array elements */ + do + { + /* allocate next item */ + cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks)); + if (new_item == NULL) + { + goto fail; /* allocation failure */ + } + + /* attach next item to list */ + if (head == NULL) + { + /* start the linked list */ + current_item = head = new_item; + } + else + { + /* add to the end and advance */ + current_item->next = new_item; + new_item->prev = current_item; + current_item = new_item; + } + + /* parse next value */ + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (!parse_value(current_item, input_buffer)) + { + goto fail; /* failed to parse value */ + } + buffer_skip_whitespace(input_buffer); + } + while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ',')); + + if (cannot_access_at_index(input_buffer, 0) || buffer_at_offset(input_buffer)[0] != ']') + { + goto fail; /* expected end of array */ + } + +success: + input_buffer->depth--; + + if (head != NULL) { + head->prev = current_item; + } + + item->type = cJSON_Array; + item->child = head; + + input_buffer->offset++; + + return true; + +fail: + if (head != NULL) + { + cJSON_Delete(head); + } + + return false; +} + +/* Render an array to text */ +static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output_pointer = NULL; + size_t length = 0; + cJSON *current_element = item->child; + + if (output_buffer == NULL) + { + return false; + } + + /* Compose the output array. */ + /* opening square bracket */ + output_pointer = ensure(output_buffer, 1); + if (output_pointer == NULL) + { + return false; + } + + *output_pointer = '['; + output_buffer->offset++; + output_buffer->depth++; + + while (current_element != NULL) + { + if (!print_value(current_element, output_buffer)) + { + return false; + } + update_offset(output_buffer); + if (current_element->next) + { + length = (size_t) (output_buffer->format ? 2 : 1); + output_pointer = ensure(output_buffer, length + 1); + if (output_pointer == NULL) + { + return false; + } + *output_pointer++ = ','; + if(output_buffer->format) + { + *output_pointer++ = ' '; + } + *output_pointer = '\0'; + output_buffer->offset += length; + } + current_element = current_element->next; + } + + output_pointer = ensure(output_buffer, 2); + if (output_pointer == NULL) + { + return false; + } + *output_pointer++ = ']'; + *output_pointer = '\0'; + output_buffer->depth--; + + return true; +} + +/* Build an object from the text. */ +static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer) +{ + cJSON *head = NULL; /* linked list head */ + cJSON *current_item = NULL; + + if (input_buffer->depth >= CJSON_NESTING_LIMIT) + { + return false; /* to deeply nested */ + } + input_buffer->depth++; + + if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '{')) + { + goto fail; /* not an object */ + } + + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '}')) + { + goto success; /* empty object */ + } + + /* check if we skipped to the end of the buffer */ + if (cannot_access_at_index(input_buffer, 0)) + { + input_buffer->offset--; + goto fail; + } + + /* step back to character in front of the first element */ + input_buffer->offset--; + /* loop through the comma separated array elements */ + do + { + /* allocate next item */ + cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks)); + if (new_item == NULL) + { + goto fail; /* allocation failure */ + } + + /* attach next item to list */ + if (head == NULL) + { + /* start the linked list */ + current_item = head = new_item; + } + else + { + /* add to the end and advance */ + current_item->next = new_item; + new_item->prev = current_item; + current_item = new_item; + } + + if (cannot_access_at_index(input_buffer, 1)) + { + goto fail; /* nothing comes after the comma */ + } + + /* parse the name of the child */ + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (!parse_string(current_item, input_buffer)) + { + goto fail; /* failed to parse name */ + } + buffer_skip_whitespace(input_buffer); + + /* swap valuestring and string, because we parsed the name */ + current_item->string = current_item->valuestring; + current_item->valuestring = NULL; + + if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != ':')) + { + goto fail; /* invalid object */ + } + + /* parse the value */ + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (!parse_value(current_item, input_buffer)) + { + goto fail; /* failed to parse value */ + } + buffer_skip_whitespace(input_buffer); + } + while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ',')); + + if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '}')) + { + goto fail; /* expected end of object */ + } + +success: + input_buffer->depth--; + + if (head != NULL) { + head->prev = current_item; + } + + item->type = cJSON_Object; + item->child = head; + + input_buffer->offset++; + return true; + +fail: + if (head != NULL) + { + cJSON_Delete(head); + } + + return false; +} + +/* Render an object to text. */ +static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output_pointer = NULL; + size_t length = 0; + cJSON *current_item = item->child; + + if (output_buffer == NULL) + { + return false; + } + + /* Compose the output: */ + length = (size_t) (output_buffer->format ? 2 : 1); /* fmt: {\n */ + output_pointer = ensure(output_buffer, length + 1); + if (output_pointer == NULL) + { + return false; + } + + *output_pointer++ = '{'; + output_buffer->depth++; + if (output_buffer->format) + { + *output_pointer++ = '\n'; + } + output_buffer->offset += length; + + while (current_item) + { + if (output_buffer->format) + { + size_t i; + output_pointer = ensure(output_buffer, output_buffer->depth); + if (output_pointer == NULL) + { + return false; + } + for (i = 0; i < output_buffer->depth; i++) + { + *output_pointer++ = '\t'; + } + output_buffer->offset += output_buffer->depth; + } + + /* print key */ + if (!print_string_ptr((unsigned char*)current_item->string, output_buffer)) + { + return false; + } + update_offset(output_buffer); + + length = (size_t) (output_buffer->format ? 2 : 1); + output_pointer = ensure(output_buffer, length); + if (output_pointer == NULL) + { + return false; + } + *output_pointer++ = ':'; + if (output_buffer->format) + { + *output_pointer++ = '\t'; + } + output_buffer->offset += length; + + /* print value */ + if (!print_value(current_item, output_buffer)) + { + return false; + } + update_offset(output_buffer); + + /* print comma if not last */ + length = ((size_t)(output_buffer->format ? 1 : 0) + (size_t)(current_item->next ? 1 : 0)); + output_pointer = ensure(output_buffer, length + 1); + if (output_pointer == NULL) + { + return false; + } + if (current_item->next) + { + *output_pointer++ = ','; + } + + if (output_buffer->format) + { + *output_pointer++ = '\n'; + } + *output_pointer = '\0'; + output_buffer->offset += length; + + current_item = current_item->next; + } + + output_pointer = ensure(output_buffer, output_buffer->format ? (output_buffer->depth + 1) : 2); + if (output_pointer == NULL) + { + return false; + } + if (output_buffer->format) + { + size_t i; + for (i = 0; i < (output_buffer->depth - 1); i++) + { + *output_pointer++ = '\t'; + } + } + *output_pointer++ = '}'; + *output_pointer = '\0'; + output_buffer->depth--; + + return true; +} + +/* Get Array size/item / object item. */ +CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array) +{ + cJSON *child = NULL; + size_t size = 0; + + if (array == NULL) + { + return 0; + } + + child = array->child; + + while(child != NULL) + { + size++; + child = child->next; + } + + /* FIXME: Can overflow here. Cannot be fixed without breaking the API */ + + return (int)size; +} + +static cJSON* get_array_item(const cJSON *array, size_t index) +{ + cJSON *current_child = NULL; + + if (array == NULL) + { + return NULL; + } + + current_child = array->child; + while ((current_child != NULL) && (index > 0)) + { + index--; + current_child = current_child->next; + } + + return current_child; +} + +CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index) +{ + if (index < 0) + { + return NULL; + } + + return get_array_item(array, (size_t)index); +} + +static cJSON *get_object_item(const cJSON * const object, const char * const name, const cJSON_bool case_sensitive) +{ + cJSON *current_element = NULL; + + if ((object == NULL) || (name == NULL)) + { + return NULL; + } + + current_element = object->child; + if (case_sensitive) + { + while ((current_element != NULL) && (current_element->string != NULL) && (strcmp(name, current_element->string) != 0)) + { + current_element = current_element->next; + } + } + else + { + while ((current_element != NULL) && (case_insensitive_strcmp((const unsigned char*)name, (const unsigned char*)(current_element->string)) != 0)) + { + current_element = current_element->next; + } + } + + if ((current_element == NULL) || (current_element->string == NULL)) { + return NULL; + } + + return current_element; +} + +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string) +{ + return get_object_item(object, string, false); +} + +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string) +{ + return get_object_item(object, string, true); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string) +{ + return cJSON_GetObjectItem(object, string) ? 1 : 0; +} + +/* Utility for array list handling. */ +static void suffix_object(cJSON *prev, cJSON *item) +{ + prev->next = item; + item->prev = prev; +} + +/* Utility for handling references. */ +static cJSON *create_reference(const cJSON *item, const internal_hooks * const hooks) +{ + cJSON *reference = NULL; + if (item == NULL) + { + return NULL; + } + + reference = cJSON_New_Item(hooks); + if (reference == NULL) + { + return NULL; + } + + memcpy(reference, item, sizeof(cJSON)); + reference->string = NULL; + reference->type |= cJSON_IsReference; + reference->next = reference->prev = NULL; + return reference; +} + +static cJSON_bool add_item_to_array(cJSON *array, cJSON *item) +{ + cJSON *child = NULL; + + if ((item == NULL) || (array == NULL) || (array == item)) + { + return false; + } + + child = array->child; + /* + * To find the last item in array quickly, we use prev in array + */ + if (child == NULL) + { + /* list is empty, start new one */ + array->child = item; + item->prev = item; + item->next = NULL; + } + else + { + /* append to the end */ + if (child->prev) + { + suffix_object(child->prev, item); + array->child->prev = item; + } + } + + return true; +} + +/* Add item to array/object. */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item) +{ + return add_item_to_array(array, item); +} + +#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) + #pragma GCC diagnostic push +#endif +#ifdef __GNUC__ +#pragma GCC diagnostic ignored "-Wcast-qual" +#endif +/* helper function to cast away const */ +static void* cast_away_const(const void* string) +{ + return (void*)string; +} +#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) + #pragma GCC diagnostic pop +#endif + + +static cJSON_bool add_item_to_object(cJSON * const object, const char * const string, cJSON * const item, const internal_hooks * const hooks, const cJSON_bool constant_key) +{ + char *new_key = NULL; + int new_type = cJSON_Invalid; + + if ((object == NULL) || (string == NULL) || (item == NULL) || (object == item)) + { + return false; + } + + if (constant_key) + { + new_key = (char*)cast_away_const(string); + new_type = item->type | cJSON_StringIsConst; + } + else + { + new_key = (char*)cJSON_strdup((const unsigned char*)string, hooks); + if (new_key == NULL) + { + return false; + } + + new_type = item->type & ~cJSON_StringIsConst; + } + + if (!(item->type & cJSON_StringIsConst) && (item->string != NULL)) + { + hooks->deallocate(item->string); + } + + item->string = new_key; + item->type = new_type; + + return add_item_to_array(object, item); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item) +{ + return add_item_to_object(object, string, item, &global_hooks, false); +} + +/* Add an item to an object with constant string as key */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item) +{ + return add_item_to_object(object, string, item, &global_hooks, true); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item) +{ + if (array == NULL) + { + return false; + } + + return add_item_to_array(array, create_reference(item, &global_hooks)); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item) +{ + if ((object == NULL) || (string == NULL)) + { + return false; + } + + return add_item_to_object(object, string, create_reference(item, &global_hooks), &global_hooks, false); +} + +CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name) +{ + cJSON *null = cJSON_CreateNull(); + if (add_item_to_object(object, name, null, &global_hooks, false)) + { + return null; + } + + cJSON_Delete(null); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name) +{ + cJSON *true_item = cJSON_CreateTrue(); + if (add_item_to_object(object, name, true_item, &global_hooks, false)) + { + return true_item; + } + + cJSON_Delete(true_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name) +{ + cJSON *false_item = cJSON_CreateFalse(); + if (add_item_to_object(object, name, false_item, &global_hooks, false)) + { + return false_item; + } + + cJSON_Delete(false_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean) +{ + cJSON *bool_item = cJSON_CreateBool(boolean); + if (add_item_to_object(object, name, bool_item, &global_hooks, false)) + { + return bool_item; + } + + cJSON_Delete(bool_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number) +{ + cJSON *number_item = cJSON_CreateNumber(number); + if (add_item_to_object(object, name, number_item, &global_hooks, false)) + { + return number_item; + } + + cJSON_Delete(number_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string) +{ + cJSON *string_item = cJSON_CreateString(string); + if (add_item_to_object(object, name, string_item, &global_hooks, false)) + { + return string_item; + } + + cJSON_Delete(string_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw) +{ + cJSON *raw_item = cJSON_CreateRaw(raw); + if (add_item_to_object(object, name, raw_item, &global_hooks, false)) + { + return raw_item; + } + + cJSON_Delete(raw_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name) +{ + cJSON *object_item = cJSON_CreateObject(); + if (add_item_to_object(object, name, object_item, &global_hooks, false)) + { + return object_item; + } + + cJSON_Delete(object_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name) +{ + cJSON *array = cJSON_CreateArray(); + if (add_item_to_object(object, name, array, &global_hooks, false)) + { + return array; + } + + cJSON_Delete(array); + return NULL; +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item) +{ + if ((parent == NULL) || (item == NULL) || (item != parent->child && item->prev == NULL)) + { + return NULL; + } + + if (item != parent->child) + { + /* not the first element */ + item->prev->next = item->next; + } + if (item->next != NULL) + { + /* not the last element */ + item->next->prev = item->prev; + } + + if (item == parent->child) + { + /* first element */ + parent->child = item->next; + } + else if (item->next == NULL) + { + /* last element */ + parent->child->prev = item->prev; + } + + /* make sure the detached item doesn't point anywhere anymore */ + item->prev = NULL; + item->next = NULL; + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which) +{ + if (which < 0) + { + return NULL; + } + + return cJSON_DetachItemViaPointer(array, get_array_item(array, (size_t)which)); +} + +CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which) +{ + cJSON_Delete(cJSON_DetachItemFromArray(array, which)); +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string) +{ + cJSON *to_detach = cJSON_GetObjectItem(object, string); + + return cJSON_DetachItemViaPointer(object, to_detach); +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string) +{ + cJSON *to_detach = cJSON_GetObjectItemCaseSensitive(object, string); + + return cJSON_DetachItemViaPointer(object, to_detach); +} + +CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string) +{ + cJSON_Delete(cJSON_DetachItemFromObject(object, string)); +} + +CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string) +{ + cJSON_Delete(cJSON_DetachItemFromObjectCaseSensitive(object, string)); +} + +/* Replace array/object items with new ones. */ +CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem) +{ + cJSON *after_inserted = NULL; + + if (which < 0 || newitem == NULL) + { + return false; + } + + after_inserted = get_array_item(array, (size_t)which); + if (after_inserted == NULL) + { + return add_item_to_array(array, newitem); + } + + if (after_inserted != array->child && after_inserted->prev == NULL) { + /* return false if after_inserted is a corrupted array item */ + return false; + } + + newitem->next = after_inserted; + newitem->prev = after_inserted->prev; + after_inserted->prev = newitem; + if (after_inserted == array->child) + { + array->child = newitem; + } + else + { + newitem->prev->next = newitem; + } + return true; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement) +{ + if ((parent == NULL) || (parent->child == NULL) || (replacement == NULL) || (item == NULL)) + { + return false; + } + + if (replacement == item) + { + return true; + } + + replacement->next = item->next; + replacement->prev = item->prev; + + if (replacement->next != NULL) + { + replacement->next->prev = replacement; + } + if (parent->child == item) + { + if (parent->child->prev == parent->child) + { + replacement->prev = replacement; + } + parent->child = replacement; + } + else + { /* + * To find the last item in array quickly, we use prev in array. + * We can't modify the last item's next pointer where this item was the parent's child + */ + if (replacement->prev != NULL) + { + replacement->prev->next = replacement; + } + if (replacement->next == NULL) + { + parent->child->prev = replacement; + } + } + + item->next = NULL; + item->prev = NULL; + cJSON_Delete(item); + + return true; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem) +{ + if (which < 0) + { + return false; + } + + return cJSON_ReplaceItemViaPointer(array, get_array_item(array, (size_t)which), newitem); +} + +static cJSON_bool replace_item_in_object(cJSON *object, const char *string, cJSON *replacement, cJSON_bool case_sensitive) +{ + if ((replacement == NULL) || (string == NULL)) + { + return false; + } + + /* replace the name in the replacement */ + if (!(replacement->type & cJSON_StringIsConst) && (replacement->string != NULL)) + { + cJSON_free(replacement->string); + } + replacement->string = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks); + if (replacement->string == NULL) + { + return false; + } + + replacement->type &= ~cJSON_StringIsConst; + + return cJSON_ReplaceItemViaPointer(object, get_object_item(object, string, case_sensitive), replacement); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem) +{ + return replace_item_in_object(object, string, newitem, false); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object, const char *string, cJSON *newitem) +{ + return replace_item_in_object(object, string, newitem, true); +} + +/* Create basic types: */ +CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_NULL; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_True; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_False; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = boolean ? cJSON_True : cJSON_False; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_Number; + item->valuedouble = num; + + /* use saturation in case of overflow */ + if (num >= INT_MAX) + { + item->valueint = INT_MAX; + } + else if (num <= (double)INT_MIN) + { + item->valueint = INT_MIN; + } + else + { + item->valueint = (int)num; + } + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_String; + item->valuestring = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks); + if(!item->valuestring) + { + cJSON_Delete(item); + return NULL; + } + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item != NULL) + { + item->type = cJSON_String | cJSON_IsReference; + item->valuestring = (char*)cast_away_const(string); + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item != NULL) { + item->type = cJSON_Object | cJSON_IsReference; + item->child = (cJSON*)cast_away_const(child); + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child) { + cJSON *item = cJSON_New_Item(&global_hooks); + if (item != NULL) { + item->type = cJSON_Array | cJSON_IsReference; + item->child = (cJSON*)cast_away_const(child); + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_Raw; + item->valuestring = (char*)cJSON_strdup((const unsigned char*)raw, &global_hooks); + if(!item->valuestring) + { + cJSON_Delete(item); + return NULL; + } + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type=cJSON_Array; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item) + { + item->type = cJSON_Object; + } + + return item; +} + +/* Create Arrays: */ +CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (numbers == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for(i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateNumber(numbers[i]); + if (!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p, n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (numbers == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for(i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateNumber((double)numbers[i]); + if(!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p, n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (numbers == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for(i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateNumber(numbers[i]); + if(!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p, n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (strings == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for (i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateString(strings[i]); + if(!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p,n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +/* Duplication */ +cJSON * cJSON_Duplicate_rec(const cJSON *item, size_t depth, cJSON_bool recurse); + +CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse) +{ + return cJSON_Duplicate_rec(item, 0, recurse ); +} + +cJSON * cJSON_Duplicate_rec(const cJSON *item, size_t depth, cJSON_bool recurse) +{ + cJSON *newitem = NULL; + cJSON *child = NULL; + cJSON *next = NULL; + cJSON *newchild = NULL; + + /* Bail on bad ptr */ + if (!item) + { + goto fail; + } + /* Create new item */ + newitem = cJSON_New_Item(&global_hooks); + if (!newitem) + { + goto fail; + } + /* Copy over all vars */ + newitem->type = item->type & (~cJSON_IsReference); + newitem->valueint = item->valueint; + newitem->valuedouble = item->valuedouble; + if (item->valuestring) + { + newitem->valuestring = (char*)cJSON_strdup((unsigned char*)item->valuestring, &global_hooks); + if (!newitem->valuestring) + { + goto fail; + } + } + if (item->string) + { + newitem->string = (item->type&cJSON_StringIsConst) ? item->string : (char*)cJSON_strdup((unsigned char*)item->string, &global_hooks); + if (!newitem->string) + { + goto fail; + } + } + /* If non-recursive, then we're done! */ + if (!recurse) + { + return newitem; + } + /* Walk the ->next chain for the child. */ + child = item->child; + while (child != NULL) + { + if(depth >= CJSON_CIRCULAR_LIMIT) { + goto fail; + } + newchild = cJSON_Duplicate_rec(child, depth + 1, true); /* Duplicate (with recurse) each item in the ->next chain */ + if (!newchild) + { + goto fail; + } + if (next != NULL) + { + /* If newitem->child already set, then crosswire ->prev and ->next and move on */ + next->next = newchild; + newchild->prev = next; + next = newchild; + } + else + { + /* Set newitem->child and move to it */ + newitem->child = newchild; + next = newchild; + } + child = child->next; + } + if (newitem && newitem->child) + { + newitem->child->prev = newchild; + } + + return newitem; + +fail: + if (newitem != NULL) + { + cJSON_Delete(newitem); + } + + return NULL; +} + +static void skip_oneline_comment(char **input) +{ + *input += static_strlen("//"); + + for (; (*input)[0] != '\0'; ++(*input)) + { + if ((*input)[0] == '\n') { + *input += static_strlen("\n"); + return; + } + } +} + +static void skip_multiline_comment(char **input) +{ + *input += static_strlen("/*"); + + for (; (*input)[0] != '\0'; ++(*input)) + { + if (((*input)[0] == '*') && ((*input)[1] == '/')) + { + *input += static_strlen("*/"); + return; + } + } +} + +static void minify_string(char **input, char **output) { + (*output)[0] = (*input)[0]; + *input += static_strlen("\""); + *output += static_strlen("\""); + + + for (; (*input)[0] != '\0'; (void)++(*input), ++(*output)) { + (*output)[0] = (*input)[0]; + + if ((*input)[0] == '\"') { + (*output)[0] = '\"'; + *input += static_strlen("\""); + *output += static_strlen("\""); + return; + } else if (((*input)[0] == '\\') && ((*input)[1] == '\"')) { + (*output)[1] = (*input)[1]; + *input += static_strlen("\""); + *output += static_strlen("\""); + } + } +} + +CJSON_PUBLIC(void) cJSON_Minify(char *json) +{ + char *into = json; + + if (json == NULL) + { + return; + } + + while (json[0] != '\0') + { + switch (json[0]) + { + case ' ': + case '\t': + case '\r': + case '\n': + json++; + break; + + case '/': + if (json[1] == '/') + { + skip_oneline_comment(&json); + } + else if (json[1] == '*') + { + skip_multiline_comment(&json); + } else { + json++; + } + break; + + case '\"': + minify_string(&json, (char**)&into); + break; + + default: + into[0] = json[0]; + json++; + into++; + } + } + + /* and null-terminate. */ + *into = '\0'; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Invalid; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_False; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xff) == cJSON_True; +} + + +CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & (cJSON_True | cJSON_False)) != 0; +} +CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_NULL; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Number; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_String; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Array; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Object; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Raw; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive) +{ + if ((a == NULL) || (b == NULL) || ((a->type & 0xFF) != (b->type & 0xFF))) + { + return false; + } + + /* check if type is valid */ + switch (a->type & 0xFF) + { + case cJSON_False: + case cJSON_True: + case cJSON_NULL: + case cJSON_Number: + case cJSON_String: + case cJSON_Raw: + case cJSON_Array: + case cJSON_Object: + break; + + default: + return false; + } + + /* identical objects are equal */ + if (a == b) + { + return true; + } + + switch (a->type & 0xFF) + { + /* in these cases and equal type is enough */ + case cJSON_False: + case cJSON_True: + case cJSON_NULL: + return true; + + case cJSON_Number: + if (compare_double(a->valuedouble, b->valuedouble)) + { + return true; + } + return false; + + case cJSON_String: + case cJSON_Raw: + if ((a->valuestring == NULL) || (b->valuestring == NULL)) + { + return false; + } + if (strcmp(a->valuestring, b->valuestring) == 0) + { + return true; + } + + return false; + + case cJSON_Array: + { + cJSON *a_element = a->child; + cJSON *b_element = b->child; + + for (; (a_element != NULL) && (b_element != NULL);) + { + if (!cJSON_Compare(a_element, b_element, case_sensitive)) + { + return false; + } + + a_element = a_element->next; + b_element = b_element->next; + } + + /* one of the arrays is longer than the other */ + if (a_element != b_element) { + return false; + } + + return true; + } + + case cJSON_Object: + { + cJSON *a_element = NULL; + cJSON *b_element = NULL; + cJSON_ArrayForEach(a_element, a) + { + /* TODO This has O(n^2) runtime, which is horrible! */ + b_element = get_object_item(b, a_element->string, case_sensitive); + if (b_element == NULL) + { + return false; + } + + if (!cJSON_Compare(a_element, b_element, case_sensitive)) + { + return false; + } + } + + /* doing this twice, once on a and b to prevent true comparison if a subset of b + * TODO: Do this the proper way, this is just a fix for now */ + cJSON_ArrayForEach(b_element, b) + { + a_element = get_object_item(a, b_element->string, case_sensitive); + if (a_element == NULL) + { + return false; + } + + if (!cJSON_Compare(b_element, a_element, case_sensitive)) + { + return false; + } + } + + return true; + } + + default: + return false; + } +} + +CJSON_PUBLIC(void *) cJSON_malloc(size_t size) +{ + return global_hooks.allocate(size); +} + +CJSON_PUBLIC(void) cJSON_free(void *object) +{ + global_hooks.deallocate(object); + object = NULL; +} diff --git a/module/dll_source_lzy/ecap/lib/cJSON.h b/module/dll_source_lzy/ecap/lib/cJSON.h new file mode 100644 index 0000000..37520bb --- /dev/null +++ b/module/dll_source_lzy/ecap/lib/cJSON.h @@ -0,0 +1,306 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#ifndef cJSON__h +#define cJSON__h + +#ifdef __cplusplus +extern "C" +{ +#endif + +#if !defined(__WINDOWS__) && (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) || defined(_WIN32)) +#define __WINDOWS__ +#endif + +#ifdef __WINDOWS__ + +/* When compiling for windows, we specify a specific calling convention to avoid issues where we are being called from a project with a different default calling convention. For windows you have 3 define options: + +CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever dllexport symbols +CJSON_EXPORT_SYMBOLS - Define this on library build when you want to dllexport symbols (default) +CJSON_IMPORT_SYMBOLS - Define this if you want to dllimport symbol + +For *nix builds that support visibility attribute, you can define similar behavior by + +setting default visibility to hidden by adding +-fvisibility=hidden (for gcc) +or +-xldscope=hidden (for sun cc) +to CFLAGS + +then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJSON_EXPORT_SYMBOLS does + +*/ + +#define CJSON_CDECL __cdecl +#define CJSON_STDCALL __stdcall + +/* export symbols by default, this is necessary for copy pasting the C and header file */ +#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && !defined(CJSON_EXPORT_SYMBOLS) +#define CJSON_EXPORT_SYMBOLS +#endif + +#if defined(CJSON_HIDE_SYMBOLS) +#define CJSON_PUBLIC(type) type CJSON_STDCALL +#elif defined(CJSON_EXPORT_SYMBOLS) +#define CJSON_PUBLIC(type) __declspec(dllexport) type CJSON_STDCALL +#elif defined(CJSON_IMPORT_SYMBOLS) +#define CJSON_PUBLIC(type) __declspec(dllimport) type CJSON_STDCALL +#endif +#else /* !__WINDOWS__ */ +#define CJSON_CDECL +#define CJSON_STDCALL + +#if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined (__SUNPRO_C)) && defined(CJSON_API_VISIBILITY) +#define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type +#else +#define CJSON_PUBLIC(type) type +#endif +#endif + +/* project version */ +#define CJSON_VERSION_MAJOR 1 +#define CJSON_VERSION_MINOR 7 +#define CJSON_VERSION_PATCH 18 + +#include + +/* cJSON Types: */ +#define cJSON_Invalid (0) +#define cJSON_False (1 << 0) +#define cJSON_True (1 << 1) +#define cJSON_NULL (1 << 2) +#define cJSON_Number (1 << 3) +#define cJSON_String (1 << 4) +#define cJSON_Array (1 << 5) +#define cJSON_Object (1 << 6) +#define cJSON_Raw (1 << 7) /* raw json */ + +#define cJSON_IsReference 256 +#define cJSON_StringIsConst 512 + +/* The cJSON structure: */ +typedef struct cJSON +{ + /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */ + struct cJSON *next; + struct cJSON *prev; + /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */ + struct cJSON *child; + + /* The type of the item, as above. */ + int type; + + /* The item's string, if type==cJSON_String and type == cJSON_Raw */ + char *valuestring; + /* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */ + int valueint; + /* The item's number, if type==cJSON_Number */ + double valuedouble; + + /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */ + char *string; +} cJSON; + +typedef struct cJSON_Hooks +{ + /* malloc/free are CDECL on Windows regardless of the default calling convention of the compiler, so ensure the hooks allow passing those functions directly. */ + void *(CJSON_CDECL *malloc_fn)(size_t sz); + void (CJSON_CDECL *free_fn)(void *ptr); +} cJSON_Hooks; + +typedef int cJSON_bool; + +/* Limits how deeply nested arrays/objects can be before cJSON rejects to parse them. + * This is to prevent stack overflows. */ +#ifndef CJSON_NESTING_LIMIT +#define CJSON_NESTING_LIMIT 1000 +#endif + +/* Limits the length of circular references can be before cJSON rejects to parse them. + * This is to prevent stack overflows. */ +#ifndef CJSON_CIRCULAR_LIMIT +#define CJSON_CIRCULAR_LIMIT 10000 +#endif + +/* returns the version of cJSON as a string */ +CJSON_PUBLIC(const char*) cJSON_Version(void); + +/* Supply malloc, realloc and free functions to cJSON */ +CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks); + +/* Memory Management: the caller is always responsible to free the results from all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is cJSON_PrintPreallocated, where the caller has full responsibility of the buffer. */ +/* Supply a block of JSON, and this returns a cJSON object you can interrogate. */ +CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value); +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length); +/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */ +/* If you supply a ptr in return_parse_end and parsing fails, then return_parse_end will contain a pointer to the error so will match cJSON_GetErrorPtr(). */ +CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated); +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated); + +/* Render a cJSON entity to text for transfer/storage. */ +CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item); +/* Render a cJSON entity to text for transfer/storage without any formatting. */ +CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item); +/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */ +CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt); +/* Render a cJSON entity to text using a buffer already allocated in memory with given length. Returns 1 on success and 0 on failure. */ +/* NOTE: cJSON is not always 100% accurate in estimating how much memory it will use, so to be safe allocate 5 bytes more than you actually need */ +CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format); +/* Delete a cJSON entity and all subentities. */ +CJSON_PUBLIC(void) cJSON_Delete(cJSON *item); + +/* Returns the number of items in an array (or object). */ +CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array); +/* Retrieve item number "index" from array "array". Returns NULL if unsuccessful. */ +CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index); +/* Get item "string" from object. Case insensitive. */ +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string); +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string); +CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string); +/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */ +CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void); + +/* Check item type and return its value */ +CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item); +CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item); + +/* These functions check the type of an item */ +CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item); + +/* These calls create a cJSON item of the appropriate type. */ +CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean); +CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num); +CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string); +/* raw json */ +CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw); +CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void); + +/* Create a string where valuestring references a string so + * it will not be freed by cJSON_Delete */ +CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string); +/* Create an object/array that only references it's elements so + * they will not be freed by cJSON_Delete */ +CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child); +CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child); + +/* These utilities create an Array of count items. + * The parameter count cannot be greater than the number of elements in the number array, otherwise array access will be out of bounds.*/ +CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count); +CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count); +CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count); +CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count); + +/* Append item to the specified array/object. */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item); +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item); +/* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object. + * WARNING: When this function was used, make sure to always check that (item->type & cJSON_StringIsConst) is zero before + * writing to `item->string` */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item); +/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item); +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item); + +/* Remove/Detach items from Arrays/Objects. */ +CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item); +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which); +CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which); +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string); +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string); +CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string); +CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string); + +/* Update array items. */ +CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem); /* Shifts pre-existing items to the right. */ +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement); +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem); +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem); +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object,const char *string,cJSON *newitem); + +/* Duplicate a cJSON item */ +CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse); +/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will + * need to be released. With recurse!=0, it will duplicate any children connected to the item. + * The item->next and ->prev pointers are always zero on return from Duplicate. */ +/* Recursively compare two cJSON items for equality. If either a or b is NULL or invalid, they will be considered unequal. + * case_sensitive determines if object keys are treated case sensitive (1) or case insensitive (0) */ +CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive); + +/* Minify a strings, remove blank characters(such as ' ', '\t', '\r', '\n') from strings. + * The input pointer json cannot point to a read-only address area, such as a string constant, + * but should point to a readable and writable address area. */ +CJSON_PUBLIC(void) cJSON_Minify(char *json); + +/* Helper functions for creating and adding items to an object at the same time. + * They return the added item or NULL on failure. */ +CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean); +CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number); +CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string); +CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw); +CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name); + +/* When assigning an integer value, it needs to be propagated to valuedouble too. */ +#define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number)) +/* helper for the cJSON_SetNumberValue macro */ +CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number); +#define cJSON_SetNumberValue(object, number) ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number)) +/* Change the valuestring of a cJSON_String object, only takes effect when type of object is cJSON_String */ +CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring); + +/* If the object is not a boolean type this does nothing and returns cJSON_Invalid else it returns the new type*/ +#define cJSON_SetBoolValue(object, boolValue) ( \ + (object != NULL && ((object)->type & (cJSON_False|cJSON_True))) ? \ + (object)->type=((object)->type &(~(cJSON_False|cJSON_True)))|((boolValue)?cJSON_True:cJSON_False) : \ + cJSON_Invalid\ +) + +/* Macro for iterating over an array or object */ +#define cJSON_ArrayForEach(element, array) for(element = (array != NULL) ? (array)->child : NULL; element != NULL; element = element->next) + +/* malloc/free objects using the malloc/free functions that have been set with cJSON_InitHooks */ +CJSON_PUBLIC(void *) cJSON_malloc(size_t size); +CJSON_PUBLIC(void) cJSON_free(void *object); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/module/dll_source_lzy/ecap/lib/device_uhd_c.cpp b/module/dll_source_lzy/ecap/lib/device_uhd_c.cpp new file mode 100644 index 0000000..74caa02 --- /dev/null +++ b/module/dll_source_lzy/ecap/lib/device_uhd_c.cpp @@ -0,0 +1,1531 @@ + +#include "device_uhd_c.h" +#include "hulc/DataOutputFormats.h" + +#include "CtrlSpecialDecode.h" +#include "_AlgmDemodulate.h" +#include "cJSON.h" +#include "device_uhd_cpp.h" +#include +#include +#include +#include + +rx_data_cbk_t s_cbk; + +typedef struct config_struct_t +{ + char cwd[PATH_MAX]; + char dirpath[PATH_MAX]; + double rx_gain_val = 0; + char rx_clock_ref[50] = {0}; + + char config_name[255]; // = "lib9002config.json"; + char config_path[PATH_MAX]; + char is_save_adsb; + char is_save_yuanshi_iq; + uint64_t save_yuanshi_size_MByte; + uint64_t save_over_byte; + char is_save_gps; + ofstream ofs_adsb; + ofstream ofs_yuanshi_iq; + ofstream ofs_gps; + +} config_struct_t; + +config_struct_t cfg; + +#include +#include +#include +#include +int32_t init9002(void **phandle) +{ + + // + { + memset(cfg.cwd, 0, sizeof(cfg.cwd)); + strcpy(cfg.rx_clock_ref, "external"); + memset(cfg.config_name, 0, sizeof(cfg.config_name)); + memset(cfg.config_path, 0, sizeof(cfg.config_path)); + cfg.rx_gain_val = 30.0; + cfg.is_save_adsb = 0; + cfg.is_save_gps = 0; + cfg.is_save_yuanshi_iq = 0; + cfg.save_yuanshi_size_MByte = 0; + cfg.save_over_byte = 0; + } + Device_UHD *pthis = new Device_UHD(); + // getcwd(cwd, sizeof(cwd) - 1); + strcpy(cfg.config_name, "lib9002config.json"); + int len = readlink("/proc/self/exe", cfg.cwd, sizeof(cfg.cwd) - 1); + cfg.cwd[len] = '\0'; + char *dir = dirname(cfg.cwd); + + strcpy(cfg.dirpath, dir); + cout << "cfg.dirpath = " << cfg.dirpath << endl; + sprintf(cfg.config_path, "%s/%s", dir, cfg.config_name); + printf("config_path = %s\n", cfg.config_path); + + ifstream ifs(cfg.config_path); + string str; + + if (ifs.is_open()) + { + std::stringstream ss; + ss << ifs.rdbuf(); + cout << "read str = " << ss.str() << endl; + str = ss.str(); + ifs.close(); + } + + else + { + ofstream ofs(cfg.config_path); + string tmp_str = "{\"gain\":\"30.0\",\"clock_ref\":\"external\",\"is_save_adsb\":\"0\",\"is_save_yuanshi_iq\":\"0\",\"save_yuanshi_size_MByte\":\"0\",\"is_save_gps\":\"0\"}"; + ofs.write(tmp_str.c_str(), tmp_str.size()); + str = tmp_str; + ofs.close(); + } + + cout << "str = " << str << endl; + + cJSON *root = nullptr; + if (str.size() > 2) + { + root = cJSON_Parse(str.data()); + } + + cJSON *obj_gain = nullptr; + obj_gain = cJSON_GetObjectItem(root, "gain"); + if (obj_gain != nullptr) + { + char *value = obj_gain->valuestring; + // cout << "value " << value << endl; + cfg.rx_gain_val = std::stof(value); + } + else + { + cJSON_AddItemToObject(root, "gain", cJSON_CreateString("30.0")); + } + + cJSON *obj_clock_ref = nullptr; + obj_clock_ref = cJSON_GetObjectItem(root, "clock_ref"); + if (obj_clock_ref != nullptr) + { + char *value = obj_clock_ref->valuestring; + // cout << "value " << value << endl; + strcpy(cfg.rx_clock_ref, value); + } + else + { + cJSON_AddItemToObject(root, "clock_ref", cJSON_CreateString("external")); + } + + cJSON *obj_is_save_adsb = nullptr; + obj_is_save_adsb = cJSON_GetObjectItem(root, "is_save_adsb"); + if (obj_is_save_adsb != nullptr) + { + char *value = obj_is_save_adsb->valuestring; + // cout << "value " << value << endl; + cfg.is_save_adsb = std::stod(value); + } + else + { + cJSON_AddItemToObject(root, "is_save_adsb", cJSON_CreateString("0")); + } + + cJSON *obj_is_save_yuanshi_iq = nullptr; + obj_is_save_yuanshi_iq = cJSON_GetObjectItem(root, "is_save_yuanshi_iq"); + if (obj_is_save_adsb != nullptr) + { + char *value = obj_is_save_yuanshi_iq->valuestring; + // cout << "value " << value << endl; + cfg.is_save_yuanshi_iq = std::stod(value); + } + else + { + cJSON_AddItemToObject(root, "is_save_yuanshi_iq", cJSON_CreateString("0")); + } + + cJSON *obj_save_yuanshi_size_MByte = nullptr; + obj_save_yuanshi_size_MByte = cJSON_GetObjectItem(root, "save_yuanshi_size_MByte"); + if (obj_save_yuanshi_size_MByte != nullptr) + { + char *value = obj_save_yuanshi_size_MByte->valuestring; + // cout << "value " << value << endl; + cfg.save_yuanshi_size_MByte = std::stod(value); + } + else + { + cJSON_AddItemToObject(root, "save_yuanshi_size_MByte", cJSON_CreateString("0")); + } + // is_save_gps + + cJSON *obj_is_save_gps = nullptr; + obj_is_save_gps = cJSON_GetObjectItem(root, "is_save_gps"); + if (obj_is_save_gps != nullptr) + { + char *value = obj_is_save_gps->valuestring; + // cout << "value " << value << endl; + cfg.is_save_gps = std::stod(value); + } + else + { + cJSON_AddItemToObject(root, "is_save_gps", cJSON_CreateString("0")); + } + char *rootstr = cJSON_Print(root); + + cout << "rootstr" << rootstr << endl; + ofstream ofs(cfg.config_path); + if (ofs.is_open()) + { + ofs.write(rootstr, strlen(rootstr)); + ofs.close(); + } + free(rootstr); + + cJSON_Delete(root); + + cout << "config_gain_val = " << cfg.rx_gain_val << endl; + cout << "rx_clock_ref = " << cfg.rx_clock_ref << endl; + cout << "config_path" << cfg.config_path << endl; + cout << "is_save_adsb" << (int)cfg.is_save_adsb << endl; + cout << "is_save_gps" << (int)cfg.is_save_gps << endl; + cout << "is_save_yuanshi_iq" << (int)cfg.is_save_yuanshi_iq << endl; + cout << "save_yuanshi_size_MByte" << (int)cfg.save_yuanshi_size_MByte << endl; + + if (cfg.is_save_adsb) + { + string adsb_path; + + time_t t = time(0); + char t_str[30]; + memset(t_str, 0, 30); + strftime(t_str, sizeof(t_str), "%Y_%m_%d_%H_%M_%S", localtime(&t)); + + adsb_path.append(cfg.dirpath); + adsb_path.append("/adsb").append(t_str).append(".txt"); + cout << " adsb_path= " << adsb_path << endl; + cfg.ofs_adsb.open(adsb_path); + } + if (cfg.is_save_gps) + { + string gps_path; + + time_t t = time(0); + char t_str[30]; + memset(t_str, 0, 30); + strftime(t_str, sizeof(t_str), "%Y_%m_%d_%H_%M_%S", localtime(&t)); + + gps_path.append(cfg.dirpath); + gps_path.append("/gps").append(t_str).append(".txt"); + + cfg.ofs_gps.open(gps_path); + } + + if (cfg.is_save_yuanshi_iq && cfg.save_yuanshi_size_MByte > 0) + { + string yuanshi_path; + + time_t t = time(0); + char t_str[30]; + memset(t_str, 0, 30); + strftime(t_str, sizeof(t_str), "%Y_%m_%d_%H_%M_%S", localtime(&t)); + + yuanshi_path.append(cfg.dirpath); + yuanshi_path.append("/yuanshi").append(t_str).append(".dat"); + + cfg.ofs_yuanshi_iq.open(yuanshi_path, ios::binary); + } + + *phandle = pthis; + return 0; +} +int32_t free9002(void **phandle) +{ + if (phandle != nullptr) + { + Device_UHD *pthis = (Device_UHD *)*phandle; + delete pthis; + pthis = nullptr; + phandle = nullptr; + + return 0; + } + return 0; +} +int32_t isDevOpened(void *phandle, int32_t *result) +{ + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + *result = (int32_t)pthis->isDevOpened(); + return 0; + } + return -1; +} +int32_t findDevices(void *phandle, uhd::device_addrs_t *addrs) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + *addrs = pthis->findDevices(); + return 0; + } + return -1; +} +int32_t openDevice(void *phandle, uhd::device_addr_t addr) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + pthis->openDevice(addr); + return 0; + } + return -1; +} +int32_t closeDevice(void *phandle) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + pthis->closeDevice(); + return 0; + } + return -1; +} +int32_t findDevInfos(void *phandle, char infos[1000]) +{ + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + string str = pthis->findDevInfos(); + strcpy(infos, str.c_str()); + return 0; + } + return -1; +} +int32_t findDevInfos2(void *phandle, char infos[1000]) +{ + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + string str = pthis->findDevInfos2(); + strcpy(infos, str.c_str()); + return 0; + } + return -1; +} +int32_t getDevTree(void *phandle, char tree_infos[1000]) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + string str = pthis->getDevTree(); + strcpy(tree_infos, str.c_str()); + return 0; + } + return -1; +} +int32_t setDevClockSource(void *phandle, char sourceStr[1000]) +{ + + if (phandle) + { + + Device_UHD *pthis = (Device_UHD *)phandle; + pthis->setDevClockSource(sourceStr); + return 0; + } + return -1; +} +int32_t getDevClockSource(void *phandle, char sourceStr[1000]) +{ + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + string str = pthis->getDevClockSource(); + strcpy(sourceStr, str.c_str()); + return 0; + } + return -1; +} +int32_t setDevInClock(void *phandle, double clockFreq) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + pthis->setDevInClock(clockFreq); + return 0; + } + return -1; +} +int32_t getDevInClockRange(void *phandle, double *min, double *max) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + pthis->getDevInClockRange(); + *min = pthis->getDevParamMin(); + *max = pthis->getDevParamMax(); + return 0; + } + return -1; +} +int32_t getDevInClock(void *phandle, double *val) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + *val = pthis->getDevInClock(); + return 0; + } + return -1; +} +int32_t getDevRXChCount(void *phandle, size_t *val) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + *val = pthis->getDevRXChCount(); + return 0; + } + return -1; +} +int32_t getDevTXChCount(void *phandle, size_t *val) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + *val = pthis->getDevTXChCount(); + return 0; + } + return -1; +} +int32_t setDevParam(void *phandle, char chStr[50], UHD_ParamType paramType, double paramValue) +{ + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + pthis->setDevParam(chStr, paramType, paramValue); + return 0; + } + return -1; +} +int32_t getDevParam(void *phandle, char chStr[50], UHD_ParamType paramType, double *paramValue) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + *paramValue = pthis->getDevParam(chStr, paramType); + return 0; + } + return -1; +} +int32_t getDevParamMin(void *phandle, double *val) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + *val = pthis->getDevParamMin(); + return 0; + } + return -1; +} +int32_t getDevParamMax(void *phandle, double *val) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + *val = pthis->getDevParamMax(); + return 0; + } + return -1; +} +int32_t setAllAntenna(void *phandle, int32_t *result) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + *result = pthis->setAllAntenna(); + return 0; + } + return -1; +} +int32_t setDevDDCParam_Any(void *phandle, char chStr[50], unsigned int jcqOffset, unsigned int jcqData) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + pthis->setDevDDCParam_Any(chStr, jcqOffset, jcqData); + return 0; + } + return -1; +} +int32_t getDevDDCParam_Any(void *phandle, char chStr[50], unsigned int jcqOffset, unsigned int *jcqData) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + unsigned int t = 0; + pthis->getDevDDCParam_Any(chStr, jcqOffset, t); + *jcqData = t; + return 0; + } + return -1; +} +int32_t setDevDataSwitch(void *phandle, char chStr[50], UHD_ParamType dataType, unsigned char ZDCh, int bSwitch) +{ + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + + pthis->setDevDataSwitch(chStr, dataType, ZDCh, bSwitch); + return 0; + } + return -1; +} +int32_t getDevDataSwitch(void *phandle, char chStr[50], UHD_ParamType dataType, unsigned char ZDCh, int *bSwitch) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + bool b = false; + pthis->getDevDataSwitch(chStr, dataType, ZDCh, b); + *bSwitch = b; + return 0; + } + return -1; +} +int32_t setDevZDParam(void *phandle, char chStr[50], unsigned char ZDCh, long long centerfreq, int bw, int sample) +{ + + if (phandle) + { + cout << "chstr:" << chStr << " centerfreq:" << centerfreq << " bw:" << bw << " sample:" << sample << endl; + Device_UHD *pthis = (Device_UHD *)phandle; + pthis->setDevZDParam(chStr, ZDCh, centerfreq, bw, sample); + + return 0; + } + return -1; +} +int32_t getDevZDParam(void *phandle, char chStr[50], unsigned char ZDCh, long long *centerfreq, int *bw, int *sample) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + long long c = 0; + int b = 0; + int s = 0; + pthis->getDevZDParam(chStr, ZDCh, c, b, s); + + *centerfreq = c; + *bw = b; + *sample = s; + return 0; + } + return -1; +} +int32_t getDevZDCenterRange(void *phandle, char chStr[50], long long &min, long long &max) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + pthis->getDevZDCenterRange(chStr, min, max); + return 0; + } + return -1; +} +int32_t getDevZDBandWidthRange(void *phandle, char chStr[50], int &min, int &max) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + pthis->getDevZDBandWidthRange(chStr, min, max); + return 0; + } + return -1; +} +int32_t getDevZDSampleFreqRange(void *phandle, char chStr[50], int arr[13], int *valid_len) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + vector v = pthis->getDevZDSampleFreqRange(chStr); + *valid_len = v.size(); + for (int i = 0; i < v.size(); ++i) + { + arr[i] = v[i]; + } + return 0; + } + return -1; +} +int32_t setDevFFTParam(void *phandle, UHD_FFTWin fftWin, UHD_FFTLen fftLen, int fftPeriod_ms) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + pthis->setDevFFTParam(fftWin, fftLen, fftPeriod_ms); + return 0; + } + return -1; +} +int32_t getDevFFTParam(void *phandle, UHD_FFTWin *fftWin, UHD_FFTLen *fftLen, int *fftPeriod_ms) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + UHD_FFTWin _fftWin; + UHD_FFTLen _fftLen; + int _fftPeriod_ms; + pthis->getDevFFTParam(_fftWin, _fftLen, _fftPeriod_ms); + *fftWin = _fftWin; + *fftLen = _fftLen; + *fftPeriod_ms = _fftPeriod_ms; + return 0; + } + return -1; +} +int32_t getDevRecvSpeed(void *phandle, int channel, double *val) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + *val = pthis->getDevSendSpeed(channel); + return 0; + } + return -1; +} +int32_t isDevRecving(void *phandle, int channel, int *result) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + *result = pthis->isDevRecving(channel); + return 0; + } + return -1; +} + +class A +{ + public: + void callBackData_Func(int channel, void *pData, int iLength) { s_cbk(channel, pData, iLength); } +}; +A a; +int32_t startDevRecv(void *phandle, int channel, rx_data_cbk_t rx_cbk) +{ + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + + s_cbk = rx_cbk; + + pthis->callBackData = std::bind(&A::callBackData_Func, &a, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3); + // pthis->callBackData = rx_cbk; + + pthis->startDevRecv(channel); + return 0; + } + return -1; +} +int32_t stopDevRecv(void *phandle, int channel) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + pthis->stopDevRecv(channel); + return 0; + } + return -1; +} +int32_t getDevSendSpeed(void *phandle, int channel, double *val) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + *val = pthis->getDevSendSpeed(channel); + return 0; + } + return -1; +} +int32_t isDevSending(void *phandle, int channel, int32_t *result) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + *result = (int32_t)pthis->isDevSending(channel); + + return 0; + } + return -1; +} +int32_t startDevSend(void *phandle, int channel, unsigned long long send_cf, unsigned long long data_sf, char *filename, int bwhile) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + pthis->startDevSend(channel, send_cf, data_sf, filename, bwhile); + return 0; + } + return -1; +} +int32_t stopDevSend(void *phandle, int channel) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + pthis->stopDevSend(channel); + return 0; + } + return -1; +} +int32_t getGPSInfo(void *phandle, char gps_info[50]) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + string str = pthis->getGPSInfo(); + + strcpy(gps_info, str.c_str()); + return 0; + } + return -1; +} +int32_t setLedEnable(void *phandle, int led_num, int bEnable) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + pthis->setLedEnable(led_num, bEnable); + return 0; + } + return -1; +} +int32_t getLedEnable(void *phandle, int led_num, int *bEnable) +{ + + if (phandle) + { + Device_UHD *pthis = (Device_UHD *)phandle; + bool b = false; + pthis->getLedEnable(led_num, b); + *bEnable = b; + return 0; + } + return -1; +} + +#include +#include +typedef struct context_t +{ + public: + void *pdev; + adsb_msg_cbk_t adsb_cbk; + thread *t_getgps; + + bool b_pool_over; + void *adsb_pusr; + +} context_t; +unsigned long long msgNo = 0; +void *phandle_math_3a_decode = nullptr; +int lastframindex = 0; +iq_cbk_t iq_cbk; +void *iq_pusr; + +#include +int BCDToDec(int bcd, int byt) +{ + if (1 == byt) + { + return bcd - (bcd >> 4) * 6; + } + else + { + int nDec = 0; + for (int i = 0; i < byt; i++) + { + uint8_t ucBcd = (uint8_t)(bcd >> (8 * i)); + nDec += ((ucBcd - (ucBcd >> 4) * 6) * (int)std::pow(100, i)); + } + return nDec; + } +} + +time_t get_2000_1_1_000_time_t() +{ + struct tm tt; + tt.tm_year = 2000 - 1900; + tt.tm_mon = 0; + tt.tm_mday = 1; + tt.tm_hour = 0; + tt.tm_min = 0; + tt.tm_sec = 0; + return mktime(&tt); +} + +int flag1 = 0; +int is_leap_year(int year) +{ + return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); +} +void day_of_year_to_month_day(int year, int day_of_year, int *month, int *day) +{ + int days_per_month[] = { + 31, // 1 月 大 + 28, // 2 月 平 + 31, // 3 月 大 + 30, // 4 月 小 + 31, // 5 月 大 + 30, // 6 月 小 + 31, // 7 月 大 + 31, // 8 月 大 + 30, // 9 月 小 + 31, // 10月 大 + 30, // 11月 小 + 31 // 12月 大 + }; + if (is_leap_year(year)) + { + days_per_month[1] = 29; + } + *month = 1; + *day = day_of_year; + for (int i = 0; i < 12 && *day > days_per_month[i]; ++i) + { + *day -= days_per_month[i]; + (*month)++; + } +} + +// uint64_t rev_cbk_lenght_per_s = 0; +// time_t recv_time_t0 = time(0); + +void _rx_data_cbk_t(int channel, void *pdata, int length) +{ + if (iq_cbk != NULL && iq_pusr != NULL) + { + iq_cbk(iq_pusr, pdata, length); + } + // if (phandle_math_3a_decode) + // { + + // int nErr = SpecDecdInput(phandle_math_3a_decode, ((char *)pdata + 64), 2048, 0); + // int a = 0; + // } + + UHD_Struct_KDDC *p = (UHD_Struct_KDDC *)pdata; + + if (p->DataType != zd_ddc) + { + return; + } + cfg.save_over_byte += length; + int mbyte = cfg.save_over_byte / (1024 * 1024); + + if (cfg.is_save_yuanshi_iq && cfg.save_yuanshi_size_MByte > 0 && cfg.ofs_yuanshi_iq.is_open() && (mbyte < (cfg.save_yuanshi_size_MByte))) + { + cfg.ofs_yuanshi_iq.write((char *)pdata, length); + return; + } + + struct_DataTime *dt = &p->DateTm; + struct tm tt2; + memset(&tt2, 0, sizeof(struct tm)); + uint64_t result_nsec = 0; + + // std::cout <<" dt_type"<<(int)dt->TimeType<TimeType) + { + case Enum_TimeType_Invlid: { + result_nsec = 0; + } + break; + case Enum_TimeType_IRIG_B: { + int B_Year = BCDToDec(dt->TimeInfo.IRIGB_Head.Year, 1) + 2000; + int B_Day = BCDToDec(dt->TimeInfo.IRIGB_Head.Day, 2); + int B_Hour = BCDToDec(dt->TimeInfo.IRIGB_Head.Hour, 1); + int B_Minute = BCDToDec(dt->TimeInfo.IRIGB_Head.Minute, 1); + int B_Second = BCDToDec(dt->TimeInfo.IRIGB_Head.Second, 1); + uint32_t B_NSec = dt->TimeInfo.IRIGB_Head.NanoSec; + + tm my_tm; + int month; + int day; + day_of_year_to_month_day(B_Year, B_Day, &month, &day); + + tt2.tm_year = B_Year - 1900; + tt2.tm_mon = month - 1; + tt2.tm_mday = day; + tt2.tm_hour = B_Hour; + tt2.tm_min = B_Minute; + tt2.tm_sec = B_Second; + + // std::cout << " y1=" << tt2.tm_year; + // std::cout << " M1=" << tt2.tm_mon; + // std::cout << " D1=" << tt2.tm_mday; + // std::cout << " H1=" << tt2.tm_hour; + // std::cout << " m1=" << tt2.tm_min; + // std::cout << " s1=" << tt2.tm_sec << endl; + // std::cout << " nsec" << B_NSec<< endl; + + time_t t2 = mktime(&tt2); + // t2+= dt->TimeInfo.RMC_Head.NanoSec; + result_nsec = t2 * 1000000000 + B_NSec; + } + break; + case Enum_TimeType_RMC: { + + // time_t t1 = get_2000_1_1_000_time_t(); + + tt2.tm_year = dt->TimeInfo.RMC_Head.Year + 2000 - 1900; + tt2.tm_mon = dt->TimeInfo.RMC_Head.Month - 1; + tt2.tm_mday = dt->TimeInfo.RMC_Head.Day; + tt2.tm_hour = dt->TimeInfo.RMC_Head.Hour; + tt2.tm_min = dt->TimeInfo.RMC_Head.Minute; + tt2.tm_sec = dt->TimeInfo.RMC_Head.Second; + + time_t t2 = mktime(&tt2); + // t2+= dt->TimeInfo.RMC_Head.NanoSec; + result_nsec = t2 * 1000000000 + dt->TimeInfo.RMC_Head.NanoSec + (8ull * 3600 * 1000000000ull); + + if (flag1 == 0) + { + // std::cout << "\n dt_type" << (int)dt->TimeType << std::endl; + + // std::cout << " y1=" << tt2.tm_year; + // std::cout << " M1=" << tt2.tm_mon; + // std::cout << " D1=" << tt2.tm_mday; + // std::cout << " H1=" << tt2.tm_hour; + // std::cout << " m1=" << tt2.tm_min; + // std::cout << " s1=" << tt2.tm_sec << endl; + // std::cout << " nsec" << tt2.tm_sec << endl; + + // std::cout << "result_nsec" << result_nsec << std::endl; + // std::cout << "this is for input" << endl; + + flag1 = 1; + } + } + break; + case Enum_TimeType_ABSCNTTM: { + uint64_t sec_n = ((uint64_t)dt->TimeInfo.ABSCNTTM_Head.Second) * 1000000000; + result_nsec = dt->TimeInfo.ABSCNTTM_Head.NanoSec + sec_n; + } + break; + case Enum_TimeType_REFCNTTM: { + uint64_t sec_n = ((uint64_t)dt->TimeInfo.REFCNTTM_Head.Second) * 1000000000; + result_nsec = dt->TimeInfo.REFCNTTM_Head.NanoSec + sec_n; + } + break; + + default: + break; + } + + // uint64_t rev_cbk_times = 0; + // time_t recv_time_t0 = time(0); + // time_t recv_time_t1 = time(0); + + // rev_cbk_lenght_per_s+=length; + // double cha_time = difftime(recv_time_t1,recv_time_t0); + // if(cha_time>1) + // { + // cout<<" recv_cbk_leng /s = "< 0) + { + // if (p->DataType == UHD_Enum_DataType::zd_ddc) + { + int cha = p->FrameIndex - lastframindex; + if (cha != 1 && cha != -65535) + { + cout << " lose frame" << " current_index" << p->FrameIndex << " lastframindex" << lastframindex << endl; + } + lastframindex = p->FrameIndex; + + // save_sata_cache.insert(save_sata_cache.end(), static_cast(pdata), static_cast(pdata) + length); + + if (phandle_math_3a_decode) + { + + // std::cout<<"result_nsec "< +// fstream g_fsTst2("test_time.txt",ios::app); +// fstream g_fsTst1("test_for_server.txt",ios::app); +time_t mesc_to_time_t(int64_t mesc) +{ + auto sec = std::chrono::duration_cast(std::chrono::milliseconds(mesc)); + auto time_point = std::chrono::system_clock::time_point(sec); + return std::chrono::system_clock::to_time_t(time_point); +} +void SpecDecdRetClbkFun(void *hdl, int taskId, MSpecDecdSigType sigType, char *data, int length) +{ + context_t *pthis = (context_t *)hdl; + USpecDecdRet *pRet = (USpecDecdRet *)data; + char cRet[1024] = {0}; + char cRet2[1024] = {0}; + switch (sigType) + { + + case MSpecDecdSigType::ADSB: { + time_t u64Time = pRet->ADSBRet.Time / 1000000000; + time_t l_tm_t = u64Time + 8 * 3600; + + tm TmTime = *(gmtime(&l_tm_t)); + TmTime.tm_year += 1900; + TmTime.tm_mon += 1; + TmTime.tm_hour; + + // // TODO:测试用 + // { + // unsigned long long ullSec = ((TmTime.tm_hour * 60) + TmTime.tm_min) * 60 + TmTime.tm_sec; + // unsigned long long ullNSec = pRet->ADSBRet.Time % 1000000000; + // unsigned long long ullTime = ((ullSec & 0x3FFFF)) << 30 | (ullNSec & 0x3FFFFFFF); + // char cTime[6] = {0}; + // memcpy(cTime, &ullTime, 6); + // for (int i = 0, j = 5; i < j; i++, j--) //小端转大端 + // { + // char cTemp = cTime[i]; + // cTime[i] = cTime[j]; + // cTime[j] = cTemp; + // } + // std::string strMsg = ""; + // for (int i = 0; i < 6; i++) + // { + // char cByte[16] = {0}; + // sprintf(cByte, " %02X", cTime[i] & 0xFF); + // strMsg += cByte; + // } + // //测试用 + // char cMsg[256] = {0}; + // sprintf(cMsg, "%s\n", strMsg.c_str()); + // // g_fsTst2.write(cMsg, strlen(cMsg)); + // // g_fsTst2.flush(); + // } + + if (flag2 == 0) + { + + // std::cout << "y2=" << TmTime.tm_year; + // std::cout << " M2=" << TmTime.tm_mon; + // std::cout << " D2=" << TmTime.tm_mday; + // std::cout << " H2=" << TmTime.tm_hour; + // std::cout << " m2=" << TmTime.tm_min; + // std::cout << " s2=" << TmTime.tm_sec << endl; + + // std::cout << "SpecDecdRetClbkFun " + // << " TmTime.tm_hour" << TmTime.tm_hour << " pRet->ADSBRet.Time" << pRet->ADSBRet.Time << " u64Time" << u64Time << std::endl; + flag2 = 1; + } + int nMsgLen = 0; + for (int i = sizeof(pRet->ADSBRet.Msg) - 1; i >= 0; i--) + { + if (0 != pRet->ADSBRet.Msg[i]) + { + nMsgLen = i + 1; + break; + } + } + if (nMsgLen >= 28) + { + nMsgLen = 28; + } + else if (nMsgLen >= 14) + { + nMsgLen = 14; + } + else + { + nMsgLen = 4; + } + // char cMsg[1024] = {0}; + // for (int i = 0; i < nMsgLen; i++) + // { + // sprintf(&cMsg[i*2], "%02x", pRet->ADSBRet.Msg[i]); + // } + // sprintf(cRet, "#%03d 0x%06x %08s %02d Lon:%f Lat:%f Alt:%f %s, %04d-%02d-%02d %02d:%02d:%02d\r", + // ++msgNo, pRet->ADSBRet.ICAO, pRet->ADSBRet.FltNo, pRet->ADSBRet.Label, pRet->ADSBRet.Longitude, pRet->ADSBRet.Latitude, pRet->ADSBRet.Altitude, cMsg, + // TmTime.tm_year, TmTime.tm_mon, TmTime.tm_mday, TmTime.tm_hour, TmTime.tm_min, TmTime.tm_sec); + // 按规定格式输出报文 + std::string strMsg = "1A"; + switch (nMsgLen / 2) + { + case 2: + strMsg += " 31"; + break; + case 7: + strMsg += " 32"; + break; + case 14: + strMsg += " 33"; + break; + default: + break; + } + unsigned long long ullSec = ((TmTime.tm_hour * 60) + TmTime.tm_min) * 60 + TmTime.tm_sec; + // if (ullSec > 86400) //86400 = 24*60*60 + // { + // return; + // } + unsigned long long ullNSec = pRet->ADSBRet.Time % 1000000000; + unsigned long long ullTime = ((ullSec & 0x3FFFF) << 30) | (ullNSec & 0x3FFFFFFF); + + char cTime[6] = {0}; + memcpy(cTime, &ullTime, 6); + for (int i = 0, j = 5; i < j; i++, j--) // 小端转大端 + { + char cTemp = cTime[i]; + cTime[i] = cTime[j]; + cTime[j] = cTemp; + } + for (int i = 0; i < 6; i++) + { + if (26 == cTime[i]) + { + strMsg += " 1A"; + } + char cByte[16] = {0}; + sprintf(cByte, " %02X", cTime[i] & 0xFF); + strMsg += cByte; + } + int nRSSI = (int)(pRet->ADSBRet.RSSI + 0.5); + if (26 == (nRSSI & 0xFF)) + { + strMsg += " 1A"; + } + char cRSSI[16] = {0}; + sprintf(cRSSI, " %02X", nRSSI & 0xFF); + strMsg += cRSSI; + for (int i = 0; i < nMsgLen / 2; i++) + { + if ('1' == pRet->ADSBRet.Msg[2 * i] && ('a' == pRet->ADSBRet.Msg[2 * i + 1] || 'A' == pRet->ADSBRet.Msg[2 * i + 1])) + { + strMsg += " 1A"; + } + char cByte[8] = {0}; + sprintf(cByte, " %C%C", toupper(pRet->ADSBRet.Msg[2 * i]), toupper(pRet->ADSBRet.Msg[2 * i + 1])); + strMsg += cByte; + } + sprintf(cRet, "%s", strMsg.c_str()); + } + + break; + + default: + break; + } + if (strlen(cRet) > 0) + { + // printf(cRet); + // printf("\n"); + } + + // //TODO:测试用 + // { + // char cMsg[256] = {0}; + // sprintf(cMsg, "%s\r", cRet); + // g_fsTst1.write(cMsg, strlen(cMsg)); + // g_fsTst1.flush(); + // } + + if (cfg.is_save_adsb && cfg.ofs_adsb.is_open()) + { + cfg.ofs_adsb << cRet; + } + pthis->adsb_cbk(pthis->adsb_pusr, cRet, strlen(cRet)); +} + +int32_t ex_declare init_adsb9002(void **phandle, adsb_msg_cbk_t cbk, void *pusr) +{ + context_t *pthis = new context_t(); + pthis->adsb_cbk = cbk; + pthis->adsb_pusr = pusr; + phandle_math_3a_decode = 0; + pthis->pdev = nullptr; + init9002(&pthis->pdev); + if (!pthis->pdev) + { + cout << "pdev init error" << endl; + return -1; + } + uhd::device_addrs_t s; + + if (findDevices(pthis->pdev, &s) != 0) + { + cout << " findDevices error!" << endl; + return -1; + } + else + { + cout << "findDevices success!" << endl; + } + if (openDevice(pthis->pdev, s[0]) != 0) + { + cout << " openDevice error!" << endl; + return -1; + } + else + { + cout << "openDevice success!" << endl; + } + if (startDevRecv(pthis->pdev, 0, _rx_data_cbk_t) != 0) + { + cout << " startDevRecv error!" << endl; + return -1; + } + else + { + cout << "startDevRecv success!" << endl; + } + + setDevDataSwitch(pthis->pdev, "RX0", UHD_ParamType::ZDDCSwitch, 0, false); + setDevDataSwitch(pthis->pdev, "RX0", UHD_ParamType::KFFTSwitch, 0, false); + setDevDataSwitch(pthis->pdev, "RX0", UHD_ParamType::KDDCSwitch, 0, false); + + setDevParam(pthis->pdev, "RX0", UHD_ParamType::CenterFreq, 1089000000); + setDevParam(pthis->pdev, "RX0", UHD_ParamType::BandWidth, 6000000); + setDevParam(pthis->pdev, "RX0", UHD_ParamType::SampleFreq, 24000000); + setDevParam(pthis->pdev, "RX0", UHD_ParamType::Gain, cfg.rx_gain_val); + + setDevZDParam(pthis->pdev, "RX0", 0, 1090000000, 3000000, 12000000); + + // setDevClockSource(pthis->pdev,"internal"); + setDevClockSource(pthis->pdev, cfg.rx_clock_ref); + cout << " REF = " << cfg.rx_clock_ref << endl; + // setDevClockSource(pthis->pdev,"external"); + setDevDataSwitch(pthis->pdev, "RX0", UHD_ParamType::KDDCSwitch, 0, true); + setDevDataSwitch(pthis->pdev, "RX0", UHD_ParamType::ZDDCSwitch, 0, true); + cout << " set 9002 genneric success!" << endl; + + int nFs = 12000000; + // cout <<" aaa"<b_pool_over = false; + pthis->t_getgps = new thread( + [=](context_t *ppthis) { + time_t t1 = time(0); + int print_times = 0; + while (ppthis->b_pool_over == false) + { + + time_t t2 = time(0); + if (difftime(t2, t1) > 2) + { + t1 = t2; + char gpsinfo[50]; + memset(gpsinfo, 0, 50); + + getGPSInfo(ppthis->pdev, gpsinfo); + string gpsinfostr = gpsinfo; + if (gpsinfostr.size() <= 0) + { + continue; + } + // cout <<" gpsinfo.size()"<adsb_cbk(pthis->adsb_pusr, c, len); + if (cfg.is_save_gps && cfg.ofs_gps.is_open()) + { + cfg.ofs_gps << "经度: " << longitude << "°" << "\t纬度: " << latitude << "°" << "\tbin_str:" << bin.c_str() << endl; + } + } + } + usleep(500000); + } + }, + pthis); + int a = 1; + *phandle = pthis; + + return 0; +} + +int32_t ex_declare free_adsb9002(void **phandle) +{ + context_t *pthis = (context_t *)*phandle; + if (pthis->pdev) + { + int32_t result = 0; + isDevOpened(pthis->pdev, &result); + if (result > 0) + { + setDevDataSwitch(pthis->pdev, "RX0", UHD_ParamType::ZDDCSwitch, 0, 0); + setDevDataSwitch(pthis->pdev, "RX0", UHD_ParamType::KDDCSwitch, 0, 0); + stopDevRecv(pthis->pdev, 0); + closeDevice(pthis->pdev); + if (pthis->t_getgps->joinable()) + { + pthis->b_pool_over = true; + pthis->t_getgps->join(); + } + pthis->t_getgps = nullptr; + } + free9002(&pthis->pdev); + } + pthis->pdev = nullptr; + SpecDecdFree(&phandle_math_3a_decode); + if (cfg.ofs_adsb.is_open()) + { + cfg.ofs_adsb.close(); + } + if (cfg.ofs_gps.is_open()) + { + cfg.ofs_gps.close(); + } + if (cfg.ofs_yuanshi_iq.is_open()) + { + cfg.ofs_yuanshi_iq.close(); + } + return 0; +} + +int ex_declare set_iq_cbk(void *phandle, iq_cbk_t recv_cbk, void *pusr) +{ + if (phandle) + { + context_t *pthis = (context_t *)phandle; + iq_cbk = recv_cbk; + iq_pusr = pusr; + return 0; + } + return -1; +} + +int ex_declare set_less_30Mhz_ddc_param(void *phandle, uint64_t cf_hz, uint64_t sf_hz, uint64_t bw_hz, int8_t sw) +{ + if (phandle) + { + context_t *pthis = (context_t *)phandle; + + setDevDataSwitch(pthis->pdev, "RX1", UHD_ParamType::KFFTSwitch, 0, false); + setDevDataSwitch(pthis->pdev, "RX1", UHD_ParamType::KDDCSwitch, 0, false); + setDevParam(pthis->pdev, "RX1", UHD_ParamType::CenterFreq, cf_hz); + setDevParam(pthis->pdev, "RX1", UHD_ParamType::BandWidth, bw_hz); + setDevParam(pthis->pdev, "RX1", UHD_ParamType::SampleFreq, sf_hz); + setDevParam(pthis->pdev, "RX1", UHD_ParamType::Gain, cfg.rx_gain_val); + setDevDataSwitch(pthis->pdev, "RX1", UHD_ParamType::KFFTSwitch, 0, true); + setDevDataSwitch(pthis->pdev, "RX1", UHD_ParamType::KDDCSwitch, 0, true); + + return 0; + } + return -1; +} + +int ex_declare set_less_30Mhz_fft_param(void *phandle, int fftWin, int fftLen, int fftPeriod_ms, int8_t sw) +{ + if (phandle) + { + context_t *pthis = (context_t *)phandle; + + setDevDataSwitch(pthis->pdev, "RX1", UHD_ParamType::KFFTSwitch, 0, false); + setDevDataSwitch(pthis->pdev, "RX1", UHD_ParamType::KDDCSwitch, 0, false); + + setDevFFTParam(pthis->pdev, (UHD_FFTWin)fftWin, (UHD_FFTLen)fftLen, fftPeriod_ms); + + setDevDataSwitch(pthis->pdev, "RX1", UHD_ParamType::KFFTSwitch, 0, true); + setDevDataSwitch(pthis->pdev, "RX1", UHD_ParamType::KDDCSwitch, 0, true); + return 0; + } + return -1; +} + +// wyc code +struct Global_Read_Buffer +{ + Global_Read_Buffer(); + ~Global_Read_Buffer(); + std::string read() + { + std::lock_guard g(mtx); + std::string ret; + std::swap(ret, buffer); + return ret; + } + void append(std::string buf) + { + std::lock_guard g(mtx); + buffer.append(buf); + } + + + void *phandle{}; + std::mutex mtx; + std::string buffer; +}; + +Global_Read_Buffer t; + +void adsb2(void *pusr, char *pmsg, int msglen) +{ + t.append(std::string(pmsg, msglen)); +} + +Global_Read_Buffer::Global_Read_Buffer() +{ + init_adsb9002(&phandle, adsb2, nullptr); +} + +Global_Read_Buffer::~Global_Read_Buffer() +{ + free_adsb9002(&phandle); +} + +std::string adsb_read() +{ + // return t.read(); + return t.read(); +} + +#include +void adsb_read(char *buf, std::uint16_t *len) +{ + auto s = t.read(); + *len = s.size(); + std::memcpy(buf, s.c_str(), *len); +} + +int adsb_set_iq_cbk(iq_cbk_t recv_cbk, void* pusr) { + return set_iq_cbk(t.phandle, recv_cbk, pusr); +} + +int adsb_set_less_30Mhz_ddc_param(uint64_t cf_hz, uint64_t sf_hz, uint64_t bw_hz, int8_t sw) { + return set_less_30Mhz_ddc_param(t.phandle, cf_hz, sf_hz, bw_hz, sw); +} + +int adsb_set_less_30Mhz_fft_param(uint64_t fftWin, uint64_t fftLen, int fftPeriod_ms, int8_t sw) { + return set_less_30Mhz_fft_param(t.phandle, fftWin, fftLen, fftPeriod_ms, sw); +} diff --git a/module/dll_source_lzy/ecap/lib/device_uhd_c.h b/module/dll_source_lzy/ecap/lib/device_uhd_c.h new file mode 100644 index 0000000..39dbe9d --- /dev/null +++ b/module/dll_source_lzy/ecap/lib/device_uhd_c.h @@ -0,0 +1,97 @@ +#ifndef _DEVICE_UHD_C_H_ +#define _DEVICE_UHD_C_H_ + +#include "makelib_common.h" +#include "device_uhd_struct.h" +// #include "device_uhd_cpp.h" +#include + + + + + +typedef void (*rx_data_cbk_t)(int channel, void *pdata, int length); + +extern "C" +{ + int32_t ex_declare init9002(void **phandle); + int32_t ex_declare free9002(void **phandle); + int32_t ex_declare isDevOpened(void *phandle, int32_t *result); + int32_t ex_declare findDevices(void *phandle, uhd::device_addrs_t *addrs); + int32_t ex_declare openDevice(void *phandle,uhd::device_addr_t addr); + int32_t ex_declare closeDevice(void *phandle); + int32_t ex_declare findDevInfos(void *phandle, char infos[1000]); + int32_t ex_declare findDevInfos2(void *phandle, char infos[1000]); + int32_t ex_declare getDevTree(void *phandle, char tree_infos[1000]); + int32_t ex_declare setDevClockSource(void *phandle, char sourceStr[1000]); + int32_t ex_declare getDevClockSource(void *phandle, char sourceStr[1000]); + int32_t ex_declare setDevInClock(void *phandle, double clockFreq); + int32_t ex_declare getDevInClockRange(void *phandle, double *min, double *max); + int32_t ex_declare getDevInClock(void *phandle, double *val); + int32_t ex_declare getDevRXChCount(void *phandle, size_t *val); + int32_t ex_declare getDevTXChCount(void *phandle, size_t *val); + int32_t ex_declare setDevParam(void *phandle, char chStr[50], UHD_ParamType paramType, double paramValue); + int32_t ex_declare getDevParam(void *phandle, char chStr[50], UHD_ParamType paramType,double *paramValue); + int32_t ex_declare getDevParamMin(void *phandle, double *val); + int32_t ex_declare getDevParamMax(void *phandle, double *val); + int32_t ex_declare setAllAntenna(void *phandle, int32_t *result); + int32_t ex_declare setDevDDCParam_Any(void *phandle, char chStr[50], unsigned int jcqOffset, unsigned int jcqData); + int32_t ex_declare getDevDDCParam_Any(void *phandle, char chStr[50], unsigned int jcqOffset, unsigned int *jcqData); + int32_t ex_declare setDevDataSwitch(void *phandle, char chStr[50], UHD_ParamType dataType, unsigned char ZDCh, int bSwitch); + int32_t ex_declare getDevDataSwitch(void *phandle, char chStr[50], UHD_ParamType dataType, unsigned char ZDCh, int *bSwitch); + int32_t ex_declare setDevZDParam(void *phandle, char chStr[50], unsigned char ZDCh, long long centerfreq, int bw, int sample); + int32_t ex_declare getDevZDParam(void *phandle, char chStr[50], unsigned char ZDCh, long long *centerfreq, int *bw, int *sample); + int32_t ex_declare getDevZDCenterRange(void *phandle, char chStr[50], long long &min, long long &max); + int32_t ex_declare getDevZDBandWidthRange(void *phandle, char chStr[50], int &min, int &max); + int32_t ex_declare getDevZDSampleFreqRange(void *phandle, char chStr[50], int arr[13], int *valid_len); + int32_t ex_declare setDevFFTParam(void *phandle, UHD_FFTWin fftWin, UHD_FFTLen fftLen, int fftPeriod_ms); + int32_t ex_declare getDevFFTParam(void *phandle, UHD_FFTWin *fftWin, UHD_FFTLen *fftLen, int *fftPeriod_ms); + int32_t ex_declare getDevRecvSpeed(void *phandle, int channel, double *val); + int32_t ex_declare isDevRecving(void *phandle,int channel, int32_t *result); + int32_t ex_declare startDevRecv(void *phandle, int channel, rx_data_cbk_t rx_cbk); + int32_t ex_declare stopDevRecv(void *phandle, int channel); + int32_t ex_declare getDevSendSpeed(void *phandle, int channel, double *val); + int32_t ex_declare isDevSending(void *phandle, int channel, int32_t *rusult); + int32_t ex_declare startDevSend(void *phandle, int channel, unsigned long long send_cf, unsigned long long data_sf, char *filename, int bwhile); + int32_t ex_declare stopDevSend(void *phandle, int channel); + int32_t ex_declare getGPSInfo(void *phandle, char gps_info[50]); + int32_t ex_declare setLedEnable(void *phandle, int led_num, int bEnable); + int32_t ex_declare getLedEnable(void *phandle,int led_num, int *bEnable); + + + + + typedef void(*adsb_msg_cbk_t)(void *pusr,char *pmsg,int msglen); + + int32_t ex_declare init_adsb9002(void **phandle,adsb_msg_cbk_t cbk,void *pusr); + int32_t ex_declare free_adsb9002(void **phandle); + + + + // 新接口 :时间 20251107 , + //TODO: 1 增加 dma 回调函数 iq 的(ddc,ffc) +} + +#include +#include "device_uhd_c.h" +#include +#include + + +extern "C" +{ + + ex_declare void adsb_read(char* buf, std::uint16_t* len); + + typedef void (*iq_cbk_t)(void* phandle, void* pdata, uint64_t length); + typedef int (*adsb_set_iq_cbk_t)(iq_cbk_t recv_cbk, void* pusr); + typedef int (*adsb_set_less_30Mhz_ddc_param_t)(uint64_t cf_hz, uint64_t sf_hz, uint64_t bw_hz, int8_t sw); + typedef int (*adsb_set_less_30Mhz_fft_param_t)(uint64_t fftWin, uint64_t fftLen, int fftPeriod_ms, int8_t sw); + ex_declare int adsb_set_iq_cbk(iq_cbk_t recv_cbk, void* pusr); + ex_declare int adsb_set_less_30Mhz_ddc_param(uint64_t cf_hz, uint64_t sf_hz, uint64_t bw_hz, int8_t sw); + ex_declare int adsb_set_less_30Mhz_fft_param(uint64_t fftWin, uint64_t fftLen, int fftPeriod_ms, int8_t sw); + +} + + +#endif //_DEVICE_UHD_C_H_ \ No newline at end of file diff --git a/module/dll_source_lzy/ecap/lib/device_uhd_cpp.cpp b/module/dll_source_lzy/ecap/lib/device_uhd_cpp.cpp new file mode 100644 index 0000000..f95471f --- /dev/null +++ b/module/dll_source_lzy/ecap/lib/device_uhd_cpp.cpp @@ -0,0 +1,2152 @@ +#include "device_uhd_cpp.h" +// #include "UHD_Probe.h" +#include "DDCSampTable.h" +#include "FIRGenLowpass_no_ipp.h" +#include "device_uhd_struct.h" +#include +#include +#include +#include +#include + +using namespace uhd; + +#define addr_dev_ref_time 0x4200 // "参考时钟" b:0101 GPS ; b:1010 外参考 ; b:1001 内参考 +#define addr_dev_version 0x420c // "设备版本" +#define addr_rx_data_sw 0x4210 //"数据接收开关" +#define addr_dev_led 0x421c +#define addr_rx_kd_fft_sw 0x4220 // fft 开关 +#define addr_rx_kd_fft_len 0x4224 // fft 长度 1k,2k,4k,8k,16k,32k +#define addr_rx_kd_fft_type 0x4228 // fft 类型 0jxc,1hnc,2hmc,3blackman +#define addr_rx_kd_fft_preiod 0x422c // fft 周期 1-1000 ms +#define addr_rx_kd_ddc_data_sw 0x4240 // 宽带数据开关 +#define addr_rx_kd_ddc_ch 0x4264 // 宽带通道号 +#define addr_rx_kd_ddc_fc 0x4270 //"过滤系数" +#define addr_rx_kd_ddc_ch_sw 0x4208 //"中频开关" 切换通道 接收模块 1:9002模块 0:30M模块 +#define addr_rx_kd_kz_speed 0x4214 // 快照速度 +#define addr_rx_ch0_30Mhz_cw 0x4278 // 接收30Mhz 控制字 +#define addr_rx_ch1_30MHz_cw 0x427c // 接收30Mhz 控制字 +#define addr_rx_kd_ch0_ddc_sf 0x4244 //"采样率" +#define addr_rx_kd_ch0_ddc_bw 0x4248 //"带宽" +#define addr_rx_kd_ch0_ddc_cf_h16 0x424c //"中心频率 高16" +#define addr_rx_kd_ch0_ddc_cf_l32 0x4250 //"中心频率 低32" +#define addr_rx_kd_ch0_ddc_df 0x4268 //"采样因子/抽取率因子" +#define addr_rx_kd_ch0_kz_sw 0x4230 // 快照开关 +#define addr_rx_kd_ch0_kz_pack_size 0x4234 // 快照包大小 +#define addr_rx_kd_ch1_ddc_sf 0x4254 //"采样率" +#define addr_rx_kd_ch1_ddc_bw 0x4258 //"带宽" +#define addr_rx_kd_ch1_ddc_cf_h16 0x425c //"中心频率 高16" +#define addr_rx_kd_ch1_ddc_cf_l32 0x4260 //"中心频率 低32" +#define addr_rx_kd_ch1_ddc_df 0x426c //"采样因子/抽取率因子" +#define addr_rx_kd_ch1_kz_sw 0x4238 // 快照开关 +#define addr_rx_kd_ch1_kz_pack_size 0x423c // 快照包大小 +#define addr_rx_zd_ch 0x4280 // 窄带通道号 +#define addr_rx_zd_ddc_data_sw 0x4284 // 窄带数据开关 +#define addr_rx_zd_df 0x4288 // 窄带抽取倍数 +#define addr_rx_zd_bw 0x428c // 窄带带宽 +#define addr_rx_zd_cw 0x4290 // 窄带控制字 +#define addr_rx_zd_fc 0x4294 // 窄带过滤系数 +#define addr_rx_zd_sf 0x4298 // 窄带采样率 +#define addr_tx_send_data_cw 0x42c0 // 发送总开关 +#define addr_tx_send_ch_sw 0x42c4 // 发送通道选择 +#define addr_tx_ch0_insert_rate 0x42c8 // 插值率 +#define addr_tx_ch1_insert_rate 0x42cc // 插值率 +#define addr_tx_ch0_30MHz_cw 0x42d0 // 发送30Mhz 控制字 +#define addr_tx_ch1_30MHz_cw 0x42d4 // 发送30Mhz 控制字 +#define addr_tm_set_h 0x42e0 // 计时高位 +#define addr_tm_set_l 0x42e4 // 计时低位 +//----------------------------------------------------------------------------------------- +#define my_iio_rx_block_point_size_big (2112 * 512) // #define my_iio_block_point_size (2112*4) +#define my_iio_block_point_size_little (2112 * 512) +#define my_iio_tx_block_point_size (2112 * 512) +#define ach_sf_count_max_hz (15.36 * 1000 * 1000) +#define rx_kz_speed_hz (1.62 * 1000 * 1000) +// #define rx_net_speed_max (500*1024*1024) +#define ZDExtraMin 0 // 窄带抽取倍数的序号,最小 +#define ZDExtraMax 12 // 窄带抽取倍数的序号,最大 +#define kz_sum ((double)(491520000 / 2)) +#define GHz (1000 * 1000 * 1000.0) +#define MHz (1000 * 1000.0) + +static unsigned long long kd_sf_all = 0; +static unsigned long long sf_all = 0; +static unsigned long long tmp_block_size = 0; +static unsigned long long tmp_sf_all = 0; +typedef struct ThreadRecvParam +{ + int channel; + void *pThis; +} ThreadRecvParam; +void addr_val_mix(int64_t addr, int64_t val, std::string &sstr) +{ + sstr.clear(); + char str[50]; + for (int i = 0; i < 50; ++i) + { + str[i] = 0; + } + sprintf(str, "%08x%08x", (unsigned int)addr, (unsigned int)val); + sstr = str; +} +bool set_esun_rx_addr_val(iio_context *ctx, int64_t addr, int64_t val) +{ + if (ctx) + { + struct iio_device *phy; + struct iio_channel *chan; + phy = iio_context_find_device(ctx, "adrv9002-phy"); + chan = iio_device_find_channel(phy, "voltage0", false); + + // cout <<" addr = 0x"<bFindedDevice = true; + dev_list.push_back(t); + p_usrp.ctx_isopen = false; + return dev_list; +} +bool Device_UHD::openDevice(uhd::device_addr_t addr) +{ + bool bRet = false; + if (this->bFindedDevice) + { + try + { + this->devAddr = addr; + uhd::usrp::multi_usrp::sptr tmp_URSP; + tmp_URSP.ctx = iio_create_context_from_uri("ip:172.22.0.2"); + // tmp_URSP.ctx = iio_create_context_from_uri("ip:192.168.1.141"); + if (tmp_URSP.ctx != NULL) + { + p_usrp = tmp_URSP; + p_usrp.ctx_isopen = true; + bRet = true; + spThread_Recv[0] = NULL; + spThread_Recv[1] = NULL; + // memset(&rxKDParam, 0, sizeof(rxKDParam)); + for (int i = 0; i < 2; i++) + { + rxKDParam[i].KCH = i; + rxKDParam[i].CenterFreq = 0; + rxKDParam[i].BandWidth = 0; /*getDevParam("RX" + i, UHD_ParamType::BandWidth);*/ + rxKDParam[i].SampleFreq = 0; /* getDevParam("RX" + i, UHD_ParamType::SampleFreq);*/ + for (int y = 0; y < ZDChMax; y++) + { + rxKDParam[i].ZDParam[y].KCH = i; + rxKDParam[i].ZDParam[y].ZCH = i * ZDChMax + y; + } + rxKDParam[i].gain = 0; + rxKDParam[i].Snapshot_Switch = false; + rxKDParam[i].Snapshot_tm_s = 0; + txKDParam[i].gain = -40; + led_val = 0; + } + kd_centerfreq_sw = 0; + fftWin = UHD_FFTWin::blkmc; + fftLen = UHD_FFTLen::_32768; + fftPeriod = 10; + } + } + catch (std::exception ex2) + { + std::cout << ex2.what() << std::endl; + p_usrp.ctx_isopen = false; + bRet = false; + } + } + return bRet; +} +void Device_UHD::closeDevice() +{ + if (p_usrp.ctx != NULL) + { + stopDevRecv(0); + stopDevRecv(1); + stopDevSend(0); + stopDevSend(1); + // 释放前,需把所有引用都赋值NULL,方可释放 + // pTree = NULL; // + iio_context_destroy(p_usrp.ctx); + p_usrp.ctx = NULL; // 内部会自动释放指针 + p_usrp.ctx_isopen = false; + } +} +bool Device_UHD::isDevOpened() const +{ + bool ret = p_usrp.ctx_isopen; + return ret; +} +string GetUHDTree(const uhd::fs_path &path, uhd::property_tree::sptr tree) +{ + return "GetUHDTree\r\n"; +} +string Device_UHD::getDevTree() +{ + return "getDevTree\r\n"; +} +string Device_UHD::findDevInfos() +{ + string ret; + char tmp[200]; + if (p_usrp.ctx != NULL) + { + try + { + { // 查询设备信息 + ret += "ip:172.22.0.2\r\n"; + } + { // 查看设备数量、名称、时钟源 + snprintf(tmp, 200, "get_num_mboards:%d", 0); + ret += string(tmp) + "\r\n"; + ret += "\r\n"; + } + { + } + { // 查询接收通道参数 + // int num = (int)pUSRP->get_rx_num_channels(); + snprintf(tmp, 200, "get_rx_num_channels:%d", 2); + ret += string(tmp) + "\r\n"; + for (int i = 0; i < 2; i++) + { + } + ret += "\r\n"; + } + { // 查询发射通道参数 + snprintf(tmp, 200, "get_tx_num_channels:%d", 2); + ret += string(tmp) + "\r\n"; + for (int i = 0; i < 2; i++) + { + { // 查询发射频率范围 + snprintf(tmp, 200, "get_tx_freq_range(%d):%f~%f", i, 0, 6 * GHz); + ret += string(tmp) + "\r\n"; + } + } + ret += "\r\n"; + } + } + catch (std::exception ex2) + { + std::cout << ex2.what() << std::endl; + } + } + return "findDevInfos\r\n"; +} +string Device_UHD::findDevInfos2() +{ + return "ok"; +} +size_t Device_UHD::getDevRXChCount() +{ + size_t bRet = 0; + try + { + if (p_usrp.ctx != NULL) + { + bRet = 2; + } + } + catch (std::exception ex2) + { + std::cout << ex2.what() << std::endl; + } + return bRet; +} +size_t Device_UHD::getDevTXChCount() +{ + size_t bRet = 0; + try + { + if (p_usrp.ctx != NULL) + { + bRet = 2; + } + } + catch (std::exception ex2) + { + std::cout << ex2.what() << std::endl; + } + return bRet; +} +bool Device_UHD::setDevClockSource(string sourceStr) +{ + std::cout << sourceStr << std::endl; + bool ret = true; + try + { + if (p_usrp.ctx != NULL) + { + if (sourceStr.compare("gpsdo") == 0) + { + set_esun_rx_addr_val(p_usrp.ctx, addr_dev_ref_time, 5); + } + else if (sourceStr.compare("external") == 0) + { + set_esun_rx_addr_val(p_usrp.ctx, addr_dev_ref_time, 10); + } + else if (sourceStr.compare("internal") == 0) + { + set_esun_rx_addr_val(p_usrp.ctx, addr_dev_ref_time, 9); + } + } + } + catch (std::exception ex2) + { + std::cout << ex2.what() << std::endl; + ret = false; + } + return ret; +} +string Device_UHD::getDevClockSource() +{ + string ret = "internal"; + try + { + if (p_usrp.ctx != NULL) + { + int64_t val; + get_esun_rx_addr_val(p_usrp.ctx, (int64_t)addr_dev_ref_time, val); + if (val == 5) + { + ret = string("gpsdo"); + } + else if (val == 9) + { + ret = string("internal"); + } + else if (val == 10) + { + ret = string("external"); + } + } + } + catch (std::exception ex2) + { + std::cout << ex2.what() << std::endl; + } + return ret; +} +bool Device_UHD::setDevInClock(double clockFreq) +{ + bool ret = true; + return ret; +} +void Device_UHD::getDevInClockRange() +{ + try + { + if (p_usrp.ctx != NULL) + { + fParamMin = 10000000; + fParamMax = 10000000; + } + } + catch (std::exception ex2) + { + std::cout << ex2.what() << std::endl; + } +} +double Device_UHD::getDevInClock() +{ + double ret = 0; + try + { + if (p_usrp.ctx != NULL) + { + ret = 10000000; + } + } + catch (std::exception ex2) + { + std::cout << ex2.what() << std::endl; + } + return ret; +} +bool Device_UHD::setDevParam(string chStr, UHD_ParamType paramType, double paramValue) +{ + cout << "chstr" << chStr << " paramType:" << (int)paramType << " paramValue" << paramValue << endl; + bool ret = true; + try + { + if (p_usrp.ctx != NULL) + { + int channel = chStr.find("0") != string::npos ? 0 : 1; + bool bTX = chStr.find("TX") != string::npos; + bool tmp_zd_switch = 0; + + //"频点", "带宽", "采样率", "增益", "校准电平" + + if (!bTX) + { + for (int i = 0; i < 8; ++i) + { + tmp_zd_switch += rxKDParam[channel].ZDParam[i].bSwitch_ZDDC; + } + switch (paramType) + { + case UHD_ParamType::CenterFreq: + // if (tmp_zd_switch) + // { + // return false; + // } + if (!bTX) + { + rxKDParam[channel].old_cf = rxKDParam[channel].CenterFreq; + rxKDParam[channel].CenterFreq = paramValue; + if (rxKDParam[channel].old_cf == 0) + { + rxKDParam[channel].old_cf = rxKDParam[channel].CenterFreq; + } + } + break; + case UHD_ParamType::BandWidth: + // if (tmp_zd_switch) + // { + // return false; + // } + if (!bTX) + { + rxKDParam[channel].old_bw = rxKDParam[channel].BandWidth; + rxKDParam[channel].BandWidth = paramValue; + if (rxKDParam[channel].old_bw == 0) + { + rxKDParam[channel].old_bw = rxKDParam[channel].BandWidth; + } + } + break; + case UHD_ParamType::SampleFreq: + // if (tmp_zd_switch) + // { + // return false; + // } + if (!bTX) + { + if (rxKDParam[channel].bSwitch_KDDC == true) + { + unsigned long long sfcnt = 0; + for (int j = 0; j < 2; ++j) + { + sfcnt += rxKDParam[j].SampleFreq * rxKDParam[j].bSwitch_KDDC; + sfcnt += rxKDParam[j].bSwitch_KFFT * ((double)fftLen / 1024 * 2112 * (1000 / (double)fftPeriod) / 4); + sfcnt += rxKDParam[j].Snapshot_Switch * rx_kz_speed_hz; + for (int i = 0; i < 8; ++i) + { + sfcnt += rxKDParam[j].ZDParam[i].SampleFreq * rxKDParam[j].ZDParam[i].bSwitch_ZDDC; + } + } + unsigned long long pre_cnt = sfcnt - rxKDParam[channel].SampleFreq + paramValue; + if (pre_cnt > ach_sf_count_max_hz + 1) + { + return false; + } + sf_all = pre_cnt; + } + rxKDParam[channel].old_sf = rxKDParam[channel].SampleFreq; + rxKDParam[channel].SampleFreq = paramValue; + if (rxKDParam[channel].old_sf == 0) + { + rxKDParam[channel].old_sf = rxKDParam[channel].SampleFreq; + } + } + break; + case UHD_ParamType::Gain: + if (!bTX) + { + + struct iio_device *phy; + struct iio_channel *chn = nullptr; + phy = iio_context_find_device(this->p_usrp.ctx, "adrv9002-phy"); + if (channel == 0) + { + chn = iio_device_find_channel(phy, "voltage0", false); + } + else if (channel == 1) + { + chn = iio_device_find_channel(phy, "voltage1", false); + } + int retno = iio_channel_attr_write_double(chn, "hardwaregain", paramValue); + if (retno != 0) + { + ret = false; + } + else + { + ret = true; + rxKDParam[channel].gain = paramValue; + } + } + return false; + break; + case UHD_ParamType::PowerRef: + break; + case UHD_ParamType::SnapshotSwitch: + if (!bTX) + { + bool bSwitch = (bool)paramValue; + if (bSwitch == true && rxKDParam[channel].Snapshot_Switch == false) + { + unsigned long long sfcnt = 0; + for (int j = 0; j < 2; ++j) + { + sfcnt += rxKDParam[j].SampleFreq * rxKDParam[j].bSwitch_KDDC; + sfcnt += rxKDParam[j].bSwitch_KFFT * ((double)fftLen / 1024 * 2112 * (1000 / (double)fftPeriod) / 4); + sfcnt += rxKDParam[j].Snapshot_Switch * rx_kz_speed_hz; + for (int i = 0; i < 8; ++i) + { + sfcnt += rxKDParam[j].ZDParam[i].SampleFreq * rxKDParam[j].ZDParam[i].bSwitch_ZDDC; + } + } + unsigned long long pre_cnt = sfcnt + rx_kz_speed_hz; + if (pre_cnt > ach_sf_count_max_hz + 1) + { + return false; + } + sf_all = pre_cnt; + } + rxKDParam[channel].Snapshot_Switch = (bool)paramValue; + // 设置获取本来的宽带 通道开关 并置为0; + unsigned char uSwitch = 0; + if (bSwitch == true) + { + rxKDParam[channel].bSwitch_KDDC = false; + for (int i = 0; i < 2; i++) + { + if (rxKDParam[i].bSwitch_KDDC) + { + uSwitch |= 0x01 << i; + } + } + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_ddc_data_sw, 0); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_ddc_data_sw, uSwitch); + } + set_esun_rx_addr_val(p_usrp.ctx, channel == 0 ? addr_rx_kd_ch0_kz_sw : addr_rx_kd_ch1_kz_sw, 0); + set_esun_rx_addr_val(p_usrp.ctx, channel == 0 ? addr_rx_kd_ch0_kz_sw : addr_rx_kd_ch1_kz_sw, rxKDParam[channel].Snapshot_Switch); + return true; + } + return false; + break; + case UHD_ParamType::Snapshot_tm_s: { + if (!bTX) + { + if (rxKDParam[channel].SampleFreq < 0) + { + return false; + } + int tmp_t_max = (int)(kz_sum / rxKDParam[channel].SampleFreq); + if (paramValue > tmp_t_max || paramValue < 0) + { + // paramValue = tmp_t_max; + rxKDParam[channel].Snapshot_tm_s = tmp_t_max; + } + else + { + rxKDParam[channel].Snapshot_tm_s = paramValue; + } + } + } + break; + defualt: + break; + } + + int kd_cur_indx = channel; + double kddcsamp = rxKDParam[channel].SampleFreq; + int ExtraPer = 0; + unsigned long long CenterFreq = rxKDParam[channel].CenterFreq; + long long BandWidth = rxKDParam[channel].BandWidth; + unsigned long long kd_centerfreq_h16 = CenterFreq & 0xffff00000000; + unsigned long long kd_centerfreq_l32 = CenterFreq & 0xffffffff; + int t = rxKDParam[channel].Snapshot_tm_s; + unsigned long long pack_size = ((unsigned int)((t * rxKDParam[channel].SampleFreq * 32.0) / (2048 * 8.0) / 16)) * 16; + set_esun_rx_addr_val(p_usrp.ctx, channel == 0 ? addr_rx_kd_ch0_kz_pack_size : addr_rx_kd_ch1_kz_pack_size, pack_size); + bool enable_6G_ch = 0; + if (CenterFreq >= 30 * MHz && CenterFreq < 6 * GHz) + { + enable_6G_ch = 1; + } + else if (CenterFreq < 30 * MHz && CenterFreq >= 0) + { + enable_6G_ch = 0; + } + if (channel == 0) + { + if (enable_6G_ch == 1) + kd_centerfreq_sw |= 0x01; + if (enable_6G_ch == 0) + kd_centerfreq_sw &= 0x02; + } + if (channel == 1) + { + if (enable_6G_ch == 1) + kd_centerfreq_sw |= 0x02; + if (enable_6G_ch == 0) + kd_centerfreq_sw &= 0x01; + } + // bool bSwitch = false; + // int kd_ddc_up = 0; + int kd_FilterCoef[128] = {0}; + for (int i = KDDCSampIndxMin0; i <= KDDCSampIndxMax0; i++) + { + double tmpssssf = (channel == 0 ?KDDCSampTab0[i][0]:KDDCSampTab1[i][0]); + if ( tmpssssf== kddcsamp) + { + ExtraPer = i; + break; + } + } + if (CenterFreq < 30 * MHz) + { + int kd_30M_ctrword = (int)((double)(CenterFreq - 15000000.0) / (channel == 0 ? define_KDDCSampleMax0 : define_KDDCSampleMax1) * pow(2, 32)); + if (kd_cur_indx == 0) + { + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_ch0_30Mhz_cw, kd_30M_ctrword); + } + if (kd_cur_indx == 1) + { + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_ch1_30MHz_cw, kd_30M_ctrword); + } + } + int kd_filterLen = SetFIRLpCoef2(kd_FilterCoef, 128, (double)BandWidth / kddcsamp, 18, 1.0); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_ddc_ch_sw, kd_centerfreq_sw); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_ddc_ch, kd_cur_indx); + + // if(rxKDParam[channel].old_bw != BandWidth || rxKDParam[channel].old_sf != kddcsamp) + // { + // if (kd_filterLen > 0) + // { + // for (int i = 0; i < kd_filterLen; i++) + // { + // set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_ddc_fc, kd_FilterCoef[i]); + // } + // } + // } + if (!(rxKDParam[channel].old_cf != CenterFreq && rxKDParam[channel].old_bw == BandWidth && rxKDParam[channel].old_sf == kddcsamp)) + { + if (kd_filterLen > 0) + { + for (int i = 0; i < kd_filterLen; i++) + { + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_ddc_fc, kd_FilterCoef[i]); + } + } + } + if (kd_cur_indx == 0) + { + struct iio_channel *chn = nullptr; + struct iio_device *phy; + phy = iio_context_find_device(p_usrp.ctx, "adrv9002-phy"); + chn = iio_device_find_channel(phy, "altvoltage0", true); + bool b1 = (CenterFreq >= (30 * MHz)); + bool b2 = (CenterFreq < (6 * GHz)); + if (b1 && b2) + { + iio_channel_attr_write_longlong(chn, "RX1_LO_frequency", CenterFreq); + } + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_ch0_ddc_df, ExtraPer); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_ch0_ddc_bw, BandWidth); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_ch0_ddc_sf, kddcsamp); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_ch0_ddc_cf_h16, kd_centerfreq_h16); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_ch0_ddc_cf_l32, kd_centerfreq_l32); + } + else if (kd_cur_indx == 1) + { + struct iio_channel *chn = nullptr; + struct iio_device *phy; + phy = iio_context_find_device(p_usrp.ctx, "adrv9002-phy"); + chn = iio_device_find_channel(phy, "altvoltage1", true); + if (CenterFreq >= 30 * MHz && CenterFreq < 6 * GHz) + { + iio_channel_attr_write_longlong(chn, "RX2_LO_frequency", CenterFreq); + } + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_ch1_ddc_df, ExtraPer); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_ch1_ddc_bw, BandWidth); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_ch1_ddc_sf, kddcsamp); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_ch1_ddc_cf_h16, kd_centerfreq_h16); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_ch1_ddc_cf_l32, kd_centerfreq_l32); + } + + struct iio_device *phy; + struct iio_channel *chn = nullptr; + phy = iio_context_find_device(this->p_usrp.ctx, "adrv9002-phy"); + if (channel == 0) + { + chn = iio_device_find_channel(phy, "voltage0", false); + } + else if (channel == 1) + { + chn = iio_device_find_channel(phy, "voltage1", false); + } + // int retno = iio_channel_attr_write_double(chn, "hardwaregain", this->rxKDParam[channel].gain); + // if (retno!=0) + // { + // ret = false; + // } + // else{ + // ret = true; + // rxKDParam[channel].gain = paramValue; + // } + } + + if (bTX) + { + if (paramType == UHD_ParamType::Gain) + { + + struct iio_device *phy; + struct iio_channel *chn = nullptr; + phy = iio_context_find_device(this->p_usrp.ctx, "adrv9002-phy"); + if (channel == 0) + { + chn = iio_device_find_channel(phy, "voltage0", true); + } + else if (channel == 1) + { + chn = iio_device_find_channel(phy, "voltage1", true); + } + int retno = iio_channel_attr_write_double(chn, "hardwaregain", paramValue); + if (retno != 0) + { + ret = false; + } + else + { + ret = true; + txKDParam[channel].gain = paramValue; + } + } + } + } + } + catch (std::exception ex2) + { + std::cout << ex2.what() << std::endl; + ret = false; + } + return ret; +} +double Device_UHD::getDevParam(string chStr, UHD_ParamType paramType) +{ + double ret; + try + { + if (p_usrp.ctx != NULL) + { + int channel = chStr.find("0") != string::npos ? 0 : 1; + bool bTX = chStr.find("TX") != string::npos; + //"频点", "带宽", "采样率", "增益", "校准电平" + if (!bTX) + { + switch (paramType) + { + case UHD_ParamType::CenterFreq: + // ret = bTX ? p_usrp->get_tx_freq(channel) : pUSRP->get_rx_freq(channel); + if (!bTX) + { + ret = rxKDParam[channel].CenterFreq; //= ret; + } + break; + case UHD_ParamType::BandWidth: + if (!bTX) + { + ret = rxKDParam[channel].BandWidth; //= ret; + } + break; + case UHD_ParamType::SampleFreq: + if (!bTX) + { + ret = rxKDParam[channel].SampleFreq; // = ret; + } + break; + case UHD_ParamType::Gain: + ret = rxKDParam[channel].gain; + break; + case UHD_ParamType::PowerRef: + ret = 10000000; + break; + case UHD_ParamType::SnapshotSwitch: + ret = rxKDParam[channel].Snapshot_Switch; + break; + case UHD_ParamType::Snapshot_tm_s: + ret = rxKDParam[channel].Snapshot_tm_s; + } + } + if (bTX) + { + if (paramType == UHD_ParamType::Gain) + { + ret = txKDParam[channel].gain; + } + } + } + } + catch (std::exception ex2) + { + std::cout << ex2.what() << std::endl; + } + return ret; +} +bool Device_UHD::setAllAntenna() +{ + bool ret = true; + return ret; +} +void Device_UHD::getDevParamRange(string chStr, UHD_ParamType paramType, double ¶mMin, double ¶mMax) +{ + try + { + if (p_usrp.ctx != NULL) + { + // uhd::meta_range_t range; + int channel = chStr.find("0") != string::npos ? 0 : 1; + bool bTX = chStr.find("TX") != string::npos; + //"频点", "带宽", "采样率", "增益", "校准电平" + switch (paramType) + { + case UHD_ParamType::CenterFreq: + fParamMin = 0; + fParamMax = 6 * GHz; + break; + case UHD_ParamType::BandWidth: + fParamMin = 0; + fParamMax = 40000000; + break; + case UHD_ParamType::SampleFreq: + fParamMin = 0; + fParamMax = (channel==0?define_KDDCSampleMax0:define_KDDCSampleMax1); + break; + case UHD_ParamType::Gain: + if (!bTX) + { + fParamMin = 0; + fParamMax = 34; + } + break; + case UHD_ParamType::PowerRef: + fParamMin = 0; + fParamMax = 0; + break; + } + } + } + catch (std::exception ex2) + { + std::cout << ex2.what() << std::endl; + } +} +double Device_UHD::getDevParamMin() const +{ + return fParamMin; +} +double Device_UHD::getDevParamMax() const +{ + return fParamMax; +} +bool Device_UHD::setDevDDCParam_Any(string chStr, unsigned int jcqOffset, unsigned int jcqData) +{ + bool ret = true; + if (p_usrp.ctx != NULL) + { + try + { + int channel = chStr.find("0") != string::npos ? 0 : 1; + set_esun_rx_addr_val(p_usrp.ctx, jcqOffset, jcqData); + } + catch (std::exception ex2) + { + std::cout << ex2.what() << std::endl; + } + } + return ret; +} +bool Device_UHD::getDevDDCParam_Any(string chStr, unsigned int jcqOffset, unsigned int &jcqData) +{ + bool ret = true; + if (p_usrp.ctx != NULL) + { + int64_t va; + try + { + int channel = chStr.find("0") != string::npos ? 0 : 1; + get_esun_rx_addr_val(p_usrp.ctx, jcqOffset, va); + jcqData = va; + } + catch (std::exception ex2) + { + std::cout << ex2.what() << std::endl; + } + } + return ret; +} +bool Device_UHD::setDevDataSwitch(string chStr, UHD_ParamType dataType, unsigned char ZDCh, bool bSwitch) +{ + cout << "chstr:" << chStr << " dataType:" << (int)dataType << " ZDCh:" << ZDCh << " bSwitch:" << bSwitch << endl; + int xx = bSwitch == true ? 1 : -1; + bool ret = true; + if (p_usrp.ctx != NULL) + { + try + { + int channel = chStr.find("0") != string::npos ? 0 : 1; + switch (dataType) + { + case KDDCSwitch: { + if (bSwitch != rxKDParam[channel].bSwitch_KDDC) + { + unsigned long long sfcnt = 0; + for (int j = 0; j < 2; ++j) + { + sfcnt += rxKDParam[j].SampleFreq * rxKDParam[j].bSwitch_KDDC; + sfcnt += rxKDParam[j].bSwitch_KFFT * ((double)fftLen / 1024 * 2112 * (1000 / (double)fftPeriod) / 4); + sfcnt += rxKDParam[j].Snapshot_Switch * rx_kz_speed_hz; + for (int i = 0; i < 8; ++i) + { + sfcnt += rxKDParam[j].ZDParam[i].SampleFreq * rxKDParam[j].ZDParam[i].bSwitch_ZDDC; + } + } + unsigned long long pre_cnt = sfcnt + (xx * rxKDParam[channel].SampleFreq); + // if (pre_cnt > ach_sf_count_max_hz + 1) + // { + // cout <<" error pre_cnt"< ach_sf_count_max_hz + 1) + { + return false; + } + sf_all = pre_cnt; + } + unsigned char uSwitch = 0; + for (int i = 0; i < 2; i++) + { + if (rxKDParam[i].bSwitch_KFFT) + { + uSwitch |= 0x01 << i; + } + } + if (bSwitch) + { + uSwitch |= (1 << channel); + } + else + { + uSwitch &= ~(1 << channel); + } + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_fft_sw, 0); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_fft_sw, uSwitch); + rxKDParam[channel].bSwitch_KFFT = bSwitch; + } + break; + case ZDDCSwitch: { + if (bSwitch != rxKDParam[channel].ZDParam[ZDCh % ZDChMax].bSwitch_ZDDC) + { + unsigned long long sfcnt = 0; + for (int j = 0; j < 2; ++j) + { + sfcnt += rxKDParam[j].SampleFreq * rxKDParam[j].bSwitch_KDDC; + sfcnt += rxKDParam[j].bSwitch_KFFT * ((double)fftLen / 1024 * 2112 * (1000 / (double)fftPeriod) / 4); + sfcnt += rxKDParam[j].Snapshot_Switch * rx_kz_speed_hz; + for (int i = 0; i < 8; ++i) + { + sfcnt += rxKDParam[j].ZDParam[i].SampleFreq * rxKDParam[j].ZDParam[i].bSwitch_ZDDC; + } + } + unsigned long long pre_cnt = sfcnt + xx * rxKDParam[channel].ZDParam[ZDCh % ZDChMax].SampleFreq; + // if (pre_cnt > ach_sf_count_max_hz + 1) + // { + // return false; + // } + sf_all = pre_cnt; + } + if (ZDCh >= 0 && ZDCh <= ZDChMax * 2) + { + rxKDParam[channel].ZDParam[ZDCh % ZDChMax].bSwitch_ZDDC = bSwitch; + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_zd_ch, ZDCh); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_zd_ddc_data_sw, 0); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_zd_ch, ZDCh); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_zd_ddc_data_sw, bSwitch); + } + else + ret = false; + } + break; + default: + ret = false; + break; + } + } + catch (std::exception ex2) + { + std::cout << ex2.what() << std::endl; + } + } + return ret; +} +bool Device_UHD::getDevDataSwitch(string chStr, UHD_ParamType dataType, unsigned char ZDCh, bool &bSwitch) +{ + bool ret = true; + if (p_usrp.ctx != NULL) + { + try + { + int channel = chStr.find("0") != string::npos ? 0 : 1; + switch (dataType) + { + case KDDCSwitch: { + bSwitch = rxKDParam[channel].bSwitch_KDDC; + } + break; + case KFFTSwitch: { + bSwitch = rxKDParam[channel].bSwitch_KFFT; + } + break; + case ZDDCSwitch: { + if (ZDCh >= 0 && ZDCh <= ZDChMax * 2) + { + bSwitch = rxKDParam[channel].ZDParam[ZDCh % ZDChMax].bSwitch_ZDDC; + } + } + break; + default: + break; + } + } + catch (std::exception ex2) + { + std::cout << ex2.what() << std::endl; + } + } + return ret; +} +bool Device_UHD::setDevFFTParam(UHD_FFTWin fftWin, UHD_FFTLen fftLen, int fftPeriod_ms) +{ + double curfftlen = (double)fftLen; + bool ret = false; + if (p_usrp.ctx != NULL) + { + try + { + { + unsigned long long d_fft_old = 0; + unsigned long long d_fft_new = 0; + unsigned long long sfcnt = 0; + for (int j = 0; j < 2; ++j) + { + double t_fft_len = (double)this->fftLen; + sfcnt += rxKDParam[j].SampleFreq * rxKDParam[j].bSwitch_KDDC; + d_fft_old += rxKDParam[j].bSwitch_KFFT * ((double)this->fftLen / 1024 * 2112 * (1000 / (double)this->fftPeriod) / 4); + d_fft_new += rxKDParam[j].bSwitch_KFFT * ((double)fftLen / 1024 * 2112 * (1000 / (double)fftPeriod_ms) / 4); + sfcnt += d_fft_old; + sfcnt += rxKDParam[j].Snapshot_Switch * rx_kz_speed_hz; + for (int i = 0; i < 8; ++i) + { + sfcnt += rxKDParam[j].ZDParam[j].SampleFreq * rxKDParam[j].ZDParam[j].bSwitch_ZDDC; + } + } + unsigned long long pre_cnt = sfcnt - d_fft_old + d_fft_new; + if (pre_cnt > ach_sf_count_max_hz + 1) + { + return -3; + } + sf_all = pre_cnt; + } + if (fftPeriod_ms >= 1 && fftPeriod_ms <= 1000) + { + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_fft_type, fftWin); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_fft_len, fftLen); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_kd_fft_preiod, fftPeriod_ms); + this->fftWin = fftWin; + this->fftLen = fftLen; + this->fftPeriod = fftPeriod_ms; + ret = true; + } + } + catch (std::exception ex2) + { + std::cout << ex2.what() << std::endl; + } + } + return ret; +} +bool Device_UHD::getDevFFTParam(UHD_FFTWin &fftWin, UHD_FFTLen &fftLen, int &fftPeriod_ms) +{ + bool ret = true; + if (p_usrp.ctx != NULL) + { + fftWin = this->fftWin; + fftLen = this->fftLen; + fftPeriod_ms = this->fftPeriod; + } + return ret; +} +bool Device_UHD::setLedEnable(int led_num, bool bEnable) +{ + int mv_size = 0; + if (led_num == 0) + { + mv_size = 1; + } + if (led_num == 1) + { + mv_size = 4; + } + if (led_num == 2) + { + mv_size = 3; + } + if (led_num == 3) + { + mv_size = 2; + } + if (led_num == 4) + { + mv_size = 0; + } + if (led_num == 5) + { + mv_size = 5; + } + if (p_usrp.ctx != NULL) + { + if (bEnable) + { + this->led_val = led_val | (1 << mv_size); + } + else + { + this->led_val &= ~(1 << mv_size); + } + set_esun_rx_addr_val(p_usrp.ctx, addr_dev_led, led_val); + return true; + } + return false; +} +bool Device_UHD::getLedEnable(int led_num, bool &bEnable) +{ + if (p_usrp.ctx != NULL) + { + int mv_size = 0; + if (led_num == 0) + { + mv_size = 1; + } + if (led_num == 1) + { + mv_size = 4; + } + if (led_num == 2) + { + mv_size = 3; + } + if (led_num == 3) + { + mv_size = 2; + } + if (led_num == 4) + { + mv_size = 0; + } + if (led_num == 5) + { + mv_size = 5; + } + int enable_val = led_val >> mv_size & 0x01; + bEnable = enable_val; + return true; + } + return false; +} +int Device_UHD::setDevZDParam(string chStr, unsigned char ZDCh, long long centerfreq, int bw, int sample) +{ + int ret = 0; + if (p_usrp.ctx != NULL) + { + try + { + int channel = chStr.find("0") != string::npos ? 0 : 1; + if (sample == 0) + { + rxKDParam[channel].ZDParam[ZDCh % ZDChMax].CenterFreq = 0; + rxKDParam[channel].ZDParam[ZDCh % ZDChMax].BandWidth = 0; + rxKDParam[channel].ZDParam[ZDCh % ZDChMax].SampleFreq = 0; + } + else + { + int kddcSam = rxKDParam[channel].SampleFreq; + long long kddcCenter = rxKDParam[channel].CenterFreq; + int kddcBW = rxKDParam[channel].BandWidth; + int samIndex = ZDExtraMin; + for (int i = ZDExtraMin; i <= ZDExtraMax; i++) + { + if ((int)(kddcSam / pow(2, i + 0)) == sample) + { + samIndex = i; + break; + } + } + int samSum = 0; + for (auto zd : rxKDParam[channel].ZDParam) + { + samSum += zd.ZCH != ZDCh ? zd.SampleFreq : 0; + } + if (samIndex < ZDExtraMin || samSum + sample > ZDSamSum) + { + ret = -3; + } + if (centerfreq < 0 || centerfreq < kddcCenter - kddcBW / 2 || centerfreq > kddcCenter + kddcBW / 2) + { + ret = -1; + } + if (bw < (int)(kddcSam / pow(2, ZDExtraMax + 2) * 0.1) || bw > (int)(kddcSam / pow(2, ZDExtraMin + 2) * 0.8)) + { + ret = -2; + } + { + unsigned long long sfcnt = 0; + for (int j = 0; j < 2; ++j) + { + sfcnt += rxKDParam[j].SampleFreq * rxKDParam[j].bSwitch_KDDC; + sfcnt += rxKDParam[j].bSwitch_KFFT * ((double)fftLen / 1024 * 2112 * (1000 / (double)fftPeriod) / 4); + sfcnt += rxKDParam[j].Snapshot_Switch * rx_kz_speed_hz; + for (int i = 0; i < 8; ++i) + { + sfcnt += rxKDParam[j].ZDParam[i].SampleFreq * rxKDParam[j].ZDParam[i].bSwitch_ZDDC; + } + } + unsigned long long pre_cnt = sfcnt - rxKDParam[channel].ZDParam[ZDCh % ZDChMax].SampleFreq + sample; + if (pre_cnt > ach_sf_count_max_hz + 1) + { + return -3; + } + sf_all = pre_cnt; + } + if (ret == 0) + { + int freqkey = (int)((double)(centerfreq - rxKDParam[channel].CenterFreq) / kddcSam * pow(2, 32)); + long long old_cf = rxKDParam[channel].ZDParam[ZDCh % ZDChMax].CenterFreq; + long long old_bw = rxKDParam[channel].ZDParam[ZDCh % ZDChMax].BandWidth; + long long old_sf = rxKDParam[channel].ZDParam[ZDCh % ZDChMax].SampleFreq; + rxKDParam[channel].ZDParam[ZDCh % ZDChMax].CenterFreq = centerfreq; + rxKDParam[channel].ZDParam[ZDCh % ZDChMax].BandWidth = bw; + rxKDParam[channel].ZDParam[ZDCh % ZDChMax].SampleFreq = sample; + int zd_is_up = rxKDParam[channel].ZDParam[ZDCh % ZDChMax].bSwitch_ZDDC; + { + int CH = ZDCh; + unsigned long long BandWidth = bw; + unsigned long long SampleFreq = sample; + unsigned long long CenterFreq = centerfreq; + int CtrWord = freqkey; + bool bSwitch = zd_is_up; + int chouqvlv_num = samIndex; + int chouqvlv = samIndex; + int zd_FilterCoef[128]; + memset(zd_FilterCoef, 0, 128 * sizeof(int)); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_zd_ch, ZDCh); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_zd_df, chouqvlv); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_zd_bw, BandWidth); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_zd_cw, CtrWord); + if (!(old_cf != CenterFreq && old_bw == BandWidth && old_sf == sample)) + { + int zd_filterLen = SetFIRLpCoef2(zd_FilterCoef, 128, (double)BandWidth / SampleFreq, 18, 1.0); + for (int i = 0; i < zd_filterLen; ++i) + { + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_zd_fc, zd_FilterCoef[i]); + } + } + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_zd_sf, SampleFreq); + // set_esun_rx_addr_val(p_usrp.ctx, addr_rx_zd_ch, ZDCh); + } + ret = 0; + } + } + } + catch (std::exception ex2) + { + std::cout << ex2.what() << std::endl; + } + } + return ret; +} +bool Device_UHD::getDevZDParam(string chStr, unsigned char ZDCh, long long ¢erfreq, int &bw, int &sample) +{ + bool ret = true; + try + { + int channel = chStr.find("0") != string::npos ? 0 : 1; + centerfreq = rxKDParam[channel].ZDParam[ZDCh % ZDChMax].CenterFreq; + bw = rxKDParam[channel].ZDParam[ZDCh % ZDChMax].BandWidth; + sample = rxKDParam[channel].ZDParam[ZDCh % ZDChMax].SampleFreq; + } + catch (std::exception ex2) + { + std::cout << ex2.what() << std::endl; + } + return ret; +} +void Device_UHD::getDevZDCenterRange(string chStr, long long &min, long long &max) +{ + int channel = chStr.find("0") != string::npos ? 0 : 1; + min = rxKDParam[channel].CenterFreq - rxKDParam[channel].BandWidth / 2; + min = std::max(min, 0LL); + max = rxKDParam[channel].CenterFreq + rxKDParam[channel].BandWidth / 2; +} +void Device_UHD::getDevZDBandWidthRange(string chStr, int &min, int &max) +{ + int channel = chStr.find("0") != string::npos ? 0 : 1; + min = rxKDParam[channel].SampleFreq / pow(2, ZDExtraMax + 2) * 0.1; + max = rxKDParam[channel].SampleFreq / pow(2, ZDExtraMin + 2) * 0.8; +} +vector Device_UHD::getDevZDSampleFreqRange(string chStr) +{ + vector vecSam; + int channel = chStr.find("0") != string::npos ? 0 : 1; + for (int i = ZDExtraMax; i >= ZDExtraMin; i--) + { + double exSam = rxKDParam[channel].SampleFreq / pow(2, i + 2); + if (exSam > ZDSamSum) + { + continue; + } + vecSam.push_back(exSam); + } + return vecSam; +} +bool old_need_sw; +void ThreadRecv_Func(ThreadRecvParam recvParam) +{ + Device_UHD *pThis = (Device_UHD *)recvParam.pThis; + int channel = recvParam.channel; + if (pThis != NULL && pThis->p_usrp.ctx != NULL) + { + try + { + std::chrono::steady_clock::time_point befTime = std::chrono::steady_clock::now(); + long long iRecvedLen = 0; + struct iio_device *phy; + struct iio_channel *chan; + phy = iio_context_find_device(pThis->p_usrp.ctx, "adrv9002-phy"); + if (pThis->p_usrp.ctx) + { + if (channel == 0) + { + chan = iio_device_find_channel(phy, "voltage0", false); + iio_channel_attr_write(chan, "ensm_mode", "rf_enabled"); + + pThis->p_usrp.iio_tx_arr[channel].tx_dev = iio_context_find_device(pThis->p_usrp.ctx, "axi-adrv9002-tx-lpc"); + stream_channels_get_disenable(pThis->p_usrp.iio_tx_arr[channel].tx_dev, pThis->p_usrp.iio_tx_arr[channel].tx_chan, true); + chan = iio_device_find_channel(phy, "voltage0", true); + iio_channel_attr_write(chan, "ensm_mode", "primed"); + + pThis->p_usrp.iio_rx_arr[channel].rx_dev = iio_context_find_device(pThis->p_usrp.ctx, "axi-adrv9002-rx-lpc"); + stream_channels_get_enable(pThis->p_usrp.iio_rx_arr[channel].rx_dev, pThis->p_usrp.iio_rx_arr[channel].rx_chan, false); + tmp_block_size = my_iio_rx_block_point_size_big; + pThis->p_usrp.iio_rx_arr[channel].rx_buf = iio_device_create_buffer(pThis->p_usrp.iio_rx_arr[channel].rx_dev, my_iio_rx_block_point_size_big, false); + } + if (channel == 1) + { + chan = iio_device_find_channel(phy, "voltage1", false); + iio_channel_attr_write(chan, "ensm_mode", "rf_enabled"); + + pThis->p_usrp.iio_tx_arr[channel].tx_dev = iio_context_find_device(pThis->p_usrp.ctx, "axi-adrv9002-tx2-lpc"); + stream_channels_get_disenable(pThis->p_usrp.iio_tx_arr[channel].tx_dev, pThis->p_usrp.iio_tx_arr[channel].tx_chan, true); + chan = iio_device_find_channel(phy, "voltage1", true); + iio_channel_attr_write(chan, "ensm_mode", "primed"); + pThis->p_usrp.iio_rx_arr[channel].rx_dev = iio_context_find_device(pThis->p_usrp.ctx, "axi-adrv9002-rx2-lpc"); + stream_channels_get_enable(pThis->p_usrp.iio_rx_arr[channel].rx_dev, pThis->p_usrp.iio_rx_arr[channel].rx_chan, false); + tmp_block_size = my_iio_rx_block_point_size_big; + pThis->p_usrp.iio_rx_arr[channel].rx_buf = iio_device_create_buffer(pThis->p_usrp.iio_rx_arr[channel].rx_dev, my_iio_rx_block_point_size_big, false); + } + // int ttret = iio_buffer_set_blocking_mode( pThis->p_usrp.iio_rx_arr[channel].rx_buf,false); + // int b =0; + } + void *buff_ptrs; + while (pThis->bThread_Recv[channel]) + { + tmp_sf_all = sf_all; + int nrxbytes = iio_buffer_refill(pThis->p_usrp.iio_rx_arr[channel].rx_buf); + int a = 0; + buff_ptrs = iio_buffer_start(pThis->p_usrp.iio_rx_arr[channel].rx_buf); + size_t recvSize = nrxbytes; // num_rx_samps * iPointSize * iChCount; + if (recvSize > 0 && nrxbytes <= tmp_block_size * 4) + { + // cout <<" have data"<ischeck_head; + if (bCheckHead) + { + int &iRecvBufSize = pThis->iRecvBufSize[channel]; // 缓存总大小 + int &iRecvBufPosi = pThis->iRecvBufPosi[channel]; // 缓存当前大小 + char *pDataBuf = (char *)pThis->pRecvBuf[channel]; // 缓存数据指针 + int length = recvSize; // 网络接收数据大小 + int lengthPosi = 0; // 网络接收数据已处理大小 + char *pData = (char *)buff_ptrs; // 网络数据指针 + char *pCheckData = NULL; // 检测包头的数据指针 + int posi = 0; + if (iRecvBufPosi > 0) + { + int needSize = iRecvBufSize - iRecvBufPosi; // 还需要补充数据量 + needSize = needSize > length ? length : needSize; + lengthPosi = needSize; + memcpy((char *)pDataBuf + iRecvBufPosi, pData, needSize); + iRecvBufPosi = needSize + iRecvBufPosi; // 当前缓存中数据长度 + pCheckData = pDataBuf; + } + else + { + iRecvBufPosi = length; + pCheckData = pData; + } + // 111 + while (pThis->bThread_Recv[channel] && posi < iRecvBufPosi) + { + if (posi + 4 < iRecvBufPosi) + { + if (((unsigned int *)(pCheckData + posi))[0] == 0xf628f6f6) + { + int packLen = (int)2112; + if (posi + packLen <= iRecvBufPosi) + { + if (pThis->callBackData != NULL) + { + pThis->callBackData(channel, pCheckData + posi, packLen); + if (*((char *)pCheckData + posi + 12) == 16) + { + char gps_info[60] = {0}; + strncpy(gps_info, pCheckData + posi + 64, 28); + pThis->gps_info = gps_info; + std::reverse(pThis->gps_info.begin(), pThis->gps_info.end()); + } + } + posi += packLen; + } + else + { + break; + } + } + else + { + posi += 1; + } + } + else + { + break; + } + } + // 如果有剩余数据 + if (posi < iRecvBufPosi) + { + memcpy(pDataBuf, pCheckData + posi, iRecvBufPosi - posi); + iRecvBufPosi = iRecvBufPosi - posi; + } + else + { + iRecvBufPosi = 0; + } + if (pCheckData != pData) + { + if (length - lengthPosi < 2112) + { + memcpy(pDataBuf + iRecvBufPosi, pData + lengthPosi, length - lengthPosi); + iRecvBufPosi += length - lengthPosi; + } + else + { + // 111 + posi = lengthPosi - iRecvBufPosi; + pCheckData = pData; + while (pThis->bThread_Recv[channel] && posi < length) + { + if (posi + 4 < length) + { + if (((unsigned int *)(pCheckData + posi))[0] == 0xf628f6f6) + { + int packLen = (int)2112; + if (posi + packLen <= length) + { + if (pThis->callBackData != NULL) + { + pThis->callBackData(channel, pCheckData + posi, packLen); + if (*((char *)pCheckData + posi + 12) == 16) + { + char gps_info[60] = {0}; + strncpy(gps_info, pCheckData + posi + 64, 28); + pThis->gps_info = gps_info; + std::reverse(pThis->gps_info.begin(), pThis->gps_info.end()); + } + } + posi += packLen; + } + else + { + break; + } + } + else + { + posi += 1; + } + } + else + { + break; + } + } + // 如果有剩余数据 + if (posi < length) + { + memcpy(pDataBuf, pCheckData + posi, length - posi); + iRecvBufPosi = length - posi; + } + else + { + iRecvBufPosi = 0; + } + // 111 + } + } + } + else + { + pThis->callBackData(channel, buff_ptrs, (int)recvSize); + if (*((char *)buff_ptrs + 12) == 16) + { + char gps_info[60] = {0}; + strncpy(gps_info, (char *)buff_ptrs + 64, 28); + pThis->gps_info = gps_info; + std::reverse(pThis->gps_info.begin(), pThis->gps_info.end()); + } + } + } + + bool need_big = false; + for (int i = 0; i < 2; ++i) + { + if (pThis->rxKDParam[i].bSwitch_KDDC == true) + { + need_big = true; + } + for (int j = 0; j < 8; ++j) + { + if (pThis->rxKDParam[i].ZDParam[j].bSwitch_ZDDC == true) + { + need_big = true; + } + } + } + if (need_big == true && need_big != old_need_sw) + { + iio_buffer_destroy(pThis->p_usrp.iio_rx_arr[channel].rx_buf); + pThis->p_usrp.iio_rx_arr[channel].rx_buf = iio_device_create_buffer(pThis->p_usrp.iio_rx_arr[channel].rx_dev, my_iio_rx_block_point_size_big, false); + old_need_sw = need_big; + } + if (need_big == false && need_big != old_need_sw) + { + iio_buffer_destroy(pThis->p_usrp.iio_rx_arr[channel].rx_buf); + pThis->p_usrp.iio_rx_arr[channel].rx_buf = iio_device_create_buffer(pThis->p_usrp.iio_rx_arr[channel].rx_dev, my_iio_rx_block_point_size_big, false); + old_need_sw = need_big; + } + std::chrono::steady_clock::time_point curTime = std::chrono::steady_clock::now(); + auto dur_ms = std::chrono::duration_cast(curTime - befTime); + if (dur_ms.count() > 1000) + { + pThis->fRecvSpeed[channel] = (double)iRecvedLen / dur_ms.count() * 1000; + iRecvedLen = 0; + befTime = curTime; + } + } + if (channel == 0) + { + chan = iio_device_find_channel(phy, "voltage0", false); + iio_channel_attr_write(chan, "ensm_mode", "primed"); + pThis->p_usrp.iio_rx_arr[channel].rx_dev = iio_context_find_device(pThis->p_usrp.ctx, "axi-adrv9002-rx-lpc"); + stream_channels_get_disenable(pThis->p_usrp.iio_rx_arr[channel].rx_dev, pThis->p_usrp.iio_rx_arr[channel].rx_chan, false); + iio_buffer_destroy(pThis->p_usrp.iio_rx_arr[channel].rx_buf); + } + if (channel == 1) + { + chan = iio_device_find_channel(phy, "voltage1", false); + iio_channel_attr_write(chan, "ensm_mode", "primed"); + pThis->p_usrp.iio_rx_arr[channel].rx_dev = iio_context_find_device(pThis->p_usrp.ctx, "axi-adrv9002-rx2-lpc"); + stream_channels_get_disenable(pThis->p_usrp.iio_rx_arr[channel].rx_dev, pThis->p_usrp.iio_rx_arr[channel].rx_chan, false); + iio_buffer_destroy(pThis->p_usrp.iio_rx_arr[channel].rx_buf); + } + } + catch (std::exception ex) + { + std::cout << ex.what() << std::endl; + } + } +} +double Device_UHD::getDevRecvSpeed(int channel) const +{ + return fRecvSpeed[channel]; +} +bool Device_UHD::isDevRecving(int channel) const +{ + return bThread_Recv[channel]; +} +void Device_UHD::startDevRecv(int channel) +{ + if (spThread_Recv[channel] != NULL) + { + bThread_Recv[channel] = false; + spThread_Recv[channel]->join(); + spThread_Recv[channel] = NULL; + if (pRecvBuf[channel] != NULL) + { + free(pRecvBuf[channel]); + pRecvBuf[channel] = NULL; + } + } + else + { + iRecvBufSize[channel] = 2112 * 2; + iRecvBufPosi[channel] = 0; + pRecvBuf[channel] = malloc(iRecvBufSize[channel]); + bThread_Recv[channel] = true; + ThreadRecvParam recvParam; + recvParam.channel = channel; + recvParam.pThis = this; + // rx_kd_ddc_sw |= (1 << channel); + // set_esun_rx_addr_val(p_usrp.ctx, addr_rx_data_sw, rx_kd_ddc_sw); + + send_all_sw &= ~(1 << channel); + set_esun_rx_addr_val(p_usrp.ctx, addr_tx_send_data_cw, send_all_sw); + + long long tmll = time(0); + + set_esun_rx_addr_val(p_usrp.ctx, addr_tm_set_l, tmll & 0xffffffff); + set_esun_rx_addr_val(p_usrp.ctx, addr_tm_set_h, tmll >> 32); + + spThread_Recv[channel] = std::make_shared(ThreadRecv_Func, recvParam); + } +} +void Device_UHD::stopDevRecv(int channel) +{ + if (spThread_Recv[channel] != NULL) + { + bThread_Recv[channel] = false; + spThread_Recv[channel]->join(); + spThread_Recv[channel] = NULL; + } +} +double Device_UHD::getDevSendSpeed(int channel) const +{ + return fSendSpeed[channel]; +} +bool Device_UHD::isDevSending(int channel) const +{ + return bThread_Send[channel]; +} +void ThreadSend_Func(Device_UHD *pThis, unsigned long long send_cf, unsigned long long data_sf, int channel, char *filename, bool bWhile) +{ + if (pThis != NULL && pThis->p_usrp.ctx_isopen) + { + std::chrono::steady_clock::time_point befTime = std::chrono::steady_clock::now(); + long long iSendedLen0 = 0; + long long iSendedLen1 = 0; + char *pdata0; + char *pdata1; + struct iio_device *phy; + struct iio_channel *chan0; + struct iio_channel *chan1; + phy = iio_context_find_device(pThis->p_usrp.ctx, "adrv9002-phy"); + // 定义缓冲区 + char buffer0[1024]; + char buffer1[1024]; + std::vector content0; + std::vector content1; + size_t read_len0 = 0; + size_t read_len1 = 0; + // set_esun_rx_addr_val(p_usrp.ctx, addr_dev_ref_time, 5); + int insert_num = 0; + int cw_30Mhz = 0; + cw_30Mhz = ((double)send_cf / ((double)122880000) * pow(2, 32)); + for (int i = 0; i <= 10; i++) + { + if (((int)define_KDDCSampleMax0 / pow(2, i)) == data_sf) + { + insert_num = i; + break; + } + } + if (channel == 0) + { + pThis->send_all_sw |= (1 << channel); + } + if (channel == 1) + { + pThis->send_all_sw |= (1 << channel); + } + if (send_cf > 30 * MHz && send_cf < 6 * GHz) + { + pThis->send_chan_sw &= ~(1 << channel); + } + if (send_cf <= 30 * MHz && send_cf > 0) + { + pThis->send_chan_sw |= (1 << channel); + } + int ch_cw = pThis->send_chan_sw; + if (pThis->p_usrp.ctx) + { + + // pThis->rxKDParam[channel].bSwitch_KDDC = false; + // pThis->rxKDParam[channel].bSwitch_KFFT = false; + // for(int i = 0; i <8;++i) + // { + // pThis->rxKDParam[0].ZDParam[i].bSwitch_ZDDC = false; + + // } + + // int kz_val = 0; + // for(int i = 0; i <2;++i) + // { + // if(pThis->rxKDParam[i].Snapshot_Switch == true) + // { + + // kz_val |=1<rxKDParam[i].Snapshot_Switch + + // kz_val &=~(1<p_usrp.ctx, addr_rx_kd_ddc_data_sw, 0); + + // set_esun_rx_addr_val(pThis->p_usrp.ctx, addr_rx_kd_ddc_data_sw, 0); + + if (send_cf > 30 * MHz && send_cf < 6 * GHz) + { + if (channel == 0) + { + + pThis->p_usrp.iio_rx_arr[channel].rx_dev = iio_context_find_device(pThis->p_usrp.ctx, "axi-adrv9002-rx-lpc"); + stream_channels_get_disenable(pThis->p_usrp.iio_rx_arr[channel].rx_dev, pThis->p_usrp.iio_rx_arr[channel].rx_chan, false); + + chan0 = iio_device_find_channel(phy, "voltage0", false); + iio_channel_attr_write(chan0, "ensm_mode", "primed"); + + chan0 = iio_device_find_channel(phy, "voltage0", true); + iio_channel_attr_write(chan0, "ensm_mode", "rf_enabled"); + set_esun_rx_addr_val(pThis->p_usrp.ctx, addr_tx_ch0_insert_rate, insert_num); + set_esun_rx_addr_val(pThis->p_usrp.ctx, addr_tx_send_ch_sw, ch_cw); + chan0 = iio_device_find_channel(phy, "altvoltage2", true); + iio_channel_attr_write_longlong(chan0, "TX1_LO_frequency", send_cf); + pThis->p_usrp.iio_tx_arr[channel].tx_dev = iio_context_find_device(pThis->p_usrp.ctx, "axi-adrv9002-tx-lpc"); + stream_channels_get_enable(pThis->p_usrp.iio_tx_arr[channel].tx_dev, pThis->p_usrp.iio_tx_arr[channel].tx_chan, true); + pThis->p_usrp.iio_tx_arr[channel].tx_buf = iio_device_create_buffer(pThis->p_usrp.iio_tx_arr[channel].tx_dev, my_iio_tx_block_point_size, false); + } + if (channel == 1) + { + + pThis->p_usrp.iio_rx_arr[channel].rx_dev = iio_context_find_device(pThis->p_usrp.ctx, "axi-adrv9002-rx2-lpc"); + stream_channels_get_disenable(pThis->p_usrp.iio_rx_arr[channel].rx_dev, pThis->p_usrp.iio_rx_arr[channel].rx_chan, false); + + chan1 = iio_device_find_channel(phy, "voltage1", false); + iio_channel_attr_write(chan1, "ensm_mode", "primed"); + + chan1 = iio_device_find_channel(phy, "voltage1", true); + iio_channel_attr_write(chan1, "ensm_mode", "rf_enabled"); + set_esun_rx_addr_val(pThis->p_usrp.ctx, addr_tx_ch1_insert_rate, insert_num); + set_esun_rx_addr_val(pThis->p_usrp.ctx, addr_tx_send_ch_sw, ch_cw); + chan1 = iio_device_find_channel(phy, "altvoltage3", true); + iio_channel_attr_write_longlong(chan1, "TX2_LO_frequency", send_cf); + pThis->p_usrp.iio_tx_arr[channel].tx_dev = iio_context_find_device(pThis->p_usrp.ctx, "axi-adrv9002-tx2-lpc"); + stream_channels_get_enable(pThis->p_usrp.iio_tx_arr[channel].tx_dev, pThis->p_usrp.iio_tx_arr[channel].tx_chan, true); + // pThis->p_usrp.iio_tx_arr[channel].tx_chan[1] = iio_device_find_channel(pThis->p_usrp.iio_tx_arr[channel].tx_dev, "voltage0", true); + // if (!iio_channel_is_enabled(pThis->p_usrp.iio_tx_arr[channel].tx_chan[1])) + // { + // iio_channel_enable(pThis->p_usrp.iio_tx_arr[channel].tx_chan[1]); + // } + pThis->p_usrp.iio_tx_arr[channel].tx_buf = iio_device_create_buffer(pThis->p_usrp.iio_tx_arr[channel].tx_dev, my_iio_tx_block_point_size, false); + } + } + else if (send_cf <= 30 * MHz && send_cf > 0) + { + if (channel == 0) + { + chan0 = iio_device_find_channel(phy, "voltage0", true); + iio_channel_attr_write(chan0, "ensm_mode", "primed"); + set_esun_rx_addr_val(pThis->p_usrp.ctx, addr_tx_ch0_insert_rate, insert_num); + set_esun_rx_addr_val(pThis->p_usrp.ctx, addr_tx_ch0_30MHz_cw, cw_30Mhz); + set_esun_rx_addr_val(pThis->p_usrp.ctx, addr_tx_send_ch_sw, ch_cw); + pThis->p_usrp.iio_tx_arr[channel].tx_dev = iio_context_find_device(pThis->p_usrp.ctx, "axi-adrv9002-tx-lpc"); + stream_channels_get_enable(pThis->p_usrp.iio_tx_arr[channel].tx_dev, pThis->p_usrp.iio_tx_arr[channel].tx_chan, true); + pThis->p_usrp.iio_tx_arr[channel].tx_buf = iio_device_create_buffer(pThis->p_usrp.iio_tx_arr[channel].tx_dev, my_iio_tx_block_point_size, false); + } + if (channel == 1) + { + chan1 = iio_device_find_channel(phy, "voltage1", true); + iio_channel_attr_write(chan1, "ensm_mode", "primed"); + set_esun_rx_addr_val(pThis->p_usrp.ctx, addr_tx_ch1_insert_rate, insert_num); + set_esun_rx_addr_val(pThis->p_usrp.ctx, addr_tx_ch1_30MHz_cw, cw_30Mhz); + set_esun_rx_addr_val(pThis->p_usrp.ctx, addr_tx_send_ch_sw, ch_cw); + pThis->p_usrp.iio_tx_arr[channel].tx_dev = iio_context_find_device(pThis->p_usrp.ctx, "axi-adrv9002-tx2-lpc"); + stream_channels_get_enable(pThis->p_usrp.iio_tx_arr[channel].tx_dev, pThis->p_usrp.iio_tx_arr[channel].tx_chan, true); + // pThis->p_usrp.iio_tx_arr[channel].tx_chan[1] = iio_device_find_channel(pThis->p_usrp.iio_tx_arr[channel].tx_dev, "voltage0", true); + // if (!iio_channel_is_enabled(pThis->p_usrp.iio_tx_arr[channel].tx_chan[1])) + // { + // iio_channel_enable(pThis->p_usrp.iio_tx_arr[channel].tx_chan[1]); + // } + pThis->p_usrp.iio_tx_arr[channel].tx_buf = iio_device_create_buffer(pThis->p_usrp.iio_tx_arr[channel].tx_dev, my_iio_tx_block_point_size, false); + } + } + } + + if (channel == 0) + { + std::ifstream file(filename, std::ios::binary); + if (!file.is_open()) + { + std::cerr << "无法打开文件" << std::endl; + return; // 返回错误代码 + } + // 逐块读取文件内容 + while (file.read(buffer0, sizeof(buffer0))) + { + std::streamsize bytesRead = file.gcount(); // 获取实际读取的字节数 + content0.insert(content0.end(), buffer0, buffer0 + bytesRead); + } + // 处理最后一块可能不足1024字节的情况 + if (file) + { + std::streamsize bytesRead = file.gcount(); + content0.insert(content0.end(), buffer0, buffer0 + bytesRead); + } + // 关闭文件 + file.close(); + } + if (channel == 1) + { + std::ifstream file(filename, std::ios::binary); + if (!file.is_open()) + { + std::cerr << "无法打开文件" << std::endl; + return; // 返回错误代码 + } + // 逐块读取文件内容 + while (file.read(buffer1, sizeof(buffer1))) + { + std::streamsize bytesRead = file.gcount(); // 获取实际读取的字节数 + content1.insert(content1.end(), buffer1, buffer1 + bytesRead); + } + // 处理最后一块可能不足1024字节的情况 + if (file) + { + std::streamsize bytesRead = file.gcount(); + content1.insert(content1.end(), buffer1, buffer1 + bytesRead); + } + // 关闭文件 + file.close(); + } + set_esun_rx_addr_val(pThis->p_usrp.ctx, addr_tx_send_data_cw, pThis->send_all_sw); + while (pThis->bThread_Send[channel]) + { + if (channel == 0) + { + size_t num_tx = iio_buffer_push(pThis->p_usrp.iio_tx_arr[channel].tx_buf); + if (num_tx <= 0 || num_tx > my_iio_tx_block_point_size * 4) + { + continue; + } + pdata0 = (char *)iio_buffer_start(pThis->p_usrp.iio_tx_arr[channel].tx_buf); + if (!pdata0) + { + continue; + } + if (content0.size() < num_tx) + { + break; + } + if (content0.size() - read_len0 < num_tx) + { + if (bWhile == true) + { + // read_len0 = 0; + + // 多余数据 + unsigned long long dysj = content0.size() - read_len0; + // 需要切割的头部数据 + unsigned long long need_cut_size = num_tx - dysj; + + ::memcpy(pdata0, content0.data() + read_len0, dysj); + ::memcpy(pdata0 + dysj, content0.data(), need_cut_size); + + read_len0 = need_cut_size; + iSendedLen0 += num_tx; + std::chrono::steady_clock::time_point curTime = std::chrono::steady_clock::now(); + auto dur_ms = std::chrono::duration_cast(curTime - befTime); + if (dur_ms.count() > 1000) + { + pThis->fSendSpeed[channel] = (double)iSendedLen0 / dur_ms.count() * 1000; + iSendedLen0 = 0; + befTime = curTime; + } + + continue; + } + else + { + break; + } + } + ::memcpy(pdata0, content0.data() + read_len0, num_tx); + read_len0 += num_tx; + iSendedLen0 += num_tx; + std::chrono::steady_clock::time_point curTime = std::chrono::steady_clock::now(); + auto dur_ms = std::chrono::duration_cast(curTime - befTime); + if (dur_ms.count() > 1000) + { + pThis->fSendSpeed[channel] = (double)iSendedLen0 / dur_ms.count() * 1000; + iSendedLen0 = 0; + befTime = curTime; + } + } + if (channel == 1) + { + size_t num_tx = iio_buffer_push(pThis->p_usrp.iio_tx_arr[channel].tx_buf); + if (num_tx <= 0 || num_tx > my_iio_tx_block_point_size * 4) + { + continue; + } + pdata1 = (char *)iio_buffer_start(pThis->p_usrp.iio_tx_arr[channel].tx_buf); + if (!pdata1) + { + continue; + } + if (content1.size() < num_tx) + { + break; + } + if (content1.size() - read_len1 < num_tx) + { + if (bWhile == true) + { + // read_len1 = 0; + + // 多余数据 + unsigned long long dysj = content1.size() - read_len1; + // 需要切割的头部数据 + unsigned long long need_cut_size = num_tx - dysj; + + ::memcpy(pdata1, content1.data() + read_len1, dysj); + ::memcpy(pdata1 + dysj, content1.data(), need_cut_size); + + read_len1 = need_cut_size; + iSendedLen1 += num_tx; + std::chrono::steady_clock::time_point curTime = std::chrono::steady_clock::now(); + auto dur_ms = std::chrono::duration_cast(curTime - befTime); + if (dur_ms.count() > 1000) + { + pThis->fSendSpeed[channel] = (double)iSendedLen1 / dur_ms.count() * 1000; + iSendedLen1 = 0; + befTime = curTime; + } + + continue; + } + else + { + break; + } + } + ::memcpy(pdata1, content1.data() + read_len1, num_tx); + read_len1 += num_tx; + iSendedLen1 += num_tx; + std::chrono::steady_clock::time_point curTime = std::chrono::steady_clock::now(); + auto dur_ms = std::chrono::duration_cast(curTime - befTime); + if (dur_ms.count() > 1000) + { + pThis->fSendSpeed[channel] = (double)iSendedLen1 / dur_ms.count() * 1000; + iSendedLen1 = 0; + befTime = curTime; + } + } + } + + //--------------------------------------------- + + pThis->send_chan_sw &= ~(1 << channel); + set_esun_rx_addr_val(pThis->p_usrp.ctx, addr_tx_send_ch_sw, ch_cw); + + pThis->send_all_sw &= ~(1 << channel); + + set_esun_rx_addr_val(pThis->p_usrp.ctx, addr_tx_send_data_cw, pThis->send_all_sw); + if (channel == 0) + { + pThis->p_usrp.iio_tx_arr[channel].tx_dev = iio_context_find_device(pThis->p_usrp.ctx, "axi-adrv9002-tx-lpc"); + stream_channels_get_disenable(pThis->p_usrp.iio_tx_arr[channel].tx_dev, pThis->p_usrp.iio_tx_arr[channel].tx_chan, true); + chan0 = iio_device_find_channel(phy, "voltage0", true); + iio_channel_attr_write(chan0, "ensm_mode", "primed"); + } + if (channel == 1) + { + pThis->p_usrp.iio_tx_arr[channel].tx_dev = iio_context_find_device(pThis->p_usrp.ctx, "axi-adrv9002-tx2-lpc"); + stream_channels_get_disenable(pThis->p_usrp.iio_tx_arr[channel].tx_dev, pThis->p_usrp.iio_tx_arr[channel].tx_chan, true); + chan0 = iio_device_find_channel(phy, "voltage1", true); + iio_channel_attr_write(chan0, "ensm_mode", "primed"); + } + + iio_buffer_destroy(pThis->p_usrp.iio_tx_arr[channel].tx_buf); + } +} +void Device_UHD::startDevSend(int channel, unsigned long long send_cf, unsigned long long data_sf, char *filename, bool bwhile) +{ + if (spThread_Send[channel] != NULL) + { + bThread_Send[channel] = false; + spThread_Send[channel]->join(); + spThread_Send[channel] = NULL; + } + else + { + bThread_Send[channel] = true; + rx_kd_ddc_sw &= ~(1 << channel); + set_esun_rx_addr_val(p_usrp.ctx, addr_rx_data_sw, rx_kd_ddc_sw); + spThread_Send[channel] = std::make_shared(ThreadSend_Func, this, send_cf, data_sf, channel, filename, bwhile); + } +} +void Device_UHD::stopDevSend(int channel) +{ + if (spThread_Send[channel] != NULL) + { + bThread_Send[channel] = false; + spThread_Send[channel]->join(); + spThread_Send[channel] = NULL; + } +} +string Device_UHD::getGPSInfo() +{ + + return this->gps_info; +} diff --git a/module/dll_source_lzy/ecap/lib/device_uhd_cpp.h b/module/dll_source_lzy/ecap/lib/device_uhd_cpp.h new file mode 100644 index 0000000..434f7c5 --- /dev/null +++ b/module/dll_source_lzy/ecap/lib/device_uhd_cpp.h @@ -0,0 +1,113 @@ +#ifndef DEVICE_UHD_H +#define DEVICE_UHD_H + +#include "device_uhd_struct.h" +#include +#include +#include +#include +#include +#include +#include +#include + +#include + + +class Device_UHD +{ +public: + uhd::device_addr_t devAddr; //设备地址 + bool bFindedDevice; + std::shared_ptr spThread_Recv[2]; + std::shared_ptr spThread_Send[2]; + uhd::property_tree::sptr pTree; + int kd_centerfreq_sw; + double fParamMin; + double fParamMax; + UHD_FFTWin fftWin;//窗类型 + UHD_FFTLen fftLen;//窗长度 + int fftPeriod;//频谱周期 1-1000,单位ms + UHD_KDParam rxKDParam[2];//rx宽带通道参数 + UHD_KDParam txKDParam[2];//tx宽带通道参数 + int FilterCoef[256];//滤波器系数数组 +public: + std::string gps_info; + int led_val; + +public: + //! Device type, used as a filter in make + //enum device_filter_t { ANY, USRP, CLOCK }; + bool isDevOpened() const; + uhd::device_addrs_t findDevices(); + bool openDevice(uhd::device_addr_t addr); + //关闭设备 + void closeDevice(); + //获取设备信息 + string findDevInfos(); + //获取设备信息2 + string findDevInfos2(); + //获取设备树 + string getDevTree(); + //设置时钟源 + bool setDevClockSource(string sourceStr); + //获取时钟源 + string getDevClockSource(); + bool setDevInClock(double clockFreq); + void getDevInClockRange(); + double getDevInClock(); + size_t getDevRXChCount(); + size_t getDevTXChCount(); + bool setDevParam(string chStr, UHD_ParamType paramType, double paramValue); + double getDevParam(string chStr, UHD_ParamType paramType); + void getDevParamRange(string chStr, UHD_ParamType paramType, double& paramMin, double& paramMax); + double getDevParamMin() const; + double getDevParamMax() const; + bool setAllAntenna(); + bool setDevDDCParam_Any(string chStr, unsigned int jcqOffset, unsigned int jcqData); + bool getDevDDCParam_Any(string chStr, unsigned int jcqOffset, unsigned int& jcqData); + bool setDevDataSwitch(string chStr, UHD_ParamType dataType, unsigned char ZDCh, bool bSwitch); + bool getDevDataSwitch(string chStr, UHD_ParamType dataType, unsigned char ZDCh, bool& bSwitch); + //采样率为0,表示该通道停止使用 + bool ischeck_head =true; + int setDevZDParam(string chStr, unsigned char ZDCh, long long centerfreq, int bw, int sample); + //采样率为0,表示该通道未使用 + bool getDevZDParam(string chStr, unsigned char ZDCh, long long& centerfreq, int& bw, int& sample); + void getDevZDCenterRange(string chStr, long long& min, long long& max); + void getDevZDBandWidthRange(string chStr, int& min, int& max); + vector getDevZDSampleFreqRange(string chStr); + bool setDevFFTParam(UHD_FFTWin fftWin, UHD_FFTLen fftLen, int fftPeriod_ms); + bool getDevFFTParam(UHD_FFTWin& fftWin, UHD_FFTLen& fftLen, int& fftPeriod_ms); + + bool bThread_Recv[2] = { 0, 0 }; + double fRecvSpeed[2] = { 0, 0 }; + void* pRecvBuf[2] = { 0, 0 }; + int iRecvBufSize[2] = { 0, 0 }; + int iRecvBufPosi[2] = { 0, 0 }; + double getDevRecvSpeed(int channel) const; + bool isDevRecving(int channel) const; + void startDevRecv(int channel); + void stopDevRecv(int channel); + double getDevSendSpeed(int channel) const; + bool isDevSending(int channel) const; + bool bThread_Send[2]= {0,0}; + double fSendSpeed[2] = {0,0}; + + int send_chan_sw =0; + int send_all_sw = 0; + int rx_kd_ddc_sw = 0; + + void startDevSend(int channel ,unsigned long long send_cf, unsigned long long data_sf,char*filename,bool bwhile); + void stopDevSend(int channel); + //uhd::usrp::multi_usrp::sptr pUSRP1; + uhd::usrp::multi_usrp::sptr p_usrp; + std::function callBackData; + + std::string getGPSInfo(); + bool setLedEnable(int led_num,bool bEnable); + bool getLedEnable(int led_num,bool &bEnable); + + + +}; +#endif // DEVICE_UHD_H diff --git a/module/dll_source_lzy/ecap/lib/device_uhd_struct.h b/module/dll_source_lzy/ecap/lib/device_uhd_struct.h new file mode 100644 index 0000000..f4a543d --- /dev/null +++ b/module/dll_source_lzy/ecap/lib/device_uhd_struct.h @@ -0,0 +1,322 @@ +#ifndef device_uhd_struct_h +#define device_uhd_struct_h +#include +#include +#include +#ifdef __linux__ +#include +#include "iio.h" +#endif +#ifdef WIN32 +#include +#endif +#include + +#pragma pack(push) +#pragma pack(1) +namespace uhd +{ + typedef std::string fs_path; + class device_addr_t + { + public: + std::string uri; + std::string to_string(void) const + { + return uri; + } + }; + typedef std::vector device_addrs_t; + namespace usrp + { + namespace multi_usrp + { + typedef struct rx_parm + { + struct iio_device *rx_dev = nullptr; + struct iio_channel *rx_chan[2]; + struct iio_buffer *rx_buf; + bool rx_chan_is_enable; + bool rx_buf_is_enable; + } rx_parm; + typedef struct tx_parm + { + struct iio_device *tx_dev = nullptr; + struct iio_channel *tx_chan[2]; + struct iio_buffer *tx_buf; + bool tx_chan_is_enable; + bool tx_buf_is_enable; + } tx_parm; + typedef struct sptr + { + struct iio_context *ctx = nullptr; + bool ctx_isopen; + struct rx_parm iio_rx_arr[2]; + struct tx_parm iio_tx_arr[2]; + device_addrs_t uri_list; + std::string cur_sourceStr; + double cur_clockFreq; + int rx0_power_reference; + int rx1_power_reference; + int tx0_power_reference; + int tx1_power_reference; + } sptr; + } + } + namespace property_tree + { + typedef std::string sptr; + } +} +#pragma pack(pop) +#define ZDSamSum 200000000//8路窄带采样率之和 +#define ZDChMax 8 //每路大通道下窄带通道总数 +enum UHD_ParamType : int +{ + CenterFreq = 0, + BandWidth = 1, + SampleFreq = 2, + Gain = 3, + PowerRef = 4, + KDDCSwitch = 5, + KFFTSwitch = 6, + ZDDCSwitch = 7, + ZDDCParam = 8, + KFFTParam = 9, + ClockSource = 10, + SnapshotSwitch = 11, + Snapshot_tm_s = 12, +}; +enum UHD_FFTWin : unsigned char +{ + jxc =0,// 矩形窗 = 0, + hnc = 1,// 汉宁窗 = 1, + hmc = 2, // 海明窗 = 2, + blkmc = 3,// 布莱克曼窗 = 3, +}; +enum UHD_FFTLen : unsigned int +{ + _1024 = 1024, + _2048 = 2048, + _4096 = 4096, + _8192 = 8192, + _16384 = 16384, + _32768 = 32768, +}; +#pragma pack(push) +#pragma pack(1) +struct UHD_ZDParam +{ + unsigned char KCH = 0;//宽带通道号 + unsigned short ZCH = 0;//窄带通道号 + long long CenterFreq = 0; // 中频 + int BandWidth = 0; //带宽 + int SampleFreq = 0; // 采样率 + int ExtraPer = 1024;//抽取率 4-4096,2的指数 + bool bSwitch_ZDDC = false; + +}; +struct UHD_KDParam +{ + unsigned char KCH = 0;//宽带通道号 + long long CenterFreq = 10000000; + + int BandWidth = 160000000; + int SampleFreq = 200000000; + + bool bSwitch_6GCH = false; + + bool bSwitch_KDDC = false; + bool bSwitch_KFFT = false; + double gain = 0; + UHD_ZDParam ZDParam[ZDChMax]; + int ExtraPer; + bool Snapshot_Switch=false; + int Snapshot_tm_s = 0; + + unsigned long long old_sf; + unsigned long long old_cf; + unsigned long long old_bw; + +}; +#pragma region 枚举/结构体 + +/** @brief TODO: 时码类型枚举 + * @enum LibWZ57_Enum_TimeType + */ +enum Enum_TimeType : uint8_t +{ + Enum_TimeType_Invlid = 0, /**< 无效的*/ + Enum_TimeType_IRIG_B = 1, /**< IRIG-B*/ + Enum_TimeType_RMC = 2, /**< RMC*/ + Enum_TimeType_ABSCNTTM = 3, /**< 绝对计数时间*/ + Enum_TimeType_REFCNTTM = 4, /**< 相对计数时间*/ +}; +typedef struct struct_DateTime +{ + + Enum_TimeType TimeType; /**< 10 时码类型*/ + + /** @brief 10个字节的时码信息 + * @details + * 根据 @ref LibWZ57_Enum_TimeType TimeType,对应不同的 联合体 + */ + union TimeInfo + { + ///@brief IRIG-B + ///@struct IRIGB_Head + struct IRIGB_Head + { + uint8_t Year; /**< 年 字节1*/ + uint16_t Day; /**< 日 字节2*/ + uint8_t Hour; /**< 时 字节1*/ + uint8_t Minute; /**< 分 字节1*/ + uint8_t Second; /**< 秒 字节1*/ + uint32_t NanoSec; /**< 纳 字节4*/ + } IRIGB_Head; + + ///@brief RMC + ///@struct RMC_Head + struct RMC_Head + { + uint8_t Year; /**< 年 字节1*/ + uint8_t Month; /**< 月 字节1*/ + uint8_t Day; /**< 日 字节1*/ + uint8_t Hour; /**< 时 字节1*/ + uint8_t Minute; /**< 分 字节1*/ + uint8_t Second; /**< 秒 字节1*/ + uint32_t NanoSec; /**< 纳 字节4*/ + } RMC_Head; + + ///@brief 绝对计数时间 + ///@struct ABSCNTTM_Head + struct ABSCNTTM_Head + { + ///@brief 秒 字节6; 基准秒计数时间+相对秒计数时间 单位:秒 + uint8_t Second[6]; + ///@brief 纳秒 字节4; + uint32_t NanoSec; + } ABSCNTTM_Head; + + ///@brief 相对计数时间 + ///@struct REFCNTTM_Head + struct REFCNTTM_Head + { + ///@brief 秒 字节6; 相对秒计数时间单位:秒 + uint8_t Second[6]; + ///@brief 纳秒 字节4; + uint32_t NanoSec; + } REFCNTTM_Head; + } TimeInfo; + +} struct_DataTime; + + + +#pragma region 枚举 +/***************************** +*数据类型 +*****************************/ +enum UHD_Enum_DataType : unsigned char +{ + zd_ddc = 1, + kd_ddc = 2, + kd_fft = 3, + GPS_Info = 16, + // 窄带DDC = 0x01, + // 宽带DDC = 0x02, + // 宽带FFT = 0x03, +}; +#pragma endregion +#pragma region 结构体 +#pragma region UHD_Struct_KFFT UHD_Struct_KDDC UHD_Struct_ZDDC +/// +/// 宽带FFT头 +/// +typedef struct +{ + /// + /// 帧标识 6 0x2828F628F6F6 固定值 + /// + unsigned int Head; + /// + /// + /// + unsigned short Head2; + /// + /// 协议版本 1 0x80 + /// + unsigned char DealVersion; + /// + /// 帧头长度 1 64 + /// + unsigned char FrameHeadLen; + /// + /// 数据长度 2 2048 + /// + unsigned short DataLen; + /// + /// 有效数据长度 2 2048 + /// + unsigned short UsefullLen; + /// + /// 数据类型 1 + /// + UHD_Enum_DataType DataType; + unsigned char Other1; + /// + /// 通道号 + /// + unsigned char Channel; + unsigned char Other2; + unsigned short ZDChannel; + /// + /// 帧计数 2 0 ~ 65535 循环递增 + /// + unsigned short FrameIndex; + /// + /// 帧起止标识 1 0x0 + /// + unsigned char FrameBeginFlag; + struct_DateTime DateTm; + /// + /// 采样率 4 单位Hz + /// + unsigned int SampleFreq_Hz; + /// + /// 带宽 4 单位Hz + /// + unsigned int BandWidth_Hz; + /// + /// 中心频点 4 单位Hz,低位 + /// + unsigned int CenterFreq_Hz_Low; + /// + /// 中心频点 2 单位Hz,高位 + /// + unsigned short CenterFreq_Hz_High; + union + { + unsigned char other5[18]; + struct + { + unsigned char other4[6]; + /// + /// FFT长度 65536 + /// + int FFTPoint; + unsigned char other5[2]; + float other6; + /// + /// 段内帧号 + /// + unsigned short SubFrame; + } FFT; + } Param; + //数据 2048 共1024个数据,1个数据2字节。 +} UHD_Struct_KFFT, UHD_Struct_KDDC, UHD_Struct_ZDDC; +#pragma endregion +#pragma endregion +#pragma pack(pop) +#pragma endregion +#endif diff --git a/module/dll_source_lzy/ecap/lib/hulc/Bit.cpp b/module/dll_source_lzy/ecap/lib/hulc/Bit.cpp new file mode 100644 index 0000000..2965e78 --- /dev/null +++ b/module/dll_source_lzy/ecap/lib/hulc/Bit.cpp @@ -0,0 +1,761 @@ +#include "Bit.h" +#include +#include +#include +#include +#include +// 2025-01-02 05:01:50 [info] 1a480118 9607f81e f020 3a24 67761dbd 1a9ecbf8 5655c75b 00601307 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _USE_GTEST +#include +using namespace yC; +#endif +constexpr std::array make_hex_to_val() { + std::array t{255}; // 初始化为255 + for (uint8_t i = '0'; i <= '9'; ++i) t[i] = i - '0'; + for (uint8_t i = 'A'; i <= 'F'; ++i) t[i] = i - 'A' + 10; + for (uint8_t i = 'a'; i <= 'f'; ++i) t[i] = i - 'a' + 10; + return t; +} +constexpr std::array make_val_to_hex(bool uppercase) { + std::uint8_t s = uppercase ? 'A' : 'a'; + std::array t{}; + for (uint8_t i = 0; i < 10; ++i) { + t[i] = '0' + i; // '0' - '9' + } + for (uint8_t i = 10; i < 16; ++i) { + t[i] = s + (i - 10); // 'a' - 'f' 'A - F' + } + return t; +} +static constexpr std::array val_to_upper_hex = make_val_to_hex(true); +static constexpr std::array val_to_lower_hex = make_val_to_hex(false); +static constexpr std::array hex_to_val = make_hex_to_val(); +constexpr const char* hex_lut_lower = "0123456789abcdef"; +constexpr const char* hex_lut_upper = "0123456789ABCDEF"; +constexpr const char* big_dian_hex_to_bin[16] = { + "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", + "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111" +}; +constexpr const char* small_dian_hex_to_bin[16] = { + "0000", "1000", "0100", "1100", "0010", "1010", "0110", "1110", + "0001", "1001", "0101", "1101", "0011", "1011", "0111", "1111" +}; +constexpr std::array, 256> make_xor_table() { + std::array, 256> t{}; + for (size_t i = 0; i < 256; ++i) { + for (size_t j = 0; j < 256; ++j) { + t[i][j] = 255; + } + } + for (size_t i = 0; i < 16; ++i) { + for (size_t j = 0; j < 16; ++j) { + t[val_to_lower_hex[i]][val_to_lower_hex[j]] = i ^ j; + t[val_to_upper_hex[i]][val_to_upper_hex[j]] = i ^ j; + } + } + return t; +} + +static constexpr std::array, 256> xor_table = make_xor_table(); +inline size_t bin4_to_hex(bool big_byte_order, const char* a) { + static size_t small_base[]{1, 2, 4, 8}; + static size_t big_base[]{8, 4, 2, 1}; + auto cur_dian = big_byte_order ? big_base : small_base; + size_t ret = 0; + for (size_t i = 0; i < 4; ++i) { + auto cur = size_t(a[i] - '0'); + ret += cur_dian[i] * cur; + } + return ret; +} + + + +namespace yC { + const bool is_big_endian = []() { + uint16_t x = 0x0102; // 设置一个已知的 16-bit 值 + auto* p = reinterpret_cast(&x); + return p[0] == 0x01; // 如果 p[0] 为 0x01,说明是大端字节序 + }(); + std::vector split(const std::string& str, const std::string& delimiter) { + std::vector tokens; + size_t start = 0; + size_t end = str.find(delimiter); + if (end == std::string::npos) return {}; + while (end != std::string::npos) { + tokens.push_back(str.substr(start, end - start)); + start = end + 1; + end = str.find(delimiter, start); + } + tokens.push_back(str.substr(start)); // Add the last token + return tokens; + } + std::string bin2mem(const std::string& bin) { + const size_t len = bin.size(); + if (len % 8 != 0) { + throw std::invalid_argument("binary string length must be a multiple of 8"); + } + std::string result; + result.reserve(len / 8); // 提前分配 + for (size_t i = 0; i < len; i += 8) { + uint8_t byte = 0; + for (size_t j = 0; j < 8; ++j) { + char bit = bin[i + j]; + if (bit == '1') { + byte |= (1 << (7 - j)); + } else if (bit != '0') { + std::ostringstream oss; + oss << "Invalid bit character '" << bit << "' at position " << (i + j); + throw std::invalid_argument(oss.str()); + } + } + result.push_back(static_cast(byte)); + } + return result; + } + + void bin2mem(void* dest, const char* data, size_t size) { + if (size % 8 != 0) { + throw std::invalid_argument("Binary string length must be a multiple of 8"); + } + uint8_t* byte_dest = static_cast(dest); // 将 dest 转换为字节指针 + for (size_t i = 0; i < size; i += 8) { + uint8_t byte = 0; + for (size_t j = 0; j < 8; ++j) { + char bit = data[i + j]; + if (bit == '1') { + byte |= (1 << (7 - j)); // 设置相应的位 + } else if (bit != '0') { + std::ostringstream oss; + oss << "Invalid bit character '" << bit << "' at position " << (i + j); + throw std::invalid_argument(oss.str()); + } + } + byte_dest[i / 8] = byte; // 将转换后的字节写入目标内存 + } + } + + void hex2mem_Ex(void* dest, const char* data, size_t size) { + // 判断输入 hex 数据的长度是否为偶数 + if (size % 2 != 0) { + throw std::invalid_argument("hex string length must be even"); + } + // 填充目标数据 + for (size_t i = 0; i < size; i += 2) { + unsigned char hi = data[i]; + unsigned char lo = data[i + 1]; + auto hi_val = hex_to_val[hi]; + auto lo_val = hex_to_val[lo]; + + if (hi_val == 255 || lo_val == 255) { + std::ostringstream oss; + oss << "hex:[" << data << "] Invalid hex: [" << data[i] << data[i + 1] << "] at pos " << i; + throw std::invalid_argument(oss.str()); + } + + // 填充目标内存 + unsigned char byte = (hi_val << 4) | lo_val; + std::memcpy(static_cast(dest) + i / 2, &byte, 1); + } + } + + void mem2hex_Ex2(void* dest, void* mem, size_t num, bool uppercase, const char* middle, size_t middle_len) { + assert(middle != nullptr); + + const char* lut = uppercase ? hex_lut_upper : hex_lut_lower; + if (middle_len == std::numeric_limits::max()) { + middle_len = (middle != nullptr) ? std::strlen(middle) : 0; + } + char* dest_ptr = static_cast(dest); + for (size_t i = 0; i < num; ++i) { + unsigned char c = static_cast(mem)[i]; + *dest_ptr++ = lut[c >> 4]; + *dest_ptr++ = lut[c & 0xF]; + // 添加分隔符 + if (middle_len > 0 && i + 1 < num) { + std::copy(middle, middle + middle_len, dest_ptr); + dest_ptr += middle_len; + } + } + } + + void hex2bin_Ex(void* dest, const char* data, size_t size, bool big_dian) { + auto& dian = big_dian ? big_dian_hex_to_bin : small_dian_hex_to_bin; + for (size_t i = 0; i < size; i++) { + auto str = dian[hex_to_val[(unsigned char)(data[i])]]; + std::memmove(static_cast(dest) + i * 4, str, 4); + } + } + + void + bin2hex_Ex(void* dest, const char* d, size_t size, bool big_dian, bool uppercase) { + const char* lut = uppercase ? hex_lut_upper : hex_lut_lower; + auto tt = get_bin2hex_size(size); + auto n1 = size; + auto n2 = tt * 4; + char cur[4] = {'0', '0', '0', '0'}; + auto r = static_cast(dest); + if (!big_dian) { + // 小端 补充后导0 + for (size_t i = 0; i < n2; i++) { + auto j = i%4; + cur[j] = i >= n1 ? '0' : d[i]; + if (j == 3) { + auto val = bin4_to_hex(false, cur); + r[tt - 1 - i/4] = lut[val]; + } + } + } else { + // 大端模式:补充前导0 + for (size_t i = 0; i < n2; i++) { + // 对应位置 + auto j = i%4; + cur[j] = i >= n1 ? '0' : d[n1 - 1 - i]; + if (j == 3) { + auto val = bin4_to_hex(false, cur); + r[tt - 1 - i/4] = lut[val]; + } + } + } + } +#ifdef _USE_GTEST + TEST(Bit2223, bin2hex_Ex) { + // EXPECT_EQ(bin2hex("01101110"), "6E"); + // + { + // 0110 1110 + // 6 E + std::string it = "1101110"; + auto size = get_bin2hex_size(it.size()); + std::string res; + res.resize(size); + bin2hex_Ex(res.data(), it.c_str(), it.size(), true, true); + EXPECT_STREQ(res.c_str(), "6E"); + } + { + // 1101 1100 + // B 3 + + std::string it = "1101110"; + auto size = get_bin2hex_size(it.size()); + std::string res; + res.resize(size); + bin2hex_Ex(res.data(), it.c_str(), it.size(), false, true); + + // std::cout << res << std::endl; + EXPECT_STREQ(res.c_str(), "3B"); + } + + + } +#endif + + + void xor_bin_Ex(void* dest, const char* s1, size_t n1, const char* s2, size_t n2, bool big_dian) { + if (n1 > n2) { + std::swap(n1, n2); + std::swap(s1, s2); + } + // n1 <= n2 + char* r = static_cast(dest); + if (!big_dian) { + // 小端 补充后导0 + for (size_t i = 0; i < n1; i++) { + r[i] = s1[i] == s2[i] ? '0' : '1'; + } + for (size_t i = n1; i < n2; i++) { + r[i] = '0' == s2[i] ? '0' : '1'; + } + } else { + // 大端模式:补充前导0 + for (size_t i = 0; i < n1; i++) { + // 对应位置 + auto c1 = s1[n1 - 1 - i]; + auto c2 = s2[n2 - 1 - i]; + r[n2 - 1 - i] = c1 == c2 ? '0' : '1'; // 对应位异或 + } + for (size_t i = n1; i < n2; i++) { + auto c1 = '0'; + auto c2 = s2[n2 - 1 - i]; + r[n2 - 1 - i] = c1 == c2 ? '0' : '1'; // 对应位异或 + } + } + } +#ifdef _USE_GTEST + TEST(Bit2223, xor_bin_Ex) { + const char* s1 = "10"; + const char* s2 = "111"; + std::string res; + res.resize(3); + xor_bin_Ex(res.data(), s1, 2, s2, 3, true); + EXPECT_STREQ(res.c_str(), "101"); + xor_bin_Ex(res.data(), s1, 2, s2, 3, false); + EXPECT_STREQ(res.c_str(), "011"); + xor_bin_Ex(res.data(), s2, 3, s1, 2, false); + EXPECT_STREQ(res.c_str(), "011"); + + s2 = "1111"; + res.resize(4); + // 0010 + // 1111 + // 1101 + xor_bin_Ex(res.data(), s1, 2, s2, 4, true); + EXPECT_STREQ(res.c_str(), "1101"); + } +#endif + + + + void xor_hex_Ex(void* dest, const char* s1, size_t n1, const char* s2, size_t n2, bool big_dian, bool uppercase) { + if (n1 > n2) { + std::swap(n1, n2); + std::swap(s1, s2); + } + auto& val_to_hex = uppercase ? val_to_upper_hex : val_to_lower_hex; + // n1 <= n2 + auto r = static_cast(dest); + if (!big_dian) { + // 小端 补充后导0 + for (size_t i = 0; i < n1; i++) { + //r[i] = s1[i] == s2[i] ? '0' : '1'; + auto c1 = s1[i]; + auto c2 = s2[i]; + r[i] = val_to_hex[xor_table[c1][c2]]; + } + for (size_t i = n1; i < n2; i++) { + //r[i] = '0' == s2[i] ? '0' : '1'; + auto c1 = '0'; + auto c2 = s2[i]; + r[i] = val_to_hex[xor_table[c1][c2]]; + } + } else { + // 大端模式:补充前导0 + for (size_t i = 0; i < n1; i++) { + // 对应位置 + auto c1 = s1[n1 - 1 - i]; + auto c2 = s2[n2 - 1 - i]; + //r[n2 - 1 - i] = c1 == c2 ? '0' : '1'; // 对应位异或 + auto idx = xor_table[c1][c2]; + r[n2 - 1 - i] = val_to_hex[idx]; // 对应位异或 + } + for (size_t i = n1; i < n2; i++) { + auto c1 = '0'; + auto c2 = s2[n2 - 1 - i]; + auto idx = xor_table[c1][c2]; + //r[n2 - 1 - i] = c1 == c2 ? '0' : '1'; // 对应位异或 + r[n2 - 1 - i] = val_to_hex[idx]; // 对应位异或 + } + } + } +#ifdef _USE_GTEST + TEST(Bi222, xor_hex_Ex) { + { + const char* s1 = "10"; + const char* s2 = "111"; + std::string res; + res.resize(3); + xor_hex_Ex(res.data(), s1, 2, s2, 3, true, true); + EXPECT_STREQ(res.c_str(), "101"); + xor_hex_Ex(res.data(), s1, 2, s2, 3, false, true); + EXPECT_STREQ(res.c_str(), "011"); + xor_hex_Ex(res.data(), s2, 3, s1, 2, false, true); + EXPECT_STREQ(res.c_str(), "011"); + } + { + const char* s1 = "ab"; + const char* s2 = "111"; + std::string res; + res.resize(3); + // 0ab 0000 0110 0111 + // 111 0001 0001 0001 + // 1ba 0001 0111 0110 + xor_hex_Ex(res.data(), s1, 2, s2, 3, true, true); + EXPECT_STREQ(res.c_str(), "1BA"); + + + + } + } +#endif + + // 将字节序从大端转换到当前平台字节序,并复制到目标内存中 + void big_endian_2_platform(const std::string& big_endian, char* dest) { + // 先复制原始数据 + std::string result = big_endian; + // 如果当前平台是小端,反转数据 + if (!is_big_endian) { + std::reverse(result.begin(), result.end()); + } + // 将转换后的数据拷贝到目标内存中 + std::memcpy(dest, result.data(), result.size()); + } + std::string big_endian_2_platform(const std::string& big_endian) { + std::string result; + result.resize(big_endian.size()); + big_endian_2_platform(big_endian, result.data()); + return result; + } + // 将字节序从小端转换到当前平台字节序,并复制到目标内存中 + void little_endian_2_platform(const std::string& little_endian, char* dest) { + // 先复制原始数据 + std::string result = little_endian; + // 如果当前平台是大端,反转数据 + if (is_big_endian) { + std::reverse(result.begin(), result.end()); + } + // 将转换后的数据拷贝到目标内存中 + std::memcpy(dest, result.data(), result.size()); + } + std::string little_endian_2_platform(const std::string& little_endian) { + std::string result; + result.resize(little_endian.size()); + big_endian_2_platform(little_endian, result.data()); + return result; + } + // 将平台字节序转换为大端字节序 + std::string platform_2_big_endian(void* t, int size) { + char* memory = reinterpret_cast(t); + // for (int i = 0; i < size; ++i) { + // std::cout << (int)memory[i] << std::endl; + // } + std::string result(memory, memory + size); + // 如果当前平台是小端,反转字符串,使其成为大端字节序 + //std::cout << "platform_2_big_endian start " << memory2hex(result) << std::endl; + if (!is_big_endian) { + std::reverse(result.begin(), result.end()); + } + //std::cout << "platform_2_big_endian end " << memory2hex(result) << std::endl; + return result; + } + // 将平台字节序转换为小端字节序 + std::string platform_2_little_endian(void* t, int size) { + char* memory = reinterpret_cast(t); + std::string result(memory, memory + size); + // 如果当前平台是大端,反转字符串,使其成为小端字节序 + if (is_big_endian) { + std::reverse(result.begin(), result.end()); + } + return result; + } +#define GET_BIT(byte, pos) (((byte) >> (pos)) & 1) +#define SET_BIT(byte, pos) ((byte) |= (1 << (pos))) +#define CLR_BIT(byte, pos) ((byte) &= ~(1 << (pos))) +#define WRITE_BIT(byte, pos, val) \ + ((byte) = ((byte) & ~(1 << (pos))) | (((val) & 1) << (pos))) + template + void bit_op(void* dest, size_t d_offset, const void* src, size_t s_offset, size_t num, BitOp op) { + auto* d = (uint8_t*)dest; + const auto* s = (const uint8_t*)src; + for (size_t i = 0; i < num; ++i) { + size_t src_pos = s_offset + i; + size_t dst_pos = d_offset + i; + uint8_t src_bit = GET_BIT(s[src_pos / 8], src_pos % 8); + uint8_t dst_bit = GET_BIT(d[dst_pos / 8], dst_pos % 8); + uint8_t res_bit = op(dst_bit, src_bit); + WRITE_BIT(d[dst_pos / 8], dst_pos % 8, res_bit); + } + } + void bit_move(void* d, size_t doff, const void* s, size_t soff, size_t n) { + bit_op(d, doff, s, soff, n, [](uint8_t, uint8_t s) { return s; }); + } + void bit_xor(void* d, size_t doff, const void* s, size_t soff, size_t n) { + bit_op(d, doff, s, soff, n, [](uint8_t d, uint8_t s) { return d ^ s; }); + } + void bit_or(void* d, size_t doff, const void* s, size_t soff, size_t n) { + bit_op(d, doff, s, soff, n, [](uint8_t d, uint8_t s) { return d | s; }); + } + void bit_and(void* d, size_t doff, const void* s, size_t soff, size_t n) { + bit_op(d, doff, s, soff, n, [](uint8_t d, uint8_t s) { return d & s; }); + } +} +constexpr uint8_t reverse8(uint8_t b) { + b = (b & 0xF0) >> 4 | (b & 0x0F) << 4; + b = (b & 0xCC) >> 2 | (b & 0x33) << 2; + b = (b & 0xAA) >> 1 | (b & 0x55) << 1; + return b; +} +constexpr std::array make_reverse8_table() { + std::array arr = {}; + for (uint16_t i = 0; i < 256; ++i) arr[i] = reverse8(static_cast(i)); + return arr; +} +constexpr auto reserve8 = make_reverse8_table(); +#define BYTE(b) reserve8[0b##b] +#ifdef _USE_GTEST +#include +using namespace yC; +// 辅助函数:字节数组转十六进制字符串(方便调试) +std::string bytes_to_hex(const std::vector& v) { + std::ostringstream oss; + for (auto b : v) { + oss << std::hex << std::setw(2) << std::setfill('0') << (int)b; + } + return oss.str(); +} +// case 2:dest 偏移,src 对齐 +TEST(BitMoveTest, DestBitOffset) { + struct Data { + std::vector dest; + size_t dest_offset; + std::vector src; + size_t src_offset; + size_t num; + std::vector expected_move; + std::vector expected_xor; + std::vector expected_or; + std::vector expected_and; + std::string msg; + }; + std::vector list; + // 1. 目标偏移2位,拷贝6位 + // 00 00000000 + // dest 000000 + // src 111100 + // xor: 111100 + // or: 111100 + // and: 000000 + Data d1{ + {BYTE(00000000), BYTE(00000000)}, + 2, + {BYTE(11110000), BYTE(00001111)}, + 0, + 6, + {BYTE(00111100), BYTE(00000000)}, + // move + {BYTE(00111100), BYTE(00000000)}, + // xor (0x3C, 0x00) + {BYTE(00111100), BYTE(00000000)}, + // or (0x3C, 0x00) + {BYTE(00000000), BYTE(00000000)}, + // and (0x00, 0x00) + "目标偏移2位,拷贝6位" + }; + + char arr[100]; + size_t a = get_mem2hex_size(2, 0); + mem2hex_Ex2(arr, d1.expected_move.data(), 2, false, ""); + + + + EXPECT_STREQ(hex2bin(std::string(arr, a)).c_str(), "0011110000000000"); + + + // 2. 目标偏移1位,拷贝9位,跨越目标字节 + // 1 000001 + // dest 000000000 + // src 011111111 + // xor: 011111111 + // or: 011111111 + // and: 000000000 + list.push_back({ + {BYTE(10000000), BYTE(00000001)}, + 1, + {BYTE(01111111), BYTE(10000000)}, + 0, + 9, + {BYTE(10111111), BYTE(11000001)}, + // move + {BYTE(10111111), BYTE(11000001)}, + // xor (0xFE, 0x83) + {BYTE(10111111), BYTE(11000001)}, + // or (0xFE, 0x83) + {BYTE(10000000), BYTE(00000001)}, + // and (0x01, 0x03) + "目标偏移1位,拷贝9位,跨字节" + }); + // 3. 目标偏移4,源偏移3,拷贝8位 + // 1100 1010 + // dest 00111010 + // src 10000000 + // xor 10111010 + // or 10111010 + // and 00000000 + list.push_back({ + {BYTE(11000011), BYTE(10101010)}, + 4, + {BYTE(11110000), BYTE(00001111)}, + 3, + 8, + {BYTE(11001000), BYTE(00001010)}, + // move + {BYTE(11001011), BYTE(10101010)}, + // xor + {BYTE(11001011), BYTE(10101010)}, + // or + {BYTE(11000000), BYTE(00001010)}, + // and + "目标偏移4,源偏移3,拷贝8位" + }); + // 4. 全1拷贝部分,全0目标 + // 00000 0000 + // dest 0000000 + // src 1111111 + // xor 1111111 + // or 1111111 + // and 0000000 + list.push_back({ + {BYTE(00000000), BYTE(00000000)}, + 5, + {BYTE(11111111), BYTE(11111111)}, + 2, + 7, + {BYTE(00000111), BYTE(11110000)}, + // move + {BYTE(00000111), BYTE(11110000)}, + // xor + {BYTE(00000111), BYTE(11110000)}, + // or + {BYTE(00000000), BYTE(00000000)}, + // and + "全1源,拷贝7位到目标末尾" + }); + // 5. 源目标均有内容(交错) + // 110 10011 + // dest 01100001 + // src 10100101 + // xor 11000100 + // or 11100101 + // and 00100001 + list.push_back({ + {BYTE(11001100), BYTE(00110011)}, + 3, + {BYTE(10101010), BYTE(01010101)}, + 4, + 8, + {BYTE(11010100), BYTE(10110011)}, + // move + {BYTE(11011000), BYTE(10010011)}, + // xor + {BYTE(11011100), BYTE(10110011)}, + // or + {BYTE(11000100), BYTE(00110011)}, + // and + "目标有内容,源偏移4,拷贝8位" + }); + // 6. 源目标完全重叠 + // 1011 01 + // dest 1001110100 + // src 1101111010 + // move 1101111010 + // xor 0100001110 + // or 1101111110 + // and 1001110000 + list.push_back({ + {BYTE(10111001), BYTE(11010001)}, + 4, + {BYTE(10110111), BYTE(10100101)}, + 2, + 10, + {BYTE(10111101), BYTE(11101001)}, + // move + {BYTE(10110100), BYTE(00111001)}, + // xor + {BYTE(10111101), BYTE(11111001)}, + // or + {BYTE(10111001), BYTE(11000001)}, + // and + "目标/源重叠,偏移不同" + }); + for (auto& d : list) { + auto dest_move = d.dest; + auto dest_xor = d.dest; + auto dest_or = d.dest; + auto dest_and = d.dest; + bit_move(dest_move.data(), d.dest_offset, d.src.data(), d.src_offset, d.num); + bit_xor(dest_xor.data(), d.dest_offset, d.src.data(), d.src_offset, d.num); + bit_or(dest_or.data(), d.dest_offset, d.src.data(), d.src_offset, d.num); + bit_and(dest_and.data(), d.dest_offset, d.src.data(), d.src_offset, d.num); + EXPECT_EQ(dest_move, d.expected_move) << "move 结果: " << hex2bin(bytes_to_hex(dest_move)) << "\n期望: " << + hex2bin(bytes_to_hex(d.expected_move)) << "\n" + d.msg; + EXPECT_EQ(dest_xor, d.expected_xor) << "xor 结果: " << bytes_to_hex(dest_xor) << "\n期望: " << + bytes_to_hex(d.expected_xor) << "\n" + d.msg; + EXPECT_EQ(dest_or, d.expected_or) << "or 结果: " << bytes_to_hex(dest_or) << "\n期望: " << + bytes_to_hex(d.expected_or) << "\n" + d.msg; + EXPECT_EQ(dest_and, d.expected_and) << "and 结果: " << bytes_to_hex(dest_and) << "\n期望: " << + bytes_to_hex(d.expected_and) << "\n" + d.msg; + } + +} + + +TEST(Bit222, WriteAndReadFullByte223) { + + + + + std::pmr::string s("11101110"); + std::string s2("11101110"); + std::cout << bin2hex(s) << std::endl; + std::cout << bin2hex(s2) << std::endl; + std::cout << bin2hex("11101110") << std::endl; + + + std::cout << "111:" << hex2bin("01") << std::endl; + std::cout << "big_dian:" << bin4_to_hex(true, "0011") << std::endl; + std::cout << "small_dian:" << bin4_to_hex(false, "0011") << std::endl; +} + +TEST(BitOpsLE, WriteAndReadFullByte) { + uint8_t buf[8] = {0}; + set_bits(buf, 0, 8, 0xAB); // 小端模式:低位在低bit + EXPECT_EQ(buf[0], 0xAB); + EXPECT_EQ(get_bits(buf, 0, 8), 0xAB); +} +TEST(BitOpsLE, CrossByteWriteAndRead) { + uint8_t buf[8] = {0}; + set_bits(buf, 4, 12, 0xF0F); // 写12位,偏移4 + EXPECT_EQ(get_bits(buf, 4, 12), 0xF0F); +} +TEST(BitOpsLE, UnalignedBitWriteAndRead) { + uint8_t buf[8] = {0}; + set_bits(buf, 5, 10, 0x2AA); // 偏移5位,写10位 + EXPECT_EQ(get_bits(buf, 5, 10), 0x2AA); +} +TEST(BitOpsLE, SingleBitWriteAndRead) { + uint8_t buf[8] = {0}; + set_bits(buf, 10, 1, 1); + EXPECT_EQ(get_bits(buf, 10, 1), 1); + set_bits(buf, 10, 1, 0); + EXPECT_EQ(get_bits(buf, 10, 1), 0); +} +TEST(BitOpsLE, WriteAndReadFullUint64) { + uint8_t buf[8] = {0}; + set_bits(buf, 0, 64, 0x123456789ABCDEF0ULL); + EXPECT_EQ(get_bits(buf, 0, 64), 0x123456789ABCDEF0ULL); +} +TEST(BitOpsLE, OverwriteZeroBits) { + uint8_t buf[8]; + std::memset(buf, 0xFF, sizeof(buf)); + set_bits(buf, 16, 16, 0x0000); + EXPECT_EQ(get_bits(buf, 16, 16), 0x0000); + // 其它位应保持原值 + for (size_t i = 0; i < 2; ++i) + EXPECT_EQ(buf[i], 0xFF); + for (size_t i = 4; i < 8; ++i) + EXPECT_EQ(buf[i], 0xFF); +} +TEST(BitOpsLE, AllZeroAndAllOne) { + uint8_t buf[8] = {0}; + set_bits(buf, 0, 64, 0xFFFFFFFFFFFFFFFFULL); + EXPECT_EQ(get_bits(buf, 0, 64), 0xFFFFFFFFFFFFFFFFULL); + set_bits(buf, 0, 64, 0x0ULL); + EXPECT_EQ(get_bits(buf, 0, 64), 0x0ULL); +} +#else +#endif diff --git a/module/dll_source_lzy/ecap/lib/hulc/Bit.h b/module/dll_source_lzy/ecap/lib/hulc/Bit.h new file mode 100644 index 0000000..59e8c58 --- /dev/null +++ b/module/dll_source_lzy/ecap/lib/hulc/Bit.h @@ -0,0 +1,309 @@ +#ifndef BitSet_H +#define BitSet_H +#include +#ifdef __linux__ +#include +#endif +#include +#include +#include +#include + +namespace yC { + template + typename std::enable_if::value, T>::type + create_string(size_t size, std::pmr::memory_resource* resource = nullptr) { + std::pmr::memory_resource* r = resource ? resource : std::pmr::get_default_resource(); + std::pmr::string ret(r); + ret.resize(size); + return ret; // 返回 std::pmr::string + } + + template + typename std::enable_if::value, T>::type + create_string(size_t size, std::pmr::memory_resource* resource = nullptr) { + std::string ret; + ret.resize(size); + return ret; // 返回 std::string + } + + template + struct cacl_type { + using type = T; + size_t size(T& a) { + return a.size(); + } + static void* data(T& a) { + return (void*)a.data(); + } + static size_t size(const T& a) { + return a.size(); + } + static void* data(const T& a) { + return (void*)a.data(); + } + }; + template <> + struct cacl_type { + using type = std::string; + static size_t size(const char* a) {return strlen(a);} + static void* data(const char* a) {return (void*)a;} + }; + + template + struct cacl_type { + using type = std::string; + static size_t size(const char (&a)[N]) { return N - 1; } + static void* data(const char (&a)[N]) { return (void*)a; } + }; + + template + struct cacl_type { + using type = std::string; + static size_t size(const char (&a)[N]) { return N - 1; } + static void* data(const char (&a)[N]) { return (void*)a; } + }; +} + + + +#define Base template , \ +typename STR_Type = std::basic_string, allocator_type>, \ +typename ret_type = typename cacl_type::type \ +> +// #define Base template <\ +// typename STR_Type, \ +// typename ret_type = typename cacl_type::type \ +// > + + +namespace yC { + // 检查当前机器是否是大端字节序 + extern const bool is_big_endian; + void big_endian_2_platform(void* dest, const char* d, size_t size); + void little_endian_2_platform(void* dest, const char* d, size_t size); + + + + void big_endian_2_platform(const std::string& big_endian, char* dest); + void little_endian_2_platform(const std::string& little_endian, char* dest); + + + std::string big_endian_2_platform(const std::string& big_endian); + std::string little_endian_2_platform(const std::string& little_endian); + std::string platform_2_big_endian(void* memory, int size); + std::string platform_2_little_endian(void* memory, int size); + + + + + inline size_t get_xor_hex_size(size_t n1, size_t n2){return std::max(n1, n2);} + void xor_hex_Ex(void* dest, const char* s1, size_t n1, const char* s2, size_t n2, bool big_dian, bool is_upper); + Base + ret_type xorHex(const STR_Type& s1, const STR_Type& s2, std::pmr::memory_resource* resource = nullptr) { + auto n1 = cacl_type::size(s1); + auto n2 = cacl_type::size(s2); + auto size = get_xor_hex_size(n1, n2); + auto ret = create_string(size, resource); + xor_hex_Ex((void*)ret.data(), (const char*)cacl_type::data(s1), n1, (const char*)cacl_type::data(s2), n2, true, true); + return ret; + } + + + inline size_t get_xor_bin_size(size_t n1, size_t n2){return std::max(n1, n2);} + void xor_bin_Ex(void* dest, const char* s1, size_t n1, const char* s2, size_t n2, bool big_dian); + Base + ret_type xorBin(const STR_Type& s1, const STR_Type& s2, std::pmr::memory_resource* resource = nullptr) { + auto n1 = cacl_type::size(s1); + auto n2 = cacl_type::size(s2); + auto size = get_xor_bin_size(n1, n2); + auto ret = create_string(size, resource); + xor_bin_Ex((void*)ret.data(), (const char*)cacl_type::data(s1), n1, (const char*)cacl_type::data(s2), n2, true); + return ret; + } + + + + + inline size_t get_bin2hex_size(size_t num) {return (num + 3) / 4;} + void bin2hex_Ex(void* dest, const char* data, size_t size, bool big_dian, bool isupper); + Base + ret_type bin2hex(const STR_Type& mem, std::pmr::memory_resource* resource = nullptr) { + auto size = cacl_type::size(mem); + auto ret = create_string(get_bin2hex_size(size), resource); + bin2hex_Ex((void*)ret.data(), (const char*)cacl_type::data(mem), size, true, true); + return ret; + } + + + + inline size_t get_hex2bin_size(size_t num) {return num * 4;} + void hex2bin_Ex(void* dest, const char* data, size_t size, bool big_dian); + Base + ret_type hex2bin(const STR_Type& mem, std::pmr::memory_resource* resource = nullptr) { + auto size = cacl_type::size(mem); + auto ret = create_string(get_hex2bin_size(size), resource); + hex2bin_Ex((void*)ret.data(), (const char*)cacl_type::data(mem), size, true); + return ret; + } + + inline size_t get_bin2mem_size(size_t num) {return num/8;}; + void bin2mem(void* dest, const char* data, size_t size); + Base + STR_Type bin2mem(const STR_Type& mem, std::pmr::memory_resource* resource = nullptr) { + auto size = cacl_type::size(mem); + auto ret = create_string(get_bin2mem_size(size), resource); + bin2mem((void*)ret.data(), (const char*)cacl_type::data(mem), size); + return ret; + } + + // inline ret_str bin2mem(param_str mem, std::pmr::memory_resource* resource = nullptr) { + // auto size = mem.size(); + // auto ret = ret_str(); + // ret.resize(get_bin2mem_size(size)); + // bin2mem((void*)ret.data(), (const char*)mem.data(), size); + // return ret; + // } + + + inline size_t get_hex2mem_size(size_t hex_hum) {return hex_hum/2;}; + void hex2mem_Ex(void* dest, const char* data, size_t size); + Base + STR_Type hex2mem(const STR_Type& mem, std::pmr::memory_resource* resource = nullptr) { + auto size = cacl_type::size(mem); + auto ret = create_string(get_hex2mem_size(size), resource); + hex2mem_Ex((void*)ret.data(), (const char*)cacl_type::data(mem), size); + return ret; + } + + // inline ret_str hex2mem(param_str hex, std::pmr::memory_resource* resource = nullptr) { + // auto size = hex.size(); + // auto ret = ret_str(); + // ret.resize(get_hex2mem_size(size)); + // hex2mem_Ex((void*)ret.data(), (const char*)hex.data(), size); + // return ret; + // } + + + inline size_t get_mem2hex_size(size_t num, size_t middle_len) { return num * 2 + (num - 1) * middle_len;} + void mem2hex_Ex2(void* dest, void* mem, size_t num, bool uppercase, const char* middle, size_t middle_len = std::numeric_limits::max()); + Base + STR_Type mem2hex(const STR_Type& mem, bool uppercase = true, const std::string& middle = "", std::pmr::memory_resource* resource = nullptr) { + auto size = cacl_type::size(mem); + auto ret = create_string(get_mem2hex_size(size, middle.size()), resource); + mem2hex_Ex2(ret.data(), cacl_type::data(mem), size, uppercase, middle.data(), middle.size()); + return ret; + } + + // inline ret_str mem2hex(param_str& mem, bool uppercase = true, const std::string& middle = "", std::pmr::memory_resource* resource = nullptr) { + // auto size = get_mem2hex_size(mem.size(), middle.size()); + // auto ret = ret_str(); + // mem2hex_Ex2(ret.data(), (void*)mem.data(), size, uppercase, middle.data(), middle.size()); + // return ret; + // } + + + template + void get_bin(std::string& msg, int& n) { + n = std::bitset(msg.substr(start, len)).to_ullong(); + } + template + void get_bin(std::string& msg, Enum& n) { + n = static_cast(std::bitset(msg.substr(start, len)).to_ullong()); + } + template + Enum get_bin(std::string& msg) { + return static_cast(std::bitset(msg.substr(start, len)).to_ullong()); + } + template + int get_bin(const std::string& msg) { + return std::bitset(msg.substr(start, len)).to_ullong(); + } + template + void set_bin(std::string& msg, unsigned long long n) { + msg.replace(start, len, std::bitset(n).to_string()); + } + template + void set_bin(std::string& msg, const std::string& value) { + if (value.size() != len) { + std::cout << "len == " << len << " bits.size() == " << value.size() << std::endl; + throw std::out_of_range("Start position and length exceed bit string size"); + } + msg.replace(start, len, value); + } + template + std::string to_bin(unsigned long long n) { + return std::bitset(n).to_string(); + } + template + std::string to_bin(double n) { + return std::bitset(static_cast(n)).to_string(); + } + template + T bin2(const std::string& binstr) { + return std::stoull(binstr, nullptr, 2); + } + template + unsigned long long hex2(const std::string& hexstr) { + return std::stoull(hexstr, nullptr, 16); + } + template <> + inline int bin2(const std::string& binstr) { + int bit_limit = sizeof(int) * 8; + if (binstr.size() > bit_limit) { + std::cout << "Bitset.h inline int bin2 error! Binary string exceeds int bit limit" << std::endl; + } + return std::stoi(binstr, nullptr, 2); + } + // 设置dest的从off位起n位,写入value的低n位 + template + void set_bits(void* dest, size_t off, size_t n, T value) { + auto d = static_cast(dest); + size_t bit_pos = off; + size_t val_pos = 0; + while (n > 0) { + size_t byte_idx = bit_pos / 8; + size_t bit_in_byte = bit_pos % 8; + size_t bits_in_this_byte = std::min(n, 8 - bit_in_byte); + // 为当前字节构建掩码 + uint8_t mask = ((1u << bits_in_this_byte) - 1) << bit_in_byte; + // 取value对应的低bits_in_this_byte位 + uint8_t v = (value >> val_pos) & ((1u << bits_in_this_byte) - 1); + // 清除目标字节对应位置后设置 + d[byte_idx] = (d[byte_idx] & ~mask) | ((v << bit_in_byte) & mask); + bit_pos += bits_in_this_byte; + val_pos += bits_in_this_byte; + n -= bits_in_this_byte; + } + } + + + + // 大批量位处理性能不好 但是通常也没有这样的场景 + void bit_move(void* d, size_t doff, const void* s, size_t soff, size_t n); + void bit_xor(void* d, size_t doff, const void* s, size_t soff, size_t n); + void bit_or(void* d, size_t doff, const void* s, size_t soff, size_t n); + void bit_and(void* d, size_t doff, const void* s, size_t soff, size_t n); + template + T get_bits(void* src, size_t off, size_t n) { + auto s = static_cast(src); + size_t bit_pos = off; + size_t val_pos = 0; + T result = 0; + while (n > 0) { + size_t byte_idx = bit_pos / 8; + size_t bit_in_byte = bit_pos % 8; + size_t bits_in_this_byte = std::min(n, 8 - bit_in_byte); + uint8_t mask = ((1u << bits_in_this_byte) - 1) << bit_in_byte; + uint8_t bits = (s[byte_idx] & mask) >> bit_in_byte; + result |= (T(bits) << val_pos); + bit_pos += bits_in_this_byte; + val_pos += bits_in_this_byte; + n -= bits_in_this_byte; + } + return result; + } +} + +#undef Base +#endif diff --git a/module/dll_source_lzy/ecap/lib/hulc/DataOutputFormats.cpp b/module/dll_source_lzy/ecap/lib/hulc/DataOutputFormats.cpp new file mode 100644 index 0000000..33c3fa0 --- /dev/null +++ b/module/dll_source_lzy/ecap/lib/hulc/DataOutputFormats.cpp @@ -0,0 +1,106 @@ +#include "DataOutputFormats.h" + +#include +#include + +using namespace yC; + +MLAT_timestamp::MLAT_timestamp() { + std::chrono::time_point t = std::chrono::high_resolution_clock::now(); + // 获取当前的系统时间(秒) + std::chrono::duration duration_since_epoch = t.time_since_epoch(); + // 获取秒数和纳秒数 + auto seconds = std::chrono::duration_cast(duration_since_epoch); + auto nanoseconds = std::chrono::duration_cast(duration_since_epoch); + // 获取当天的秒数和纳秒数 + this->daysec = seconds.count() % 86400; // 86400 = 24 * 60 * 60 (一天的秒数) + this->nanosec = nanoseconds.count() % 86400000000000; // 1秒 = 10^9纳秒 + memory = bin2mem(to_bin_string()); + parse_hhmmss(); +} + + +MLAT_timestamp::MLAT_timestamp(const std::string& memory_6) : memory(memory_6) { + assert(memory_6.size() == 6); + auto msg_bin = hex2bin(mem2hex(memory)); + daysec = std::bitset<18>(msg_bin.substr(0, 18)).to_ulong(); + nanosec = std::bitset<30>(msg_bin.substr(18, 30)).to_ulong(); + parse_hhmmss(); + + //assert(memory_6 == bin2mem(to_bin_string()), "MLAT_timestamp,内存转换错误!"); +} + +MLAT_timestamp::MLAT_timestamp(std::uint32_t daysec, std::uint32_t nanosec) : daysec(daysec), nanosec(nanosec) { + parse_hhmmss(); +} + + +std::string MLAT_timestamp::to_bin_string() const { + std::bitset<18> daysec_bits = daysec; + std::bitset<30> nanosec_bits = nanosec; + return daysec_bits.to_string() + nanosec_bits.to_string(); +} + +// std::string MLAT_timestamp::to_memory() { +// return bin2memory(to_bin_string()); +// } + +std::string MLAT_timestamp::to_memory() const { + return memory; +} + +void MLAT_timestamp::parse_hhmmss() { + hh = (daysec/3600) % 24; + mm = (daysec/60) % 60; + ss = daysec % 60; +} +std::string packet_to_escape_format(std::string t) { + std::string result = "\x1a"; + for (size_t i = 1; i < t.size(); ++i) { + result.push_back(t[i]); // 插入当前字符 + if (t[i] == '\x1a') { + result.push_back('\x1a'); // 如果是 0x1a,插入另一个 0x1a + } + } + return result; +} +void Binary_Format_handle_buffer(std::string& buffer, const std::string& data, const std::function& callback) { + size_t i = 0; + while (i < data.size()) { + if (data[i] == 0x1A) { + // 如果遇到起始标记 0x1A + if (i + 1 < data.size() && data[i + 1] == 0x1A) { + // 如果是转义的 0x1A 0x1A,继续处理 + buffer.push_back(0x1A); // 添加一个正常的 0x1A 字节 + i += 2; // 跳过这两个字节 + } else { + // 检测到起始标记 0x1A,认为是新消息的开始 + if (!buffer.empty()) { + // 如果当前消息 buffer 中已有数据,调用回调函数处理当前消息 + callback(buffer); + buffer.clear(); // 清空当前消息的缓存 + } + buffer.push_back(0x1A); + // 跳过当前的 SOP 标记 (0x1A) + i++; + } + } else + { + // 如果不是 0x1A,直接将数据添加到 buffer 中 + buffer.push_back(data[i]); + i++; + } + } +} + + + +// 9 + 2 +// 9 + 7 +// 9 + 14 +std::string mode_s_msg_packet_to_server_packet(std::uint32_t id, std::string packet) { + std::string id_code = yC::platform_2_big_endian((char*)&id, sizeof(id)); + //assert(id_code.size() == 4, "id.size != 4"); + packet.insert(1, id_code.c_str(), 4); + return packet; +} \ No newline at end of file diff --git a/module/dll_source_lzy/ecap/lib/hulc/DataOutputFormats.h b/module/dll_source_lzy/ecap/lib/hulc/DataOutputFormats.h new file mode 100644 index 0000000..aab359e --- /dev/null +++ b/module/dll_source_lzy/ecap/lib/hulc/DataOutputFormats.h @@ -0,0 +1,531 @@ +#ifndef DATAOUTPUTFORMATS_H +#define DATAOUTPUTFORMATS_H +#include "base_format.h" +using namespace yC; + +// AVR format +// *02E99619FACDAE; +// *8D3C5EE69901BD9540078D37335F; +// *7700; +inline std::string create_AVR_format(const std::string& msg_hex) { + return "*" + msg_hex + ";"; +} + +// @016CE3671C7423FFE7AB7BFCAB; +// @016CE3671AA8A800199A8BB80030A8000628F400; +// @016CE3671C747700; + +// @5500068BA46CB402c18d34fc8000; +inline std::string create_MLAT_AVR_format(const std::string& msg_hex, MLAT_timestamp* timestamp) { + //std::string signal_level_str = bin2hex(std::bitset<8>(signal_level).to_string()); + //std::cout << "signal:" << signal_level_str << std::endl; + return "@" + bin2hex(timestamp->to_bin_string()) + msg_hex + ";"; +} + + +// Binary Format +// "1" : 6 byte MLAT timestamp, 1 byte signal level, 2 byte Mode-AC +// "2" : 6 byte MLAT timestamp, 1 byte signal level, 7 byte Mode-S short frame +// "3" : 6 byte MLAT timestamp, 1 byte signal level, 14 byte Mode-S long frame +// "4" : 6 byte MLAT timestamp, 1 byte unused, DIP switch configuration settings, time stamp error ticks as int8_t (1 tick is 15ns) (message "4" not on Mode-S Beast classic) +// : true 0x1a +// is 0x1a, and "1", "2" and "3" are 0x31, 0x32 and 0x33 +inline std::string create_Binary_Format_memory(const std::string& msg_hex, char signal_level, MLAT_timestamp* timestamp) { + std::string type; + switch (msg_hex.size()) { + case 4: type = '1'; + break; + case 14: type = '2'; + break; + case 28: type = '3'; + break; + default: std::cerr << msg_hex << "create_Binary_Format error is not a valid binary format." << std::endl; + throw std::runtime_error("create_Binary_Format error!"); + } + + + std::string t = timestamp->to_memory() + signal_level + yC::hex2mem(msg_hex); + + // std::cout << "msg_hex.size():" << msg_hex.size() << std::endl; + // std::cout << "hex2memory(msg_hex):" << hex2memory(msg_hex).size() << std::endl; + // std::cout << t.size() << std::endl; + std::string result; + + // 遍历原始字符串 + for (size_t i = 0; i < t.size(); ++i) { + result.push_back(t[i]); // 插入当前字符 + if (t[i] == '\x1a') { + result.push_back('\x1a'); // 如果是 0x1a,插入另一个 0x1a + } + } + + return char(0x1a) + type + result; +} + +// 把要传递的信息转化成转义字符 二进制==>转义二进制 +std::string packet_to_escape_format(std::string t); + +inline std::string unescape_packet(std::string t) { + std::string result; + for (size_t i = 0; i < t.size(); ++i) { + if (t[i] == '\x1a' && i + 1 < t.size() && t[i + 1] == '\x1a') { + result.push_back('\x1a'); // 如果是连续的两个 \x1a,只添加一个 + ++i; // 跳过下一个 \x1a + } else { + result.push_back(t[i]); // 否则,直接添加当前字符 + } + } + return result; +} + + +// 用于dip_setting +// FPGA switch settings +// Bit 0: Data output mode(port 10002 only) Binary AVR hexdump +// Bit 1: Raw data frame types DF11, DF17 and DF18 only no pre-filtering +// Bit 2: Timestamps within AVR format enabled disabled +// Bit 3: not used +// Bit 4: Timestamp mode GPS legacy 12MHz +// Bit 5: FPGA/USB handshake disabled enabled +// Bit 6: 1 bit forward error correction (FEC) disabled enabled +// Bit 7: Mode-A/C decoding enabled disabled +// GPS status information +// Bit 0: Antenna status good fail +// Bit 1: Tracking at least 1 satellite true false +// Bit 2: Tracking at least 3 satellites true false +// Bit 3: Time value base UTC time GPS time (8sec offset) +// Bit 4: unused +// Bit 5: unused +// Bit 6: unused +// Bit 7: Daysec value range 0 ... 86399 1 ... 86400 +inline std::string create_Binary_Format_4(MLAT_timestamp timestamp, char signal_level, char dip_setting, char time_stamp_error_ticks) { + return char(0x1a) + "4" + timestamp.to_bin_string() + char(0xaa) + dip_setting + time_stamp_error_ticks; +} + +//相对时间戳(无 GPS):在没有连接 GPS 接收器的情况下,时间戳是一个 48 位无符号数字, +//计数 12 MHz 周期。时间戳大约每 271 天换行一次。 +struct TCXO_Clock { + unsigned long long times; + + explicit TCXO_Clock(const std::string& hex) { + times = std::bitset<48>(hex2bin(hex)).to_ullong(); + } + + [[nodiscard]] std::string to_string() const { + // 每个周期的时间是 1 / 12,000,000 秒 + double seconds = static_cast(times) / 12000000.0; + // 计算小时、分钟、秒 + int hours = static_cast(seconds / 3600); + seconds -= hours * 3600; + int minutes = static_cast(seconds / 60); + seconds -= minutes * 60; + int secs = static_cast(seconds); + // 格式化为时分秒字符串 + std::ostringstream oss; + oss.fill('0'); + oss << hours << ":"; + oss.width(2); + oss << minutes << ":"; + oss.width(2); + oss << secs; + return oss.str(); + } +}; + +/* +Periodic status message which is emitted every second +0x1A 0x48 0x01 0x18 SerNum Flags I.U. xTime Lat Lon Alt Sat HDOP +Fields: + SerNum 32-bit(1) Device Serial Number + Flags 16-bit(1) Status Flags* + I.U. 16-bit Internal Use + xTime 32-bit(1) Unix-Timestamp (Seconds since midnight 1970-01-01, UTC) + Lat 32-bit(1) Latitude as 32-bit BAM 2, thus 232 ≡ 360° + Lon 32-bit(1) Latitude as 32-bit BAM 2 + Alt 16-bit(1) Signed altitude meters + Sat 8-bit Number of satellites used in fix + HDOP 8-bit HDOP * 10, thus a value of 12 is HDOP 1.2 +1) MSB-first +2) https://en.wikipedia.org/wiki/Binary_scaling#Binary_angles + Status Flags: + 1xxx xxxx xxxx xxxx - GPS device detected -> Using absolute timestamp + x1xx xxxx xxxx xxxx - GPS valid (GGA, RMC present) + xx1x xxxx xxxx xxxx - GPS currently has a valid fix + xxx1 xxxx xxxx xxxx - High accuracy absolute time is available via PPS + xxxx xxxx 1xxx xxxx - TX-Queue overflow since start-up (normal if HW-handshaking is used) + xxxx xxxx x1xx xxxx - TX-Queue overflow during last second (probably due to HW-handshaking) + xxxx xxxx xx1x xxxx - Excessive NMEA found (other than GGA/RMC) +*/ +// +// All HULC messages (Type 0x48) have the following structure: +// 0x1A 0x48 ID LEN +// Fields: +// ID: HULC Message ID +// LEN: Number of bytes following +struct HULC_Message { + std::uint8_t head; + std::uint8_t id; + std::uint8_t len; // 指示下面的长度 +}; + + + + +struct HULC_Status_Message : HULC_Message { + std::uint32_t SerNum{}; + std::uint16_t Flags{}; // MSB大端字节序 + std::uint16_t I_U_{}; // Internal Use + std::uint32_t xTime{}; // Unix-Timestamp (Seconds since midnight 1970-01-01, UTC) + std::int32_t Lat{}; + std::int32_t Lon{}; + std::int16_t Alt{}; + std::uint8_t Sat{}; // Sat字段记录了定位过程中使用的卫星数量 + std::uint8_t HDOP{}; + + [[nodiscard]] double get_HDOP() const { + // HDOP(Horizontal Dilution of Precision) 描述的是 水平精度的衰减,即 GPS 系统的水平定位精度与卫星的几何布局有关。HDOP 数值越低,说明卫星的几何布局越好,定位精度越高。 + // 较低的 HDOP 值(例如 1-2)表示卫星信号较强,且卫星的分布较为理想,因此定位精度较高。 + // 较高的 HDOP 值(例如 5 或更高)表示卫星信号较弱,或卫星的分布较差,可能导致较差的定位精度。 + return double(HDOP) / 10.0; + } + + void set_latitude(double latitude) { + // 根据经纬度设置 Lat 值 + Lat = static_cast((latitude / 360.0) * pow(2, 32)); + } + + void set_longitude(double longitude) { + // 根据经纬度设置 Lon 值 + Lon = static_cast((longitude / 360.0) * pow(2, 32)); + } + + [[nodiscard]] double get_latitude() const { + return (static_cast(Lat) / pow(2, 32)) * 360.0; + } + + [[nodiscard]] double get_longitude() const { + return (static_cast(Lon) / pow(2, 32)) * 360.0; + } + + [[nodiscard]] std::string get_latitude_d_m_s() const{ + return decimalToDMS(get_latitude()); + } + + [[nodiscard]] std::string get_longitude_d_m_s() const{ + return decimalToDMS(get_longitude()); + } + + [[nodiscard]] std::string get_timestamp_string() const{ + return convert_timestamp_to_string(xTime); + } + + static std::string convert_timestamp_to_string(std::uint32_t time32) { + std::time_t time = time32; + std::stringstream ss; + ss << std::put_time(std::gmtime(&time), "%Y-%m-%d %H:%M:%S"); // 使用 std::put_time 格式化日期 + return ss.str( + + ); + // 返回格式化后的字符串 + // std::time_t time = time32; + // std::stringstream ss; + // // 将时间戳转换为本地时间 + // ss << std::put_time(std::localtime(&time), "%Y-%m-%d %H:%M:%S"); // 使用 std::localtime 格式化日期 + // return ss.str(); // 返回格式化后的字符串 + // // Unix Timestamp + // std::time_t timestamp = xTime; + // + // std::tm* ptm = std::gmtime(×tamp); + // + // return std::asctime(ptm); + } + + + // 转化经纬度变成 度 分 秒 + static std::string decimalToDMS(double decimalDegree) { + int degrees = static_cast(decimalDegree); + double minutesDouble = (decimalDegree - degrees) * 60; + int minutes = static_cast(minutesDouble); + int seconds = static_cast((minutesDouble - minutes) * 60.0); + return "(" + std::to_string(degrees) + "°" + std::to_string(minutes) + "'" + std::to_string(seconds) + "\")"; + } + /* + Status Flags: + 1xxx xxxx xxxx xxxx - GPS device detected -> Using absolute timestamp + x1xx xxxx xxxx xxxx - GPS valid (GGA, RMC present) + xx1x xxxx xxxx xxxx - GPS currently has a valid fix + xxx1 xxxx xxxx xxxx - High accuracy absolute time is available via PPS + xxxx xxxx 1xxx xxxx - TX-Queue overflow since start-up (normal if HW-handshaking is used) + xxxx xxxx x1xx xxxx - TX-Queue overflow during last second (probably due to HW-handshaking) + xxxx xxxx xx1x xxxx - Excessive NMEA found (other than GGA/RMC) + */ + [[nodiscard]] bool GPS_device_detected() const { + return Flags & (1 << 15); // 检查第 15 位,GPS 设备是否检测到 + } + + [[nodiscard]] bool GPS_valid() const { + return Flags & (1 << 14); // 检查第 14 位,GPS 数据是否有效 + } + + [[nodiscard]] bool GPS_has_valid_fix() const { + return Flags & (1 << 13); // 检查第 13 位,GPS 是否有有效定位 + } + + [[nodiscard]] bool GPS_high_accuracy_time() const { + return Flags & (1 << 12); // 检查第 12 位,是否通过 PPS 提供高精度绝对时间 + } + + [[nodiscard]] bool TX_queue_overflow_since_startup() const { + return Flags & (1 << 7); // 检查第 7 位,自启动以来是否发生 TX 队列溢出 + } + + [[nodiscard]] bool TX_queue_overflow_last_second() const { + return Flags & (1 << 6); // 检查第 6 位,过去一秒内是否发生 TX 队列溢出 + } + + [[nodiscard]] bool excessive_NMEA_found() const { + return Flags & (1 << 5); // 检查第 5 位,是否发现过多的 NMEA 数据(非 GGA/RMC) + } + + [[nodiscard]] Json toJson() const { + Json ret = Json::object(); + ret.append({"序列号", SerNum}); + ret.append({"状态标志", Flags}); + ret.append({"内部使用", I_U_}); + ret.append({"时间戳", get_timestamp_string()}); + ret.append({"纬度", std::to_string(get_latitude()) + " " + get_latitude_d_m_s()}); + ret.append({"经度", std::to_string(get_longitude()) + " " + get_longitude_d_m_s()}); + ret.append({"高度", Alt}); + ret.append({"卫星数量", Sat}); + ret.append({"HDOP", get_HDOP()}); + ret.append({"GPS设备检测到", GPS_device_detected()}); + ret.append({"GPS有效", GPS_valid()}); + ret.append({"GPS有效定位", GPS_has_valid_fix()}); + ret.append({"GPS高精度时间", GPS_high_accuracy_time()}); + ret.append({"启动以来TX队列溢出", TX_queue_overflow_since_startup()}); + ret.append({"过去一秒TX队列溢出", TX_queue_overflow_last_second()}); + ret.append({"发现过多NMEA数据", excessive_NMEA_found()}); + return ret; + } + + + static double decodeLatitudeFromBAM(const std::string& bigdian4) { + std::uint32_t value; + yC::big_endian_2_platform(bigdian4, (char*)&value); + // BAM 格式解码公式 + // return (static_cast(value) / pow(2, 32)) * 360.0; + return (static_cast(value) / pow(2, 32)) * 360.0; + } + std::string toBinary() { + std::string binary = {0x1a, 0x48, 0x01, 0x18}; + binary.append(yC::platform_2_big_endian(&SerNum, 4)); + binary.append(yC::platform_2_big_endian(&Flags, 2)); + binary.append(std::string((char*)&I_U_, 2)); // 内部使用没说什么序 默认大端序 + binary.append(yC::platform_2_big_endian(&xTime, 4)); + binary.append(yC::platform_2_big_endian(&Lat, 4)); + binary.append(yC::platform_2_big_endian(&Lon, 4)); + binary.append(yC::platform_2_big_endian(&Alt, 2)); + // 没说什么序 一字节 大端小端 等同 + binary.append({(char)Sat}); + binary.append({(char)HDOP}); + return binary; + } +}; + + + +static void hulc_big_endian_set(const std::string& msg, void* field, int start, int len) { + auto str = msg.substr(start, len); + yC::big_endian_2_platform(str, (char*)field); +} + +static void hulc_set2(const std::string& msg, void* field, int start, int len) { + auto it = msg.substr(start, len); + std::memcpy(field, it.data(), len); +} +// msg 是文本二进制字符串 转义后的 1a34 +static HULC_Status_Message create_HULC_Status_Message(const std::string& msg) { + HULC_Status_Message ret{}; + hulc_big_endian_set(msg, &ret.SerNum, 4, 4); + hulc_big_endian_set(msg, &ret.Flags, 8, 2); + hulc_set2(msg, &ret.I_U_, 10, 2); + hulc_big_endian_set(msg, &ret.xTime, 12, 4); + hulc_big_endian_set(msg, &ret.Lat, 16, 4); + hulc_big_endian_set(msg, &ret.Lon, 20, 4); + hulc_big_endian_set(msg, &ret.Alt, 24, 2); + hulc_set2(msg, &ret.Sat, 26, 1); + hulc_set2(msg, &ret.HDOP, 27, 1); + return ret; +} + + +struct HULC_Reply_to_command : HULC_Message { + std::uint8_t CMD; + std::uint8_t POO_14; +}; + +// 0x1A 0x48 0x01 0x18 SerNum Flags I.U. xTime Lat Lon Alt Sat HDOP +inline std::uint8_t get_id(const std::string& msg) { + return msg[2]; +} + +inline std::uint8_t get_len(const std::string& msg) { + return msg[3]; +} + +// Type Payload Size Description +// 0x31 4 bytes Mode-A/C raw data +// 0x32 7 bytes Mode-S Short Squitter raw data +// 0x33 14 bytes Mode-S Extended Squitter raw data +// 0x48 variable HULC Message, see below for details +// HULC Protocol uses the byte 0x1A as start-of-packet (SOP) marker. In order to avoid misinterpretation +// of normal data bytes with value 0x1A as SOP, each occurrence of data byte 0x1A is doubled in the +// data stream during transmission ('escaping'). It is thus necessary during reception to detect every +// 0x1A not followed by another 0x1A as an SOP marker and to reduce every occurrence of a double +// 0x1A to a single 0x1A data byte ('un-escaping'). +// Example of a 4-byte long packet including SOP marker and 0x1A data bytes: +// Before Escaping: 1A 32 27 1A E8 57 F0 1A 6C +// During Transmission: 1A 32 27 1A 1A E8 57 F0 1A 1A 6C +// After Un-Escaping: 1A 32 27 1A E8 57 F0 1A 6C +void Binary_Format_handle_buffer(std::string& buffer, const std::string& data, const std::function& callback); +/* Command Message (Host ==> Device) +The command-message has a simple ASCII based structure. Each message starts with a ‘#’ (0x23) and +ends with ‘’ (0x0D, 0x0A). In-between are one to 16 bytes in 2-digit hexadecimal representation +using upper-case letters, separated by ‘-’ (0x2D). +For example: + ‘#00’ or hexadecimal 0x23 0x30 0x30 0x0D 0x0A + ‘#43-02’ or hexadecimal 0x23 0x34 0x33 0x2D 0x30 0x32 0x0D 0x0A + The first byte is mandatory and holds the command while the remaining bytes are parameters. + Available commands depend on the selected protocol and are discussed in the respective protocol + section. +*/ + +std::string mode_s_msg_packet_to_server_packet(std::uint32_t id, std::string packet); + + + +// 1a34 radarcape 状态帧消息 +// https://wiki.jetvision.de/wiki/Radarcape:Version_History#Status_Frame_0x34_contents_were_extended_with_GPS_and_UTC_information +// 状态帧0x34内容已扩展为 GPS 和 UTC 信息 +// 当选择 GPS 时间戳时,状态帧由 1PPS 脉冲触发,在传统 12MHz 时间戳的情况下随机触发。 +// 状态帧包含有效的时间戳 +// 信号电平值为零/保留 + + +#define SETGET(name, pos) void set_##name(bool value) { set(pos, value); } \ +bool get_##name() { return get(pos); } + +#define SETGET2(Type, name, pos) void set_##name(Type value) { set(pos, (uint8_t)value); } \ +Type get_##name() { return (Type)get(pos); } + +struct BYTE_Settings { +protected: + uint8_t settings{}; // 8 位的字段,存储所有设置 + void set(uint8_t pos, bool value) { + if (value) { + // 设置指定位置的位为 1 + settings |= (1 << pos); + } else { + // 设置指定位置的位为 0 + settings &= ~(1 << pos); + } + } + [[nodiscard]] bool get(uint8_t pos) const { + // 获取指定位置的位值 + return (settings >> pos) & 0x01; + } +}; +struct FPGA_Setting : BYTE_Settings { + enum class Data_Output_Mode { AVR_hexdump, Binary }; + enum class Raw_Data_Frame_Type { No_Pre_Filtering, DF11_17_18_only }; + enum class Timestamp_Mode { Legacy_12MHz, GPS }; + SETGET2(Data_Output_Mode, data_output_mode, 0) + SETGET2(Raw_Data_Frame_Type, raw_data_frame_type, 1) + SETGET(timestamps_within_AVR_format, 2) + SETGET2(Timestamp_Mode, timestamp_mode, 4) + SETGET(serial_flow_control, 5) + SETGET(FEC, 6) // 1位转发错误校正 + SETGET(mode_ac_decoding , 7) + Json toJson() { + Json ret = Json::object(); + ret.append({"Data_Output_Mode", to_string(get_data_output_mode())}); + ret.append({"Raw_Data_Frame_Type", to_string(get_raw_data_frame_type())}); + ret.append({"timestamps_within_AVR_format", get_timestamps_within_AVR_format()}); + ret.append({"timestamps_mode", to_string(get_timestamp_mode())}); + ret.append({"serial_flow_control", get_serial_flow_control()}); + ret.append({"1位转发错误校正", get_FEC()}); + ret.append({"mode_ac_decoding", get_mode_ac_decoding()}); + return ret; + } + +}; + +struct GPS_Setting : BYTE_Settings { + enum class Time_Value_Base { UTC, GPS }; + enum class Daysec_Range { R_0_86399, R_1_86400 }; + SETGET(antenna_status, 0) // 位 0: 天线状态 + SETGET(tracking_at_least_1_satellite, 1) // 位 1: 至少跟踪 1 颗卫星 + SETGET(tracking_at_least_3_satellites, 2) // 位 2: 至少跟踪 3 颗卫星 + SETGET2(Time_Value_Base, time_value_base, 3) // 位 3: 时间值基数 (UTC/GPS) + SETGET(unused4, 4) // 位 4: 保留 + SETGET(unused5, 5) // 位 5: 保留 + SETGET(unused6, 6) // 位 6: 保留 + SETGET2(Daysec_Range, daysec_range, 7) // 位 7: Daysec 值范围 + Json toJson() { + Json ret = Json::object(); // 创建 JSON 对象 + ret.append({"antenna_status", get_antenna_status()}); + ret.append({"至少跟踪 1 颗卫星", get_tracking_at_least_1_satellite()}); + ret.append({"至少跟踪 3 颗卫星", get_tracking_at_least_3_satellites()}); + ret.append({"timestamps_mode", to_string(get_time_value_base())}); + ret.append({"daysec_range", to_string(get_daysec_range())}); + return ret; + } +}; + +struct Radarcape_STATUS_Message { + FPGA_Setting fpga_settings; + std::uint8_t pps_nanosecond_offset{}; // 包含 1PPS 事件时纳秒计时器的偏移量,单位为 15.625ns。正常值范围为 -3 ... +3。 + GPS_Setting gps_settings; + void set_pps_nanosecond(double value) { + if (value < 0.0 || value > 4000) { + std::cerr << "Invalid value. Must be in range [0.0, 4000.0]." << std::endl; + return; + } + pps_nanosecond_offset = static_cast((value)/15.625); + } + [[nodiscard]] double get_pps_nanosecond() const { + return (double)pps_nanosecond_offset * 15.625; + } + std::string toBinary() { + std::string binary = {0x1a, 0x34}; + binary.append(reinterpret_cast(&fpga_settings), 1); + binary.append(reinterpret_cast(&pps_nanosecond_offset), 1); + binary.append(reinterpret_cast(&gps_settings), 1); + return binary; + } + + Json toJson() { + Json ret = Json::object(); + ret.append({"pps_nanosecond_offset", get_pps_nanosecond()}); + ret.append({"fpga_settings", fpga_settings.toJson()}); + ret.append({"gps_settings", gps_settings.toJson()}); + return ret; + } + +}; + +// 消息5字节 +// +static Radarcape_STATUS_Message create_Radarcape_STATUS_Message(const std::string& msg_5) { + std::string msg = yC::big_endian_2_platform(msg_5.substr(2)); + Radarcape_STATUS_Message ret{}; + std::memcpy(&ret, (void*)(msg.data()), 3); + return ret; +} + + + +#undef SETGET +#undef SETGET2 + +#endif diff --git a/module/dll_source_lzy/ecap/lib/hulc/base_format.h b/module/dll_source_lzy/ecap/lib/hulc/base_format.h new file mode 100644 index 0000000..6708353 --- /dev/null +++ b/module/dll_source_lzy/ecap/lib/hulc/base_format.h @@ -0,0 +1,74 @@ + +#ifndef BASE_FORMAT_H +#define BASE_FORMAT_H +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Bit.h" +#include "Json.h" +#include "magic_enum/export.h" + + +// 1纳秒是 10 -9次方秒 +struct MLAT_timestamp { + explicit MLAT_timestamp(); + explicit MLAT_timestamp(const std::string& memory_6); + MLAT_timestamp(std::uint32_t daysec, std::uint32_t nanosec); + std::uint32_t daysec{}; // 当天的秒数 高18位 + std::uint32_t nanosec{}; // 当天的纳秒数 低30位 + std::string to_bin_string() const; + std::string to_memory() const; + unsigned long hh{}; + unsigned long mm{}; + unsigned long ss{}; + std::string memory{}; + bool operator<(const MLAT_timestamp& other) const { + // 比较 daysec(高18位) + if (daysec != other.daysec) { + return daysec < other.daysec; + } + // 如果 daysec 相等,比较 nanosec(低30位) + return nanosec < other.nanosec; + } + + + [[nodiscard]] Json toJson() const { + Json ret = Json::object(); + ret.append({"秒", daysec}); + ret.append({"纳秒", nanosec}); + ret.append({"时间", std::to_string(hh) + ":" + std::to_string(mm) + ":" + std::to_string(ss)}); + return ret; + } + + [[nodiscard]] std::string to_string() const { + return + "{" + std::to_string(daysec) + "," + std::to_string(nanosec) + "}_" + + "[" + + std::to_string(hh) + "时:" + + std::to_string(mm) + "分:" + + std::to_string(ss) + "秒" + "]"; + } + + void parse_hhmmss(); +}; + +#endif diff --git a/module/dll_source_lzy/ecap/lib/hulc/magic_enum/export.h b/module/dll_source_lzy/ecap/lib/hulc/magic_enum/export.h new file mode 100644 index 0000000..2150056 --- /dev/null +++ b/module/dll_source_lzy/ecap/lib/hulc/magic_enum/export.h @@ -0,0 +1,114 @@ +#ifndef yc_magic_enum_H +#define yc_magic_enum_H +#include "magic_enum/magic_enum.hpp" +#include +#include + +template +EnumType to_enum(const std::string& str) { + auto opt = magic_enum::enum_cast(str); + if (opt.has_value()) { + return opt.value(); // 返回枚举值 + } + std::cerr << std::string(magic_enum::enum_type_name()) +" 字符串转换枚举值错误!str:" + str + "\n"; + exit(-1); +} + +template +std::optional to_enum2(const std::string& str) { + auto opt = magic_enum::enum_cast(str); + if (opt.has_value()) { + return opt.value(); // 返回枚举值 + } + return std::nullopt; +} + +template +std::string to_string(EnumType type) { + return std::string(magic_enum::enum_name(type)); +} + +template +std::optional int_to_enum(int enum_value) { + // 静态断言,确保 EnumType 是枚举类型 + static_assert(std::is_enum_v, "EnumType must be an enum type"); + // 使用 magic_enum 获取所有的枚举值 + auto enum_values = magic_enum::enum_values(); + // 检查是否存在匹配的枚举值 + for (auto value : enum_values) { + if (static_cast(value) == enum_value) { + return value; // 返回匹配的枚举值 + } + } + // 如果没有匹配的枚举值,返回 std::nullopt + return std::nullopt; +} + +template +std::optional enum_int_to_string(int enum_value) { + auto tmp = int_to_enum(enum_value); + if (!tmp.has_value()) return std::nullopt; + return to_string(tmp.value()); +} + +template +std::vector split_flags(Enum flags) +{ + static_assert(std::is_enum_v, "Template parameter must be an enum type"); + std::vector setFlags; + for (auto flag : magic_enum::enum_values()) + { + if ((flags & flag) == flag) + { + setFlags.push_back(flag); + } + } + return setFlags; +} + + +inline std::string to_string(const char* val) { + return std::string(val); +} + +template <> +inline std::string to_string(std::string val) { + return val; +} +template <> +inline std::string to_string(bool val) { + return val ? "true" : "false"; +} +template <> +inline std::string to_string(void* val) { + std::ostringstream oss; + oss << "0x" << std::hex << std::showbase << reinterpret_cast(val); + return oss.str(); +} + +#define IMPL_to_string_from_std(Type) template <> \ +inline std::string to_string(Type val) { \ + return std::to_string(val); \ +} \ + +IMPL_to_string_from_std(signed char) +IMPL_to_string_from_std(short) +IMPL_to_string_from_std(int) +IMPL_to_string_from_std(long) +IMPL_to_string_from_std(long long) +IMPL_to_string_from_std(unsigned char) +IMPL_to_string_from_std(unsigned short) +IMPL_to_string_from_std(unsigned int) +IMPL_to_string_from_std(unsigned long) +IMPL_to_string_from_std(unsigned long long) +IMPL_to_string_from_std(float) +IMPL_to_string_from_std(double) +IMPL_to_string_from_std(long double) +#undef IMPL_to_string_from_std + + + + + + +#endif \ No newline at end of file diff --git a/module/dll_source_lzy/ecap/lib/hulc/magic_enum/magic_enum/LICENSE b/module/dll_source_lzy/ecap/lib/hulc/magic_enum/magic_enum/LICENSE new file mode 100644 index 0000000..20acf2f --- /dev/null +++ b/module/dll_source_lzy/ecap/lib/hulc/magic_enum/magic_enum/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 - 2024 Daniil Goncharov + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/module/dll_source_lzy/ecap/lib/hulc/magic_enum/magic_enum/magic_enum.hpp b/module/dll_source_lzy/ecap/lib/hulc/magic_enum/magic_enum/magic_enum.hpp new file mode 100644 index 0000000..158207e --- /dev/null +++ b/module/dll_source_lzy/ecap/lib/hulc/magic_enum/magic_enum/magic_enum.hpp @@ -0,0 +1,1508 @@ +// __ __ _ ______ _____ +// | \/ | (_) | ____| / ____|_ _ +// | \ / | __ _ __ _ _ ___ | |__ _ __ _ _ _ __ ___ | | _| |_ _| |_ +// | |\/| |/ _` |/ _` | |/ __| | __| | '_ \| | | | '_ ` _ \ | | |_ _|_ _| +// | | | | (_| | (_| | | (__ | |____| | | | |_| | | | | | | | |____|_| |_| +// |_| |_|\__,_|\__, |_|\___| |______|_| |_|\__,_|_| |_| |_| \_____| +// __/ | https://github.com/Neargye/magic_enum +// |___/ version 0.9.7 +// +// Licensed under the MIT License . +// SPDX-License-Identifier: MIT +// Copyright (c) 2019 - 2024 Daniil Goncharov . +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#ifndef NEARGYE_MAGIC_ENUM_HPP +#define NEARGYE_MAGIC_ENUM_HPP + +#define MAGIC_ENUM_VERSION_MAJOR 0 +#define MAGIC_ENUM_VERSION_MINOR 9 +#define MAGIC_ENUM_VERSION_PATCH 7 + +#ifndef MAGIC_ENUM_USE_STD_MODULE +#include +#include +#include +#include +#include +#include +#include +#endif + +#if defined(MAGIC_ENUM_CONFIG_FILE) +# include MAGIC_ENUM_CONFIG_FILE +#endif + +#ifndef MAGIC_ENUM_USE_STD_MODULE +#if !defined(MAGIC_ENUM_USING_ALIAS_OPTIONAL) +# include +#endif +#if !defined(MAGIC_ENUM_USING_ALIAS_STRING) +# include +#endif +#if !defined(MAGIC_ENUM_USING_ALIAS_STRING_VIEW) +# include +#endif +#endif + +#if defined(MAGIC_ENUM_NO_ASSERT) +# define MAGIC_ENUM_ASSERT(...) static_cast(0) +#elif !defined(MAGIC_ENUM_ASSERT) +# include +# define MAGIC_ENUM_ASSERT(...) assert((__VA_ARGS__)) +#endif + +#if defined(__clang__) +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Wunknown-warning-option" +# pragma clang diagnostic ignored "-Wenum-constexpr-conversion" +# pragma clang diagnostic ignored "-Wuseless-cast" // suppresses 'static_cast('\0')' for char_type = char (common on Linux). +#elif defined(__GNUC__) +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wmaybe-uninitialized" // May be used uninitialized 'return {};'. +# pragma GCC diagnostic ignored "-Wuseless-cast" // suppresses 'static_cast('\0')' for char_type = char (common on Linux). +#elif defined(_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 26495) // Variable 'static_str::chars_' is uninitialized. +# pragma warning(disable : 28020) // Arithmetic overflow: Using operator '-' on a 4 byte value and then casting the result to a 8 byte value. +# pragma warning(disable : 26451) // The expression '0<=_Param_(1)&&_Param_(1)<=1-1' is not true at this call. +# pragma warning(disable : 4514) // Unreferenced inline function has been removed. +#endif + +// Checks magic_enum compiler compatibility. +#if defined(__clang__) && __clang_major__ >= 5 || defined(__GNUC__) && __GNUC__ >= 9 || defined(_MSC_VER) && _MSC_VER >= 1910 || defined(__RESHARPER__) +# undef MAGIC_ENUM_SUPPORTED +# define MAGIC_ENUM_SUPPORTED 1 +#endif + +// Checks magic_enum compiler aliases compatibility. +#if defined(__clang__) && __clang_major__ >= 5 || defined(__GNUC__) && __GNUC__ >= 9 || defined(_MSC_VER) && _MSC_VER >= 1920 +# undef MAGIC_ENUM_SUPPORTED_ALIASES +# define MAGIC_ENUM_SUPPORTED_ALIASES 1 +#endif + +// Enum value must be greater or equals than MAGIC_ENUM_RANGE_MIN. By default MAGIC_ENUM_RANGE_MIN = -128. +// If need another min range for all enum types by default, redefine the macro MAGIC_ENUM_RANGE_MIN. +#if !defined(MAGIC_ENUM_RANGE_MIN) +# define MAGIC_ENUM_RANGE_MIN -128 +#endif + +// Enum value must be less or equals than MAGIC_ENUM_RANGE_MAX. By default MAGIC_ENUM_RANGE_MAX = 127. +// If need another max range for all enum types by default, redefine the macro MAGIC_ENUM_RANGE_MAX. +#if !defined(MAGIC_ENUM_RANGE_MAX) +# define MAGIC_ENUM_RANGE_MAX 127 +#endif + +// Improve ReSharper C++ intellisense performance with builtins, avoiding unnecessary template instantiations. +#if defined(__RESHARPER__) +# undef MAGIC_ENUM_GET_ENUM_NAME_BUILTIN +# undef MAGIC_ENUM_GET_TYPE_NAME_BUILTIN +# if __RESHARPER__ >= 20230100 +# define MAGIC_ENUM_GET_ENUM_NAME_BUILTIN(V) __rscpp_enumerator_name(V) +# define MAGIC_ENUM_GET_TYPE_NAME_BUILTIN(T) __rscpp_type_name() +# else +# define MAGIC_ENUM_GET_ENUM_NAME_BUILTIN(V) nullptr +# define MAGIC_ENUM_GET_TYPE_NAME_BUILTIN(T) nullptr +# endif +#endif + +namespace magic_enum { + +// If need another optional type, define the macro MAGIC_ENUM_USING_ALIAS_OPTIONAL. +#if defined(MAGIC_ENUM_USING_ALIAS_OPTIONAL) +MAGIC_ENUM_USING_ALIAS_OPTIONAL +#else +using std::optional; +#endif + +// If need another string_view type, define the macro MAGIC_ENUM_USING_ALIAS_STRING_VIEW. +#if defined(MAGIC_ENUM_USING_ALIAS_STRING_VIEW) +MAGIC_ENUM_USING_ALIAS_STRING_VIEW +#else +using std::string_view; +#endif + +// If need another string type, define the macro MAGIC_ENUM_USING_ALIAS_STRING. +#if defined(MAGIC_ENUM_USING_ALIAS_STRING) +MAGIC_ENUM_USING_ALIAS_STRING +#else +using std::string; +#endif + +using char_type = string_view::value_type; +static_assert(std::is_same_v, "magic_enum::customize requires same string_view::value_type and string::value_type"); +static_assert([] { + if constexpr (std::is_same_v) { + constexpr const char c[] = "abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789|"; + constexpr const wchar_t wc[] = L"abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789|"; + static_assert(std::size(c) == std::size(wc), "magic_enum::customize identifier characters are multichars in wchar_t."); + + for (std::size_t i = 0; i < std::size(c); ++i) { + if (c[i] != wc[i]) { + return false; + } + } + } + return true; +} (), "magic_enum::customize wchar_t is not compatible with ASCII."); + +namespace customize { + +// Enum value must be in range [MAGIC_ENUM_RANGE_MIN, MAGIC_ENUM_RANGE_MAX]. By default MAGIC_ENUM_RANGE_MIN = -128, MAGIC_ENUM_RANGE_MAX = 127. +// If need another range for all enum types by default, redefine the macro MAGIC_ENUM_RANGE_MIN and MAGIC_ENUM_RANGE_MAX. +// If need another range for specific enum type, add specialization enum_range for necessary enum type. +template +struct enum_range { + static constexpr int min = MAGIC_ENUM_RANGE_MIN; + static constexpr int max = MAGIC_ENUM_RANGE_MAX; +}; + +static_assert(MAGIC_ENUM_RANGE_MAX > MAGIC_ENUM_RANGE_MIN, "MAGIC_ENUM_RANGE_MAX must be greater than MAGIC_ENUM_RANGE_MIN."); + +namespace detail { + +enum class customize_tag { + default_tag, + invalid_tag, + custom_tag +}; + +} // namespace magic_enum::customize::detail + +class customize_t : public std::pair { + public: + constexpr customize_t(string_view srt) : std::pair{detail::customize_tag::custom_tag, srt} {} + constexpr customize_t(const char_type* srt) : customize_t{string_view{srt}} {} + constexpr customize_t(detail::customize_tag tag) : std::pair{tag, string_view{}} { + MAGIC_ENUM_ASSERT(tag != detail::customize_tag::custom_tag); + } +}; + +// Default customize. +inline constexpr auto default_tag = customize_t{detail::customize_tag::default_tag}; +// Invalid customize. +inline constexpr auto invalid_tag = customize_t{detail::customize_tag::invalid_tag}; + +// If need custom names for enum, add specialization enum_name for necessary enum type. +template +constexpr customize_t enum_name(E) noexcept { + return default_tag; +} + +// If need custom type name for enum, add specialization enum_type_name for necessary enum type. +template +constexpr customize_t enum_type_name() noexcept { + return default_tag; +} + +} // namespace magic_enum::customize + +namespace detail { + +template +struct supported +#if defined(MAGIC_ENUM_SUPPORTED) && MAGIC_ENUM_SUPPORTED || defined(MAGIC_ENUM_NO_CHECK_SUPPORT) + : std::true_type {}; +#else + : std::false_type {}; +#endif + +template , std::enable_if_t, int> = 0> +using enum_constant = std::integral_constant; + +template +inline constexpr bool always_false_v = false; + +template +struct has_is_flags : std::false_type {}; + +template +struct has_is_flags::is_flags)>> : std::bool_constant::is_flags)>>> {}; + +template +struct range_min : std::integral_constant {}; + +template +struct range_min::min)>> : std::integral_constant::min), customize::enum_range::min> {}; + +template +struct range_max : std::integral_constant {}; + +template +struct range_max::max)>> : std::integral_constant::max), customize::enum_range::max> {}; + +struct str_view { + const char* str_ = nullptr; + std::size_t size_ = 0; +}; + +template +class static_str { + public: + constexpr explicit static_str(str_view str) noexcept : static_str{str.str_, std::make_integer_sequence{}} { + MAGIC_ENUM_ASSERT(str.size_ == N); + } + + constexpr explicit static_str(string_view str) noexcept : static_str{str.data(), std::make_integer_sequence{}} { + MAGIC_ENUM_ASSERT(str.size() == N); + } + + constexpr const char_type* data() const noexcept { return chars_; } + + constexpr std::uint16_t size() const noexcept { return N; } + + constexpr operator string_view() const noexcept { return {data(), size()}; } + + private: + template + constexpr static_str(const char* str, std::integer_sequence) noexcept : chars_{static_cast(str[I])..., static_cast('\0')} {} + + template + constexpr static_str(string_view str, std::integer_sequence) noexcept : chars_{str[I]..., static_cast('\0')} {} + + char_type chars_[static_cast(N) + 1]; +}; + +template <> +class static_str<0> { + public: + constexpr explicit static_str() = default; + + constexpr explicit static_str(str_view) noexcept {} + + constexpr explicit static_str(string_view) noexcept {} + + constexpr const char_type* data() const noexcept { return nullptr; } + + constexpr std::uint16_t size() const noexcept { return 0; } + + constexpr operator string_view() const noexcept { return {}; } +}; + +template > +class case_insensitive { + static constexpr char_type to_lower(char_type c) noexcept { + return (c >= static_cast('A') && c <= static_cast('Z')) ? static_cast(c + (static_cast('a') - static_cast('A'))) : c; + } + + public: + template + constexpr auto operator()(L lhs, R rhs) const noexcept -> std::enable_if_t, char_type> && std::is_same_v, char_type>, bool> { + return Op{}(to_lower(lhs), to_lower(rhs)); + } +}; + +constexpr std::size_t find(string_view str, char_type c) noexcept { +#if defined(__clang__) && __clang_major__ < 9 && defined(__GLIBCXX__) || defined(_MSC_VER) && _MSC_VER < 1920 && !defined(__clang__) +// https://stackoverflow.com/questions/56484834/constexpr-stdstring-viewfind-last-of-doesnt-work-on-clang-8-with-libstdc +// https://developercommunity.visualstudio.com/content/problem/360432/vs20178-regression-c-failed-in-test.html + constexpr bool workaround = true; +#else + constexpr bool workaround = false; +#endif + + if constexpr (workaround) { + for (std::size_t i = 0; i < str.size(); ++i) { + if (str[i] == c) { + return i; + } + } + + return string_view::npos; + } else { + return str.find(c); + } +} + +template +constexpr bool is_default_predicate() noexcept { + return std::is_same_v, std::equal_to> || + std::is_same_v, std::equal_to<>>; +} + +template +constexpr bool is_nothrow_invocable() { + return is_default_predicate() || + std::is_nothrow_invocable_r_v; +} + +template +constexpr bool cmp_equal(string_view lhs, string_view rhs, [[maybe_unused]] BinaryPredicate&& p) noexcept(is_nothrow_invocable()) { +#if defined(_MSC_VER) && _MSC_VER < 1920 && !defined(__clang__) + // https://developercommunity.visualstudio.com/content/problem/360432/vs20178-regression-c-failed-in-test.html + // https://developercommunity.visualstudio.com/content/problem/232218/c-constexpr-string-view.html + constexpr bool workaround = true; +#else + constexpr bool workaround = false; +#endif + + if constexpr (!is_default_predicate() || workaround) { + if (lhs.size() != rhs.size()) { + return false; + } + + const auto size = lhs.size(); + for (std::size_t i = 0; i < size; ++i) { + if (!p(lhs[i], rhs[i])) { + return false; + } + } + + return true; + } else { + return lhs == rhs; + } +} + +template +constexpr bool cmp_less(L lhs, R rhs) noexcept { + static_assert(std::is_integral_v && std::is_integral_v, "magic_enum::detail::cmp_less requires integral type."); + + if constexpr (std::is_signed_v == std::is_signed_v) { + // If same signedness (both signed or both unsigned). + return lhs < rhs; + } else if constexpr (std::is_same_v) { // bool special case + return static_cast(lhs) < rhs; + } else if constexpr (std::is_same_v) { // bool special case + return lhs < static_cast(rhs); + } else if constexpr (std::is_signed_v) { + // If 'right' is negative, then result is 'false', otherwise cast & compare. + return rhs > 0 && lhs < static_cast>(rhs); + } else { + // If 'left' is negative, then result is 'true', otherwise cast & compare. + return lhs < 0 || static_cast>(lhs) < rhs; + } +} + +template +constexpr I log2(I value) noexcept { + static_assert(std::is_integral_v, "magic_enum::detail::log2 requires integral type."); + + if constexpr (std::is_same_v) { // bool special case + return MAGIC_ENUM_ASSERT(false), value; + } else { + auto ret = I{0}; + for (; value > I{1}; value >>= I{1}, ++ret) {} + + return ret; + } +} + +#if defined(__cpp_lib_array_constexpr) && __cpp_lib_array_constexpr >= 201603L +# define MAGIC_ENUM_ARRAY_CONSTEXPR 1 +#else +template +constexpr std::array, N> to_array(T (&a)[N], std::index_sequence) noexcept { + return {{a[I]...}}; +} +#endif + +template +inline constexpr bool is_enum_v = std::is_enum_v && std::is_same_v>; + +template +constexpr auto n() noexcept { + static_assert(is_enum_v, "magic_enum::detail::n requires enum type."); + + if constexpr (supported::value) { +#if defined(MAGIC_ENUM_GET_TYPE_NAME_BUILTIN) + constexpr auto name_ptr = MAGIC_ENUM_GET_TYPE_NAME_BUILTIN(E); + constexpr auto name = name_ptr ? str_view{name_ptr, std::char_traits::length(name_ptr)} : str_view{}; +#elif defined(__clang__) + str_view name; + if constexpr (sizeof(__PRETTY_FUNCTION__) == sizeof(__FUNCTION__)) { + static_assert(always_false_v, "magic_enum::detail::n requires __PRETTY_FUNCTION__."); + return str_view{}; + } else { + name.size_ = sizeof(__PRETTY_FUNCTION__) - 36; + name.str_ = __PRETTY_FUNCTION__ + 34; + } +#elif defined(__GNUC__) + auto name = str_view{__PRETTY_FUNCTION__, sizeof(__PRETTY_FUNCTION__) - 1}; + if constexpr (sizeof(__PRETTY_FUNCTION__) == sizeof(__FUNCTION__)) { + static_assert(always_false_v, "magic_enum::detail::n requires __PRETTY_FUNCTION__."); + return str_view{}; + } else if (name.str_[name.size_ - 1] == ']') { + name.size_ -= 50; + name.str_ += 49; + } else { + name.size_ -= 40; + name.str_ += 37; + } +#elif defined(_MSC_VER) + // CLI/C++ workaround (see https://github.com/Neargye/magic_enum/issues/284). + str_view name; + name.str_ = __FUNCSIG__; + name.str_ += 40; + name.size_ += sizeof(__FUNCSIG__) - 57; +#else + auto name = str_view{}; +#endif + std::size_t p = 0; + for (std::size_t i = name.size_; i > 0; --i) { + if (name.str_[i] == ':') { + p = i + 1; + break; + } + } + if (p > 0) { + name.size_ -= p; + name.str_ += p; + } + return name; + } else { + return str_view{}; // Unsupported compiler or Invalid customize. + } +} + +template +constexpr auto type_name() noexcept { + [[maybe_unused]] constexpr auto custom = customize::enum_type_name(); + static_assert(std::is_same_v, customize::customize_t>, "magic_enum::customize requires customize_t type."); + if constexpr (custom.first == customize::detail::customize_tag::custom_tag) { + constexpr auto name = custom.second; + static_assert(!name.empty(), "magic_enum::customize requires not empty string."); + return static_str{name}; + } else if constexpr (custom.first == customize::detail::customize_tag::invalid_tag) { + return static_str<0>{}; + } else if constexpr (custom.first == customize::detail::customize_tag::default_tag) { + constexpr auto name = n(); + return static_str{name}; + } else { + static_assert(always_false_v, "magic_enum::customize invalid."); + } +} + +template +inline constexpr auto type_name_v = type_name(); + +template +constexpr auto n() noexcept { + static_assert(is_enum_v, "magic_enum::detail::n requires enum type."); + + if constexpr (supported::value) { +#if defined(MAGIC_ENUM_GET_ENUM_NAME_BUILTIN) + constexpr auto name_ptr = MAGIC_ENUM_GET_ENUM_NAME_BUILTIN(V); + auto name = name_ptr ? str_view{name_ptr, std::char_traits::length(name_ptr)} : str_view{}; +#elif defined(__clang__) + str_view name; + if constexpr (sizeof(__PRETTY_FUNCTION__) == sizeof(__FUNCTION__)) { + static_assert(always_false_v, "magic_enum::detail::n requires __PRETTY_FUNCTION__."); + return str_view{}; + } else { + name.size_ = sizeof(__PRETTY_FUNCTION__) - 36; + name.str_ = __PRETTY_FUNCTION__ + 34; + } + if (name.size_ > 22 && name.str_[0] == '(' && name.str_[1] == 'a' && name.str_[10] == ' ' && name.str_[22] == ':') { + name.size_ -= 23; + name.str_ += 23; + } + if (name.str_[0] == '(' || name.str_[0] == '-' || (name.str_[0] >= '0' && name.str_[0] <= '9')) { + name = str_view{}; + } +#elif defined(__GNUC__) + auto name = str_view{__PRETTY_FUNCTION__, sizeof(__PRETTY_FUNCTION__) - 1}; + if constexpr (sizeof(__PRETTY_FUNCTION__) == sizeof(__FUNCTION__)) { + static_assert(always_false_v, "magic_enum::detail::n requires __PRETTY_FUNCTION__."); + return str_view{}; + } else if (name.str_[name.size_ - 1] == ']') { + name.size_ -= 55; + name.str_ += 54; + } else { + name.size_ -= 40; + name.str_ += 37; + } + if (name.str_[0] == '(') { + name = str_view{}; + } +#elif defined(_MSC_VER) + str_view name; + if ((__FUNCSIG__[5] == '_' && __FUNCSIG__[35] != '(') || (__FUNCSIG__[5] == 'c' && __FUNCSIG__[41] != '(')) { + // CLI/C++ workaround (see https://github.com/Neargye/magic_enum/issues/284). + name.str_ = __FUNCSIG__; + name.str_ += 35; + name.size_ = sizeof(__FUNCSIG__) - 52; + } +#else + auto name = str_view{}; +#endif + std::size_t p = 0; + for (std::size_t i = name.size_; i > 0; --i) { + if (name.str_[i] == ':') { + p = i + 1; + break; + } + } + if (p > 0) { + name.size_ -= p; + name.str_ += p; + } + return name; + } else { + return str_view{}; // Unsupported compiler or Invalid customize. + } +} + +#if defined(_MSC_VER) && !defined(__clang__) && _MSC_VER < 1920 +# define MAGIC_ENUM_VS_2017_WORKAROUND 1 +#endif + +#if defined(MAGIC_ENUM_VS_2017_WORKAROUND) +template +constexpr auto n() noexcept { + static_assert(is_enum_v, "magic_enum::detail::n requires enum type."); + +# if defined(MAGIC_ENUM_GET_ENUM_NAME_BUILTIN) + constexpr auto name_ptr = MAGIC_ENUM_GET_ENUM_NAME_BUILTIN(V); + auto name = name_ptr ? str_view{name_ptr, std::char_traits::length(name_ptr)} : str_view{}; +# else + // CLI/C++ workaround (see https://github.com/Neargye/magic_enum/issues/284). + str_view name; + name.str_ = __FUNCSIG__; + name.size_ = sizeof(__FUNCSIG__) - 17; + std::size_t p = 0; + for (std::size_t i = name.size_; i > 0; --i) { + if (name.str_[i] == ',' || name.str_[i] == ':') { + p = i + 1; + break; + } + } + if (p > 0) { + name.size_ -= p; + name.str_ += p; + } + if (name.str_[0] == '(' || name.str_[0] == '-' || (name.str_[0] >= '0' && name.str_[0] <= '9')) { + name = str_view{}; + } + return name; +# endif +} +#endif + +template +constexpr auto enum_name() noexcept { + [[maybe_unused]] constexpr auto custom = customize::enum_name(V); + static_assert(std::is_same_v, customize::customize_t>, "magic_enum::customize requires customize_t type."); + if constexpr (custom.first == customize::detail::customize_tag::custom_tag) { + constexpr auto name = custom.second; + static_assert(!name.empty(), "magic_enum::customize requires not empty string."); + return static_str{name}; + } else if constexpr (custom.first == customize::detail::customize_tag::invalid_tag) { + return static_str<0>{}; + } else if constexpr (custom.first == customize::detail::customize_tag::default_tag) { +#if defined(MAGIC_ENUM_VS_2017_WORKAROUND) + constexpr auto name = n(); +#else + constexpr auto name = n(); +#endif + return static_str{name}; + } else { + static_assert(always_false_v, "magic_enum::customize invalid."); + } +} + +template +inline constexpr auto enum_name_v = enum_name(); + +template +constexpr bool is_valid() noexcept { +#if defined(__clang__) && __clang_major__ >= 16 + // https://reviews.llvm.org/D130058, https://reviews.llvm.org/D131307 + constexpr E v = __builtin_bit_cast(E, V); +#else + constexpr E v = static_cast(V); +#endif + [[maybe_unused]] constexpr auto custom = customize::enum_name(v); + static_assert(std::is_same_v, customize::customize_t>, "magic_enum::customize requires customize_t type."); + if constexpr (custom.first == customize::detail::customize_tag::custom_tag) { + constexpr auto name = custom.second; + static_assert(!name.empty(), "magic_enum::customize requires not empty string."); + return name.size() != 0; + } else if constexpr (custom.first == customize::detail::customize_tag::default_tag) { +#if defined(MAGIC_ENUM_VS_2017_WORKAROUND) + return n().size_ != 0; +#else + return n().size_ != 0; +#endif + } else { + return false; + } +} + +enum class enum_subtype { + common, + flags +}; + +template > +constexpr U ualue(std::size_t i) noexcept { + if constexpr (std::is_same_v) { // bool special case + static_assert(O == 0, "magic_enum::detail::ualue requires valid offset."); + + return static_cast(i); + } else if constexpr (S == enum_subtype::flags) { + return static_cast(U{1} << static_cast(static_cast(i) + O)); + } else { + return static_cast(static_cast(i) + O); + } +} + +template > +constexpr E value(std::size_t i) noexcept { + return static_cast(ualue(i)); +} + +template > +constexpr int reflected_min() noexcept { + if constexpr (S == enum_subtype::flags) { + return 0; + } else { + constexpr auto lhs = range_min::value; + constexpr auto rhs = (std::numeric_limits::min)(); + + if constexpr (cmp_less(rhs, lhs)) { + return lhs; + } else { + return rhs; + } + } +} + +template > +constexpr int reflected_max() noexcept { + if constexpr (S == enum_subtype::flags) { + return std::numeric_limits::digits - 1; + } else { + constexpr auto lhs = range_max::value; + constexpr auto rhs = (std::numeric_limits::max)(); + + if constexpr (cmp_less(lhs, rhs)) { + return lhs; + } else { + return rhs; + } + } +} + +#define MAGIC_ENUM_FOR_EACH_256(T) \ + T( 0)T( 1)T( 2)T( 3)T( 4)T( 5)T( 6)T( 7)T( 8)T( 9)T( 10)T( 11)T( 12)T( 13)T( 14)T( 15)T( 16)T( 17)T( 18)T( 19)T( 20)T( 21)T( 22)T( 23)T( 24)T( 25)T( 26)T( 27)T( 28)T( 29)T( 30)T( 31) \ + T( 32)T( 33)T( 34)T( 35)T( 36)T( 37)T( 38)T( 39)T( 40)T( 41)T( 42)T( 43)T( 44)T( 45)T( 46)T( 47)T( 48)T( 49)T( 50)T( 51)T( 52)T( 53)T( 54)T( 55)T( 56)T( 57)T( 58)T( 59)T( 60)T( 61)T( 62)T( 63) \ + T( 64)T( 65)T( 66)T( 67)T( 68)T( 69)T( 70)T( 71)T( 72)T( 73)T( 74)T( 75)T( 76)T( 77)T( 78)T( 79)T( 80)T( 81)T( 82)T( 83)T( 84)T( 85)T( 86)T( 87)T( 88)T( 89)T( 90)T( 91)T( 92)T( 93)T( 94)T( 95) \ + T( 96)T( 97)T( 98)T( 99)T(100)T(101)T(102)T(103)T(104)T(105)T(106)T(107)T(108)T(109)T(110)T(111)T(112)T(113)T(114)T(115)T(116)T(117)T(118)T(119)T(120)T(121)T(122)T(123)T(124)T(125)T(126)T(127) \ + T(128)T(129)T(130)T(131)T(132)T(133)T(134)T(135)T(136)T(137)T(138)T(139)T(140)T(141)T(142)T(143)T(144)T(145)T(146)T(147)T(148)T(149)T(150)T(151)T(152)T(153)T(154)T(155)T(156)T(157)T(158)T(159) \ + T(160)T(161)T(162)T(163)T(164)T(165)T(166)T(167)T(168)T(169)T(170)T(171)T(172)T(173)T(174)T(175)T(176)T(177)T(178)T(179)T(180)T(181)T(182)T(183)T(184)T(185)T(186)T(187)T(188)T(189)T(190)T(191) \ + T(192)T(193)T(194)T(195)T(196)T(197)T(198)T(199)T(200)T(201)T(202)T(203)T(204)T(205)T(206)T(207)T(208)T(209)T(210)T(211)T(212)T(213)T(214)T(215)T(216)T(217)T(218)T(219)T(220)T(221)T(222)T(223) \ + T(224)T(225)T(226)T(227)T(228)T(229)T(230)T(231)T(232)T(233)T(234)T(235)T(236)T(237)T(238)T(239)T(240)T(241)T(242)T(243)T(244)T(245)T(246)T(247)T(248)T(249)T(250)T(251)T(252)T(253)T(254)T(255) + +template +constexpr void valid_count(bool* valid, std::size_t& count) noexcept { +#define MAGIC_ENUM_V(O) \ + if constexpr ((I + O) < Size) { \ + if constexpr (is_valid(I + O)>()) { \ + valid[I + O] = true; \ + ++count; \ + } \ + } + + MAGIC_ENUM_FOR_EACH_256(MAGIC_ENUM_V) + + if constexpr ((I + 256) < Size) { + valid_count(valid, count); + } +#undef MAGIC_ENUM_V +} + +template +struct valid_count_t { + std::size_t count = 0; + bool valid[N] = {}; +}; + +template +constexpr auto valid_count() noexcept { + valid_count_t vc; + valid_count(vc.valid, vc.count); + return vc; +} + +template +constexpr auto values() noexcept { + constexpr auto vc = valid_count(); + + if constexpr (vc.count > 0) { +#if defined(MAGIC_ENUM_ARRAY_CONSTEXPR) + std::array values = {}; +#else + E values[vc.count] = {}; +#endif + for (std::size_t i = 0, v = 0; v < vc.count; ++i) { + if (vc.valid[i]) { + values[v++] = value(i); + } + } +#if defined(MAGIC_ENUM_ARRAY_CONSTEXPR) + return values; +#else + return to_array(values, std::make_index_sequence{}); +#endif + } else { + return std::array{}; + } +} + +template > +constexpr auto values() noexcept { + constexpr auto min = reflected_min(); + constexpr auto max = reflected_max(); + constexpr auto range_size = max - min + 1; + static_assert(range_size > 0, "magic_enum::enum_range requires valid size."); + + return values(); +} + +template > +constexpr enum_subtype subtype(std::true_type) noexcept { + if constexpr (std::is_same_v) { // bool special case + return enum_subtype::common; + } else if constexpr (has_is_flags::value) { + return customize::enum_range::is_flags ? enum_subtype::flags : enum_subtype::common; + } else { +#if defined(MAGIC_ENUM_AUTO_IS_FLAGS) + constexpr auto flags_values = values(); + constexpr auto default_values = values(); + if (flags_values.size() == 0 || default_values.size() > flags_values.size()) { + return enum_subtype::common; + } + for (std::size_t i = 0; i < default_values.size(); ++i) { + const auto v = static_cast(default_values[i]); + if (v != 0 && (v & (v - 1)) != 0) { + return enum_subtype::common; + } + } + return enum_subtype::flags; +#else + return enum_subtype::common; +#endif + } +} + +template +constexpr enum_subtype subtype(std::false_type) noexcept { + // For non-enum type return default common subtype. + return enum_subtype::common; +} + +template > +inline constexpr auto subtype_v = subtype(std::is_enum{}); + +template +inline constexpr auto values_v = values(); + +template > +using values_t = decltype((values_v)); + +template +inline constexpr auto count_v = values_v.size(); + +template > +inline constexpr auto min_v = (count_v > 0) ? static_cast(values_v.front()) : U{0}; + +template > +inline constexpr auto max_v = (count_v > 0) ? static_cast(values_v.back()) : U{0}; + +template +constexpr auto names(std::index_sequence) noexcept { + constexpr auto names = std::array{{enum_name_v[I]>...}}; + return names; +} + +template +inline constexpr auto names_v = names(std::make_index_sequence>{}); + +template > +using names_t = decltype((names_v)); + +template +constexpr auto entries(std::index_sequence) noexcept { + constexpr auto entries = std::array, sizeof...(I)>{{{values_v[I], enum_name_v[I]>}...}}; + return entries; +} + +template +inline constexpr auto entries_v = entries(std::make_index_sequence>{}); + +template > +using entries_t = decltype((entries_v)); + +template > +constexpr bool is_sparse() noexcept { + if constexpr (count_v == 0) { + return false; + } else if constexpr (std::is_same_v) { // bool special case + return false; + } else { + constexpr auto max = (S == enum_subtype::flags) ? log2(max_v) : max_v; + constexpr auto min = (S == enum_subtype::flags) ? log2(min_v) : min_v; + constexpr auto range_size = max - min + 1; + + return range_size != count_v; + } +} + +template > +inline constexpr bool is_sparse_v = is_sparse(); + +template +struct is_reflected +#if defined(MAGIC_ENUM_NO_CHECK_REFLECTED_ENUM) + : std::true_type {}; +#else + : std::bool_constant && (count_v != 0)> {}; +#endif + +template +inline constexpr bool is_reflected_v = is_reflected, S>{}; + +template +struct enable_if_enum {}; + +template +struct enable_if_enum { + using type = R; + static_assert(supported::value, "magic_enum unsupported compiler (https://github.com/Neargye/magic_enum#compiler-compatibility)."); +}; + +template , typename D = std::decay_t> +using enable_if_t = typename enable_if_enum && std::is_invocable_r_v, R>::type; + +template >, int> = 0> +using enum_concept = T; + +template > +struct is_scoped_enum : std::false_type {}; + +template +struct is_scoped_enum : std::bool_constant>> {}; + +template > +struct is_unscoped_enum : std::false_type {}; + +template +struct is_unscoped_enum : std::bool_constant>> {}; + +template >> +struct underlying_type {}; + +template +struct underlying_type : std::underlying_type> {}; + +#if defined(MAGIC_ENUM_ENABLE_HASH) || defined(MAGIC_ENUM_ENABLE_HASH_SWITCH) + +template +struct constexpr_hash_t; + +template +struct constexpr_hash_t>> { + constexpr auto operator()(Value value) const noexcept { + using U = typename underlying_type::type; + if constexpr (std::is_same_v) { // bool special case + return static_cast(value); + } else { + return static_cast(value); + } + } + using secondary_hash = constexpr_hash_t; +}; + +template +struct constexpr_hash_t>> { + static constexpr std::uint32_t crc_table[256] { + 0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x076dc419L, 0x706af48fL, 0xe963a535L, 0x9e6495a3L, + 0x0edb8832L, 0x79dcb8a4L, 0xe0d5e91eL, 0x97d2d988L, 0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L, 0x90bf1d91L, + 0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL, 0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L, + 0x136c9856L, 0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L, 0xfa0f3d63L, 0x8d080df5L, + 0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L, 0xa2677172L, 0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL, + 0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L, 0x32d86ce3L, 0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L, + 0x26d930acL, 0x51de003aL, 0xc8d75180L, 0xbfd06116L, 0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L, 0xb8bda50fL, + 0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L, 0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL, + 0x76dc4190L, 0x01db7106L, 0x98d220bcL, 0xefd5102aL, 0x71b18589L, 0x06b6b51fL, 0x9fbfe4a5L, 0xe8b8d433L, + 0x7807c9a2L, 0x0f00f934L, 0x9609a88eL, 0xe10e9818L, 0x7f6a0dbbL, 0x086d3d2dL, 0x91646c97L, 0xe6635c01L, + 0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL, 0x6c0695edL, 0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L, + 0x65b0d9c6L, 0x12b7e950L, 0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L, 0xfbd44c65L, + 0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L, 0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL, + 0x4369e96aL, 0x346ed9fcL, 0xad678846L, 0xda60b8d0L, 0x44042d73L, 0x33031de5L, 0xaa0a4c5fL, 0xdd0d7cc9L, + 0x5005713cL, 0x270241aaL, 0xbe0b1010L, 0xc90c2086L, 0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL, + 0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L, 0x59b33d17L, 0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL, + 0xedb88320L, 0x9abfb3b6L, 0x03b6e20cL, 0x74b1d29aL, 0xead54739L, 0x9dd277afL, 0x04db2615L, 0x73dc1683L, + 0xe3630b12L, 0x94643b84L, 0x0d6d6a3eL, 0x7a6a5aa8L, 0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L, 0x7d079eb1L, + 0xf00f9344L, 0x8708a3d2L, 0x1e01f268L, 0x6906c2feL, 0xf762575dL, 0x806567cbL, 0x196c3671L, 0x6e6b06e7L, + 0xfed41b76L, 0x89d32be0L, 0x10da7a5aL, 0x67dd4accL, 0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L, + 0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L, 0xd1bb67f1L, 0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL, + 0xd80d2bdaL, 0xaf0a1b4cL, 0x36034af6L, 0x41047a60L, 0xdf60efc3L, 0xa867df55L, 0x316e8eefL, 0x4669be79L, + 0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L, 0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL, + 0xc5ba3bbeL, 0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L, 0xc2d7ffa7L, 0xb5d0cf31L, 0x2cd99e8bL, 0x5bdeae1dL, + 0x9b64c2b0L, 0xec63f226L, 0x756aa39cL, 0x026d930aL, 0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x05005713L, + 0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0x0cb61b38L, 0x92d28e9bL, 0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L, + 0x86d3d2d4L, 0xf1d4e242L, 0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L, 0x18b74777L, + 0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL, 0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L, + 0xa00ae278L, 0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L, 0xa7672661L, 0xd06016f7L, 0x4969474dL, 0x3e6e77dbL, + 0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L, 0x37d83bf0L, 0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L, + 0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L, 0xbad03605L, 0xcdd70693L, 0x54de5729L, 0x23d967bfL, + 0xb3667a2eL, 0xc4614ab8L, 0x5d681b02L, 0x2a6f2b94L, 0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL, 0x2d02ef8dL + }; + constexpr std::uint32_t operator()(string_view value) const noexcept { + auto crc = static_cast(0xffffffffL); + for (const auto c : value) { + crc = (crc >> 8) ^ crc_table[(crc ^ static_cast(c)) & 0xff]; + } + return crc ^ 0xffffffffL; + } + + struct secondary_hash { + constexpr std::uint32_t operator()(string_view value) const noexcept { + auto acc = static_cast(2166136261ULL); + for (const auto c : value) { + acc = ((acc ^ static_cast(c)) * static_cast(16777619ULL)) & (std::numeric_limits::max)(); + } + return static_cast(acc); + } + }; +}; + +template +inline constexpr Hash hash_v{}; + +template +constexpr auto calculate_cases(std::size_t Page) noexcept { + constexpr std::array values = *GlobValues; + constexpr std::size_t size = values.size(); + + using switch_t = std::invoke_result_t; + static_assert(std::is_integral_v && !std::is_same_v); + const std::size_t values_to = (std::min)(static_cast(256), size - Page); + + std::array result{}; + auto fill = result.begin(); + { + auto first = values.begin() + static_cast(Page); + auto last = values.begin() + static_cast(Page + values_to); + while (first != last) { + *fill++ = hash_v(*first++); + } + } + + // dead cases, try to avoid case collisions + for (switch_t last_value = result[values_to - 1]; fill != result.end() && last_value != (std::numeric_limits::max)(); *fill++ = ++last_value) { + } + + { + auto it = result.begin(); + auto last_value = (std::numeric_limits::min)(); + for (; fill != result.end(); *fill++ = last_value++) { + while (last_value == *it) { + ++last_value, ++it; + } + } + } + + return result; +} + +template +constexpr R invoke_r(F&& f, Args&&... args) noexcept(std::is_nothrow_invocable_r_v) { + if constexpr (std::is_void_v) { + std::forward(f)(std::forward(args)...); + } else { + return static_cast(std::forward(f)(std::forward(args)...)); + } +} + +enum class case_call_t { + index, + value +}; + +template +inline constexpr auto default_result_type_lambda = []() noexcept(std::is_nothrow_default_constructible_v) { return T{}; }; + +template <> +inline constexpr auto default_result_type_lambda = []() noexcept {}; + +template +constexpr bool has_duplicate() noexcept { + using value_t = std::decay_t; + using hash_value_t = std::invoke_result_t; + std::arraysize()> hashes{}; + std::size_t size = 0; + for (auto elem : *Arr) { + hashes[size] = hash_v(elem); + for (auto i = size++; i > 0; --i) { + if (hashes[i] < hashes[i - 1]) { + auto tmp = hashes[i]; + hashes[i] = hashes[i - 1]; + hashes[i - 1] = tmp; + } else if (hashes[i] == hashes[i - 1]) { + return false; + } else { + break; + } + } + } + return true; +} + +#define MAGIC_ENUM_CASE(val) \ + case cases[val]: \ + if constexpr ((val) + Page < size) { \ + if (!pred(values[val + Page], searched)) { \ + break; \ + } \ + if constexpr (CallValue == case_call_t::index) { \ + if constexpr (std::is_invocable_r_v>) { \ + return detail::invoke_r(std::forward(lambda), std::integral_constant{}); \ + } else if constexpr (std::is_invocable_v>) { \ + MAGIC_ENUM_ASSERT(false && "magic_enum::detail::constexpr_switch wrong result type."); \ + } \ + } else if constexpr (CallValue == case_call_t::value) { \ + if constexpr (std::is_invocable_r_v>) { \ + return detail::invoke_r(std::forward(lambda), enum_constant{}); \ + } else if constexpr (std::is_invocable_r_v>) { \ + MAGIC_ENUM_ASSERT(false && "magic_enum::detail::constexpr_switch wrong result type."); \ + } \ + } \ + break; \ + } else [[fallthrough]]; + +template ::value_type>, + typename BinaryPredicate = std::equal_to<>, + typename Lambda, + typename ResultGetterType> +constexpr decltype(auto) constexpr_switch( + Lambda&& lambda, + typename std::decay_t::value_type searched, + ResultGetterType&& def, + BinaryPredicate&& pred = {}) { + using result_t = std::invoke_result_t; + using hash_t = std::conditional_t(), Hash, typename Hash::secondary_hash>; + static_assert(has_duplicate(), "magic_enum::detail::constexpr_switch duplicated hash found, please report it: https://github.com/Neargye/magic_enum/issues."); + constexpr std::array values = *GlobValues; + constexpr std::size_t size = values.size(); + constexpr std::array cases = calculate_cases(Page); + + switch (hash_v(searched)) { + MAGIC_ENUM_FOR_EACH_256(MAGIC_ENUM_CASE) + default: + if constexpr (size > 256 + Page) { + return constexpr_switch(std::forward(lambda), searched, std::forward(def)); + } + break; + } + return def(); +} + +#undef MAGIC_ENUM_CASE + +#endif + +} // namespace magic_enum::detail + +// Checks is magic_enum supported compiler. +inline constexpr bool is_magic_enum_supported = detail::supported::value; + +template +using Enum = detail::enum_concept; + +// Checks whether T is an Unscoped enumeration type. +// Provides the member constant value which is equal to true, if T is an [Unscoped enumeration](https://en.cppreference.com/w/cpp/language/enum#Unscoped_enumeration) type. Otherwise, value is equal to false. +template +struct is_unscoped_enum : detail::is_unscoped_enum {}; + +template +inline constexpr bool is_unscoped_enum_v = is_unscoped_enum::value; + +// Checks whether T is an Scoped enumeration type. +// Provides the member constant value which is equal to true, if T is an [Scoped enumeration](https://en.cppreference.com/w/cpp/language/enum#Scoped_enumerations) type. Otherwise, value is equal to false. +template +struct is_scoped_enum : detail::is_scoped_enum {}; + +template +inline constexpr bool is_scoped_enum_v = is_scoped_enum::value; + +// If T is a complete enumeration type, provides a member typedef type that names the underlying type of T. +// Otherwise, if T is not an enumeration type, there is no member type. Otherwise (T is an incomplete enumeration type), the program is ill-formed. +template +struct underlying_type : detail::underlying_type {}; + +template +using underlying_type_t = typename underlying_type::type; + +template +using enum_constant = detail::enum_constant; + +// Returns type name of enum. +template +[[nodiscard]] constexpr auto enum_type_name() noexcept -> detail::enable_if_t { + constexpr string_view name = detail::type_name_v>; + static_assert(!name.empty(), "magic_enum::enum_type_name enum type does not have a name."); + + return name; +} + +// Returns number of enum values. +template > +[[nodiscard]] constexpr auto enum_count() noexcept -> detail::enable_if_t { + return detail::count_v, S>; +} + +// Returns enum value at specified index. +// No bounds checking is performed: the behavior is undefined if index >= number of enum values. +template > +[[nodiscard]] constexpr auto enum_value(std::size_t index) noexcept -> detail::enable_if_t> { + using D = std::decay_t; + static_assert(detail::is_reflected_v, "magic_enum requires enum implementation and valid max and min."); + + if constexpr (detail::is_sparse_v) { + return MAGIC_ENUM_ASSERT(index < detail::count_v), detail::values_v[index]; + } else { + constexpr auto min = (S == detail::enum_subtype::flags) ? detail::log2(detail::min_v) : detail::min_v; + + return MAGIC_ENUM_ASSERT(index < detail::count_v), detail::value(index); + } +} + +// Returns enum value at specified index. +template > +[[nodiscard]] constexpr auto enum_value() noexcept -> detail::enable_if_t> { + using D = std::decay_t; + static_assert(detail::is_reflected_v, "magic_enum requires enum implementation and valid max and min."); + static_assert(I < detail::count_v, "magic_enum::enum_value out of range."); + + return enum_value(I); +} + +// Returns std::array with enum values, sorted by enum value. +template > +[[nodiscard]] constexpr auto enum_values() noexcept -> detail::enable_if_t> { + using D = std::decay_t; + static_assert(detail::is_reflected_v, "magic_enum requires enum implementation and valid max and min."); + + return detail::values_v; +} + +// Returns integer value from enum value. +template +[[nodiscard]] constexpr auto enum_integer(E value) noexcept -> detail::enable_if_t> { + return static_cast>(value); +} + +// Returns underlying value from enum value. +template +[[nodiscard]] constexpr auto enum_underlying(E value) noexcept -> detail::enable_if_t> { + return static_cast>(value); +} + +// Obtains index in enum values from enum value. +// Returns optional with index. +template > +[[nodiscard]] constexpr auto enum_index(E value) noexcept -> detail::enable_if_t> { + using D = std::decay_t; + using U = underlying_type_t; + static_assert(detail::is_reflected_v, "magic_enum requires enum implementation and valid max and min."); + + if constexpr (detail::is_sparse_v || (S == detail::enum_subtype::flags)) { +#if defined(MAGIC_ENUM_ENABLE_HASH) + return detail::constexpr_switch<&detail::values_v, detail::case_call_t::index>( + [](std::size_t i) { return optional{i}; }, + value, + detail::default_result_type_lambda>); +#else + for (std::size_t i = 0; i < detail::count_v; ++i) { + if (enum_value(i) == value) { + return i; + } + } + return {}; // Invalid value or out of range. +#endif + } else { + const auto v = static_cast(value); + if (v >= detail::min_v && v <= detail::max_v) { + return static_cast(v - detail::min_v); + } + return {}; // Invalid value or out of range. + } +} + +// Obtains index in enum values from enum value. +// Returns optional with index. +template +[[nodiscard]] constexpr auto enum_index(E value) noexcept -> detail::enable_if_t> { + using D = std::decay_t; + static_assert(detail::is_reflected_v, "magic_enum requires enum implementation and valid max and min."); + + return enum_index(value); +} + +// Obtains index in enum values from static storage enum variable. +template >> +[[nodiscard]] constexpr auto enum_index() noexcept -> detail::enable_if_t {\ + using D = std::decay_t; + static_assert(detail::is_reflected_v, "magic_enum requires enum implementation and valid max and min."); + constexpr auto index = enum_index(V); + static_assert(index, "magic_enum::enum_index enum value does not have a index."); + + return *index; +} + +// Returns name from static storage enum variable. +// This version is much lighter on the compile times and is not restricted to the enum_range limitation. +template +[[nodiscard]] constexpr auto enum_name() noexcept -> detail::enable_if_t { + constexpr string_view name = detail::enum_name_v, V>; + static_assert(!name.empty(), "magic_enum::enum_name enum value does not have a name."); + + return name; +} + +// Returns name from enum value. +// If enum value does not have name or value out of range, returns empty string. +template > +[[nodiscard]] constexpr auto enum_name(E value) noexcept -> detail::enable_if_t { + using D = std::decay_t; + static_assert(detail::is_reflected_v, "magic_enum requires enum implementation and valid max and min."); + + if (const auto i = enum_index(value)) { + return detail::names_v[*i]; + } + return {}; +} + +// Returns name from enum value. +// If enum value does not have name or value out of range, returns empty string. +template +[[nodiscard]] constexpr auto enum_name(E value) -> detail::enable_if_t { + using D = std::decay_t; + static_assert(detail::is_reflected_v, "magic_enum requires enum implementation and valid max and min."); + + return enum_name(value); +} + +// Returns std::array with names, sorted by enum value. +template > +[[nodiscard]] constexpr auto enum_names() noexcept -> detail::enable_if_t> { + using D = std::decay_t; + static_assert(detail::is_reflected_v, "magic_enum requires enum implementation and valid max and min."); + + return detail::names_v; +} + +// Returns std::array with pairs (value, name), sorted by enum value. +template > +[[nodiscard]] constexpr auto enum_entries() noexcept -> detail::enable_if_t> { + using D = std::decay_t; + static_assert(detail::is_reflected_v, "magic_enum requires enum implementation and valid max and min."); + + return detail::entries_v; +} + +// Allows you to write magic_enum::enum_cast("bar", magic_enum::case_insensitive); +inline constexpr auto case_insensitive = detail::case_insensitive<>{}; + +// Obtains enum value from integer value. +// Returns optional with enum value. +template > +[[nodiscard]] constexpr auto enum_cast(underlying_type_t value) noexcept -> detail::enable_if_t>> { + using D = std::decay_t; + static_assert(detail::is_reflected_v, "magic_enum requires enum implementation and valid max and min."); + + if constexpr (detail::is_sparse_v || (S == detail::enum_subtype::flags)) { +#if defined(MAGIC_ENUM_ENABLE_HASH) + return detail::constexpr_switch<&detail::values_v, detail::case_call_t::value>( + [](D v) { return optional{v}; }, + static_cast(value), + detail::default_result_type_lambda>); +#else + for (std::size_t i = 0; i < detail::count_v; ++i) { + if (value == static_cast>(enum_value(i))) { + return static_cast(value); + } + } + return {}; // Invalid value or out of range. +#endif + } else { + if (value >= detail::min_v && value <= detail::max_v) { + return static_cast(value); + } + return {}; // Invalid value or out of range. + } +} + +// Obtains enum value from name. +// Returns optional with enum value. +template , typename BinaryPredicate = std::equal_to<>> +[[nodiscard]] constexpr auto enum_cast(string_view value, [[maybe_unused]] BinaryPredicate p = {}) noexcept(detail::is_nothrow_invocable()) -> detail::enable_if_t>, BinaryPredicate> { + using D = std::decay_t; + static_assert(detail::is_reflected_v, "magic_enum requires enum implementation and valid max and min."); + +#if defined(MAGIC_ENUM_ENABLE_HASH) + if constexpr (detail::is_default_predicate()) { + return detail::constexpr_switch<&detail::names_v, detail::case_call_t::index>( + [](std::size_t i) { return optional{detail::values_v[i]}; }, + value, + detail::default_result_type_lambda>, + [&p](string_view lhs, string_view rhs) { return detail::cmp_equal(lhs, rhs, p); }); + } +#endif + for (std::size_t i = 0; i < detail::count_v; ++i) { + if (detail::cmp_equal(value, detail::names_v[i], p)) { + return enum_value(i); + } + } + return {}; // Invalid value or out of range. +} + +// Checks whether enum contains value with such value. +template > +[[nodiscard]] constexpr auto enum_contains(E value) noexcept -> detail::enable_if_t { + using D = std::decay_t; + using U = underlying_type_t; + + return static_cast(enum_cast(static_cast(value))); +} + +// Checks whether enum contains value with such value. +template +[[nodiscard]] constexpr auto enum_contains(E value) noexcept -> detail::enable_if_t { + using D = std::decay_t; + using U = underlying_type_t; + + return static_cast(enum_cast(static_cast(value))); +} + +// Checks whether enum contains value with such integer value. +template > +[[nodiscard]] constexpr auto enum_contains(underlying_type_t value) noexcept -> detail::enable_if_t { + using D = std::decay_t; + + return static_cast(enum_cast(value)); +} + +// Checks whether enum contains enumerator with such name. +template , typename BinaryPredicate = std::equal_to<>> +[[nodiscard]] constexpr auto enum_contains(string_view value, BinaryPredicate p = {}) noexcept(detail::is_nothrow_invocable()) -> detail::enable_if_t { + using D = std::decay_t; + + return static_cast(enum_cast(value, std::move(p))); +} + +// Returns true if the enum integer value is in the range of values that can be reflected. +template > +[[nodiscard]] constexpr auto enum_reflected(underlying_type_t value) noexcept -> detail::enable_if_t { + using D = std::decay_t; + + if constexpr (detail::is_reflected_v) { + constexpr auto min = detail::reflected_min(); + constexpr auto max = detail::reflected_max(); + return value >= min && value <= max; + } else { + return false; + } +} + +// Returns true if the enum value is in the range of values that can be reflected. +template > +[[nodiscard]] constexpr auto enum_reflected(E value) noexcept -> detail::enable_if_t { + using D = std::decay_t; + + return enum_reflected(static_cast>(value)); +} + +// Returns true if the enum value is in the range of values that can be reflected. +template +[[nodiscard]] constexpr auto enum_reflected(E value) noexcept -> detail::enable_if_t { + using D = std::decay_t; + + return enum_reflected(value); +} + +template +inline constexpr auto as_flags = AsFlags ? detail::enum_subtype::flags : detail::enum_subtype::common; + +template +inline constexpr auto as_common = AsFlags ? detail::enum_subtype::common : detail::enum_subtype::flags; + +namespace bitwise_operators { + +template = 0> +constexpr E operator~(E rhs) noexcept { + return static_cast(~static_cast>(rhs)); +} + +template = 0> +constexpr E operator|(E lhs, E rhs) noexcept { + return static_cast(static_cast>(lhs) | static_cast>(rhs)); +} + +template = 0> +constexpr E operator&(E lhs, E rhs) noexcept { + return static_cast(static_cast>(lhs) & static_cast>(rhs)); +} + +template = 0> +constexpr E operator^(E lhs, E rhs) noexcept { + return static_cast(static_cast>(lhs) ^ static_cast>(rhs)); +} + +template = 0> +constexpr E& operator|=(E& lhs, E rhs) noexcept { + return lhs = (lhs | rhs); +} + +template = 0> +constexpr E& operator&=(E& lhs, E rhs) noexcept { + return lhs = (lhs & rhs); +} + +template = 0> +constexpr E& operator^=(E& lhs, E rhs) noexcept { + return lhs = (lhs ^ rhs); +} + +} // namespace magic_enum::bitwise_operators + +} // namespace magic_enum + +#if defined(__clang__) +# pragma clang diagnostic pop +#elif defined(__GNUC__) +# pragma GCC diagnostic pop +#elif defined(_MSC_VER) +# pragma warning(pop) +#endif + +#undef MAGIC_ENUM_GET_ENUM_NAME_BUILTIN +#undef MAGIC_ENUM_GET_TYPE_NAME_BUILTIN +#undef MAGIC_ENUM_VS_2017_WORKAROUND +#undef MAGIC_ENUM_ARRAY_CONSTEXPR +#undef MAGIC_ENUM_FOR_EACH_256 + +#endif // NEARGYE_MAGIC_ENUM_HPP diff --git a/module/dll_source_lzy/ecap/lib/hulc/magic_enum/magic_enum/magic_enum_all.hpp b/module/dll_source_lzy/ecap/lib/hulc/magic_enum/magic_enum/magic_enum_all.hpp new file mode 100644 index 0000000..7a05281 --- /dev/null +++ b/module/dll_source_lzy/ecap/lib/hulc/magic_enum/magic_enum/magic_enum_all.hpp @@ -0,0 +1,44 @@ +// __ __ _ ______ _____ +// | \/ | (_) | ____| / ____|_ _ +// | \ / | __ _ __ _ _ ___ | |__ _ __ _ _ _ __ ___ | | _| |_ _| |_ +// | |\/| |/ _` |/ _` | |/ __| | __| | '_ \| | | | '_ ` _ \ | | |_ _|_ _| +// | | | | (_| | (_| | | (__ | |____| | | | |_| | | | | | | | |____|_| |_| +// |_| |_|\__,_|\__, |_|\___| |______|_| |_|\__,_|_| |_| |_| \_____| +// __/ | https://github.com/Neargye/magic_enum +// |___/ version 0.9.7 +// +// Licensed under the MIT License . +// SPDX-License-Identifier: MIT +// Copyright (c) 2019 - 2024 Daniil Goncharov . +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#ifndef NEARGYE_MAGIC_ENUM_ALL_HPP +#define NEARGYE_MAGIC_ENUM_ALL_HPP + +#include "magic_enum.hpp" +#include "../magic_enum_containers.hpp" +#include "../magic_enum_flags.hpp" +#include "../magic_enum_format.hpp" +#include "../magic_enum_fuse.hpp" +#include "../magic_enum_iostream.hpp" +#include "../magic_enum_switch.hpp" +#include "../magic_enum_utility.hpp" + +#endif // NEARGYE_MAGIC_ENUM_ALL_HPP diff --git a/module/dll_source_lzy/ecap/lib/hulc/magic_enum/magic_enum/magic_enum_containers.hpp b/module/dll_source_lzy/ecap/lib/hulc/magic_enum/magic_enum/magic_enum_containers.hpp new file mode 100644 index 0000000..f817306 --- /dev/null +++ b/module/dll_source_lzy/ecap/lib/hulc/magic_enum/magic_enum/magic_enum_containers.hpp @@ -0,0 +1,1174 @@ +// __ __ _ ______ _____ +// | \/ | (_) | ____| / ____|_ _ +// | \ / | __ _ __ _ _ ___ | |__ _ __ _ _ _ __ ___ | | _| |_ _| |_ +// | |\/| |/ _` |/ _` | |/ __| | __| | '_ \| | | | '_ ` _ \ | | |_ _|_ _| +// | | | | (_| | (_| | | (__ | |____| | | | |_| | | | | | | | |____|_| |_| +// |_| |_|\__,_|\__, |_|\___| |______|_| |_|\__,_|_| |_| |_| \_____| +// __/ | https://github.com/Neargye/magic_enum +// |___/ version 0.9.7 +// +// Licensed under the MIT License . +// SPDX-License-Identifier: MIT +// Copyright (c) 2019 - 2024 Daniil Goncharov . +// Copyright (c) 2022 - 2023 Bela Schaum . +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#ifndef NEARGYE_MAGIC_ENUM_CONTAINERS_HPP +#define NEARGYE_MAGIC_ENUM_CONTAINERS_HPP + +#include "magic_enum.hpp" + +#if !defined(MAGIC_ENUM_NO_EXCEPTION) && (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) +#ifndef MAGIC_ENUM_USE_STD_MODULE +# include +#endif +# define MAGIC_ENUM_THROW(...) throw (__VA_ARGS__) +#else +#ifndef MAGIC_ENUM_USE_STD_MODULE +# include +#endif +# define MAGIC_ENUM_THROW(...) std::abort() +#endif + +namespace magic_enum::containers { + +namespace detail { + +template +static constexpr bool is_transparent_v{}; + +template +static constexpr bool is_transparent_v>{true}; + +template , typename T1, typename T2> +constexpr bool equal(T1&& t1, T2&& t2, Eq&& eq = {}) { + auto first1 = t1.begin(); + auto last1 = t1.end(); + auto first2 = t2.begin(); + auto last2 = t2.end(); + + for (; first1 != last1; ++first1, ++first2) { + if (first2 == last2 || !eq(*first1, *first2)) { + return false; + } + } + return first2 == last2; +} + +template , typename T1, typename T2> +constexpr bool lexicographical_compare(T1&& t1, T2&& t2, Cmp&& cmp = {}) noexcept { + auto first1 = t1.begin(); + auto last1 = t1.end(); + auto first2 = t2.begin(); + auto last2 = t2.end(); + + // copied from std::lexicographical_compare + for (; (first1 != last1) && (first2 != last2); ++first1, (void)++first2) { + if (cmp(*first1, *first2)) { + return true; + } + if (cmp(*first2, *first1)) { + return false; + } + } + return (first1 == last1) && (first2 != last2); +} + +template +constexpr std::size_t popcount(T x) noexcept { + std::size_t c = 0; + while (x > 0) { + c += x & 1; + x >>= 1; + } + return c; +} + +template , typename ForwardIt, typename E> +constexpr ForwardIt lower_bound(ForwardIt first, ForwardIt last, E&& e, Cmp&& comp = {}) { + auto count = std::distance(first, last); + for (auto it = first; count > 0;) { + auto step = count / 2; + std::advance(it, step); + if (comp(*it, e)) { + first = ++it; + count -= step + 1; + } else { + count = step; + } + } + return first; +} + +template , typename BidirIt, typename E> +constexpr auto equal_range(BidirIt begin, BidirIt end, E&& e, Cmp&& comp = {}) { + const auto first = lower_bound(begin, end, e, comp); + return std::pair{first, lower_bound(std::make_reverse_iterator(end), std::make_reverse_iterator(first), e, [&comp](auto&& lhs, auto&& rhs) { return comp(rhs, lhs); }).base()}; +} + +template , typename = void> +class indexing { + [[nodiscard]] static constexpr auto get_indices() noexcept { + // reverse result index mapping + std::array()> rev_res{}; + + // std::iota + for (std::size_t i = 0; i < enum_count(); ++i) { + rev_res[i] = i; + } + + constexpr auto orig_values = enum_values(); + constexpr Cmp cmp{}; + + // ~std::sort + for (std::size_t i = 0; i < enum_count(); ++i) { + for (std::size_t j = i + 1; j < enum_count(); ++j) { + if (cmp(orig_values[rev_res[j]], orig_values[rev_res[i]])) { + auto tmp = rev_res[i]; + rev_res[i] = rev_res[j]; + rev_res[j] = tmp; + } + } + } + + std::array()> sorted_values{}; + // reverse the sorted indices + std::array()> res{}; + for (std::size_t i = 0; i < enum_count(); ++i) { + res[rev_res[i]] = i; + sorted_values[i] = orig_values[rev_res[i]]; + } + + return std::pair{sorted_values, res}; + } + + static constexpr auto indices = get_indices(); + + public: + [[nodiscard]] static constexpr const E* begin() noexcept { return indices.first.data(); } + + [[nodiscard]] static constexpr const E* end() noexcept { return indices.first.data() + indices.first.size(); } + + [[nodiscard]] static constexpr const E* it(std::size_t i) noexcept { return indices.first.data() + i; } + + [[nodiscard]] static constexpr optional at(E val) noexcept { + if (auto i = enum_index(val)) { + return indices.second[*i]; + } + return {}; + } +}; + +template +class indexing> && (std::is_same_v> || std::is_same_v>)>> { + static constexpr auto& values = enum_values(); + + public: + [[nodiscard]] static constexpr const E* begin() noexcept { return values.data(); } + + [[nodiscard]] static constexpr const E* end() noexcept { return values.data() + values.size(); } + + [[nodiscard]] static constexpr const E* it(std::size_t i) noexcept { return values.data() + i; } + + [[nodiscard]] static constexpr optional at(E val) noexcept { return enum_index(val); } +}; + +template +struct indexing { + using is_transparent = std::true_type; + + template + [[nodiscard]] static constexpr optional at(E val) noexcept { + return indexing::at(val); + } +}; + +template , typename = void> +struct name_sort_impl { + [[nodiscard]] constexpr bool operator()(E e1, E e2) const noexcept { return Cmp{}(enum_name(e1), enum_name(e2)); } +}; + +template +struct name_sort_impl { + using is_transparent = std::true_type; + + template + struct FullCmp : C {}; + + template + struct FullCmp && std::is_invocable_v>> { + [[nodiscard]] constexpr bool operator()(string_view s1, string_view s2) const noexcept { return lexicographical_compare(s1, s2); } + }; + + template + [[nodiscard]] constexpr std::enable_if_t< + // at least one of need to be an enum type + (std::is_enum_v> || std::is_enum_v>) && + // if both is enum, only accept if the same enum + (!std::is_enum_v> || !std::is_enum_v> || std::is_same_v) && + // is invocable with comparator + (std::is_invocable_r_v, std::conditional_t>, string_view, E1>, std::conditional_t>, string_view, E2>>), + bool> + operator()(E1 e1, E2 e2) const noexcept { + using D1 = std::decay_t; + using D2 = std::decay_t; + constexpr FullCmp<> cmp{}; + + if constexpr (std::is_enum_v && std::is_enum_v) { + return cmp(enum_name(e1), enum_name(e2)); + } else if constexpr (std::is_enum_v) { + return cmp(enum_name(e1), e2); + } else /* if constexpr (std::is_enum_v) */ { + return cmp(e1, enum_name(e2)); + } + } +}; + +struct raw_access_t {}; + +template +struct FilteredIterator { + Parent parent; + Iterator first; + Iterator last; + Iterator current; + Getter getter; + Predicate predicate; + + using iterator_category = std::bidirectional_iterator_tag; + using value_type = std::remove_reference_t>; + using difference_type = std::ptrdiff_t; + using pointer = value_type*; + using reference = value_type&; + + constexpr FilteredIterator() noexcept = default; + constexpr FilteredIterator(const FilteredIterator&) = default; + constexpr FilteredIterator& operator=(const FilteredIterator&) = default; + constexpr FilteredIterator(FilteredIterator&&) noexcept = default; + constexpr FilteredIterator& operator=(FilteredIterator&&) noexcept = default; + + template && std::is_convertible_v>*> + constexpr explicit FilteredIterator(const FilteredIterator& other) + : parent(other.parent), first(other.first), last(other.last), current(other.current), getter(other.getter), predicate(other.predicate) {} + + constexpr FilteredIterator(Parent p, Iterator begin, Iterator end, Iterator curr, Getter get = {}, Predicate pred = {}) + : parent(p), first(std::move(begin)), last(std::move(end)), current(std::move(curr)), getter{std::move(get)}, predicate{std::move(pred)} { + if (current == first && !predicate(parent, current)) { + ++*this; + } + } + + [[nodiscard]] constexpr reference operator*() const { return getter(parent, current); } + + [[nodiscard]] constexpr pointer operator->() const { return std::addressof(**this); } + + constexpr FilteredIterator& operator++() { + do { + ++current; + } while (current != last && !predicate(parent, current)); + return *this; + } + + [[nodiscard]] constexpr FilteredIterator operator++(int) { + FilteredIterator cp = *this; + ++*this; + return cp; + } + + constexpr FilteredIterator& operator--() { + do { + --current; + } while (current != first && !predicate(parent, current)); + return *this; + } + + [[nodiscard]] constexpr FilteredIterator operator--(int) { + FilteredIterator cp = *this; + --*this; + return cp; + } + + [[nodiscard]] friend constexpr bool operator==(const FilteredIterator& lhs, const FilteredIterator& rhs) { return lhs.current == rhs.current; } + + [[nodiscard]] friend constexpr bool operator!=(const FilteredIterator& lhs, const FilteredIterator& rhs) { return lhs.current != rhs.current; } +}; + +} // namespace detail + +template +using name_less = detail::name_sort_impl; + +template +using name_greater = detail::name_sort_impl>; + +using name_less_case_insensitive = detail::name_sort_impl>>; + +using name_greater_case_insensitive = detail::name_sort_impl>>; + +template +using default_indexing = detail::indexing; + +template > +using comparator_indexing = detail::indexing; + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// ARRAY // +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +template > +struct array { + static_assert(std::is_enum_v); + static_assert(std::is_trivially_constructible_v); + static_assert(enum_count() > 0 && Index::at(enum_values().front())); + + using index_type = Index; + using container_type = std::array()>; + + using value_type = typename container_type::value_type; + using size_type = typename container_type::size_type; + using difference_type = typename container_type::difference_type; + using reference = typename container_type::reference; + using const_reference = typename container_type::const_reference; + using pointer = typename container_type::pointer; + using const_pointer = typename container_type::const_pointer; + using iterator = typename container_type::iterator; + using const_iterator = typename container_type::const_iterator; + using reverse_iterator = typename container_type::reverse_iterator; + using const_reverse_iterator = typename container_type::const_reverse_iterator; + + constexpr reference at(E pos) { + if (auto index = index_type::at(pos)) { + return a[*index]; + } + MAGIC_ENUM_THROW(std::out_of_range("magic_enum::containers::array::at Unrecognized position")); + } + + constexpr const_reference at(E pos) const { + if (auto index = index_type::at(pos)) { + return a[*index]; + } + MAGIC_ENUM_THROW(std::out_of_range("magic_enum::containers::array::at: Unrecognized position")); + } + + [[nodiscard]] constexpr reference operator[](E pos) { + auto i = index_type::at(pos); + return MAGIC_ENUM_ASSERT(i), a[*i]; + } + + [[nodiscard]] constexpr const_reference operator[](E pos) const { + auto i = index_type::at(pos); + return MAGIC_ENUM_ASSERT(i), a[*i]; + } + + [[nodiscard]] constexpr reference front() noexcept { return a.front(); } + + [[nodiscard]] constexpr const_reference front() const noexcept { return a.front(); } + + [[nodiscard]] constexpr reference back() noexcept { return a.back(); } + + [[nodiscard]] constexpr const_reference back() const noexcept { return a.back(); } + + [[nodiscard]] constexpr pointer data() noexcept { return a.data(); } + + [[nodiscard]] constexpr const_pointer data() const noexcept { return a.data(); } + + [[nodiscard]] constexpr iterator begin() noexcept { return a.begin(); } + + [[nodiscard]] constexpr const_iterator begin() const noexcept { return a.begin(); } + + [[nodiscard]] constexpr const_iterator cbegin() const noexcept { return a.cbegin(); } + + [[nodiscard]] constexpr iterator end() noexcept { return a.end(); } + + [[nodiscard]] constexpr const_iterator end() const noexcept { return a.end(); } + + [[nodiscard]] constexpr const_iterator cend() const noexcept { return a.cend(); } + + [[nodiscard]] constexpr iterator rbegin() noexcept { return a.rbegin(); } + + [[nodiscard]] constexpr const_iterator rbegin() const noexcept { return a.rbegin(); } + + [[nodiscard]] constexpr const_iterator crbegin() const noexcept { return a.crbegin(); } + + [[nodiscard]] constexpr iterator rend() noexcept { return a.rend(); } + + [[nodiscard]] constexpr const_iterator rend() const noexcept { return a.rend(); } + + [[nodiscard]] constexpr const_iterator crend() const noexcept { return a.crend(); } + + [[nodiscard]] constexpr bool empty() const noexcept { return a.empty(); } + + [[nodiscard]] constexpr size_type size() const noexcept { return a.size(); } + + [[nodiscard]] constexpr size_type max_size() const noexcept { return a.max_size(); } + + constexpr void fill(const V& value) { + for (auto& v : a) { + v = value; + } + } + + constexpr void swap(array& other) noexcept(std::is_nothrow_swappable_v) { + for (std::size_t i = 0; i < a.size(); ++i) { + auto v = std::move(other.a[i]); + other.a[i] = std::move(a[i]); + a[i] = std::move(v); + } + } + + [[nodiscard]] friend constexpr bool operator==(const array& a1, const array& a2) { return detail::equal(a1, a2); } + + [[nodiscard]] friend constexpr bool operator!=(const array& a1, const array& a2) { return !detail::equal(a1, a2); } + + [[nodiscard]] friend constexpr bool operator<(const array& a1, const array& a2) { return detail::lexicographical_compare(a1, a2); } + + [[nodiscard]] friend constexpr bool operator<=(const array& a1, const array& a2) { return !detail::lexicographical_compare(a2, a1); } + + [[nodiscard]] friend constexpr bool operator>(const array& a1, const array& a2) { return detail::lexicographical_compare(a2, a1); } + + [[nodiscard]] friend constexpr bool operator>=(const array& a1, const array& a2) { return !detail::lexicographical_compare(a1, a2); } + + container_type a; +}; + +namespace detail { + +template +constexpr array> to_array_impl(T (&a)[N], std::index_sequence) { + return {{a[I]...}}; +} + +template +constexpr array> to_array_impl(T(&&a)[N], std::index_sequence) { + return {{std::move(a[I])...}}; +} + +} // namespace detail + +template +constexpr std::enable_if_t<(enum_count() == N), array>> to_array(T (&a)[N]) { + return detail::to_array_impl(a, std::make_index_sequence{}); +} + +template +constexpr std::enable_if_t<(enum_count() == N), array>> to_array(T(&&a)[N]) { + return detail::to_array_impl(std::move(a), std::make_index_sequence{}); +} + +template +constexpr std::enable_if_t<(enum_count() == sizeof...(Ts)), array>>> make_array(Ts&&... ts) { + return {{std::forward(ts)...}}; +} + +inline constexpr detail::raw_access_t raw_access{}; + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// BITSET // +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +template > +class bitset { + static_assert(std::is_enum_v); + static_assert(std::is_trivially_constructible_v); + static_assert(enum_count() > 0 && Index::at(enum_values().front())); + + using base_type = std::conditional_t() <= 8, std::uint_least8_t, + std::conditional_t() <= 16, std::uint_least16_t, + std::conditional_t() <= 32, std::uint_least32_t, + std::uint_least64_t>>>; + + static constexpr std::size_t bits_per_base = sizeof(base_type) * 8; + static constexpr std::size_t base_type_count = (enum_count() > 0 ? (enum_count() - 1) / bits_per_base + 1 : 0); + static constexpr std::size_t not_interested = base_type_count * bits_per_base - enum_count(); + static constexpr base_type last_value_max = (base_type{1} << (bits_per_base - not_interested)) - 1; + + template + class reference_impl { + friend class bitset; + + parent_t parent; + std::size_t num_index; + base_type bit_index; + + constexpr reference_impl(parent_t p, std::size_t i) noexcept : reference_impl(p, std::pair{i / bits_per_base, base_type{1} << (i % bits_per_base)}) {} + + constexpr reference_impl(parent_t p, std::pair i) noexcept : parent(p), num_index(std::get<0>(i)), bit_index(std::get<1>(i)) {} + + public: + constexpr reference_impl& operator=(bool v) noexcept { + if (v) { + parent->a[num_index] |= bit_index; + } else { + parent->a[num_index] &= ~bit_index; + } + return *this; + } + + constexpr reference_impl& operator=(const reference_impl& v) noexcept { + if (this == &v) { + return *this; + } + *this = static_cast(v); + return *this; + } + + [[nodiscard]] constexpr operator bool() const noexcept { return (parent->a[num_index] & bit_index) > 0; } + + [[nodiscard]] constexpr bool operator~() const noexcept { return !static_cast(*this); } + + constexpr reference_impl& flip() noexcept { + *this = ~*this; + return *this; + } + }; + + template + [[nodiscard]] constexpr T to_(detail::raw_access_t) const { + T res{}; + T flag{1}; + for (std::size_t i = 0; i < size(); ++i, flag <<= 1) { + if (const_reference{this, i}) { + if (i >= sizeof(T) * 8) { + MAGIC_ENUM_THROW(std::overflow_error("magic_enum::containers::bitset::to: Cannot represent enum in this type")); + } + res |= flag; + } + } + return res; + } + + public: + using index_type = Index; + using container_type = std::array; + using reference = reference_impl<>; + using const_reference = reference_impl; + + constexpr explicit bitset(detail::raw_access_t = raw_access) noexcept : a{{}} {} + + constexpr explicit bitset(detail::raw_access_t, unsigned long long val) : a{{}} { + unsigned long long bit{1}; + for (std::size_t i = 0; i < (sizeof(val) * 8); ++i, bit <<= 1) { + if ((val & bit) > 0) { + if (i >= enum_count()) { + MAGIC_ENUM_THROW(std::out_of_range("magic_enum::containers::bitset::constructor: Upper bit set in raw number")); + } + + reference{this, i} = true; + } + } + } + + constexpr explicit bitset(detail::raw_access_t, string_view sv, string_view::size_type pos = 0, string_view::size_type n = string_view::npos, char_type zero = static_cast('0'), char_type one = static_cast('1')) + : a{{}} { + std::size_t i = 0; + for (auto c : sv.substr(pos, n)) { + if (c == one) { + if (i >= enum_count()) { + MAGIC_ENUM_THROW(std::out_of_range("magic_enum::containers::bitset::constructor: Upper bit set in raw string")); + } + reference{this, i} = true; + } else if (c != zero) { + MAGIC_ENUM_THROW(std::invalid_argument("magic_enum::containers::bitset::constructor: Unrecognized character in raw string")); + } + ++i; + } + } + + constexpr explicit bitset(detail::raw_access_t, const char_type* str, std::size_t n = ~std::size_t{0}, char_type zero = static_cast('0'), char_type one = static_cast('1')) + : bitset(string_view{str, (std::min)(std::char_traits::length(str), n)}, 0, n, zero, one) {} + + constexpr bitset(std::initializer_list starters) : a{{}} { + if constexpr (magic_enum::detail::subtype_v == magic_enum::detail::enum_subtype::flags) { + for (auto& f : starters) { + *this |= bitset(f); + } + } else { + for (auto& f : starters) { + set(f); + } + } + } + template && magic_enum::detail::subtype_v == magic_enum::detail::enum_subtype::flags, int> = 0> + constexpr explicit bitset(V starter) : a{{}} { + auto u = enum_underlying(starter); + for (E v : enum_values()) { + if (auto ul = enum_underlying(v); (ul & u) != 0) { + u &= ~ul; + (*this)[v] = true; + } + } + if (u != 0) { + MAGIC_ENUM_THROW(std::invalid_argument("magic_enum::containers::bitset::constructor: Unrecognized enum value in flag")); + } + } + + template > + constexpr explicit bitset(string_view sv, Cmp&& cmp = {}, char_type sep = static_cast('|')) { + for (std::size_t to = 0; (to = magic_enum::detail::find(sv, sep)) != string_view::npos; sv.remove_prefix(to + 1)) { + if (auto v = enum_cast(sv.substr(0, to), cmp)) { + set(*v); + } else { + MAGIC_ENUM_THROW(std::invalid_argument("magic_enum::containers::bitset::constructor: Unrecognized enum value in string")); + } + } + if (!sv.empty()) { + if (auto v = enum_cast(sv, cmp)) { + set(*v); + } else { + MAGIC_ENUM_THROW(std::invalid_argument("magic_enum::containers::bitset::constructor: Unrecognized enum value in string")); + } + } + } + + [[nodiscard]] friend constexpr bool operator==(const bitset& lhs, const bitset& rhs) noexcept { return detail::equal(lhs.a, rhs.a); } + + [[nodiscard]] friend constexpr bool operator!=(const bitset& lhs, const bitset& rhs) noexcept { return !detail::equal(lhs.a, rhs.a); } + + [[nodiscard]] constexpr bool operator[](E pos) const { + auto i = index_type::at(pos); + return MAGIC_ENUM_ASSERT(i), static_cast(const_reference(this, *i)); + } + + [[nodiscard]] constexpr reference operator[](E pos) { + auto i = index_type::at(pos); + return MAGIC_ENUM_ASSERT(i), reference{this, *i}; + } + + constexpr bool test(E pos) const { + if (auto i = index_type::at(pos)) { + return static_cast(const_reference(this, *i)); + } + MAGIC_ENUM_THROW(std::out_of_range("magic_enum::containers::bitset::test: Unrecognized position")); + } + + [[nodiscard]] constexpr bool all() const noexcept { + if constexpr (base_type_count == 0) { + return true; + } + + for (std::size_t i = 0; i < base_type_count - (not_interested > 0); ++i) { + auto check = ~a[i]; + if (check) { + return false; + } + } + + if constexpr (not_interested > 0) { + return a[base_type_count - 1] == last_value_max; + } + } + + [[nodiscard]] constexpr bool any() const noexcept { + for (auto& v : a) { + if (v > 0) { + return true; + } + } + return false; + } + + [[nodiscard]] constexpr bool none() const noexcept { return !any(); } + + [[nodiscard]] constexpr std::size_t count() const noexcept { + std::size_t c = 0; + for (auto& v : a) { + c += detail::popcount(v); + } + return c; + } + + [[nodiscard]] constexpr std::size_t size() const noexcept { return enum_count(); } + + [[nodiscard]] constexpr std::size_t max_size() const noexcept { return enum_count(); } + + constexpr bitset& operator&=(const bitset& other) noexcept { + for (std::size_t i = 0; i < base_type_count; ++i) { + a[i] &= other.a[i]; + } + return *this; + } + + constexpr bitset& operator|=(const bitset& other) noexcept { + for (std::size_t i = 0; i < base_type_count; ++i) { + a[i] |= other.a[i]; + } + return *this; + } + + constexpr bitset& operator^=(const bitset& other) noexcept { + for (std::size_t i = 0; i < base_type_count; ++i) { + a[i] ^= other.a[i]; + } + return *this; + } + + [[nodiscard]] constexpr bitset operator~() const noexcept { + bitset res; + for (std::size_t i = 0; i < base_type_count - (not_interested > 0); ++i) { + res.a[i] = ~a[i]; + } + + if constexpr (not_interested > 0) { + res.a[base_type_count - 1] = ~a[base_type_count - 1] & last_value_max; + } + return res; + } + + constexpr bitset& set() noexcept { + for (std::size_t i = 0; i < base_type_count - (not_interested > 0); ++i) { + a[i] = ~base_type{0}; + } + + if constexpr (not_interested > 0) { + a[base_type_count - 1] = last_value_max; + } + return *this; + } + + constexpr bitset& set(E pos, bool value = true) { + if (auto i = index_type::at(pos)) { + reference{this, *i} = value; + return *this; + } + MAGIC_ENUM_THROW(std::out_of_range("magic_enum::containers::bitset::set: Unrecognized position")); + } + + constexpr bitset& reset() noexcept { return *this = bitset{}; } + + constexpr bitset& reset(E pos) { + if (auto i = index_type::at(pos)) { + reference{this, *i} = false; + return *this; + } + MAGIC_ENUM_THROW(std::out_of_range("magic_enum::containers::bitset::reset: Unrecognized position")); + } + + constexpr bitset& flip() noexcept { return *this = ~*this; } + + [[nodiscard]] friend constexpr bitset operator&(const bitset& lhs, const bitset& rhs) noexcept { + bitset cp = lhs; + cp &= rhs; + return cp; + } + + [[nodiscard]] friend constexpr bitset operator|(const bitset& lhs, const bitset& rhs) noexcept { + bitset cp = lhs; + cp |= rhs; + return cp; + } + + [[nodiscard]] friend constexpr bitset operator^(const bitset& lhs, const bitset& rhs) noexcept { + bitset cp = lhs; + cp ^= rhs; + return cp; + } + + template + [[nodiscard]] constexpr explicit operator std::enable_if_t == magic_enum::detail::enum_subtype::flags, E>() const { + E res{}; + for (const auto& e : enum_values()) { + if (test(e)) { + res |= e; + } + } + return res; + } + + [[nodiscard]] string to_string(char_type sep = static_cast('|')) const { + string name; + + for (const auto& e : enum_values()) { + if (test(e)) { + if (!name.empty()) { + name.append(1, sep); + } + auto n = enum_name(e); + name.append(n.data(), n.size()); + } + } + return name; + } + + [[nodiscard]] string to_string(detail::raw_access_t, char_type zero = static_cast('0'), char_type one = static_cast('1')) const { + string name; + name.reserve(size()); + for (std::size_t i = 0; i < size(); ++i) { + name.append(1, const_reference{this, i} ? one : zero); + } + return name; + } + + [[nodiscard]] constexpr unsigned long long to_ullong(detail::raw_access_t raw) const { return to_(raw); } + + [[nodiscard]] constexpr unsigned long long to_ulong(detail::raw_access_t raw) const { return to_(raw); } + + friend std::ostream& operator<<(std::ostream& o, const bitset& bs) { return o << bs.to_string(); } + + friend std::istream& operator>>(std::istream& i, bitset& bs) { + string s; + if (i >> s; !s.empty()) { + bs = bitset(string_view{s}); + } + return i; + } + + private: + container_type a; +}; + +template +explicit bitset(V starter) -> bitset; + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// SET // +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +template > +class set { + using index_type = detail::indexing; + struct Getter { + constexpr const E& operator()(const set*, const E* p) const noexcept { return *p; } + }; + struct Predicate { + constexpr bool operator()(const set* h, const E* e) const noexcept { return h->a[*e]; } + }; + + public: + using container_type = bitset; + using key_type = E; + using value_type = E; + using size_type = std::size_t; + using difference_type = std::ptrdiff_t; + using key_compare = Cmp; + using value_compare = Cmp; + using reference = value_type&; + using const_reference = const value_type&; + using pointer = value_type*; + using const_pointer = const value_type*; + using iterator = detail::FilteredIterator; + using const_iterator = detail::FilteredIterator; + using reverse_iterator = std::reverse_iterator; + using const_reverse_iterator = std::reverse_iterator; + + constexpr set() noexcept = default; + + template + constexpr set(InputIt first, InputIt last) { + while (first != last) { + insert(*first++); + } + } + + constexpr set(std::initializer_list ilist) { + for (auto e : ilist) { + insert(e); + } + } + template && magic_enum::detail::subtype_v == magic_enum::detail::enum_subtype::flags, int> = 0> + constexpr explicit set(V starter) { + auto u = enum_underlying(starter); + for (E v : enum_values()) { + if ((enum_underlying(v) & u) != 0) { + insert(v); + } + } + } + + constexpr set(const set&) noexcept = default; + constexpr set(set&&) noexcept = default; + + constexpr set& operator=(const set&) noexcept = default; + constexpr set& operator=(set&&) noexcept = default; + constexpr set& operator=(std::initializer_list ilist) { + for (auto e : ilist) { + insert(e); + } + } + + constexpr const_iterator begin() const noexcept { + return const_iterator{this, index_type::begin(), index_type::end(), index_type::begin()}; + } + + constexpr const_iterator end() const noexcept { + return const_iterator{this, index_type::begin(), index_type::end(), index_type::end()}; + } + + constexpr const_iterator cbegin() const noexcept { return begin(); } + + constexpr const_iterator cend() const noexcept { return end(); } + + constexpr const_reverse_iterator rbegin() const noexcept { return {end()}; } + + constexpr const_reverse_iterator rend() const noexcept { return {begin()}; } + + constexpr const_reverse_iterator crbegin() const noexcept { return rbegin(); } + + constexpr const_reverse_iterator crend() const noexcept { return rend(); } + + [[nodiscard]] constexpr bool empty() const noexcept { return s == 0; } + + [[nodiscard]] constexpr size_type size() const noexcept { return s; } + + [[nodiscard]] constexpr size_type max_size() const noexcept { return a.max_size(); } + + constexpr void clear() noexcept { + a.reset(); + s = 0; + } + + constexpr std::pair insert(const value_type& value) noexcept { + if (auto i = index_type::at(value)) { + typename container_type::reference ref = a[value]; + bool r = !ref; + if (r) { + ref = true; + ++s; + } + + return {iterator{this, index_type::begin(), index_type::end(), index_type::it(*i)}, r}; + } + return {end(), false}; + } + + constexpr std::pair insert(value_type&& value) noexcept { return insert(value); } + + constexpr iterator insert(const_iterator, const value_type& value) noexcept { return insert(value).first; } + + constexpr iterator insert(const_iterator hint, value_type&& value) noexcept { return insert(hint, value); } + + template + constexpr void insert(InputIt first, InputIt last) noexcept { + while (first != last) { + insert(*first++); + } + } + + constexpr void insert(std::initializer_list ilist) noexcept { + for (auto v : ilist) { + insert(v); + } + } + + template + constexpr std::pair emplace(Args&&... args) noexcept { + return insert({std::forward(args)...}); + } + + template + constexpr iterator emplace_hint(const_iterator, Args&&... args) noexcept { + return emplace(std::forward(args)...).first; + } + + constexpr iterator erase(const_iterator pos) noexcept { + erase(*pos++); + return pos; + } + + constexpr iterator erase(const_iterator first, const_iterator last) noexcept { + while ((first = erase(first)) != last) { + } + return first; + } + + constexpr size_type erase(const key_type& key) noexcept { + typename container_type::reference ref = a[key]; + bool res = ref; + if (res) { + --s; + } + ref = false; + return res; + } + + template + constexpr std::enable_if_t, size_type> erase(K&& x) noexcept { + size_type c = 0; + for (auto [first, last] = detail::equal_range(index_type::begin(), index_type::end(), x, key_compare{}); first != last;) { + c += erase(*first++); + } + return c; + } + + void swap(set& other) noexcept { + set cp = *this; + *this = other; + other = cp; + } + + [[nodiscard]] constexpr size_type count(const key_type& key) const noexcept { return index_type::at(key) && a[key]; } + + template + [[nodiscard]] constexpr std::enable_if_t, size_type> count(const K& x) const { + size_type c = 0; + for (auto [first, last] = detail::equal_range(index_type::begin(), index_type::end(), x, key_compare{}); first != last; ++first) { + c += count(*first); + } + return c; + } + + [[nodiscard]] constexpr const_iterator find(const key_type& key) const noexcept { + if (auto i = index_type::at(key); i && a.test(key)) { + return const_iterator{this, index_type::begin(), index_type::end(), index_type::it(*i)}; + } + return end(); + } + + template + [[nodiscard]] constexpr std::enable_if_t, const_iterator> find(const K& x) const { + for (auto [first, last] = detail::equal_range(index_type::begin(), index_type::end(), x, key_compare{}); first != last; ++first) { + if (a.test(*first)) { + return find(*first); + } + } + return end(); + } + + [[nodiscard]] constexpr bool contains(const key_type& key) const noexcept { return count(key); } + + template + [[nodiscard]] constexpr std::enable_if_t, bool> contains(const K& x) const noexcept { + return count(x) > 0; + } + + [[nodiscard]] constexpr std::pair equal_range(const key_type& key) const noexcept { return {lower_bound(key), upper_bound(key)}; } + + template + [[nodiscard]] constexpr std::enable_if_t, std::pair> equal_range(const K& x) const noexcept { + return {lower_bound(x), upper_bound(x)}; + } + + [[nodiscard]] constexpr const_iterator lower_bound(const key_type& key) const noexcept { + if (auto i = index_type::at(key)) { + auto it = const_iterator{this, index_type::begin(), index_type::end(), index_type::it(*i)}; + return a.test(key) ? it : std::next(it); + } + return end(); + } + + template + [[nodiscard]] constexpr std::enable_if_t, const_iterator> lower_bound(const K& x) const noexcept { + auto [first, last] = detail::equal_range(index_type::begin(), index_type::end(), x, key_compare{}); + return first != last ? lower_bound(*first) : end(); + } + + [[nodiscard]] constexpr const_iterator upper_bound(const key_type& key) const noexcept { + if (auto i = index_type::at(key)) { + return std::next(const_iterator{this, index_type::begin(), index_type::end(), index_type::it(*i)}); + } + return end(); + } + + template + [[nodiscard]] constexpr std::enable_if_t, const_iterator> upper_bound(const K& x) const noexcept { + auto [first, last] = detail::equal_range(index_type::begin(), index_type::end(), x, key_compare{}); + return first != last ? upper_bound(*std::prev(last)) : end(); + } + + [[nodiscard]] constexpr key_compare key_comp() const { return {}; } + + [[nodiscard]] constexpr value_compare value_comp() const { return {}; } + + [[nodiscard]] constexpr friend bool operator==(const set& lhs, const set& rhs) noexcept { return lhs.a == rhs.a; } + + [[nodiscard]] constexpr friend bool operator!=(const set& lhs, const set& rhs) noexcept { return lhs.a != rhs.a; } + + [[nodiscard]] constexpr friend bool operator<(const set& lhs, const set& rhs) noexcept { + if (lhs.s < rhs.s) { + return true; + } + if (rhs.s < lhs.s) { + return false; + } + + for (auto it = index_type::begin(); it != index_type::end(); ++it) { + if (auto c = rhs.contains(*it); c != lhs.contains(*it)) { + return c; + } + } + return false; + } + + [[nodiscard]] constexpr friend bool operator<=(const set& lhs, const set& rhs) noexcept { return !(rhs < lhs); } + + [[nodiscard]] constexpr friend bool operator>(const set& lhs, const set& rhs) noexcept { return rhs < lhs; } + + [[nodiscard]] constexpr friend bool operator>=(const set& lhs, const set& rhs) noexcept { return !(lhs < rhs); } + + template + size_type erase_if(Pred pred) { + auto old_size = size(); + for (auto i = begin(), last = end(); i != last;) { + if (pred(*i)) { + i = erase(i); + } else { + ++i; + } + } + return old_size - size(); + } + + private: + container_type a; + std::size_t s = 0; +}; + +template +explicit set(V starter) -> set; + +template +constexpr std::enable_if_t<(std::is_integral_v && I < enum_count()), V&> get(array& a) noexcept { + return a.a[I]; +} + +template +constexpr std::enable_if_t<(std::is_integral_v && I < enum_count()), V&&> get(array&& a) noexcept { + return std::move(a.a[I]); +} + +template +constexpr std::enable_if_t<(std::is_integral_v && I < enum_count()), const V&> get(const array& a) noexcept { + return a.a[I]; +} + +template +constexpr std::enable_if_t<(std::is_integral_v && I < enum_count()), const V&&> get(const array&& a) noexcept { + return std::move(a.a[I]); +} + +template +constexpr std::enable_if_t && enum_contains(Enum), V&> get(array& a) { + return a[Enum]; +} + +template +constexpr std::enable_if_t && enum_contains(Enum), V&&> get(array&& a) { + return std::move(a[Enum]); +} + +template +constexpr std::enable_if_t && enum_contains(Enum), const V&> get(const array& a) { + return a[Enum]; +} + +template +constexpr std::enable_if_t && enum_contains(Enum), const V&&> get(const array&& a) { + return std::move(a[Enum]); +} + +} // namespace magic_enum::containers + +#endif // NEARGYE_MAGIC_ENUM_CONTAINERS_HPP diff --git a/module/dll_source_lzy/ecap/lib/hulc/magic_enum/magic_enum/magic_enum_flags.hpp b/module/dll_source_lzy/ecap/lib/hulc/magic_enum/magic_enum/magic_enum_flags.hpp new file mode 100644 index 0000000..f2d81b5 --- /dev/null +++ b/module/dll_source_lzy/ecap/lib/hulc/magic_enum/magic_enum/magic_enum_flags.hpp @@ -0,0 +1,222 @@ +// __ __ _ ______ _____ +// | \/ | (_) | ____| / ____|_ _ +// | \ / | __ _ __ _ _ ___ | |__ _ __ _ _ _ __ ___ | | _| |_ _| |_ +// | |\/| |/ _` |/ _` | |/ __| | __| | '_ \| | | | '_ ` _ \ | | |_ _|_ _| +// | | | | (_| | (_| | | (__ | |____| | | | |_| | | | | | | | |____|_| |_| +// |_| |_|\__,_|\__, |_|\___| |______|_| |_|\__,_|_| |_| |_| \_____| +// __/ | https://github.com/Neargye/magic_enum +// |___/ version 0.9.7 +// +// Licensed under the MIT License . +// SPDX-License-Identifier: MIT +// Copyright (c) 2019 - 2024 Daniil Goncharov . +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#ifndef NEARGYE_MAGIC_ENUM_FLAGS_HPP +#define NEARGYE_MAGIC_ENUM_FLAGS_HPP + +#include "magic_enum.hpp" + +#if defined(__clang__) +# pragma clang diagnostic push +#elif defined(__GNUC__) +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wmaybe-uninitialized" // May be used uninitialized 'return {};'. +#elif defined(_MSC_VER) +# pragma warning(push) +#endif + +namespace magic_enum { + +namespace detail { + +template > +constexpr U values_ors() noexcept { + static_assert(S == enum_subtype::flags, "magic_enum::detail::values_ors requires valid subtype."); + + auto ors = U{0}; + for (std::size_t i = 0; i < count_v; ++i) { + ors |= static_cast(values_v[i]); + } + + return ors; +} + +} // namespace magic_enum::detail + +// Returns name from enum-flags value. +// If enum-flags value does not have name or value out of range, returns empty string. +template +[[nodiscard]] auto enum_flags_name(E value, char_type sep = static_cast('|')) -> detail::enable_if_t { + using D = std::decay_t; + using U = underlying_type_t; + constexpr auto S = detail::enum_subtype::flags; + static_assert(detail::is_reflected_v, "magic_enum requires enum implementation and valid max and min."); + + string name; + auto check_value = U{0}; + for (std::size_t i = 0; i < detail::count_v; ++i) { + if (const auto v = static_cast(enum_value(i)); (static_cast(value) & v) != 0) { + if (const auto n = detail::names_v[i]; !n.empty()) { + check_value |= v; + if (!name.empty()) { + name.append(1, sep); + } + name.append(n.data(), n.size()); + } else { + return {}; // Value out of range. + } + } + } + + if (check_value != 0 && check_value == static_cast(value)) { + return name; + } + return {}; // Invalid value or out of range. +} + +// Obtains enum-flags value from integer value. +// Returns optional with enum-flags value. +template +[[nodiscard]] constexpr auto enum_flags_cast(underlying_type_t value) noexcept -> detail::enable_if_t>> { + using D = std::decay_t; + using U = underlying_type_t; + constexpr auto S = detail::enum_subtype::flags; + static_assert(detail::is_reflected_v, "magic_enum requires enum implementation and valid max and min."); + + if constexpr (detail::count_v == 0) { + static_cast(value); + return {}; // Empty enum. + } else { + if constexpr (detail::is_sparse_v) { + auto check_value = U{0}; + for (std::size_t i = 0; i < detail::count_v; ++i) { + if (const auto v = static_cast(enum_value(i)); (value & v) != 0) { + check_value |= v; + } + } + + if (check_value != 0 && check_value == value) { + return static_cast(value); + } + } else { + constexpr auto min = detail::min_v; + constexpr auto max = detail::values_ors(); + + if (value >= min && value <= max) { + return static_cast(value); + } + } + return {}; // Invalid value or out of range. + } +} + +// Obtains enum-flags value from name. +// Returns optional with enum-flags value. +template > +[[nodiscard]] constexpr auto enum_flags_cast(string_view value, [[maybe_unused]] BinaryPredicate p = {}) noexcept(detail::is_nothrow_invocable()) -> detail::enable_if_t>, BinaryPredicate> { + using D = std::decay_t; + using U = underlying_type_t; + constexpr auto S = detail::enum_subtype::flags; + static_assert(detail::is_reflected_v, "magic_enum requires enum implementation and valid max and min."); + + if constexpr (detail::count_v == 0) { + static_cast(value); + return {}; // Empty enum. + } else { + auto result = U{0}; + while (!value.empty()) { + const auto d = detail::find(value, '|'); + const auto s = (d == string_view::npos) ? value : value.substr(0, d); + auto f = U{0}; + for (std::size_t i = 0; i < detail::count_v; ++i) { + if (detail::cmp_equal(s, detail::names_v[i], p)) { + f = static_cast(enum_value(i)); + result |= f; + break; + } + } + if (f == U{0}) { + return {}; // Invalid value or out of range. + } + value.remove_prefix((d == string_view::npos) ? value.size() : d + 1); + } + + if (result != U{0}) { + return static_cast(result); + } + return {}; // Invalid value or out of range. + } +} + +// Checks whether enum-flags contains value with such value. +template +[[nodiscard]] constexpr auto enum_flags_contains(E value) noexcept -> detail::enable_if_t { + using D = std::decay_t; + using U = underlying_type_t; + + return static_cast(enum_flags_cast(static_cast(value))); +} + +// Checks whether enum-flags contains value with such integer value. +template +[[nodiscard]] constexpr auto enum_flags_contains(underlying_type_t value) noexcept -> detail::enable_if_t { + using D = std::decay_t; + + return static_cast(enum_flags_cast(value)); +} + +// Checks whether enum-flags contains enumerator with such name. +template > +[[nodiscard]] constexpr auto enum_flags_contains(string_view value, BinaryPredicate p = {}) noexcept(detail::is_nothrow_invocable()) -> detail::enable_if_t { + using D = std::decay_t; + + return static_cast(enum_flags_cast(value, std::move(p))); +} + +// Checks whether `flags set` contains `flag`. +// Note: If `flag` equals 0, it returns false, as 0 is not a flag. +template +constexpr auto enum_flags_test(E flags, E flag) noexcept -> detail::enable_if_t { + using U = underlying_type_t; + + return static_cast(flag) && ((static_cast(flags) & static_cast(flag)) == static_cast(flag)); +} + +// Checks whether `lhs flags set` and `rhs flags set` have common flags. +// Note: If `lhs flags set` or `rhs flags set` equals 0, it returns false, as 0 is not a flag, and therfore cannot have any matching flag. +template +constexpr auto enum_flags_test_any(E lhs, E rhs) noexcept -> detail::enable_if_t { + using U = underlying_type_t; + + return (static_cast(lhs) & static_cast(rhs)) != 0; +} + +} // namespace magic_enum + +#if defined(__clang__) +# pragma clang diagnostic pop +#elif defined(__GNUC__) +# pragma GCC diagnostic pop +#elif defined(_MSC_VER) +# pragma warning(pop) +#endif + +#endif // NEARGYE_MAGIC_ENUM_FLAGS_HPP diff --git a/module/dll_source_lzy/ecap/lib/hulc/magic_enum/magic_enum/magic_enum_format.hpp b/module/dll_source_lzy/ecap/lib/hulc/magic_enum/magic_enum/magic_enum_format.hpp new file mode 100644 index 0000000..f10371f --- /dev/null +++ b/module/dll_source_lzy/ecap/lib/hulc/magic_enum/magic_enum/magic_enum_format.hpp @@ -0,0 +1,114 @@ +// __ __ _ ______ _____ +// | \/ | (_) | ____| / ____|_ _ +// | \ / | __ _ __ _ _ ___ | |__ _ __ _ _ _ __ ___ | | _| |_ _| |_ +// | |\/| |/ _` |/ _` | |/ __| | __| | '_ \| | | | '_ ` _ \ | | |_ _|_ _| +// | | | | (_| | (_| | | (__ | |____| | | | |_| | | | | | | | |____|_| |_| +// |_| |_|\__,_|\__, |_|\___| |______|_| |_|\__,_|_| |_| |_| \_____| +// __/ | https://github.com/Neargye/magic_enum +// |___/ version 0.9.7 +// +// Licensed under the MIT License . +// SPDX-License-Identifier: MIT +// Copyright (c) 2019 - 2024 Daniil Goncharov . +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#ifndef NEARGYE_MAGIC_ENUM_FORMAT_HPP +#define NEARGYE_MAGIC_ENUM_FORMAT_HPP + +#include "magic_enum.hpp" +#include "magic_enum_flags.hpp" + +#if !defined(MAGIC_ENUM_DEFAULT_ENABLE_ENUM_FORMAT) +# define MAGIC_ENUM_DEFAULT_ENABLE_ENUM_FORMAT 1 +# define MAGIC_ENUM_DEFAULT_ENABLE_ENUM_FORMAT_AUTO_DEFINE +#endif + +namespace magic_enum::customize { + // customize enum to enable/disable automatic std::format + template + constexpr bool enum_format_enabled() noexcept { + return MAGIC_ENUM_DEFAULT_ENABLE_ENUM_FORMAT; + } +} // magic_enum::customize + +#if defined(__cpp_lib_format) + +#ifndef MAGIC_ENUM_USE_STD_MODULE +#include +#endif + +template +struct std::formatter> && magic_enum::customize::enum_format_enabled(), char>> : std::formatter { + template + auto format(E e, FormatContext& ctx) const { + static_assert(std::is_same_v, "formatter requires string_view::value_type type same as char."); + using D = std::decay_t; + + if constexpr (magic_enum::detail::supported::value) { + if constexpr (magic_enum::detail::subtype_v == magic_enum::detail::enum_subtype::flags) { + if (const auto name = magic_enum::enum_flags_name(e); !name.empty()) { + return formatter::format(std::string_view{name.data(), name.size()}, ctx); + } + } else { + if (const auto name = magic_enum::enum_name(e); !name.empty()) { + return formatter::format(std::string_view{name.data(), name.size()}, ctx); + } + } + } + return formatter::format(std::to_string(magic_enum::enum_integer(e)), ctx); + } +}; + +#endif + +#if defined(FMT_VERSION) + +#include +struct fmt::formatter> && magic_enum::customize::enum_format_enabled(), char>> : fmt::formatter { + template + auto format(E e, FormatContext& ctx) const { + static_assert(std::is_same_v, "formatter requires string_view::value_type type same as char."); + using D = std::decay_t; + + if constexpr (magic_enum::detail::supported::value) { + if constexpr (magic_enum::detail::subtype_v == magic_enum::detail::enum_subtype::flags) { + if (const auto name = magic_enum::enum_flags_name(e); !name.empty()) { + return formatter::format(std::string_view{name.data(), name.size()}, ctx); + } + } else { + if (const auto name = magic_enum::enum_name(e); !name.empty()) { + return formatter::format(std::string_view{name.data(), name.size()}, ctx); + } + } + } + return formatter::format(std::to_string(magic_enum::enum_integer(e)), ctx); + } +}; + +#endif + +#if defined(MAGIC_ENUM_DEFAULT_ENABLE_ENUM_FORMAT_AUTO_DEFINE) +# undef MAGIC_ENUM_DEFAULT_ENABLE_ENUM_FORMAT +# undef MAGIC_ENUM_DEFAULT_ENABLE_ENUM_FORMAT_AUTO_DEFINE +#endif + +#endif // NEARGYE_MAGIC_ENUM_FORMAT_HPP diff --git a/module/dll_source_lzy/ecap/lib/hulc/magic_enum/magic_enum/magic_enum_fuse.hpp b/module/dll_source_lzy/ecap/lib/hulc/magic_enum/magic_enum/magic_enum_fuse.hpp new file mode 100644 index 0000000..6b2a3ef --- /dev/null +++ b/module/dll_source_lzy/ecap/lib/hulc/magic_enum/magic_enum/magic_enum_fuse.hpp @@ -0,0 +1,89 @@ +// __ __ _ ______ _____ +// | \/ | (_) | ____| / ____|_ _ +// | \ / | __ _ __ _ _ ___ | |__ _ __ _ _ _ __ ___ | | _| |_ _| |_ +// | |\/| |/ _` |/ _` | |/ __| | __| | '_ \| | | | '_ ` _ \ | | |_ _|_ _| +// | | | | (_| | (_| | | (__ | |____| | | | |_| | | | | | | | |____|_| |_| +// |_| |_|\__,_|\__, |_|\___| |______|_| |_|\__,_|_| |_| |_| \_____| +// __/ | https://github.com/Neargye/magic_enum +// |___/ version 0.9.7 +// +// Licensed under the MIT License . +// SPDX-License-Identifier: MIT +// Copyright (c) 2019 - 2024 Daniil Goncharov . +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#ifndef NEARGYE_MAGIC_ENUM_FUSE_HPP +#define NEARGYE_MAGIC_ENUM_FUSE_HPP + +#include "magic_enum.hpp" + +namespace magic_enum { + +namespace detail { + +template +constexpr optional fuse_one_enum(optional hash, E value) noexcept { + if (hash) { + if (const auto index = enum_index(value)) { + return (*hash << log2((enum_count() << 1) - 1)) | *index; + } + } + return {}; +} + +template +constexpr optional fuse_enum(E value) noexcept { + return fuse_one_enum(0, value); +} + +template +constexpr optional fuse_enum(E head, Es... tail) noexcept { + return fuse_one_enum(fuse_enum(tail...), head); +} + +template +constexpr auto typesafe_fuse_enum(Es... values) noexcept { + enum class enum_fuse_t : std::uintmax_t; + const auto fuse = fuse_enum(values...); + if (fuse) { + return optional{static_cast(*fuse)}; + } + return optional{}; +} + +} // namespace magic_enum::detail + +// Returns a bijective mix of several enum values. This can be used to emulate 2D switch/case statements. +template +[[nodiscard]] constexpr auto enum_fuse(Es... values) noexcept { + static_assert((std::is_enum_v> && ...), "magic_enum::enum_fuse requires enum type."); + static_assert(sizeof...(Es) >= 2, "magic_enum::enum_fuse requires at least 2 values."); + static_assert((detail::log2(enum_count>() + 1) + ...) <= (sizeof(std::uintmax_t) * 8), "magic_enum::enum_fuse does not work for large enums"); +#if defined(MAGIC_ENUM_NO_TYPESAFE_ENUM_FUSE) + const auto fuse = detail::fuse_enum...>(values...); +#else + const auto fuse = detail::typesafe_fuse_enum...>(values...); +#endif + return MAGIC_ENUM_ASSERT(fuse), fuse; +} + +} // namespace magic_enum + +#endif // NEARGYE_MAGIC_ENUM_FUSE_HPP diff --git a/module/dll_source_lzy/ecap/lib/hulc/magic_enum/magic_enum/magic_enum_iostream.hpp b/module/dll_source_lzy/ecap/lib/hulc/magic_enum/magic_enum/magic_enum_iostream.hpp new file mode 100644 index 0000000..6130dcb --- /dev/null +++ b/module/dll_source_lzy/ecap/lib/hulc/magic_enum/magic_enum/magic_enum_iostream.hpp @@ -0,0 +1,117 @@ +// __ __ _ ______ _____ +// | \/ | (_) | ____| / ____|_ _ +// | \ / | __ _ __ _ _ ___ | |__ _ __ _ _ _ __ ___ | | _| |_ _| |_ +// | |\/| |/ _` |/ _` | |/ __| | __| | '_ \| | | | '_ ` _ \ | | |_ _|_ _| +// | | | | (_| | (_| | | (__ | |____| | | | |_| | | | | | | | |____|_| |_| +// |_| |_|\__,_|\__, |_|\___| |______|_| |_|\__,_|_| |_| |_| \_____| +// __/ | https://github.com/Neargye/magic_enum +// |___/ version 0.9.7 +// +// Licensed under the MIT License . +// SPDX-License-Identifier: MIT +// Copyright (c) 2019 - 2024 Daniil Goncharov . +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#ifndef NEARGYE_MAGIC_ENUM_IOSTREAM_HPP +#define NEARGYE_MAGIC_ENUM_IOSTREAM_HPP + +#include "magic_enum.hpp" +#include "magic_enum_flags.hpp" + +#ifndef MAGIC_ENUM_USE_STD_MODULE +#include +#endif + +namespace magic_enum { + +namespace ostream_operators { + +template = 0> +std::basic_ostream& operator<<(std::basic_ostream& os, E value) { + using D = std::decay_t; + using U = underlying_type_t; + + if constexpr (detail::supported::value) { + if constexpr (detail::subtype_v == detail::enum_subtype::flags) { + if (const auto name = enum_flags_name(value); !name.empty()) { + for (const auto c : name) { + os.put(c); + } + return os; + } + } else { + if (const auto name = enum_name(value); !name.empty()) { + for (const auto c : name) { + os.put(c); + } + return os; + } + } + } + return (os << static_cast(value)); +} + +template = 0> +std::basic_ostream& operator<<(std::basic_ostream& os, optional value) { + return value ? (os << *value) : os; +} + +} // namespace magic_enum::ostream_operators + +namespace istream_operators { + +template = 0> +std::basic_istream& operator>>(std::basic_istream& is, E& value) { + using D = std::decay_t; + + std::basic_string s; + is >> s; + if constexpr (detail::supported::value) { + if constexpr (detail::subtype_v == detail::enum_subtype::flags) { + if (const auto v = enum_flags_cast(s)) { + value = *v; + } else { + is.setstate(std::basic_ios::failbit); + } + } else { + if (const auto v = enum_cast(s)) { + value = *v; + } else { + is.setstate(std::basic_ios::failbit); + } + } + } else { + is.setstate(std::basic_ios::failbit); + } + return is; +} + +} // namespace magic_enum::istream_operators + +namespace iostream_operators { + +using magic_enum::ostream_operators::operator<<; +using magic_enum::istream_operators::operator>>; + +} // namespace magic_enum::iostream_operators + +} // namespace magic_enum + +#endif // NEARGYE_MAGIC_ENUM_IOSTREAM_HPP diff --git a/module/dll_source_lzy/ecap/lib/hulc/magic_enum/magic_enum/magic_enum_switch.hpp b/module/dll_source_lzy/ecap/lib/hulc/magic_enum/magic_enum/magic_enum_switch.hpp new file mode 100644 index 0000000..63fc19a --- /dev/null +++ b/module/dll_source_lzy/ecap/lib/hulc/magic_enum/magic_enum/magic_enum_switch.hpp @@ -0,0 +1,195 @@ +// __ __ _ ______ _____ +// | \/ | (_) | ____| / ____|_ _ +// | \ / | __ _ __ _ _ ___ | |__ _ __ _ _ _ __ ___ | | _| |_ _| |_ +// | |\/| |/ _` |/ _` | |/ __| | __| | '_ \| | | | '_ ` _ \ | | |_ _|_ _| +// | | | | (_| | (_| | | (__ | |____| | | | |_| | | | | | | | |____|_| |_| +// |_| |_|\__,_|\__, |_|\___| |______|_| |_|\__,_|_| |_| |_| \_____| +// __/ | https://github.com/Neargye/magic_enum +// |___/ version 0.9.7 +// +// Licensed under the MIT License . +// SPDX-License-Identifier: MIT +// Copyright (c) 2019 - 2024 Daniil Goncharov . +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#ifndef NEARGYE_MAGIC_ENUM_SWITCH_HPP +#define NEARGYE_MAGIC_ENUM_SWITCH_HPP + +#include "magic_enum.hpp" + +namespace magic_enum { + +namespace detail { + +struct default_result_type {}; + +template +struct identity { + using type = T; +}; + +struct nonesuch {}; + +template > +struct invoke_result : identity {}; + +template +struct invoke_result : std::invoke_result {}; + +template +using invoke_result_t = typename invoke_result::type; + +template +constexpr auto common_invocable(std::index_sequence) noexcept { + static_assert(std::is_enum_v, "magic_enum::detail::invocable_index requires enum type."); + + if constexpr (count_v == 0) { + return identity{}; + } else { + return std::common_type[I]>>...>{}; + } +} + +template +constexpr auto result_type() noexcept { + static_assert(std::is_enum_v, "magic_enum::detail::result_type requires enum type."); + + constexpr auto seq = std::make_index_sequence>{}; + using R = typename decltype(common_invocable(seq))::type; + if constexpr (std::is_same_v) { + if constexpr (std::is_same_v) { + return identity{}; + } else { + return identity{}; + } + } else { + if constexpr (std::is_convertible_v) { + return identity{}; + } else if constexpr (std::is_convertible_v) { + return identity{}; + } else { + return identity{}; + } + } +} + +template , typename R = typename decltype(result_type())::type> +using result_t = std::enable_if_t && !std::is_same_v, R>; + +#if !defined(MAGIC_ENUM_ENABLE_HASH) && !defined(MAGIC_ENUM_ENABLE_HASH_SWITCH) + +template +inline constexpr auto default_result_type_lambda = []() noexcept(std::is_nothrow_default_constructible_v) { return T{}; }; + +template <> +inline constexpr auto default_result_type_lambda = []() noexcept {}; + +template +constexpr decltype(auto) constexpr_switch_impl(F&& f, E value, Def&& def) { + if constexpr(I < End) { + constexpr auto v = enum_constant()>{}; + if (value == v) { + if constexpr (std::is_invocable_r_v) { + return static_cast(std::forward(f)(v)); + } else { + return def(); + } + } else { + return constexpr_switch_impl(std::forward(f), value, std::forward(def)); + } + } else { + return def(); + } +} + +template +constexpr decltype(auto) constexpr_switch(F&& f, E value, Def&& def) { + static_assert(is_enum_v, "magic_enum::detail::constexpr_switch requires enum type."); + + if constexpr (count_v == 0) { + return def(); + } else { + return constexpr_switch_impl<0, count_v, R, E, S>(std::forward(f), value, std::forward(def)); + } +} +#endif + +} // namespace magic_enum::detail + +template , typename F, typename R = detail::result_t> +constexpr decltype(auto) enum_switch(F&& f, E value) { + using D = std::decay_t; + static_assert(std::is_enum_v, "magic_enum::enum_switch requires enum type."); + static_assert(detail::is_reflected_v, "magic_enum requires enum implementation and valid max and min."); + +#if defined(MAGIC_ENUM_ENABLE_HASH) || defined(MAGIC_ENUM_ENABLE_HASH_SWITCH) + return detail::constexpr_switch<&detail::values_v, detail::case_call_t::value>( + std::forward(f), + value, + detail::default_result_type_lambda); +#else + return detail::constexpr_switch( + std::forward(f), + value, + detail::default_result_type_lambda); +#endif +} + +template > +constexpr decltype(auto) enum_switch(F&& f, E value) { + return enum_switch(std::forward(f), value); +} + +template , typename F, typename R = detail::result_t> +constexpr decltype(auto) enum_switch(F&& f, E value, Result&& result) { + using D = std::decay_t; + static_assert(std::is_enum_v, "magic_enum::enum_switch requires enum type."); + static_assert(detail::is_reflected_v, "magic_enum requires enum implementation and valid max and min."); + +#if defined(MAGIC_ENUM_ENABLE_HASH) || defined(MAGIC_ENUM_ENABLE_HASH_SWITCH) + return detail::constexpr_switch<&detail::values_v, detail::case_call_t::value>( + std::forward(f), + value, + [&result]() -> R { return std::forward(result); }); +#else + return detail::constexpr_switch( + std::forward(f), + value, + [&result]() -> R { return std::forward(result); }); +#endif +} + +template > +constexpr decltype(auto) enum_switch(F&& f, E value, Result&& result) { + return enum_switch(std::forward(f), value, std::forward(result)); +} + +} // namespace magic_enum + +template <> +struct std::common_type : magic_enum::detail::identity {}; + +template +struct std::common_type : magic_enum::detail::identity {}; + +template +struct std::common_type : magic_enum::detail::identity {}; + +#endif // NEARGYE_MAGIC_ENUM_SWITCH_HPP diff --git a/module/dll_source_lzy/ecap/lib/hulc/magic_enum/magic_enum/magic_enum_utility.hpp b/module/dll_source_lzy/ecap/lib/hulc/magic_enum/magic_enum/magic_enum_utility.hpp new file mode 100644 index 0000000..5368b02 --- /dev/null +++ b/module/dll_source_lzy/ecap/lib/hulc/magic_enum/magic_enum/magic_enum_utility.hpp @@ -0,0 +1,138 @@ +// __ __ _ ______ _____ +// | \/ | (_) | ____| / ____|_ _ +// | \ / | __ _ __ _ _ ___ | |__ _ __ _ _ _ __ ___ | | _| |_ _| |_ +// | |\/| |/ _` |/ _` | |/ __| | __| | '_ \| | | | '_ ` _ \ | | |_ _|_ _| +// | | | | (_| | (_| | | (__ | |____| | | | |_| | | | | | | | |____|_| |_| +// |_| |_|\__,_|\__, |_|\___| |______|_| |_|\__,_|_| |_| |_| \_____| +// __/ | https://github.com/Neargye/magic_enum +// |___/ version 0.9.7 +// +// Licensed under the MIT License . +// SPDX-License-Identifier: MIT +// Copyright (c) 2019 - 2024 Daniil Goncharov . +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#ifndef NEARGYE_MAGIC_ENUM_UTILITY_HPP +#define NEARGYE_MAGIC_ENUM_UTILITY_HPP + +#include "magic_enum.hpp" + +namespace magic_enum { + +namespace detail { + +template +constexpr auto for_each(F&& f, std::index_sequence) { + constexpr bool has_void_return = (std::is_void_v[I]>>> || ...); + constexpr bool all_same_return = (std::is_same_v[0]>>, std::invoke_result_t[I]>>> && ...); + + if constexpr (has_void_return) { + (f(enum_constant[I]>{}), ...); + } else if constexpr (all_same_return) { + return std::array{f(enum_constant[I]>{})...}; + } else { + return std::tuple{f(enum_constant[I]>{})...}; + } +} + +template +constexpr bool all_invocable(std::index_sequence) { + if constexpr (count_v == 0) { + return false; + } else { + return (std::is_invocable_v[I]>> && ...); + } +} + +} // namespace magic_enum::detail + +template , typename F, detail::enable_if_t = 0> +constexpr auto enum_for_each(F&& f) { + using D = std::decay_t; + static_assert(std::is_enum_v, "magic_enum::enum_for_each requires enum type."); + static_assert(detail::is_reflected_v, "magic_enum requires enum implementation and valid max and min."); + constexpr auto sep = std::make_index_sequence>{}; + + if constexpr (detail::all_invocable(sep)) { + return detail::for_each(std::forward(f), sep); + } else { + static_assert(detail::always_false_v, "magic_enum::enum_for_each requires invocable of all enum value."); + } +} + +template > +[[nodiscard]] constexpr auto enum_next_value(E value, std::ptrdiff_t n = 1) noexcept -> detail::enable_if_t>> { + using D = std::decay_t; + constexpr std::ptrdiff_t count = detail::count_v; + + if (const auto i = enum_index(value)) { + const std::ptrdiff_t index = (static_cast(*i) + n); + if (index >= 0 && index < count) { + return enum_value(static_cast(index)); + } + } + return {}; +} + +template > +[[nodiscard]] constexpr auto enum_next_value_circular(E value, std::ptrdiff_t n = 1) noexcept -> detail::enable_if_t> { + using D = std::decay_t; + constexpr std::ptrdiff_t count = detail::count_v; + + if (const auto i = enum_index(value)) { + const std::ptrdiff_t index = ((((static_cast(*i) + n) % count) + count) % count); + if (index >= 0 && index < count) { + return enum_value(static_cast(index)); + } + } + return MAGIC_ENUM_ASSERT(false), value; +} + +template > +[[nodiscard]] constexpr auto enum_prev_value(E value, std::ptrdiff_t n = 1) noexcept -> detail::enable_if_t>> { + using D = std::decay_t; + constexpr std::ptrdiff_t count = detail::count_v; + + if (const auto i = enum_index(value)) { + const std::ptrdiff_t index = (static_cast(*i) - n); + if (index >= 0 && index < count) { + return enum_value(static_cast(index)); + } + } + return {}; +} + +template > +[[nodiscard]] constexpr auto enum_prev_value_circular(E value, std::ptrdiff_t n = 1) noexcept -> detail::enable_if_t> { + using D = std::decay_t; + constexpr std::ptrdiff_t count = detail::count_v; + + if (const auto i = enum_index(value)) { + const std::ptrdiff_t index = ((((static_cast(*i) - n) % count) + count) % count); + if (index >= 0 && index < count) { + return enum_value(static_cast(index)); + } + } + return MAGIC_ENUM_ASSERT(false), value; +} + +} // namespace magic_enum + +#endif // NEARGYE_MAGIC_ENUM_UTILITY_HPP diff --git a/module/dll_source_lzy/ecap/lib/makelib_common.h b/module/dll_source_lzy/ecap/lib/makelib_common.h new file mode 100644 index 0000000..7205625 --- /dev/null +++ b/module/dll_source_lzy/ecap/lib/makelib_common.h @@ -0,0 +1,14 @@ +#pragma once +#define export 1 +#if defined(_MSC_VER) || defined(WIN64) || defined(WIN32) || defined(__NT__) +#define ex_export __declspec(dllexport) +#define ex_emport __declspec(dllimport) +#else // linux or mac +#define ex_export __attribute__((visibility("default"))) +#define ex_emport __attribute__((visibility("default"))) +#endif +#if defined(export) +#define ex_declare ex_export +#else +#define ex_declare ex_emport +#endif \ No newline at end of file diff --git a/module/dll_source_lzy/ecap/lib9002.so b/module/dll_source_lzy/ecap/lib9002.so new file mode 100644 index 0000000..b02d4f9 Binary files /dev/null and b/module/dll_source_lzy/ecap/lib9002.so differ diff --git a/module/get_track_tool_main_backup.cpp b/module/get_track_tool_main_backup.cpp new file mode 100644 index 0000000..28fb013 --- /dev/null +++ b/module/get_track_tool_main_backup.cpp @@ -0,0 +1,277 @@ +#include +#include +#include +#include "Local_Server/Data_Source.h" +#include "Local_Server/Data_Source.h" +#include "SSR/export.h" +using namespace Psc; +int max_distance = 700; +class MY_File_Data_Source : public File_Data_Source { +public: + BaseLogger* logger{}; + void pre_handle(const std::string& data) override {} + void handle_mode_s(std::string& packet) override {} +}; +std::map air_map; +static size_t line_num = 0; +static size_t line_num_ex = 0; +namespace fs = std::filesystem; +// "C:/wyc/CLionProjects/plantSunCat/mainProjects/Radarcape/data/pos/110.txt" +void handle(const fs::path& file_path, const fs::path& rel_path) { + line_num = 0; + line_num_ex = 0; + MY_File_Data_Source fs; + auto u8_string = rel_path.u8string(); + std::string t(u8_string.begin(), u8_string.end()); + auto path = get_exe_dir() + "/tarck_logs/" + t; + auto ttt = file_path.u8string(); + std::string fp(ttt.begin(), ttt.end()); + auto key = fp; + std::replace(key.begin(), key.end(), '/', '_'); + std::replace(key.begin(), key.end(), '\\', '_'); + fs.logger = new BaseLogger(path, 100 * 100 * 10000, 1); + fs.key = key; + fs.data_type = Mock_Data_Type::BIN_Blank_One_Line_With_Escape; + fs.file_path = fp; + fs.play_mode = Play_Mode::analysis; + fs.open(); + std::string buffer; + auto mode_data = fs.read(); + while (!mode_data.empty()) { + line_num_ex++; + Binary_Format_handle_buffer(buffer, mode_data, [&](std::string& packet) { + line_num++; + if (packet[0] != 0x1a) { + std::cout << "first:" << mem2hex(packet) << std::endl; + return; + } + std::string error_len = key + " " + LOG_POS_SIMPLE + " mode_s_error_length"; + auto type = packet[1]; + if (type == Msg::AC) { + if (packet.size() != Msg::AC_len) { + fs.logger->c_debug(error_len, {}, + std::to_string(type) + " size:" + std::to_string(packet.size()) + " hex:" + + mem2hex(packet) + " should:" + std::to_string(Msg::AC_len)); + return; + } + } else if (type == Msg::S7) { + if (packet.size() != Mode_S_Msg::S7_len) { + fs.logger->c_debug(error_len, {}, + std::to_string(type) + " size:" + std::to_string(packet.size()) + " hex:" + + mem2hex(packet) + " should:" + std::to_string(Msg::S7_len)); + return; + } + } else if (type == Msg::S14) { + if (packet.size() != Msg::S14_len) { + fs.logger->c_debug(error_len, {}, + std::to_string(type) + " size:" + std::to_string(packet.size()) + " hex:" + + mem2hex(packet) + " should:" + std::to_string(Msg::S14_len)); + return; + } + } else if (type == Msg::Radarcape_status) { + if (packet.size() != Msg::Radarcape_status_len) { + fs.logger->c_debug(error_len, {}, + std::to_string(type) + " size:" + std::to_string(packet.size()) + " hex:" + + mem2hex(packet) + " should:" + std::to_string(Msg::Radarcape_status_len)); + return; + } + } else if (type == Msg::HULC_Status) { + if (packet.size() != Msg::HULC_len) { + fs.logger->c_debug(error_len, {}, + std::to_string(type) + " HULC size:" + std::to_string(packet.size()) + " hex:" + + mem2hex(packet)); + return; + } + } else { + // std::cout << "unknown_type:" << mem2hex(packet); + rotating_log("unknown_type", mem2hex(packet)); + return; + } + bool mode_s = type == Msg::S7 || type == Msg::S14; + if (!mode_s) {} + if (type == Msg::AC) {} else if (type == Msg::HULC_Status) {} else if (type == Msg::Radarcape_status) { + auto msg = create_Radarcape_STATUS_Message(packet); + std::cout << msg.toJson().to_json_string() << std::endl; + fs.logger->debug("Radarcape_status/radarcape", {}, msg.toJson().to_json_string()); + } else if (mode_s) { + // 拓展点 + auto mode_s_msg = std::make_unique(nullptr, packet); + std::string& msg_hex = mode_s_msg->msg_hex; + std::string msg_bin = hex2bin(mode_s_msg->msg_hex); + auto df = ::decode_df(msg_bin); + std::string icao = ::decode_icao(msg_bin); + JSON msg_json = JSON::object(); + MLAT_timestamp* mlat_timestamp = &mode_s_msg->mlat_timestamp; + Log_Type lt({}, { + {"行号", std::to_string(line_num)}, + {"ICAO", icao}, + //{"DF", std::to_string(static_cast(df))}, + {"signal_level", std::to_string((int)mode_s_msg->signal_level)}, + {"时间戳", mode_s_msg->mlat_timestamp.to_string()}, + //{"msg_hex", msg_hex}, + {"msg_hex_blank", mem2hex(hex2mem(msg_hex), true, " ")} + }); + lt.new_line = true; + //fs.logger->debug("收到报文", lt, ""); + if (mode_s_msg->df == Downlink_Format::Extended_Squitter_17) { + if (!with_PI::check_crc(msg_bin, icao)) { + fs.logger->error("crc_error", lt.append("pos", LOG_POS_SIMPLE), ""); + return; + } + int tc = type_code(msg_bin); + auto& icao = mode_s_msg->icao; + if (air_map.find(icao) == air_map.end()) { + auto i = new Aircraft_Info(icao); + air_map[icao] = i; + } + auto& info = *air_map[mode_s_msg->icao]; + // if (tc >= 5 && tc <= 8) { + // auto& tt = info.BDS06_surface_position.value; + // if (!tt.has_value()) { + // tt = typename std::remove_reference_t::value_type(); + // } + // auto& t = tt.value(); + // info.refresh_pos(true); + // t.base_station_pos = CPR::Position{37, 121}; + // t.parse(msg_bin); + // auto p = t.parse_message(msg_bin, static_cast(mlat_timestamp->daysec), max_distance); + // if (p.has_value()) { + // info.surface_pos_track_list.push(p.value()); + // std::cout << "第一次出现地面轨迹 手动崩溃!" << std::endl; + // std::exit(0); + // fs.logger->debug("surface/地面轨迹", lt, info.surface_pos_track_list.to_string()); + // } + // msg_json.append_list(t.toJson().children); + // } else + if ((tc >= 9 && tc <= 18) || (tc >= 20 && tc <= 22)) { + auto& tt = info.BDS05_airborne_position.value; + if (!tt.has_value()) { + tt = typename std::remove_reference_t::value_type(); + } + auto& t = tt.value(); + t.parse(msg_bin); + info.refresh_pos(true); + auto p = t.parse_message(msg_bin, static_cast(mlat_timestamp->daysec), max_distance); + if (p.has_value()) { + double meter = t.get_alt_meter(); + double x, y, z; + CPR::WGS84_LBH_to_XYZ(p->lon, p->lat, meter, x, y, z); + std::ostringstream oss; + oss << std::fixed << std::setprecision(10); + oss << std::endl; + oss << "经度-纬度-高度(m)" << "[" << p->lon << ", " << p->lat << ", " << meter << "]" << + std::endl; + oss << "笛卡尔坐标系:" << "[" << x << ", " << y << ", " << z << "]" << " Altitude_type:" << + to_string(t.get_altitude_type()) << std::endl; + fs.logger->debug("坐标解析成功", lt, oss.str()); + Position_3D p2(p->lat, p->lon, 0); + info.air_pos_track_list.push(p2); + } else { + fs.logger->debug("坐标解析失败", lt, "\n"); + } + msg_json.append_list(t.toJson().children); + } else { + lt.append("tc", std::to_string(tc)); + fs.logger->debug("未知的tc", lt, "\n"); + } + } + } + }); + mode_data = fs.read(); + } + std::cout << "line_num: " << line_num << std::endl; + std::cout << "line_num_ex: " << line_num_ex << std::endl; + fs.close(); +} +// void list_directory(const fs::path& dir_path, const std::string& relative_path = "") { +// for (const auto& entry : fs::directory_iterator(dir_path)) { +// std::string file_path = entry.path().string(); +// std::string filename = entry.path().filename().string(); +// std::string full_relative_path = relative_path.empty() ? filename : relative_path + "/" + filename; +// if (fs::is_directory(entry.status())) { +// list_directory(dir_path, full_relative_path); // 递归遍历子目录 +// } else { +// handle(file_path, full_relative_path + filename); // 对文件进行处理 +// } +// } +// } +void list_directory(const fs::path& dir_path, const fs::path& base_path) { + for (const auto& entry : fs::directory_iterator(dir_path)) { + fs::path file_path = entry.path(); + auto relative_path = fs::relative(file_path, base_path); // 计算相对路径 + if (fs::is_directory(entry.status())) { + list_directory(file_path, base_path); // 递归遍历子目录 + } else { + std::cout << "Full path: " << (const char*)file_path.u8string().c_str() << std::endl; // 输出完整路径 + std::cout << "Relative path: " << (const char*)relative_path.u8string().c_str() << std::endl; // 输出相对路径 + handle(file_path, relative_path); + } + } +} +std::wstring _transformString2Wstring(const std::string& s) { + setlocale(LC_CTYPE, "en_US.UTF-8"); + const char* _Source = s.c_str(); + size_t len = strlen(_Source) + 1; + size_t converted = 0; + wchar_t* wStr = new wchar_t[len]; + mbstowcs_s(&converted, wStr, len, _Source, _TRUNCATE); + std::wstring result(wStr); + delete[] wStr; + return result; +} +std::wstring gbk_to_wstring(const std::string& gbk) { + int len = MultiByteToWideChar(CP_ACP, 0, gbk.c_str(), -1, nullptr, 0); + std::wstring wstr(len, L'\0'); + MultiByteToWideChar(CP_ACP, 0, gbk.c_str(), -1, &wstr[0], len); + // 去掉末尾'\0' + if (!wstr.empty() && wstr.back() == L'\0') wstr.pop_back(); + return wstr; +} +int main(int argc, char* argv[]) { + // 检查命令行参数是否提供了目录路径 + if (argc < 2) { + std::cerr << "Usage: " << argv[0] << " " << std::endl; + return 1; + } + set_console_utf8(); + Base_Logger_Manager::instance().init(); + auto path = Psc::get_exe_dir() + "/tarck_logs/mode_s.log"; + mode_s_logger = new BaseLogger(path, 100 * 100 * 10000, 1); + std::string aaa = argv[1]; + std::u8string dp((char8_t*)platform_2_utf8(aaa).data()); + auto dir_path = std::filesystem::path(dp); + if (!fs::exists(dir_path)) { + std::cerr << "!fs::exists(pa)." << std::endl; + return 1; + } + if (!fs::is_directory(dir_path)) { + std::cerr << "!fs::is_directory(pa)." << std::endl; + return 1; + } + // 遍历目录下的所有文件 + // for (const auto& entry : fs::directory_iterator(dir_path)) { + // std::string file_path = entry.path().string(); + // std::string filename = entry.path().filename().string(); + // std::cout << "Full path: " << file_path << std::endl; + // std::cout << "File name: " << filename << std::endl; + // handle(file_path, filename); + // } + list_directory(dir_path, dir_path); + return 0; +} +// std::vector maybe_dir_path_list { +// dir_path, +// gbk_to_utf8(dir_path) +// }; +// bool find = false; +// for (auto& maybe_dir_path : maybe_dir_path_list) { +// if (fs::exists(maybe_dir_path) && fs::is_directory(maybe_dir_path)) { +// dir_path = maybe_dir_path; +// find = true; +// break; +// } +// } +// if (!find) { +// std::cerr << "The path does not exist or is not a directory." << std::endl; +// return 1; +// } diff --git a/module/mlat_source/main.h b/module/mlat_source/main.h new file mode 100644 index 0000000..3d00367 --- /dev/null +++ b/module/mlat_source/main.h @@ -0,0 +1,27 @@ + +#define MY_LIBRARY_EXPORTS +#ifdef _WIN32 // Windows 平台 + #ifdef MY_LIBRARY_EXPORTS // 如果正在构建库 + #define MY_LIBRARY_API __declspec(dllexport) // 导出符号 + #else + #define MY_LIBRARY_API __declspec(dllimport) // 导入符号 + #endif +#else // 对于 Linux 和其他 Unix-like 系统 + #define MY_LIBRARY_API __attribute__((visibility("default"))) // 导出符号 +#endif +#include + + +#include +extern "C" { +#pragma pack(push, 8) + struct MLAT_Data { + char icao[6]; + double lon; + double lat; + }; +#pragma pack(pop) + MY_LIBRARY_API void read(MLAT_Data* buf, std::uint16_t* len); +} + + diff --git a/module/mlat_source/mlat_dll.cpp b/module/mlat_source/mlat_dll.cpp new file mode 100644 index 0000000..4c54ca1 --- /dev/null +++ b/module/mlat_source/mlat_dll.cpp @@ -0,0 +1,158 @@ +#include +#include +#include +#include + +#include "main.h" +#include +#include // 蹇呴』鍖呭惈杩欎釜澶存枃浠朵互浣跨敤 std::memcpy +#include +#include +#include +#include +#include + +using Func_Type = void(*)(MLAT_Data* buf, std::uint16_t* len); +Func_Type read_func_ptr{}; + + +double lon = 121.473701; +double lat = 121.473701; + +// void read(MLAT_Data* buf, std::uint16_t* len) { +// // 第二条 +// strncpy(buf[0].icao, "XYZ789", sizeof(buf[1].icao)); +// buf[0].lon = lon; +// buf[0].lat = lat; +// lon += 0.001; +// lat += 0.001; +// +// *len = 1; +// } +time_t datetime_to_timestamp(const std::string& datetime) { + std::tm tm = {}; + std::istringstream ss(datetime); + ss >> std::get_time(&tm, "%Y-%m-%d %H:%M:%S"); + if (ss.fail()) { + throw std::runtime_error("时间格式错误"); + } + // std::mktime按本地时区转换 + return std::mktime(&tm); +} + +struct Base_MLAT_Data { + MLAT_Data mlat_data; + std::string msg; +}; + +std::vector read_lines() { + Base_Logger_Manager::instance()->init(); + std::multimap ordered_multimap; + std::ifstream fin("C:/wyc/CLionProjects/plantSunCat/mainProjects/Radarcape/data/0701/info.txt"); + if (!fin) { + std::cerr << "无法打开文件!" << std::endl; + return {}; + } + std::string line; + while (std::getline(fin, line)) { + if (line.empty()) continue; + + std::vector fields; + std::stringstream ss(line); + std::string item; + while (std::getline(ss, item, ';')) { + fields.push_back(item); + } + // 检查字段数 + if (fields.size() < 9) continue; + // 2025-07-03 10:16:21;VG_MSDW;28069B;2025-06-27 08:00:14;A800103FFF9CCB27FFFCA89DE0D3;121.691398;37.344925;8000;;0000;2_1_3 + // 按 1-base 提取 + std::string icao = fields[2]; + icao.resize(6, '_'); + std::string msg = fields[4]; + std::string lon = fields[5]; + std::string lat = fields[6]; + std::string alt = fields[7]; + + + std::string time = fields[3]; + // 输出(或者你可以存到 vector 里) + // std::cout << icao << " " << lat << " " << lon << " " << alt << std::endl; + + Base_MLAT_Data b; + //cur.icao = icao; + b.mlat_data.lon = stod(lon); + b.mlat_data.lat = stod(lat); + b.msg = line + "\n"; + + + //std::cout << cur.lat << " " << cur.lon << std::endl; + // if (35 < cur.lat && cur.lat < 37 + // && + // 120 < cur.lon && cur.lon < 122 + // ) { + // + // pure_log("@/logs/mlat_.log", line + "\n"); + // } + + + size_t icao_size = icao.size(); + + + strncpy(b.mlat_data.icao, icao.c_str(), 6); + ordered_multimap.insert({datetime_to_timestamp(time), b}); + } + std::vector list; + for (auto it : ordered_multimap) { + Base_MLAT_Data& b = it.second; + list.push_back(b.mlat_data); + auto icao = std::string(b.mlat_data.icao, 6); + //if (icao == "78139F") + + // 58161E_mlat_result.log + + pure_log("@/logs/icao/" + icao + "_mlat_result.log", b.msg); + + } + return list; +} +std::vector all; + +void read(MLAT_Data* buf, std::uint16_t* len) { + if (all.empty()) { + all = read_lines(); + } + static size_t pos = 0; // 上一次拷贝结束后的位置 + const size_t BATCH = 100; + size_t total = all.size(); + size_t n = std::min(BATCH, total - pos); // 本次实际要拷贝多少 + + for (size_t i = 0; i < n; ++i) { + buf[i] = all[pos + i]; + } + *len = static_cast(n); + + pos += n; + if (pos >= total) { + pos = 0; // 如果需要循环一轮后归零,否则你可以不归零 + } +} + + + + + +int main() { + // std::uint16_t size; + // MLAT_Data arr[1000]; + // read(arr, &size); + + printf("默认最大文件数: %d\n", _getmaxstdio()); + _setmaxstdio(2048); // 可以设置更高(最高8192,部分环境2048) + printf("修改后最大文件数: %d\n", _getmaxstdio()); + + + for (int i = 0; i < 1000; ++i) { + pure_log("@/logs/num/" + std::to_string(i) + ".log", "\n"); + } +} diff --git a/module/test_drogon/main.cpp b/module/test_drogon/main.cpp new file mode 100644 index 0000000..ff2b8fc --- /dev/null +++ b/module/test_drogon/main.cpp @@ -0,0 +1,32 @@ +#include + +using namespace drogon; + +class GlobalMid : public HttpMiddleware { +public: + void invoke(const HttpRequestPtr &req, + MiddlewareNextCallback &&next, + MiddlewareCallback &&done) override { + + LOG_DEBUG << "进入全局中间件:" << req->path(); + next([done](auto resp) { + resp->addHeader("X-Global", "Yes"); + LOG_DEBUG << "离开全局中间件"; + done(resp); + }); + } +}; + +int main() { + app().registerMiddleware(std::make_shared()); + + app().registerHandler("/hello", [](const HttpRequestPtr &request, + std::function &&cb){ + auto resp = HttpResponse::newHttpResponse(); + resp->setBody("OK"); + cb(resp); + }, {Get}); + + app().addListener("0.0.0.0", 80); + app().run(); +} \ No newline at end of file diff --git a/module/test_memory_lose.cpp b/module/test_memory_lose.cpp new file mode 100644 index 0000000..df90a0a --- /dev/null +++ b/module/test_memory_lose.cpp @@ -0,0 +1,194 @@ +#include +#include +#include "Base/export.h" +#include "Bit.h" +#include "Socket/Socket.h" +using Func_Type = void(*)(char* buf, std::uint16_t* len); + + +int main(int argc, char* argv[]) { + bool use_dll = false; + std::string ip = "127.0.0.1"; + uint16_t port = 12345; + // 检查命令行参数数量 + if (argc >= 2) { + // 解析 use_dll 参数 + if (std::string(argv[1]) == "true") { + use_dll = true; + } else if (std::string(argv[1]) == "false") { + use_dll = false; + } + + // 解析 ip 参数(如果有) + if (argc >= 3) { + ip = argv[2]; + } + + // 解析 port 参数(如果有) + if (argc >= 4) { + try { + port = std::stoi(argv[3]); + } catch (const std::invalid_argument& e) { + std::cerr << "Invalid port number." << std::endl; + return 1; + } catch (const std::out_of_range& e) { + std::cerr << "Port number out of range." << std::endl; + return 1; + } + } + } + + + + // 输出解析后的参数 + std::cout << "use_dll: " << (use_dll ? "true" : "false") << std::endl; + std::cout << "ip: " << ip << std::endl; + std::cout << "port: " << port << std::endl; + + Func_Type read_func_ptr = nullptr; + if (use_dll) { + auto path = Psc::get_abs_path("@/x86_linux_Release_lib9002so/lib9002.so"); + auto lib = Psc::load_library(path); + if (lib == nullptr) std::exit(1); + read_func_ptr = (Func_Type)Psc::load_function(lib, "adsb_read"); + if (read_func_ptr == nullptr) std::exit(2); + } + + Base_Logger_Manager::instance().init(); + + + + Psc::socket::Server_Socket socket; + socket.type = Psc::socket::Socket_Type::TCP; + socket.create(); + + + std::thread read_thread([&socket, ip, port]() { + socket.listen(ip, port); + }); + read_thread.detach(); + Psc::socket::socket_logger = new BaseLogger(Psc::get_exe_dir() + "/test_memory_lose.log", 1024 * 1024 * 100, 1); + //auto play_back_logger = new BaseLogger(Psc::get_exe_dir() + "/play_back.log", 1024 * 1024 * 100, 1); + + std::vector clients; + while (true) { + std::string data; + + if (use_dll) { + char buf[std::numeric_limits::max()]; + std::uint16_t len; + read_func_ptr(buf, &len); + data = std::string(buf, len); + socket.flush_clients(); + socket.write_to_all_clients(data); + //play_back_logger->debug({}, {}, data + " "); + + pure_log(Psc::get_exe_dir() + "/play_back.log", data + " " + "\n"); + } else { + + data = std::string(100, '7'); + socket.flush_clients(); + socket.write_to_all_clients(data); + } + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } +} + +int main2(int argc, char* argv[]) { + bool use_dll = false; + std::string ip = "127.0.0.1"; + uint16_t port = 12345; + // 检查命令行参数数量 + if (argc >= 2) { + // 解析 use_dll 参数 + if (std::string(argv[1]) == "true") { + use_dll = true; + } else if (std::string(argv[1]) == "false") { + use_dll = false; + } + + // 解析 ip 参数(如果有) + if (argc >= 3) { + ip = argv[2]; + } + + // 解析 port 参数(如果有) + if (argc >= 4) { + try { + port = std::stoi(argv[3]); + } catch (const std::invalid_argument& e) { + std::cerr << "Invalid port number." << std::endl; + return 1; + } catch (const std::out_of_range& e) { + std::cerr << "Port number out of range." << std::endl; + return 1; + } + } + } + + + + // 输出解析后的参数 + std::cout << "use_dll: " << (use_dll ? "true" : "false") << std::endl; + std::cout << "ip: " << ip << std::endl; + std::cout << "port: " << port << std::endl; + + Func_Type read_func_ptr = nullptr; + if (use_dll) { + auto path = Psc::get_abs_path("@/x86_linux_Release_lib9002so/lib9002.so"); + auto lib = Psc::load_library(path); + if (lib == nullptr) std::exit(1); + read_func_ptr = (Func_Type)Psc::load_function(lib, "adsb_read"); + if (read_func_ptr == nullptr) std::exit(2); + } + + + + + Psc::socket::Client_Socket socket; + socket.type = Psc::socket::Socket_Type::TCP; + socket.create(); + Psc::socket::Sockaddr_In addr; + if (use_dll) { + addr = Psc::socket::Sockaddr_In{ip, port}; + } else { + addr = Psc::socket::Sockaddr_In{ip, port}; + } + + + std::cout << "connect:" << addr.to_string() << std::endl; + socket.set_dest_address(addr); + bool c = socket.connect(); + while (true) { + + std::string data; + if (use_dll) { + char buf[std::numeric_limits::max()]; + std::uint16_t len; + read_func_ptr(buf, &len); + data = std::string(buf, len); + } else { + data = std::string(100, '7'); + } + + + + + // if (data.size() < 500) { + // std::cout << "read[" << data.size() << "]:" << memory2hex(data) << std::endl; + // } else { + // std::cout << "read[" << data.size() << "]:" << std::endl; + // } + //std::cout << "read[" << data.size() << "]:" << std::endl; + + int send = socket.send(data); + if (send == -1) { + if (Psc::socket::is_needed_reconnect(socket.socket_fd)) { + std::cout << socket.socket_fd << " 重新连接 " << std::endl; + socket.connect(); + } + + } + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } +} diff --git a/script/api.http b/script/api.http new file mode 100644 index 0000000..6603ce9 --- /dev/null +++ b/script/api.http @@ -0,0 +1,476 @@ + + +# @ip = 192.168.1.175 +# @port = 9081 +# @prefix = api/ + +@ip = localhost +@port = 80 +@prefix = api/ + +### aircraftlist.json +GET http://{{ip}}:{{port}}/aircraftlist.json + +### aircraftlist.json +GET http://192:168.205.116/aircraftlist.json + + + +### aircraft_list aircraftlist.json 默认版本使用默认数据源 +GET http://192.168.205.116:9081/aircraftlist.json + + +### aircraft_list aircraftlist.json 默认版本使用默认数据源 +GET http://27.216.218.236:9081/aircraftlist.json + +### aircraft_list aircraftlist.json 的带数据源版本 +POST http://{{ip}}:{{port}}/{{prefix}}aircraft_list +Authorization: 123 + +{ + "data_source_key": "binary_data48__2025-01-06.222333" +} + + + + + +### 获取错误日志 +POST http://{{ip}}:{{port}}/{{prefix}}get_debug_log + +{ + "serial_number": 3 +} + + +### 获取错误日志 +POST http://{{ip}}:{{port}}/{{prefix}}get_mode_s_basic_config + +{ +} + + + + + +### 获取飞机基础信息 +POST http://{{ip}}:{{port}}/{{prefix}}get_aircraft_base_info + +{ + "data_source_key": "radcap24", + "icao": "71C510" +} + +### 获取飞机详细信息 +POST http://{{ip}}:{{port}}/{{prefix}}get_general_info + + + +### 获取飞机详细信息 +POST http://{{ip}}:{{port}}/{{prefix}}get_aircraft_detail_info + +{ + "data_source_key": "radcap24", + "icao": "71C510" +} + +### 获取飞机轨迹 最后的几个 +POST http://{{ip}}:{{port}}/{{prefix}}get_aircraft_track_list + +{ + "data_source_key": "binary_data48__2025-01-06.2", + "icao": "780C6D", + "last_size":106 +} + + + +### 获取飞机在某个时间点之后 +POST http://{{ip}}:{{port}}/{{prefix}}get_aircraft_list_after +Authorization: 123 + +{ + "timestamp": 1743407092 +} + + +### 请求飞机变更列表 +POST http://{{ip}}:{{port}}/{{prefix}}aircraft_change_list +Authorization: 123 + +{ + "data_source_key": "binary_data48__2025-01-06.222333" +} + + + + +#### 版本 +POST http://{{ip}}:{{port}}/{{prefix}}version +Authorization: 123 + +### 登录 +#{ +# "status": 200, +# "data": { +# "status": true +# } +#} +POST http://{{ip}}:{{port}}/{{prefix}}login +Content-Type: application/json +Authorization: 123 + +{ + "account": "admin", + "password": "123" +} + +### 获取多点服务器配置 +POST http://{{ip}}:{{port}}/{{prefix}}get_mlat_server_config + + +### 设置多点服务器配置 +POST http://{{ip}}:{{port}}/{{prefix}}set_mlat_server_config + +{ + "ip": "192.168.1.24", + "port": 1111, + "id": 1 +} + + + +### 基站位置 +POST http://{{ip}}:{{port}}/{{prefix}}get_base_station_location +Authorization: 123 + +{ + "data_source_key": "radcap254" +} + + +### 获取 设备配置 +POST http://{{ip}}:{{port}}/{{prefix}}get_device_config +Content-Type: application/json +Authorization: 123 + +### +GET http://192.168.208.191/ui/map +### +GET http://192.168.208.191/ + + + + +### 设置 设备配置 +POST http://{{ip}}:{{port}}/{{prefix}}set_device_config +Content-Type: application/json +Authorization: 123 + +{ + "net": [ + { + "key": "device", + "ip": "192.168.1.193", + "netmask": "255.255.255.0", + "gateway": "192.168.1.1", + "port": 80 + }, + { + "key": "wifi", + "ip": "192.168.10.193", + "netmask": "255.255.255.0", + "gateway": "192.168.10.1", + "port": 80 + } + ] +} + +### 获取 数据源 整体 +POST http://{{ip}}:{{port}}/{{prefix}}get_mode_s_data_source_config + +### 获取基站 +POST http://{{ip}}:{{port}}/{{prefix}}get_base_station_location + +{ + "data_source_key": "radcap254" +} + + + + +### 获取 全部 数据馈送 端口配置 +@data_feed_name = data_feed + +POST http://{{ip}}:{{port}}/{{prefix}}get_data_feed_config +Content-Type: application/json +Authorization: 123 + + + + +### 获取 全部 数据馈送 端口配置 +POST http://{{ip}}:{{port}}/{{prefix}}aircraft_change_list +Content-Type: application/json + + +### 设置数据馈送端口配置 +POST http://{{ip}}:{{port}}/{{prefix}}update_{{data_feed_name}} +Content-Type: application/json +Authorization: 123 + +{ + "key": "Port_10005", + "enable": false, + "net_send_type": "TCP_Client", + "url": "0.0.0.0", + "port": 10005, + "output_format": "BIN", + "use_status": true, + "mode_s_output_type": "NO_POS_Mode_S", + "use_mode_ac": false +} + +### 查 +POST http://{{ip}}:{{port}}/{{prefix}}search_{{data_feed_name}} +Content-Type: application/json +Authorization: 123 + +{ + "key": "Port_10003" +} + + + + +### 数据源-数据馈送-关系配置相关项目 +@relation_name = source_feed_relation +### 查全体 +POST http://{{ip}}:{{port}}/{{prefix}}get_{{relation_name}}_config + + +### 查 +POST http://{{ip}}:{{port}}/{{prefix}}search_{{relation_name}} + +{ + "key":"1" +} + +### 增 +POST http://{{ip}}:{{port}}/{{prefix}}insert_{{relation_name}} + +### 删 +POST http://{{ip}}:{{port}}/{{prefix}}remove_{{relation_name}} + +### 改 +POST http://{{ip}}:{{port}}/{{prefix}}update_{{relation_name}} + +### 上移 +POST http://{{ip}}:{{port}}/{{prefix}}rise_{{relation_name}} + +### 下移 +POST http://{{ip}}:{{port}}/{{prefix}}fall_{{relation_name}} + + +### 多点定位相关接口 +POST http://{{ip}}:{{port}}/{{prefix}}get_mlat_list + + + +### 多点定位相关接口 +GET http://192.168.1.75/tiles/0.png +### +GET http://192.168.1.75/tiles/3/-3/1.png + + +### 多点定位相关接口 +GET http://127.0.0.1/tiles/0.png + + + + +// DSP 相关接口 + +### DSP 获取数据 +POST http://{{ip}}:{{port}}/{{prefix}}get_dsp_data +Authorization: 123 + +### 更新 +POST http://{{ip}}:{{port}}/{{prefix}}update_dsp +Authorization: 123 + +{ + "port": 80 + "center_freq": 80 + "band_width": 80 + "sample_rate": 80 +} + +### 获取 +POST http://{{ip}}:{{port}}/{{prefix}}get_dsp_config +Authorization: 123 + +### 获取 +POST http://{{ip}}:{{port}}/{{prefix}}get_dsp_data + +### 获取 +GET http://127.0.0.1:80/hello + +### 获取 +GET http://{{ip}}:{{port}} +### 获取 +GET http://{{ip}}:{{port}}/tiles/3/-3/1.png + +### 获取 +GET http://{{ip}}:{{port}}/assets/index-emIKMKOm.js + +### +GET http://{{ip}}:{{port}}/lightningchart-js/lcjs.theme.js +### +http://localhost:8848/api/method/test + +### 获取 +POST http://192.168.1.110:9081/api/get_dsp_data + + +### 开始录制 +POST http://{{ip}}:{{port}}/{{prefix}}start_record_iq_stream + +{ + dir: "C:\wyc\plantSunCat\build" + file_name: "test.txt" +} + + +### 结束录制 +POST http://{{ip}}:{{port}}/{{prefix}}end_record_iq_stream + +### 结束录制 +GET http://{{ip}}:{{port}}/aircraftlist.json + +### 结束录制 +POST http://{{ip}}:{{port}}/download_iq + +### + +POST http://{{ip}}:{{port}}/{{prefix}}get_dsp_config + + + +### + +GET http://{{ip}}:{{port}}/get_debug_info + +### + +POST http://{{ip}}:{{port}}/{{prefix}}version + +### +GET http://192.168.1.112:9081/get_debug_info + +### +GET http://{{ip}}:{{port}}/tiles/3/-2/-1.png + + +### + +POST http://{{ip}}:{{port}}/let_oom + +{ +} + +### + +POST http://{{ip}}:{{port}}/let_dump + +{ +} + +### +POST http://192.168.1.114:9081/let_dump + +{ +} + +### + +POST http://192.168.1.110:9081/api/version + +### +POST http://192.168.1.114:9081/let_oom + +{ +} + + +### +POST http://192.168.204.116:9081/api/get_data_feed_server_connect + +{ + "key": "mode_acs_shared_memory" +} + + +### +POST http://{{ip}}:{{port}}/{{prefix}}get_data_source_connect + +{ + "key": "mode_acs_shared_memory" +} + + + +#### 在线升级 +#POST http://{{ip}}:{{port}}/{{prefix}}import_version +#Content-Type: multipart/form-data; boundary=----CLION_BOUNDARY +# +#------CLION_BOUNDARY +#Content-Disposition: form-data; name="file"; filename="v1.0.2.zip" +#Content-Type: application/octet-stream +# +#< C:\Users\wyc\Desktop\version_control\v1.0.2.zip +#------CLION_BOUNDARY-- + + +### 在线升级(纯内存解压) +POST http://192.168.1.102:9081/{{prefix}}import_version +Content-Type: application/zip +dir: v1.0.2 + +< C:/Users/wyc/Desktop/version_control/v1.0.2.zip + +### 在线升级(纯内存解压) +POST http://{{ip}}:{{port}}/{{prefix}}import_version +Content-Type: application/zip +dir: v1.0.2 + +< C:/Users/wyc/Desktop/version_control/v1.0.2.zip + +### 导出日志(下载 logs) +POST http://{{ip}}:{{port}}/{{prefix}}export_logs + +### 导出版本(下载 zip) +POST http://{{ip}}:{{port}}/{{prefix}}export_version + + + + +### 重启设备 +POST http://192.168.1.102:9081/{{prefix}}restart_device + + +### +GET https://planespotters.live/api/aircraft/hex/780F0E?icaoType=B738 + + +### +GET https://planespotters.live/api/aircraft/hex/780F0E + +### +GET https://planespotters.live/api/radar/trace/8963e5 + +### +GET https://planespotters.live/api/radar/trace/780F0E + +### +GET https://t.plnspttrs.net/09923/1733381_73bcce8cad_280.jpg \ No newline at end of file diff --git a/script/old/ecap.service b/script/old/ecap.service new file mode 100644 index 0000000..a44f160 --- /dev/null +++ b/script/old/ecap.service @@ -0,0 +1,48 @@ +[Unit] +Description=ecap_server Daemon +After=network.target +Requires=heco22.service +After=heco22.service +BindsTo=heco22.service + + +# 防止启动失败 → 无限重启风暴 频率限制在 5 次 / 60 秒 +StartLimitIntervalSec=60 +StartLimitBurst=5 + +[Service] +Type=simple +ExecStartPre=/bin/bash -c 'until ping -c 1 172.22.0.2 > /dev/null 2>&1; do echo "Waiting for network..."; sleep 3; done' +ExecStart=/home/heco/ys_ecap_server/ecap_server +WorkingDirectory=/home/heco/ys_ecap_server + +# 只有失败时才重启 +Restart=on-failure +RestartSec=5 + +# 明确指定正常退出(0)时,不会重启 +SuccessExitStatus=0 75 +# 进程异常退出时重启 如果进程返回RestartPreventExitStatus时,不会重启 +RestartPreventExitStatus=2 3 + + + +# 或系统关机 / 重启时,systemd 首先发送给该服务主进程的信号。 +KillSignal=SIGTERM +TimeoutStopSec=30 +# 进程文件描述符数量 +LimitNOFILE=65535 +# cat /proc/sys/kernel/core_pattern 针对单个进程 生成 core dump 等价于 ulimit -c unlimited +LimitCORE=infinity + +# 该服务进程 以及它 fork 的所有子进程,在运行期间 不能获得任何“新的权限”。 +NoNewPrivileges=yes +# # 隔离临时目录 +PrivateTmp=yes + +# 把服务进程的 标准输出(stdout), 标准错误(stderr) 重定向到 systemd journal。 +StandardOutput=journal +StandardError=journal + +[Install] +WantedBy=multi-user.target diff --git a/script/old/heco22.service b/script/old/heco22.service new file mode 100644 index 0000000..593277f --- /dev/null +++ b/script/old/heco22.service @@ -0,0 +1,47 @@ +[Unit] +Description=heco22 Daemon +After=network.target +PartOf=ecap.service + + + + +# 防止启动失败 → 无限重启风暴 频率限制在 5 次 / 60 秒 +StartLimitIntervalSec=60 +StartLimitBurst=5 + +[Service] +Type=simple +ExecStart=/home/heco/ys_ecap_server/start_22.sh + + +# 只有失败时才重启 +Restart=on-failure +RestartSec=5 + +# 明确指定正常退出(0)时,不会重启 +SuccessExitStatus=0 75 +# 进程异常退出时重启 如果进程返回RestartPreventExitStatus时,不会重启 +RestartPreventExitStatus=2 3 + + + +# 或系统关机 / 重启时,systemd 首先发送给该服务主进程的信号。 +KillSignal=SIGTERM +TimeoutStopSec=30 +# 进程文件描述符数量 +LimitNOFILE=65535 +# cat /proc/sys/kernel/core_pattern 针对单个进程 生成 core dump 等价于 ulimit -c unlimited +LimitCORE=infinity + +# 该服务进程 以及它 fork 的所有子进程,在运行期间 不能获得任何“新的权限”。 +NoNewPrivileges=yes +# # 隔离临时目录 +PrivateTmp=yes + +# 把服务进程的 标准输出(stdout), 标准错误(stderr) 重定向到 systemd journal。 +StandardOutput=journal +StandardError=journal + +[Install] +WantedBy=multi-user.target diff --git a/script/rc.local b/script/rc.local new file mode 100644 index 0000000..a1858e0 --- /dev/null +++ b/script/rc.local @@ -0,0 +1,5 @@ +#!/bin/bash + +/home/heco/ys_ecap_server/protect.bash & + +exit 0 diff --git a/script/scp.bash b/script/scp.bash new file mode 100644 index 0000000..f1264c4 --- /dev/null +++ b/script/scp.bash @@ -0,0 +1,53 @@ +#!/bin/bash + +# 第一次要手动连入 通过下面的测试 +# ** WARNING: connection is not using a post-quantum key exchange algorithm. +# ** This session may be vulnerable to "store now, decrypt later" attacks. +# ** The server may need to be upgraded. See https://openssh.com/pq.html + + + +# C:\msys64\msys2_shell.cmd +# -mingw64 -defterm -no-start -here + + +ver_dir_name="v1.0.3" +dstHost="192.168.1.101" + + +tmp_dir="/c/Users/wyc/Desktop/version_control/tmp" +file_name="ecap_server" + +srcUser="wyc" +srcHost="192.168.1.8" +src_dir="/aenv/proj/plant_sun_cat/cmake-build-ubuntu_20_04-release2" +SRC_PASS="123" + +dstUser="heco" + +dst_dir="/home/heco/ys_ecap_server/${ver_dir_name}" +DST_PASS="123456" + + +sshpass -p "123" scp -o StrictHostKeyChecking=no "${srcUser}@${srcHost}:${src_dir}/${file_name}" "${tmp_dir}" +sshpass -p "123456" scp -o StrictHostKeyChecking=no "${tmp_dir}/${file_name}" "${dstUser}@${dstHost}:${dst_dir}" + + +#expect + +# 合并执行 +#export SSHPASS=$SRC_PASS +#sshpass -e ssh "${srcUser}@${srcHost}" "cat ${src_dir}/${file_name}" | \ +# sshpass -p "$DST_PASS" ssh "${dstUser}@${dstHost}" "cat > ${dst_dir}/${file_name}" +# + + +# 检查 SCP 命令的返回值 +if [ $? -eq 0 ]; then + echo "传输成功!" +else + echo "传输失败:$?" +fi + +#echo "按任意键继续..." +#read -n 1 -s \ No newline at end of file diff --git a/script/scp.ps1 b/script/scp.ps1 new file mode 100644 index 0000000..58622d0 --- /dev/null +++ b/script/scp.ps1 @@ -0,0 +1,31 @@ +chcp 65001 + + + +$srcUser = "wyc" +$srcHost = "192.168.1.8" +$srcPath = "/aenv/proj/plant_sun_cat/cmake-build-ubuntu_20_04-release2/ecap_server" + +$dstUser = "heco" +$dstHost = "192.168.1.102" +$dstPath = "/home/heco/ys_ecap_server/v1.0.2/" +#$dstPath = "/home/heco/ys_ecap_server/test/" + + + + +#scp "${srcUser}@${srcHost}:${srcPath}" "${dstUser}@${dstHost}:${dstPath}" + + +#$dstPath = "C:\Users\wyc\Desktop\version_control" + +scp "vm_ubuntu_2004:${srcPath}" "${dstUser}@${dstHost}:${dstPath}" +#scp "vm_ubuntu_2004:${srcPath}" "$dstPath" + + + +if ($LASTEXITCODE -eq 0) { + Write-Host "SCP_DONE OK!" +} else { + Write-Host "SCP_FAILED:$LASTEXITCODE" +} \ No newline at end of file diff --git a/script/scp_wwwroot.bash b/script/scp_wwwroot.bash new file mode 100644 index 0000000..82cdb0c --- /dev/null +++ b/script/scp_wwwroot.bash @@ -0,0 +1,33 @@ +#!/bin/bash + +# 第一次要手动连入 通过下面的测试 +# ** WARNING: connection is not using a post-quantum key exchange algorithm. +# ** This session may be vulnerable to "store now, decrypt later" attacks. +# ** The server may need to be upgraded. See https://openssh.com/pq.html + + + +file_name="wwwroot" + + +ver_dir_name="v1.0.3" +dstHost="192.168.1.102" + +src_dir="C:\Users\wyc\Desktop\version_control\${ver_dir_name}" +dstUser="heco" +dstHost="192.168.1.102" +dst_dir="/home/heco/ys_ecap_server/${ver_dir_name}" +DST_PASS="123456" + + +sshpass -p "$DST_PASS" ssh "${dstUser}@${dstHost}" "rm -rf '${dst_dir}/${file_name}'" +sshpass -p "$DST_PASS" scp -o StrictHostKeyChecking=no -r "${src_dir}/${file_name}" "${dstUser}@${dstHost}:${dst_dir}/${file_name}" + + + +# 检查 SCP 命令的返回值 +if [ $? -eq 0 ]; then + echo "传输成功!" +else + echo "传输失败:$?" +fi diff --git a/script/start_22.sh b/script/start_22.sh new file mode 100644 index 0000000..721d8f6 --- /dev/null +++ b/script/start_22.sh @@ -0,0 +1,70 @@ +#!/bin/bash + +sudo supervisorctl stop hs +sudo rm /dev/shm/* +cd /home/heco/HECO/HECOService +export LD_LIBRARY_PATH=/home/heco/HECO/HECOService:$LD_LIBRARY_PATH +./HECOService + + + + + +# /usr/bin/supervisorctl stop hs +# /usr/bin/supervisorctl stop hs + +#sudo supervisorctl reread +#sudo supervisorctl update +# sudo systemctl daemon-reload + +# 版本切换设置 +# /etc/systemd/system/ecap.service +# sudo systemctl daemon-reload +# sudo systemctl start ecap +# systemctl status ecap +# sudo systemctl enable ecap +# systemctl is-enabled ecap +# 停止 +#sudo systemctl stop ecap +# 重启 +#sudo systemctl restart ecap +# 重新加载(程序不重启) +#sudo systemctl reload ecap # 前提是程序支持 SIGHUP +# 查看日志 +#journalctl -u ecap +#journalctl -u ecap -f +# echo 'ECAP_DIR=/home/heco/ys_ecap_server/v1.0.2' | sudo tee -a /etc/ecap/env + + +# ln -sf /home/heco/ys_ecap_server/v1.0.2/ecap_server /home/heco/ys_ecap_server + + + +# ps -ef | grep start_22.sh + + + +# pstree -sp $(pgrep -o HECOService) + +# # pstree -sp 712 + + +# systemd(1)───sshd(655)───sshd(1788)───sshd(1876)───bash(1898)───bash(18630)───HECOService(18641)─┬─{HECOService}(18642) +# ├─{HECOService}(18660) +# ├─{HECOService}(18661) +# └─{HECOService}(18662) + + + +# systemd(1)───sshd(655)───sshd(1788)───sshd(1876)───bash(1898)───HECOService(20409)─┬─curl(20451) +# ├─{HECOService}(20425) +# ├─{HECOService}(20448) +# ├─{HECOService}(20449) +# └─{HECOService}(20450) + + + +# systemd(1)───HECOService(41201)─┬─{HECOService}(41218) +# ├─{HECOService}(41242) +# ├─{HECOService}(41243) +# └─{HECOService}(41244) diff --git a/script/upgrade.ps1 b/script/upgrade.ps1 new file mode 100644 index 0000000..f8ba4da --- /dev/null +++ b/script/upgrade.ps1 @@ -0,0 +1,15 @@ +# upgrade.legacy +# 打印传入的所有参数 + +Write-Host "upgrade.legacy called" +Write-Host "Argument count: $($args.Count)" + +for ($i = 0; $i -lt $args.Count; $i++) { + Write-Host "arg[$i] = $($args[$i])" +} + +# 也可以单独按语义取(如果你约定了顺序) +# $version = $args[0] +# $dir = $args[1] +# Write-Host "version = $version" +# Write-Host "dir = $dir" diff --git a/script/重启fpga b/script/重启fpga new file mode 100644 index 0000000..6e7ae9b --- /dev/null +++ b/script/重启fpga @@ -0,0 +1,14 @@ +ssh root@172.22.0.2 /sbin/reboot + + +analog + + +ping 172.22.0.2 + + +// 看服务重启次数 +systemctl show ecap -p NRestarts + +// 看失败历史 +systemctl show ecap -p ExecMainStatus -p ExecMainStartTimestamp diff --git a/ssh b/ssh new file mode 100644 index 0000000..ea2ee90 --- /dev/null +++ b/ssh @@ -0,0 +1,6 @@ +ssh -p 35024 -N -L 1234:127.0.0.1:1234 heco@192.168.101.7 + + + + +sudo -E gdb --args ./v1.1.2/ecap_server main @/config_mlat.json \ No newline at end of file diff --git a/todolist.txt b/todolist.txt new file mode 100644 index 0000000..2eefc50 --- /dev/null +++ b/todolist.txt @@ -0,0 +1,10 @@ +@D:/ae/proj/projects/ECAP_Server/module/Local_Server/server/libarchive.h#L31-35 这个文件 不合规则的检查 不和规则应该是意料之中的 所以 不符合规则用 expectd@D:/ae/proj/projects/ECAP_Server/module/Local_Server/server/libarchive.h#L9 返回结果 + +同时 + +@D:/ae/proj/projects/ECAP_Server/module/Local_Server/server/server.cpp#L313-317 这个位置检查结果 不和规则 后端给出明确的不和规原因 + + +#include "Core/Base/expected.h" using unexpected = tl::unexpected; + +使用的是这里的包装expected \ No newline at end of file diff --git a/初版升级步骤.txt b/初版升级步骤.txt new file mode 100644 index 0000000..cdcd6fc --- /dev/null +++ b/初版升级步骤.txt @@ -0,0 +1,21 @@ +# 关闭正在运行的守护进程 +sudo pkill -9 pt +sudo pkill -9 protect.bash +sudo pkill -9 ecap_server + +# 删除旧的守护进程配置 +sudo systemctl disable rc-local.service +sudo systemctl stop rc-local.service +删除 /home/heco/ys_ecap_server 下 protect.bash + + +# 添加新的守护进程配置 +ecap.service 复制到 /etc/systemd/system 更改权限777 +sudo systemctl daemon-reload +sudo systemctl enable ecap +复制文件夹 lib v1.0.2,复制文件 restart_device.bash upgrade.bash 到 /home/heco/ys_ecap_server 全部更改权限777 +ln -sf /home/heco/ys_ecap_server/v1.0.2/ecap_server /home/heco/ys_ecap_server/ecap_server 全部更改权限777 + + +# 启动新的守护进程 +sudo systemctl start ecap \ No newline at end of file diff --git a/多点定位数据模拟以及算法规范.txt b/多点定位数据模拟以及算法规范.txt new file mode 100644 index 0000000..bd8977f --- /dev/null +++ b/多点定位数据模拟以及算法规范.txt @@ -0,0 +1,28 @@ + + + + +模拟出三个基站 + + +模拟一条飞机的航线 一个列表 一堆轨迹点 算没到达一个位置与各个时间戳值 +发送 做定位 + + + +# 使用 objcopy 命令将字符串嵌入到 ELF 文件的 .note 部分 +echo -n "Author: John Doe\nVendor: MyCompany\nVersion: 1.0.0" > metadata.txt + +# 将字符串内容直接嵌入 ELF 文件 +objcopy --add-section .note.metadata=metadata.txt ./rls_cxx_Linux_Debug + + +readelf -d + + +readelf -p .info./rls_cxx_Linux_Debug +readelf -S ./rls_cxx_Linux_Debug + + +objdump -s --section=.note.metadata ./rls_cxx_Linux_Debug +objdump -s ./rls_cxx_Linux_Debug diff --git a/多进程隔离.txt b/多进程隔离.txt new file mode 100644 index 0000000..8f45c9b --- /dev/null +++ b/多进程隔离.txt @@ -0,0 +1,15 @@ + +代码用宏来隔离 +1. dsp 共享内存数据隔离实现完成 单侧dsp adsb先放一下,开始测试 + +2. 拓展数据源 一个共享内存数据源,接收adsb 测试数据 + + + +sudo nohup valgrind --leak-check=full --track-origins=yes ./ecap_server > valgrind_output.log 2>&1 & + + + +heco@heco:~/ys_ecap_server/ecap_1201$ sudo nohup valgrind --leak-check=full --track-origins=yes ./ecap_server > ./valgrind_output222.log 2>&1 + +