diff --git a/.gitattributes b/.gitattributes index a23bfa2cc..6fd6e9396 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1,48 @@ -*.fits binary \ No newline at end of file +# Git attributes for SDRangel +# normalize text files to LF and identify binary files. +* text=auto eol=lf + +# Vendored Cesium content: preserve upstream line endings. +plugins/feature/map/Cesium/** -text + +# Generated Swagger UI files +sdrbase/resources/webapi/doc/swagger-ui/** -text + +# Generated Swagger documentation and client code +sdrbase/resources/webapi/doc/swagger/** -text +swagger/sdrangel/code/** -text + +# SDRangel configuration and preset files +*.cfgx binary +*.prex binary + +# Binary image files. +*.png binary +*.PNG binary +*.bmp binary +*.BMP binary +*.xcf binary +*.XCF binary +*.jpg binary +*.JPG binary +*.fits binary +*.FITS binary +*.ico binary +*.ICO binary +*.icns binary +*.icns binary +*.gif binary +*.GIF binary + +# Binary audio/media files. +*.wav binary +*.WAV binary +*.wasm binary +*.WASM binary + +# Binary fonts. +*.ttf binary +*.TTF binary + +# Binary document files. +*.odg binary diff --git a/.github/workflows/coverity.yml b/.github/workflows/coverity.yml index 92865c862..870e46f6d 100644 --- a/.github/workflows/coverity.yml +++ b/.github/workflows/coverity.yml @@ -1,55 +1,55 @@ -name: SDRangel Linux Coverity build - -# Run every day at 3:00am UTC -on: - schedule: - - cron: '0 3 * * *' - workflow_dispatch: - -jobs: - build_coverity: - if: github.repository == 'f4exb/sdrangel' - # run once on latest - runs-on: ubuntu-24.04 - env: - COVERITY_SCAN_PROJECT_NAME: ${{ github.repository }} - COVERITY_SCAN_PROJECT_ID : "33161" - COVERITY_SCAN_NOTIFICATION_EMAIL: ${{ secrets.COVERITY_SCAN_NOTIFICATION_EMAIL }} - COVERITY_SCAN_TOKEN: ${{ secrets.COVERITY_SCAN_TOKEN }} - steps: - - uses: actions/checkout@v4 - with: - submodules: true - fetch-depth: 0 - - name: Check Coverity - id: coverity_check - run: | - ./.github/workflows/coverity.sh --precheck - # keep dependencies synced with linux.yml - - name: Install dependencies - if: steps.coverity_check.outputs.run == 'true' - run: | - sudo apt-get update - sudo apt-get install software-properties-common - sudo add-apt-repository -y ppa:ettusresearch/uhd - sudo apt-get update - sudo apt-get -y install build-essential cmake git xxd \ - devscripts fakeroot debhelper libfftw3-dev qtbase5-dev libopengl-dev libqt5opengl5-dev \ - qttools5-dev qttools5-dev-tools qtmultimedia5-dev libqt5multimedia5-plugins libqt5websockets5-dev \ - libqt5quick5 qtwebengine5-dev qtbase5-private-dev \ - qml-module-qtlocation qml-module-qtpositioning qml-module-qtquick-window2 qml-module-qtquick-dialogs \ - qml-module-qtquick-controls qml-module-qtquick-controls2 qml-module-qtquick-layouts qml-module-qtgraphicaleffects \ - libqt5serialport5-dev qtdeclarative5-dev qtpositioning5-dev qtlocation5-dev \ - libqt5charts5-dev libqt5texttospeech5-dev libqt5gamepad5-dev libqt5svg5-dev libfaad-dev libflac-dev zlib1g-dev \ - libusb-1.0-0-dev libhidapi-dev libboost-all-dev libasound2-dev libopencv-dev libopencv-imgcodecs-dev \ - libxml2-dev bison flex ffmpeg libpostproc-dev libavcodec-dev libavformat-dev \ - libopus-dev libcodec2-dev libairspy-dev libhackrf-dev \ - libbladerf-dev libsoapysdr-dev libiio-dev libuhd-dev libhamlib-dev libunwind-dev \ - libavahi-client-dev libavahi-common-dev libaio-dev \ - python3-mako python3-cheetah python3-numpy \ - autoconf automake libtool ninja-build - bash cmake/ci/build_sdrplay.sh - - name: Build SDRangel for Coverity - if: steps.coverity_check.outputs.run == 'true' - run: | - ./.github/workflows/coverity.sh +name: SDRangel Linux Coverity build + +# Run every day at 3:00am UTC +on: + schedule: + - cron: '0 3 * * *' + workflow_dispatch: + +jobs: + build_coverity: + if: github.repository == 'f4exb/sdrangel' + # run once on latest + runs-on: ubuntu-24.04 + env: + COVERITY_SCAN_PROJECT_NAME: ${{ github.repository }} + COVERITY_SCAN_PROJECT_ID : "33161" + COVERITY_SCAN_NOTIFICATION_EMAIL: ${{ secrets.COVERITY_SCAN_NOTIFICATION_EMAIL }} + COVERITY_SCAN_TOKEN: ${{ secrets.COVERITY_SCAN_TOKEN }} + steps: + - uses: actions/checkout@v4 + with: + submodules: true + fetch-depth: 0 + - name: Check Coverity + id: coverity_check + run: | + ./.github/workflows/coverity.sh --precheck + # keep dependencies synced with linux.yml + - name: Install dependencies + if: steps.coverity_check.outputs.run == 'true' + run: | + sudo apt-get update + sudo apt-get install software-properties-common + sudo add-apt-repository -y ppa:ettusresearch/uhd + sudo apt-get update + sudo apt-get -y install build-essential cmake git xxd \ + devscripts fakeroot debhelper libfftw3-dev qtbase5-dev libopengl-dev libqt5opengl5-dev \ + qttools5-dev qttools5-dev-tools qtmultimedia5-dev libqt5multimedia5-plugins libqt5websockets5-dev \ + libqt5quick5 qtwebengine5-dev qtbase5-private-dev \ + qml-module-qtlocation qml-module-qtpositioning qml-module-qtquick-window2 qml-module-qtquick-dialogs \ + qml-module-qtquick-controls qml-module-qtquick-controls2 qml-module-qtquick-layouts qml-module-qtgraphicaleffects \ + libqt5serialport5-dev qtdeclarative5-dev qtpositioning5-dev qtlocation5-dev \ + libqt5charts5-dev libqt5texttospeech5-dev libqt5gamepad5-dev libqt5svg5-dev libfaad-dev libflac-dev zlib1g-dev \ + libusb-1.0-0-dev libhidapi-dev libboost-all-dev libasound2-dev libopencv-dev libopencv-imgcodecs-dev \ + libxml2-dev bison flex ffmpeg libpostproc-dev libavcodec-dev libavformat-dev \ + libopus-dev libcodec2-dev libairspy-dev libhackrf-dev \ + libbladerf-dev libsoapysdr-dev libiio-dev libuhd-dev libhamlib-dev libunwind-dev \ + libavahi-client-dev libavahi-common-dev libaio-dev \ + python3-mako python3-cheetah python3-numpy \ + autoconf automake libtool ninja-build + bash cmake/ci/build_sdrplay.sh + - name: Build SDRangel for Coverity + if: steps.coverity_check.outputs.run == 'true' + run: | + ./.github/workflows/coverity.sh diff --git a/.github/workflows/git-attributes.yml b/.github/workflows/git-attributes.yml new file mode 100644 index 000000000..7637713bd --- /dev/null +++ b/.github/workflows/git-attributes.yml @@ -0,0 +1,29 @@ +name: Check Git attributes + +on: + pull_request: + +jobs: + check-gitattributes: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + + - name: Check for line ending violations + run: | + # Re-normalize all files according to .gitattributes + git add --renormalize . + + # Check if renormalization changed anything + if git diff --cached --name-only | grep -q .; then + echo "::error::The following files have line endings that don't match .gitattributes settings:" + git diff --cached --name-only + echo "" + echo "To fix, run:" + echo " git add --renormalize ." + echo " git commit -m 'Normalize line endings'" + exit 1 + fi + + echo "All files have correct line endings." diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 8095b2fc5..852974b39 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -1,76 +1,76 @@ -name: SDRangel Linux release build - -on: - push: - branches: - - linux_github_release - tags: - - 'v*' - workflow_dispatch: - -jobs: - build_deb: - strategy: - fail-fast: false - matrix: - os: [ubuntu-22.04, ubuntu-24.04] - runs-on: ${{ matrix.os }} - steps: - - uses: actions/checkout@v4 - with: - submodules: true - fetch-depth: 0 - - name: Install dependencies - # ensure changes in dependencies get added to coverity.yml - run: | - sudo apt-get update - sudo apt-get install software-properties-common - sudo add-apt-repository -y ppa:ettusresearch/uhd - sudo apt-get update - sudo apt-get -y install build-essential cmake git xxd \ - devscripts fakeroot debhelper libfftw3-dev qtbase5-dev libopengl-dev libqt5opengl5-dev \ - qttools5-dev qttools5-dev-tools qtmultimedia5-dev libqt5multimedia5-plugins libqt5websockets5-dev \ - libqt5quick5 qtwebengine5-dev qtbase5-private-dev \ - qml-module-qtlocation qml-module-qtpositioning qml-module-qtquick-window2 qml-module-qtquick-dialogs \ - qml-module-qtquick-controls qml-module-qtquick-controls2 qml-module-qtquick-layouts qml-module-qtgraphicaleffects \ - libqt5serialport5-dev qtdeclarative5-dev qtpositioning5-dev qtlocation5-dev \ - libqt5charts5-dev libqt5texttospeech5-dev libqt5gamepad5-dev libqt5svg5-dev libfaad-dev libflac-dev zlib1g-dev \ - libusb-1.0-0-dev libhidapi-dev libboost-all-dev libasound2-dev libopencv-dev libopencv-imgcodecs-dev \ - libxml2-dev bison flex ffmpeg libpostproc-dev libavcodec-dev libavformat-dev \ - libopus-dev libcodec2-dev libairspy-dev libhackrf-dev \ - libbladerf-dev libsoapysdr-dev libiio-dev libuhd-dev libhamlib-dev libunwind-dev \ - libavahi-client-dev libavahi-common-dev libaio-dev \ - python3-mako python3-cheetah python3-numpy \ - autoconf automake libtool ninja-build - bash cmake/ci/build_sdrplay.sh - - name: Build SDRangel - run: | - if [ "${RUNNING_IN_ACT:-}" = "true" ]; then - mkdir -p /tmp/build - rsync -a --delete . /tmp/build/sdrangel/ - cd /tmp/build/sdrangel - debuild -i -us -uc -b - cp ../sdrangel_*_amd64.deb "$GITHUB_WORKSPACE"/ - else - debuild -i -us -uc -b - fi - - name: Get version - id: get_version - run: | - if [[ "${{github.ref_name}}" == "linux_github_release" ]]; then - echo "version=$(echo ${{github.sha}} | cut -c1-7)" >> $GITHUB_OUTPUT - else - echo "version=$(echo ${{github.ref_name}} | cut -c2-)" >> $GITHUB_OUTPUT - fi - - name: Rename - run: mv ../sdrangel_*_amd64.deb sdrangel_${{ steps.get_version.outputs.version }}_${{ matrix.os }}_amd64.deb - - name: Upload artifact - uses: actions/upload-artifact@v4 - with: - name: sdrangel_${{ steps.get_version.outputs.version }}_${{ matrix.os }}_amd64.deb - path: sdrangel_${{ steps.get_version.outputs.version }}_${{ matrix.os }}_amd64.deb - - name: Upload release - if: startsWith(github.ref, 'refs/tags/') - uses: softprops/action-gh-release@v2 - with: - files: sdrangel_${{ steps.get_version.outputs.version }}_${{ matrix.os }}_amd64.deb +name: SDRangel Linux release build + +on: + push: + branches: + - linux_github_release + tags: + - 'v*' + workflow_dispatch: + +jobs: + build_deb: + strategy: + fail-fast: false + matrix: + os: [ubuntu-22.04, ubuntu-24.04] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v4 + with: + submodules: true + fetch-depth: 0 + - name: Install dependencies + # ensure changes in dependencies get added to coverity.yml + run: | + sudo apt-get update + sudo apt-get install software-properties-common + sudo add-apt-repository -y ppa:ettusresearch/uhd + sudo apt-get update + sudo apt-get -y install build-essential cmake git xxd \ + devscripts fakeroot debhelper libfftw3-dev qtbase5-dev libopengl-dev libqt5opengl5-dev \ + qttools5-dev qttools5-dev-tools qtmultimedia5-dev libqt5multimedia5-plugins libqt5websockets5-dev \ + libqt5quick5 qtwebengine5-dev qtbase5-private-dev \ + qml-module-qtlocation qml-module-qtpositioning qml-module-qtquick-window2 qml-module-qtquick-dialogs \ + qml-module-qtquick-controls qml-module-qtquick-controls2 qml-module-qtquick-layouts qml-module-qtgraphicaleffects \ + libqt5serialport5-dev qtdeclarative5-dev qtpositioning5-dev qtlocation5-dev \ + libqt5charts5-dev libqt5texttospeech5-dev libqt5gamepad5-dev libqt5svg5-dev libfaad-dev libflac-dev zlib1g-dev \ + libusb-1.0-0-dev libhidapi-dev libboost-all-dev libasound2-dev libopencv-dev libopencv-imgcodecs-dev \ + libxml2-dev bison flex ffmpeg libpostproc-dev libavcodec-dev libavformat-dev \ + libopus-dev libcodec2-dev libairspy-dev libhackrf-dev \ + libbladerf-dev libsoapysdr-dev libiio-dev libuhd-dev libhamlib-dev libunwind-dev \ + libavahi-client-dev libavahi-common-dev libaio-dev \ + python3-mako python3-cheetah python3-numpy \ + autoconf automake libtool ninja-build + bash cmake/ci/build_sdrplay.sh + - name: Build SDRangel + run: | + if [ "${RUNNING_IN_ACT:-}" = "true" ]; then + mkdir -p /tmp/build + rsync -a --delete . /tmp/build/sdrangel/ + cd /tmp/build/sdrangel + debuild -i -us -uc -b + cp ../sdrangel_*_amd64.deb "$GITHUB_WORKSPACE"/ + else + debuild -i -us -uc -b + fi + - name: Get version + id: get_version + run: | + if [[ "${{github.ref_name}}" == "linux_github_release" ]]; then + echo "version=$(echo ${{github.sha}} | cut -c1-7)" >> $GITHUB_OUTPUT + else + echo "version=$(echo ${{github.ref_name}} | cut -c2-)" >> $GITHUB_OUTPUT + fi + - name: Rename + run: mv ../sdrangel_*_amd64.deb sdrangel_${{ steps.get_version.outputs.version }}_${{ matrix.os }}_amd64.deb + - name: Upload artifact + uses: actions/upload-artifact@v4 + with: + name: sdrangel_${{ steps.get_version.outputs.version }}_${{ matrix.os }}_amd64.deb + path: sdrangel_${{ steps.get_version.outputs.version }}_${{ matrix.os }}_amd64.deb + - name: Upload release + if: startsWith(github.ref, 'refs/tags/') + uses: softprops/action-gh-release@v2 + with: + files: sdrangel_${{ steps.get_version.outputs.version }}_${{ matrix.os }}_amd64.deb diff --git a/.github/workflows/sdrangel.yml b/.github/workflows/sdrangel.yml index aeb349ab4..13deaad3b 100644 --- a/.github/workflows/sdrangel.yml +++ b/.github/workflows/sdrangel.yml @@ -137,3 +137,38 @@ jobs: run: | cd build make -j3 + + build_linux: + runs-on: ubuntu-24.04 + permissions: + contents: read + steps: + - uses: actions/checkout@v4 + with: + submodules: true + fetch-depth: 0 + - name: Install dependencies + run: | + sudo apt-get update + sudo apt-get install software-properties-common + sudo add-apt-repository -y ppa:ettusresearch/uhd + sudo apt-get update + sudo apt-get -y install build-essential cmake git xxd \ + devscripts fakeroot debhelper libfftw3-dev qtbase5-dev libopengl-dev libqt5opengl5-dev \ + qttools5-dev qttools5-dev-tools qtmultimedia5-dev libqt5multimedia5-plugins libqt5websockets5-dev \ + libqt5quick5 qtwebengine5-dev qtbase5-private-dev \ + qml-module-qtlocation qml-module-qtpositioning qml-module-qtquick-window2 qml-module-qtquick-dialogs \ + qml-module-qtquick-controls qml-module-qtquick-controls2 qml-module-qtquick-layouts qml-module-qtgraphicaleffects \ + libqt5serialport5-dev qtdeclarative5-dev qtpositioning5-dev qtlocation5-dev \ + libqt5charts5-dev libqt5texttospeech5-dev libqt5gamepad5-dev libqt5svg5-dev libfaad-dev libflac-dev zlib1g-dev \ + libusb-1.0-0-dev libhidapi-dev libboost-all-dev libasound2-dev libopencv-dev libopencv-imgcodecs-dev \ + libxml2-dev bison flex ffmpeg libpostproc-dev libavcodec-dev libavformat-dev \ + libopus-dev libcodec2-dev libairspy-dev libhackrf-dev \ + libbladerf-dev libsoapysdr-dev libiio-dev libuhd-dev libhamlib-dev libunwind-dev \ + libavahi-client-dev libavahi-common-dev libaio-dev \ + python3-mako python3-cheetah python3-numpy \ + autoconf automake libtool ninja-build + bash cmake/ci/build_sdrplay.sh + - name: Build SDRangel on Linux + run: | + debuild -i -us -uc -b diff --git a/android/qt6/AndroidManifest.xml b/android/qt6/AndroidManifest.xml index e7bd96b12..d90bab2ae 100644 --- a/android/qt6/AndroidManifest.xml +++ b/android/qt6/AndroidManifest.xml @@ -1,67 +1,67 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/qt6/res/mipmap-anydpi-v26/ic_launcher.xml b/android/qt6/res/mipmap-anydpi-v26/ic_launcher.xml index fcd3a1e20..ec59d6ec5 100644 --- a/android/qt6/res/mipmap-anydpi-v26/ic_launcher.xml +++ b/android/qt6/res/mipmap-anydpi-v26/ic_launcher.xml @@ -2,4 +2,4 @@ - \ No newline at end of file + diff --git a/app/crashhandler.h b/app/crashhandler.h index 2c857ccb7..447d06a06 100644 --- a/app/crashhandler.h +++ b/app/crashhandler.h @@ -1,26 +1,26 @@ -/////////////////////////////////////////////////////////////////////////////////// -// Copyright (C) 2025 Jon Beniston, M7RCE // -// // -// This program is free software; you can redistribute it and/or modify // -// it under the terms of the GNU General Public License as published by // -// the Free Software Foundation as version 3 of the License, or // -// (at your option) any later version. // -// // -// This program is distributed in the hope that it will be useful, // -// but WITHOUT ANY WARRANTY; without even the implied warranty of // -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // -// GNU General Public License V3 for more details. // -// // -// You should have received a copy of the GNU General Public License // -// along with this program. If not, see . // -/////////////////////////////////////////////////////////////////////////////////// - -#pragma once - -#include "loggerwithfile.h" - -void installCrashHandler(qtwebapp::LoggerWithFile *logger); - -#ifdef _WIN32 -void logWindowsStackTrace(); -#endif +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2025 Jon Beniston, M7RCE // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// (at your option) any later version. // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#include "loggerwithfile.h" + +void installCrashHandler(qtwebapp::LoggerWithFile *logger); + +#ifdef _WIN32 +void logWindowsStackTrace(); +#endif diff --git a/cmake/Modules/FindCM256cc.cmake b/cmake/Modules/FindCM256cc.cmake index b7b0b2a22..3cb90ca64 100644 --- a/cmake/Modules/FindCM256cc.cmake +++ b/cmake/Modules/FindCM256cc.cmake @@ -53,4 +53,4 @@ if (NOT CM256CC_FOUND) INCLUDE(FindPackageHandleStandardArgs) FIND_PACKAGE_HANDLE_STANDARD_ARGS(CM256CC DEFAULT_MSG CM256CC_LIBRARIES CM256CC_INCLUDE_DIR) MARK_AS_ADVANCED(CM256CC_LIBRARIES CM256CC_INCLUDE_DIR) -endif (NOT CM256CC_FOUND) \ No newline at end of file +endif (NOT CM256CC_FOUND) diff --git a/cmake/Modules/FindCodec2.cmake b/cmake/Modules/FindCodec2.cmake index de1bc91b3..c9257b4f5 100644 --- a/cmake/Modules/FindCodec2.cmake +++ b/cmake/Modules/FindCodec2.cmake @@ -53,4 +53,4 @@ if (NOT CODEC2_FOUND) INCLUDE(FindPackageHandleStandardArgs) FIND_PACKAGE_HANDLE_STANDARD_ARGS(CODEC2 DEFAULT_MSG CODEC2_LIBRARIES CODEC2_INCLUDE_DIR) MARK_AS_ADVANCED(CODEC2_LIBRARIES CODEC2_INCLUDE_DIR) -endif (NOT CODEC2_FOUND) \ No newline at end of file +endif (NOT CODEC2_FOUND) diff --git a/cmake/Modules/FindFFmpeg.cmake b/cmake/Modules/FindFFmpeg.cmake index 0d741c4ba..abe9595fe 100644 --- a/cmake/Modules/FindFFmpeg.cmake +++ b/cmake/Modules/FindFFmpeg.cmake @@ -148,4 +148,4 @@ foreach (_component ${FFmpeg_FIND_COMPONENTS}) endforeach () # Give a nice error message if some of the required vars are missing. -find_package_handle_standard_args(FFmpeg DEFAULT_MSG ${_FFmpeg_REQUIRED_VARS}) \ No newline at end of file +find_package_handle_standard_args(FFmpeg DEFAULT_MSG ${_FFmpeg_REQUIRED_VARS}) diff --git a/cmake/Modules/FindLibMbe.cmake b/cmake/Modules/FindLibMbe.cmake index 28638a576..98014e980 100644 --- a/cmake/Modules/FindLibMbe.cmake +++ b/cmake/Modules/FindLibMbe.cmake @@ -31,4 +31,4 @@ if (NOT LIBMBE_FOUND) endif (LIBMBE_INCLUDE_DIR AND LIBMBE_LIBRARIES) mark_as_advanced(LIBMBE_INCLUDE_DIR LIBMBE_LIBRARIES) -endif (NOT LIBMBE_FOUND) \ No newline at end of file +endif (NOT LIBMBE_FOUND) diff --git a/cmake/Modules/FindLibXTRX.cmake b/cmake/Modules/FindLibXTRX.cmake index 8bcd8286a..5154c2503 100644 --- a/cmake/Modules/FindLibXTRX.cmake +++ b/cmake/Modules/FindLibXTRX.cmake @@ -31,4 +31,4 @@ if(NOT LIBXTRX_FOUND) mark_as_advanced(LIBXTRX_INCLUDE_DIRS LIBXTRX_LIBRARY) -endif(NOT LIBXTRX_FOUND) \ No newline at end of file +endif(NOT LIBXTRX_FOUND) diff --git a/cmake/Modules/FindLimeSuite.cmake b/cmake/Modules/FindLimeSuite.cmake index 2aafa2fbe..541d68e42 100644 --- a/cmake/Modules/FindLimeSuite.cmake +++ b/cmake/Modules/FindLimeSuite.cmake @@ -31,4 +31,4 @@ if (NOT LIMESUITE_FOUND) endif (LIMESUITE_INCLUDE_DIR AND LIMESUITE_LIBRARY) mark_as_advanced(LIMESUITE_INCLUDE_DIR LIMESUITE_LIBRARY) -endif (NOT LIMESUITE_FOUND) \ No newline at end of file +endif (NOT LIMESUITE_FOUND) diff --git a/cmake/Modules/FindOpus.cmake b/cmake/Modules/FindOpus.cmake index 2ec4281dc..b3b82345c 100644 --- a/cmake/Modules/FindOpus.cmake +++ b/cmake/Modules/FindOpus.cmake @@ -49,4 +49,4 @@ find_package_handle_standard_args(Opus OPUS_INCLUDE_DIRS OPUS_LIBRARIES HAVE_OPUS_OPUS_H ) -mark_as_advanced(OPUS_INCLUDE_DIRS OPUS_LIBRARIES HAVE_OPUS_OPUS_H) \ No newline at end of file +mark_as_advanced(OPUS_INCLUDE_DIRS OPUS_LIBRARIES HAVE_OPUS_OPUS_H) diff --git a/cmake/Modules/FindSerialDV.cmake b/cmake/Modules/FindSerialDV.cmake index 6d6862699..a0787a91c 100644 --- a/cmake/Modules/FindSerialDV.cmake +++ b/cmake/Modules/FindSerialDV.cmake @@ -31,4 +31,4 @@ if (NOT LIBSERIALDV_FOUND) endif (LIBSERIALDV_INCLUDE_DIR AND LIBSERIALDV_LIBRARY) mark_as_advanced(LIBSERIALDV_INCLUDE_DIR LIBSERIALDV_LIBRARY) -endif (NOT LIBSERIALDV_FOUND) \ No newline at end of file +endif (NOT LIBSERIALDV_FOUND) diff --git a/cmake/include/uninstall.cmake.in b/cmake/include/uninstall.cmake.in index 2c34c8199..2037e3653 100644 --- a/cmake/include/uninstall.cmake.in +++ b/cmake/include/uninstall.cmake.in @@ -18,4 +18,4 @@ foreach(file ${files}) else(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}") message(STATUS "File $ENV{DESTDIR}${file} does not exist.") endif(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}") -endforeach(file) \ No newline at end of file +endforeach(file) diff --git a/debian/compat b/debian/compat index 9a037142a..f599e28b8 100644 --- a/debian/compat +++ b/debian/compat @@ -1 +1 @@ -10 \ No newline at end of file +10 diff --git a/debian/source/format b/debian/source/format index 46ebe0266..163aaf8d8 100644 --- a/debian/source/format +++ b/debian/source/format @@ -1 +1 @@ -3.0 (quilt) \ No newline at end of file +3.0 (quilt) diff --git a/doc/model/SDRAngel.mdj b/doc/model/SDRAngel.mdj index 13dac666c..e4a3648e2 100644 --- a/doc/model/SDRAngel.mdj +++ b/doc/model/SDRAngel.mdj @@ -32722,4 +32722,4 @@ "visibility": "public" } ] -} \ No newline at end of file +} diff --git a/httpserver/httpconnectionhandler.cpp b/httpserver/httpconnectionhandler.cpp index 272458010..376fc74f2 100644 --- a/httpserver/httpconnectionhandler.cpp +++ b/httpserver/httpconnectionhandler.cpp @@ -13,6 +13,7 @@ HttpConnectionHandler::HttpConnectionHandler(QSettings* settings, HttpRequestHan { Q_ASSERT(settings != 0); Q_ASSERT(requestHandler != 0); + setObjectName("httpCnnctnHndlr"); this->settings = settings; this->listenerSettings = 0; this->requestHandler = requestHandler; diff --git a/json_udp_data_format.readme.md b/json_udp_data_format.readme.md index cf27676ba..cdd1ceff6 100644 --- a/json_udp_data_format.readme.md +++ b/json_udp_data_format.readme.md @@ -173,4 +173,4 @@ ... "payload_hex": "ffffffff363e0c47..." } - } \ No newline at end of file + } diff --git a/logging/bufferlogger.cpp b/logging/bufferlogger.cpp index 4f9b0bc6b..c0849de94 100644 --- a/logging/bufferlogger.cpp +++ b/logging/bufferlogger.cpp @@ -1,50 +1,50 @@ -/////////////////////////////////////////////////////////////////////////////////// -// Copyright (C) 2025 Jon Beniston, M7RCE // -// // -// This program is free software; you can redistribute it and/or modify // -// it under the terms of the GNU General Public License as published by // -// the Free Software Foundation as version 3 of the License, or // -// (at your option) any later version. // -// // -// This program is distributed in the hope that it will be useful, // -// but WITHOUT ANY WARRANTY; without even the implied warranty of // -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // -// GNU General Public License V3 for more details. // -// // -// You should have received a copy of the GNU General Public License // -// along with this program. If not, see . // -/////////////////////////////////////////////////////////////////////////////////// - -#include "bufferlogger.h" - -using namespace qtwebapp; - -BufferLogger::BufferLogger(int maxSize, QObject *parent) : - Logger(parent), - m_maxSize(maxSize) -{ -} - -BufferLogger::~BufferLogger() -{ -} - -void BufferLogger::write(const LogMessage* logMessage) -{ - QString text = qPrintable(logMessage->toString("{timestamp} {type} {msg}", "yyyy-MM-dd HH:mm:ss.zzz")); - m_messages.enqueue(text); - while (m_messages.size() > m_maxSize) { - m_messages.dequeue(); - } -} - -QString BufferLogger::getLog() const -{ - QString log; - - for (const auto& s : m_messages) { - log.append(s); - } - - return log; -} +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2025 Jon Beniston, M7RCE // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// (at your option) any later version. // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include "bufferlogger.h" + +using namespace qtwebapp; + +BufferLogger::BufferLogger(int maxSize, QObject *parent) : + Logger(parent), + m_maxSize(maxSize) +{ +} + +BufferLogger::~BufferLogger() +{ +} + +void BufferLogger::write(const LogMessage* logMessage) +{ + QString text = qPrintable(logMessage->toString("{timestamp} {type} {msg}", "yyyy-MM-dd HH:mm:ss.zzz")); + m_messages.enqueue(text); + while (m_messages.size() > m_maxSize) { + m_messages.dequeue(); + } +} + +QString BufferLogger::getLog() const +{ + QString log; + + for (const auto& s : m_messages) { + log.append(s); + } + + return log; +} diff --git a/logging/bufferlogger.h b/logging/bufferlogger.h index fa4807e90..cce4c371a 100644 --- a/logging/bufferlogger.h +++ b/logging/bufferlogger.h @@ -1,46 +1,46 @@ -/////////////////////////////////////////////////////////////////////////////////// -// Copyright (C) 2025 Jon Beniston, M7RCE // -// // -// This program is free software; you can redistribute it and/or modify // -// it under the terms of the GNU General Public License as published by // -// the Free Software Foundation as version 3 of the License, or // -// (at your option) any later version. // -// // -// This program is distributed in the hope that it will be useful, // -// but WITHOUT ANY WARRANTY; without even the implied warranty of // -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // -// GNU General Public License V3 for more details. // -// // -// You should have received a copy of the GNU General Public License // -// along with this program. If not, see . // -/////////////////////////////////////////////////////////////////////////////////// - -#pragma once - -#include - -#include "logger.h" -#include "export.h" - -namespace qtwebapp { - -// A ring-buffer like logger for holding m_maxSize recent log messages -class LOGGING_API BufferLogger : public Logger { - Q_OBJECT - Q_DISABLE_COPY(BufferLogger) - -public: - BufferLogger(int maxSize, QObject *parent = nullptr); - virtual ~BufferLogger(); - - void write(const LogMessage* logMessage) override; - QString getLog() const; // Get last m_maxSize messages as one big string - -private: - - int m_maxSize; // Maximum number of messages to store - QQueue m_messages; // Queue containing last m_maxSize messages - -}; - -} +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2025 Jon Beniston, M7RCE // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// (at your option) any later version. // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#include + +#include "logger.h" +#include "export.h" + +namespace qtwebapp { + +// A ring-buffer like logger for holding m_maxSize recent log messages +class LOGGING_API BufferLogger : public Logger { + Q_OBJECT + Q_DISABLE_COPY(BufferLogger) + +public: + BufferLogger(int maxSize, QObject *parent = nullptr); + virtual ~BufferLogger(); + + void write(const LogMessage* logMessage) override; + QString getLog() const; // Get last m_maxSize messages as one big string + +private: + + int m_maxSize; // Maximum number of messages to store + QQueue m_messages; // Queue containing last m_maxSize messages + +}; + +} diff --git a/logging/readme.md b/logging/readme.md index 8b6af9220..c3f34c31a 100644 --- a/logging/readme.md +++ b/logging/readme.md @@ -6,4 +6,4 @@ This is based on the logging part of QtWebApp from Stefan Frings - [Link to API documentation](http://stefanfrings.de/qtwebapp/api/index.html) - [Link to tutorial](http://stefanfrings.de/qtwebapp/tutorial/index.html) -Some changes have been made to support the option of having a console logging plus optional file logging \ No newline at end of file +Some changes have been made to support the option of having a console logging plus optional file logging diff --git a/modemm17/M17FrameDecoder.h b/modemm17/M17FrameDecoder.h index 2656350b4..ed9c033b7 100644 --- a/modemm17/M17FrameDecoder.h +++ b/modemm17/M17FrameDecoder.h @@ -407,4 +407,4 @@ struct M17FrameDecoder State state() const { return state_; } }; -} // modemm17 \ No newline at end of file +} // modemm17 diff --git a/plugins/channelmimo/beamsteeringcwmod/beamsteeringcwmod.cpp b/plugins/channelmimo/beamsteeringcwmod/beamsteeringcwmod.cpp index 8f303b1e3..4f52f4540 100644 --- a/plugins/channelmimo/beamsteeringcwmod/beamsteeringcwmod.cpp +++ b/plugins/channelmimo/beamsteeringcwmod/beamsteeringcwmod.cpp @@ -102,6 +102,7 @@ void BeamSteeringCWMod::startSources() qDebug("BeamSteeringCWMod::startSources"); m_thread = new QThread(this); + m_thread->setObjectName("BeamSteerCWMod"); m_basebandSource = new BeamSteeringCWModBaseband(); m_basebandSource->moveToThread(m_thread); diff --git a/plugins/channelmimo/doa2/doa2.cpp b/plugins/channelmimo/doa2/doa2.cpp index d26643304..0c73faea5 100644 --- a/plugins/channelmimo/doa2/doa2.cpp +++ b/plugins/channelmimo/doa2/doa2.cpp @@ -105,6 +105,7 @@ void DOA2::startSinks() qDebug("DOA2::startSinks"); m_thread = new QThread(this); + m_thread->setObjectName("DOA2"); m_basebandSink = new DOA2Baseband(m_fftSize); m_basebandSink->setScopeSink(&m_scopeSink); m_basebandSink->moveToThread(m_thread); diff --git a/plugins/channelmimo/interferometer/interferometer.cpp b/plugins/channelmimo/interferometer/interferometer.cpp index 6db7cd563..f92f0d30a 100644 --- a/plugins/channelmimo/interferometer/interferometer.cpp +++ b/plugins/channelmimo/interferometer/interferometer.cpp @@ -124,6 +124,7 @@ void Interferometer::startSinks() qDebug("Interferometer::startSinks"); m_thread = new QThread(this); + m_thread->setObjectName("Interferometer"); m_basebandSink = new InterferometerBaseband(m_fftSize); m_basebandSink->setSpectrumSink(&m_spectrumVis); m_basebandSink->setScopeSink(&m_scopeSink); diff --git a/plugins/channelrx/chanalyzer/chanalyzer.cpp b/plugins/channelrx/chanalyzer/chanalyzer.cpp index 0cf5f0c7c..bc49996c5 100644 --- a/plugins/channelrx/chanalyzer/chanalyzer.cpp +++ b/plugins/channelrx/chanalyzer/chanalyzer.cpp @@ -53,6 +53,7 @@ ChannelAnalyzer::ChannelAnalyzer(DeviceAPI *deviceAPI) : { qDebug("ChannelAnalyzer::ChannelAnalyzer"); setObjectName(m_channelId); + m_thread.setObjectName("Channelyzer"); getBasebandSampleRate(); m_basebandSink = new ChannelAnalyzerBaseband(); m_basebandSink->moveToThread(&m_thread); diff --git a/plugins/channelrx/channelpower/channelpower.cpp b/plugins/channelrx/channelpower/channelpower.cpp index 398309cde..d87a0c386 100644 --- a/plugins/channelrx/channelpower/channelpower.cpp +++ b/plugins/channelrx/channelpower/channelpower.cpp @@ -49,6 +49,7 @@ ChannelPower::ChannelPower(DeviceAPI *deviceAPI) : m_centerFrequency(0) { setObjectName(m_channelId); + m_thread.setObjectName("ChannelPower"); m_basebandSink = new ChannelPowerBaseband(); m_basebandSink->setChannel(this); diff --git a/plugins/channelrx/demodadsb/adsbdemod.cpp b/plugins/channelrx/demodadsb/adsbdemod.cpp index fdd49ea81..eb67c05d0 100644 --- a/plugins/channelrx/demodadsb/adsbdemod.cpp +++ b/plugins/channelrx/demodadsb/adsbdemod.cpp @@ -64,6 +64,7 @@ ADSBDemod::ADSBDemod(DeviceAPI *devieAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("ADSBDemodBB"); m_basebandSink = new ADSBDemodBaseband(); m_basebandSink->moveToThread(m_thread); diff --git a/plugins/channelrx/demodadsb/adsbdemodsinkworker.h b/plugins/channelrx/demodadsb/adsbdemodsinkworker.h index 38a8c45d4..ab8e2c3aa 100644 --- a/plugins/channelrx/demodadsb/adsbdemodsinkworker.h +++ b/plugins/channelrx/demodadsb/adsbdemodsinkworker.h @@ -66,6 +66,7 @@ public: m_correlationThresholdLinear(0.02f), m_crc() { + setObjectName("ADSBDemodWork"); } void run() override; MessageQueue *getInputMessageQueue() { return &m_inputMessageQueue; } diff --git a/plugins/channelrx/demodadsb/sideviews/ReadMe.txt b/plugins/channelrx/demodadsb/sideviews/ReadMe.txt index 5bc03889c..b998ad1df 100644 --- a/plugins/channelrx/demodadsb/sideviews/ReadMe.txt +++ b/plugins/channelrx/demodadsb/sideviews/ReadMe.txt @@ -1,18 +1,18 @@ -SECTION FROM THE MANUAL RELATING TO THE USE OF OPERATOR FLAGS - -The operator column can be used to display a graphic for each aircraft, typically to show its -operator. Operator flag graphic files must be in .bmp format and must be placed in an -OperatorFlags subdirectory. To set an aircraft to display the operator flag, enter the name of -the file minus the .bmp extension into the OperatorFlagCode of the Edit Aircraft Details dialog -box. - -For example, if you enter “BAW” into the OperatorFlagCode field of an aircraft, and you have -previously placed the file “BAW.bmp” into the directory -C:\Program Files\Kinetic\BaseStation\OperatorFlags, then the baw bitmap will be displayed in the -Operator column for that aircraft. - -Note: We do not envisage users typically entering these codes using this interface. Instead, we -have provided this feature so that those existing third party applications that use BaseStation’s -database interface to write registration data into the database can write in flag codes matching -existing flag data sets, allowing the users of those third party products to have operator flags -automatically appear. \ No newline at end of file +SECTION FROM THE MANUAL RELATING TO THE USE OF OPERATOR FLAGS + +The operator column can be used to display a graphic for each aircraft, typically to show its +operator. Operator flag graphic files must be in .bmp format and must be placed in an +OperatorFlags subdirectory. To set an aircraft to display the operator flag, enter the name of +the file minus the .bmp extension into the OperatorFlagCode of the Edit Aircraft Details dialog +box. + +For example, if you enter “BAW” into the OperatorFlagCode field of an aircraft, and you have +previously placed the file “BAW.bmp” into the directory +C:\Program Files\Kinetic\BaseStation\OperatorFlags, then the baw bitmap will be displayed in the +Operator column for that aircraft. + +Note: We do not envisage users typically entering these codes using this interface. Instead, we +have provided this feature so that those existing third party applications that use BaseStation’s +database interface to write registration data into the database can write in flag codes matching +existing flag data sets, allowing the users of those third party products to have operator flags +automatically appear. diff --git a/plugins/channelrx/demodais/aisdemod.cpp b/plugins/channelrx/demodais/aisdemod.cpp index 788bcb984..110193814 100644 --- a/plugins/channelrx/demodais/aisdemod.cpp +++ b/plugins/channelrx/demodais/aisdemod.cpp @@ -51,6 +51,7 @@ AISDemod::AISDemod(DeviceAPI *deviceAPI) : m_centerFrequency(0) { setObjectName(m_channelId); + m_thread.setObjectName("AISDemod"); m_basebandSink = new AISDemodBaseband(this); m_basebandSink->setMessageQueueToChannel(getInputMessageQueue()); diff --git a/plugins/channelrx/demodam/amdemod.cpp b/plugins/channelrx/demodam/amdemod.cpp index e155331bd..5fae85e75 100644 --- a/plugins/channelrx/demodam/amdemod.cpp +++ b/plugins/channelrx/demodam/amdemod.cpp @@ -127,6 +127,7 @@ void AMDemod::start() qDebug("AMDemod::start"); m_thread = new QThread(); + m_thread->setObjectName("AMDemod"); m_basebandSink = new AMDemodBaseband(); m_basebandSink->setChannel(this); m_basebandSink->moveToThread(m_thread); diff --git a/plugins/channelrx/demodapt/aptdemod.cpp b/plugins/channelrx/demodapt/aptdemod.cpp index 4628bb56e..be6ace9ae 100644 --- a/plugins/channelrx/demodapt/aptdemod.cpp +++ b/plugins/channelrx/demodapt/aptdemod.cpp @@ -54,6 +54,8 @@ APTDemod::APTDemod(DeviceAPI *deviceAPI) : m_basebandSampleRate(0) { setObjectName(m_channelId); + m_imageThread.setObjectName("APTDemodImage"); + m_thread.setObjectName("APTDemodBB"); m_basebandSink = new APTDemodBaseband(); m_basebandSink->moveToThread(&m_thread); diff --git a/plugins/channelrx/demodatv/atvdemod.cpp b/plugins/channelrx/demodatv/atvdemod.cpp index 078845d7e..a99e8db78 100644 --- a/plugins/channelrx/demodatv/atvdemod.cpp +++ b/plugins/channelrx/demodatv/atvdemod.cpp @@ -41,6 +41,7 @@ ATVDemod::ATVDemod(DeviceAPI *deviceAPI) : { qDebug("ATVDemod::ATVDemod"); setObjectName(m_channelId); + m_thread.setObjectName("ATVDemodBB"); m_basebandSink = new ATVDemodBaseband(); m_basebandSink->setFifoLabel(QString("%1 [%2:%3]") diff --git a/plugins/channelrx/demodbfm/bfmdemod.cpp b/plugins/channelrx/demodbfm/bfmdemod.cpp index a75a0be1c..f1ded1896 100644 --- a/plugins/channelrx/demodbfm/bfmdemod.cpp +++ b/plugins/channelrx/demodbfm/bfmdemod.cpp @@ -126,6 +126,7 @@ void BFMDemod::start() qDebug() << "BFMDemod::start"; m_thread = new QThread(); + m_thread->setObjectName("BFMDemod"); m_basebandSink = new BFMDemodBaseband(); m_basebandSink->setSpectrumSink(&m_spectrumVis); m_basebandSink->setChannel(this); diff --git a/plugins/channelrx/demodchirpchat/chirpchatdemod.cpp b/plugins/channelrx/demodchirpchat/chirpchatdemod.cpp index 285204884..25012617a 100644 --- a/plugins/channelrx/demodchirpchat/chirpchatdemod.cpp +++ b/plugins/channelrx/demodchirpchat/chirpchatdemod.cpp @@ -136,6 +136,7 @@ void ChirpChatDemod::start() qDebug() << "ChirpChatDemod::start"; m_decoderThread = new QThread(this); + m_decoderThread->setObjectName("CCDemod:decode"); m_decoder = new ChirpChatDemodDecoder(); m_decoder->setOutputMessageQueue(getInputMessageQueue()); m_decoder->setNbSymbolBits(m_settings.m_spreadFactor, m_settings.m_deBits); @@ -151,6 +152,7 @@ void ChirpChatDemod::start() m_decoderThread->start(); m_thread = new QThread(this); + m_thread->setObjectName("CCDemod:bb"); m_basebandSink = new ChirpChatDemodBaseband(); m_basebandSink->setSpectrumSink(&m_spectrumVis); m_basebandSink->setDecoderMessageQueue(m_decoder->getInputMessageQueue()); diff --git a/plugins/channelrx/demoddab/dabdemod.cpp b/plugins/channelrx/demoddab/dabdemod.cpp index c7546dc4b..69f37b864 100644 --- a/plugins/channelrx/demoddab/dabdemod.cpp +++ b/plugins/channelrx/demoddab/dabdemod.cpp @@ -79,6 +79,7 @@ DABDemod::DABDemod(DeviceAPI *deviceAPI) : m_reportTII(0) { setObjectName(m_channelId); + m_thread.setObjectName("DABDemodBB"); m_basebandSink = new DABDemodBaseband(); m_basebandSink->setMessageQueueToChannel(getInputMessageQueue()); diff --git a/plugins/channelrx/demoddatv/datvcstlnlut.h b/plugins/channelrx/demoddatv/datvcstlnlut.h index ac9888398..1ddc6a36f 100644 --- a/plugins/channelrx/demoddatv/datvcstlnlut.h +++ b/plugins/channelrx/demoddatv/datvcstlnlut.h @@ -191,4 +191,4 @@ static cstln_lut * make_dvbs2_constellation( } -#endif // DATV_CSTLN_LUT_H \ No newline at end of file +#endif // DATV_CSTLN_LUT_H diff --git a/plugins/channelrx/demoddatv/datvideorender.h b/plugins/channelrx/demoddatv/datvideorender.h index ed79aa37f..88124e5ed 100644 --- a/plugins/channelrx/demoddatv/datvideorender.h +++ b/plugins/channelrx/demoddatv/datvideorender.h @@ -187,6 +187,7 @@ class DATVideoRenderThread : public QThread public: DATVideoRenderThread() { + setObjectName("DATVideoRender"); m_renderer = nullptr; m_stream = nullptr; m_renderingVideo = false; @@ -194,6 +195,7 @@ class DATVideoRenderThread : public QThread DATVideoRenderThread(DATVideoRender *renderer, DATVideostream *stream) { + setObjectName("DATVideoRender"); m_renderer = renderer; m_stream = stream; m_renderingVideo = false; diff --git a/plugins/channelrx/demoddsc/dscdemod.cpp b/plugins/channelrx/demoddsc/dscdemod.cpp index 5abbacb32..cc71264f6 100644 --- a/plugins/channelrx/demoddsc/dscdemod.cpp +++ b/plugins/channelrx/demoddsc/dscdemod.cpp @@ -52,6 +52,7 @@ DSCDemod::DSCDemod(DeviceAPI *deviceAPI) : m_basebandSampleRate(0) { setObjectName(m_channelId); + m_thread.setObjectName("DSCDemodBB"); m_basebandSink = new DSCDemodBaseband(this); m_basebandSink->setMessageQueueToChannel(getInputMessageQueue()); diff --git a/plugins/channelrx/demoddsd/dsddemod.cpp b/plugins/channelrx/demoddsd/dsddemod.cpp index cba3835d8..ee579bce6 100644 --- a/plugins/channelrx/demoddsd/dsddemod.cpp +++ b/plugins/channelrx/demoddsd/dsddemod.cpp @@ -156,6 +156,7 @@ void DSDDemod::start() qDebug() << "DSDDemod::start"; m_thread = new QThread(); + m_thread->setObjectName("DSDDemod"); m_basebandSink = new DSDDemodBaseband(); m_basebandSink->setFifoLabel(QString("%1 [%2:%3]") .arg(m_channelId) diff --git a/plugins/channelrx/demodendoftrain/endoftraindemod.cpp b/plugins/channelrx/demodendoftrain/endoftraindemod.cpp index e4a58f2dd..86c8054c5 100644 --- a/plugins/channelrx/demodendoftrain/endoftraindemod.cpp +++ b/plugins/channelrx/demodendoftrain/endoftraindemod.cpp @@ -47,6 +47,7 @@ EndOfTrainDemod::EndOfTrainDemod(DeviceAPI *deviceAPI) : m_basebandSampleRate(0) { setObjectName(m_channelId); + m_thread.setObjectName("EndOfTrainBB"); m_basebandSink = new EndOfTrainDemodBaseband(this); m_basebandSink->setMessageQueueToChannel(getInputMessageQueue()); diff --git a/plugins/channelrx/demodfreedv/freedvdemod.cpp b/plugins/channelrx/demodfreedv/freedvdemod.cpp index d5c94e74b..f4ca85a6d 100644 --- a/plugins/channelrx/demodfreedv/freedvdemod.cpp +++ b/plugins/channelrx/demodfreedv/freedvdemod.cpp @@ -55,6 +55,7 @@ FreeDVDemod::FreeDVDemod(DeviceAPI *deviceAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("FreeDVDemod"); m_basebandSink = new FreeDVDemodBaseband(); m_basebandSink->setSpectrumSink(&m_spectrumVis); m_basebandSink->moveToThread(m_thread); diff --git a/plugins/channelrx/demodft8/ft8demod.cpp b/plugins/channelrx/demodft8/ft8demod.cpp index 507e31eab..e08287b1c 100644 --- a/plugins/channelrx/demodft8/ft8demod.cpp +++ b/plugins/channelrx/demodft8/ft8demod.cpp @@ -158,6 +158,7 @@ void FT8Demod::start() qDebug() << "FT8Demod::start"; m_thread = new QThread(); + m_thread->setObjectName("FT8Demod"); m_basebandSink = new FT8DemodBaseband(); m_basebandSink->setFifoLabel(QString("%1 [%2:%3]") .arg(m_channelId) diff --git a/plugins/channelrx/demodft8/ft8demodbaseband.cpp b/plugins/channelrx/demodft8/ft8demodbaseband.cpp index c9188de73..8525c87ae 100644 --- a/plugins/channelrx/demodft8/ft8demodbaseband.cpp +++ b/plugins/channelrx/demodft8/ft8demodbaseband.cpp @@ -42,6 +42,7 @@ FT8DemodBaseband::FT8DemodBaseband() : m_ft8WorkerBuffer = new int16_t[FT8DemodSettings::m_ft8SampleRate*15]; m_workerThread = new QThread(); + m_workerThread->setObjectName("FT8DemodBB:W"); m_ft8DemodWorker = new FT8DemodWorker(); m_ft8DemodWorker->moveToThread(m_workerThread); @@ -63,6 +64,7 @@ FT8DemodBaseband::FT8DemodBaseband() : m_workerThread->start(); m_pskReporterThread = new QThread(); + m_pskReporterThread->setObjectName("pskReporter"); m_pskReporterWorker = new PskReporterWorker(); m_ft8DemodWorker->setPSKReportingMessageQueue(m_pskReporterWorker->getInputMessageQueue()); m_pskReporterWorker->moveToThread(m_pskReporterThread); diff --git a/plugins/channelrx/demodils/ilsdemod.cpp b/plugins/channelrx/demodils/ilsdemod.cpp index 8879d1574..147aa8604 100644 --- a/plugins/channelrx/demodils/ilsdemod.cpp +++ b/plugins/channelrx/demodils/ilsdemod.cpp @@ -60,6 +60,7 @@ ILSDemod::ILSDemod(DeviceAPI *deviceAPI) : m_angle(NAN) { setObjectName(m_channelId); + m_thread.setObjectName("ILSDemodBB"); m_basebandSink = new ILSDemodBaseband(); m_basebandSink->setMessageQueueToChannel(getInputMessageQueue()); diff --git a/plugins/channelrx/demodinmarsat/inmarsatdemod.cpp b/plugins/channelrx/demodinmarsat/inmarsatdemod.cpp index f91c32824..da1b937a3 100644 --- a/plugins/channelrx/demodinmarsat/inmarsatdemod.cpp +++ b/plugins/channelrx/demodinmarsat/inmarsatdemod.cpp @@ -47,6 +47,7 @@ InmarsatDemod::InmarsatDemod(DeviceAPI *deviceAPI) : m_basebandSampleRate(0) { setObjectName(m_channelId); + m_thread.setObjectName("InmarsatBB"); m_basebandSink = new InmarsatDemodBaseband(this); m_basebandSink->setMessageQueueToChannel(getInputMessageQueue()); diff --git a/plugins/channelrx/demodm17/m17demod.cpp b/plugins/channelrx/demodm17/m17demod.cpp index ba3254399..d912ea615 100644 --- a/plugins/channelrx/demodm17/m17demod.cpp +++ b/plugins/channelrx/demodm17/m17demod.cpp @@ -133,6 +133,7 @@ void M17Demod::start() qDebug() << "M17Demod::start"; m_thread = new QThread(this); + m_thread->setObjectName("M17Demod"); m_basebandSink = new M17DemodBaseband(); m_basebandSink->setChannel(this); m_basebandSink->setDemodInputMessageQueue(&m_inputMessageQueue); diff --git a/plugins/channelrx/demodmeshcore/meshcoredemod.cpp b/plugins/channelrx/demodmeshcore/meshcoredemod.cpp index c301e3cc4..6175f025f 100644 --- a/plugins/channelrx/demodmeshcore/meshcoredemod.cpp +++ b/plugins/channelrx/demodmeshcore/meshcoredemod.cpp @@ -296,6 +296,7 @@ void MeshcoreDemod::startPipelines(const std::vector& configs) runtime.settings = config.settings; runtime.decoderThread = new QThread(); + runtime.decoderThread->setObjectName(QString("MCDemod:dc:%1").arg(runtime.id)); runtime.decoder = new MeshcoreDemodDecoder(); runtime.decoder->setOutputMessageQueue(getInputMessageQueue()); runtime.decoder->setPipelineMetadata(runtime.id, runtime.name, runtime.presetName); @@ -305,6 +306,7 @@ void MeshcoreDemod::startPipelines(const std::vector& configs) runtime.decoderThread->start(); runtime.basebandThread = new QThread(); + runtime.basebandThread->setObjectName(QString("MCDemod:bb:%1").arg(runtime.id)); runtime.basebandSink = new MeshcoreDemodBaseband(); if (config.id == 0) { @@ -464,6 +466,7 @@ void MeshcoreDemod::applyExtraPipelineSettings(const QVectorsetObjectName(QString("MCDemod:dc:%1").arg(runtime.id)); runtime.decoder = new MeshcoreDemodDecoder(); runtime.decoder->setOutputMessageQueue(getInputMessageQueue()); runtime.decoder->setPipelineMetadata(runtime.id, runtime.name, runtime.presetName); @@ -472,6 +475,7 @@ void MeshcoreDemod::applyExtraPipelineSettings(const QVectorstart(); runtime.basebandThread = new QThread(); + runtime.basebandThread->setObjectName(QString("MCDemod:bb:%1").arg(runtime.id)); runtime.basebandSink = new MeshcoreDemodBaseband(); // Secondary pipelines (id != 0) do not own the spectrum visualiser. runtime.basebandSink->setDecoderMessageQueue(runtime.decoder->getInputMessageQueue()); diff --git a/plugins/channelrx/demodmeshtastic/meshtasticdemod.cpp b/plugins/channelrx/demodmeshtastic/meshtasticdemod.cpp index 74afae893..e54011d6c 100644 --- a/plugins/channelrx/demodmeshtastic/meshtasticdemod.cpp +++ b/plugins/channelrx/demodmeshtastic/meshtasticdemod.cpp @@ -295,6 +295,7 @@ void MeshtasticDemod::startPipelines(const std::vector& configs) runtime.settings = config.settings; runtime.decoderThread = new QThread(); + runtime.decoderThread->setObjectName(QString("Mesh:dc:%1").arg(config.id)); runtime.decoder = new MeshtasticDemodDecoder(); runtime.decoder->setOutputMessageQueue(getInputMessageQueue()); runtime.decoder->setPipelineMetadata(runtime.id, runtime.name, runtime.presetName); @@ -304,6 +305,7 @@ void MeshtasticDemod::startPipelines(const std::vector& configs) runtime.decoderThread->start(); runtime.basebandThread = new QThread(); + runtime.basebandThread->setObjectName(QString("Mesh:bb:%1").arg(config.id)); runtime.basebandSink = new MeshtasticDemodBaseband(); if (config.id == 0) { @@ -463,6 +465,7 @@ void MeshtasticDemod::applyExtraPipelineSettings(const QVectorsetObjectName(QString("Mesh:dc:%1").arg(config.id)); runtime.decoder = new MeshtasticDemodDecoder(); runtime.decoder->setOutputMessageQueue(getInputMessageQueue()); runtime.decoder->setPipelineMetadata(runtime.id, runtime.name, runtime.presetName); @@ -471,6 +474,7 @@ void MeshtasticDemod::applyExtraPipelineSettings(const QVectorstart(); runtime.basebandThread = new QThread(); + runtime.basebandThread->setObjectName(QString("Mesh:bb:%1").arg(config.id)); runtime.basebandSink = new MeshtasticDemodBaseband(); // Secondary pipelines (id != 0) do not own the spectrum visualiser. runtime.basebandSink->setDecoderMessageQueue(runtime.decoder->getInputMessageQueue()); diff --git a/plugins/channelrx/demodnavtex/navtexdemod.cpp b/plugins/channelrx/demodnavtex/navtexdemod.cpp index 42c86a4fe..5f7fb4e37 100644 --- a/plugins/channelrx/demodnavtex/navtexdemod.cpp +++ b/plugins/channelrx/demodnavtex/navtexdemod.cpp @@ -52,6 +52,7 @@ NavtexDemod::NavtexDemod(DeviceAPI *deviceAPI) : m_basebandSampleRate(0) { setObjectName(m_channelId); + m_thread.setObjectName("NavtexDemodBB"); m_basebandSink = new NavtexDemodBaseband(); m_basebandSink->setMessageQueueToChannel(getInputMessageQueue()); diff --git a/plugins/channelrx/demodnfm/nfmdemod.cpp b/plugins/channelrx/demodnfm/nfmdemod.cpp index 2991f9422..b9583d581 100644 --- a/plugins/channelrx/demodnfm/nfmdemod.cpp +++ b/plugins/channelrx/demodnfm/nfmdemod.cpp @@ -129,6 +129,7 @@ void NFMDemod::start() qDebug() << "NFMDemod::start"; m_thread = new QThread(); + m_thread->setObjectName("NFMDemod"); m_basebandSink = new NFMDemodBaseband(); m_basebandSink->setFifoLabel(QString("%1 [%2:%3]") .arg(m_channelId) diff --git a/plugins/channelrx/demodpacket/packetdemod.cpp b/plugins/channelrx/demodpacket/packetdemod.cpp index 9ba17d67f..f249a6d0a 100644 --- a/plugins/channelrx/demodpacket/packetdemod.cpp +++ b/plugins/channelrx/demodpacket/packetdemod.cpp @@ -51,6 +51,7 @@ PacketDemod::PacketDemod(DeviceAPI *deviceAPI) : m_basebandSampleRate(0) { setObjectName(m_channelId); + m_thread.setObjectName("PacketDemodBB"); m_basebandSink = new PacketDemodBaseband(this); m_basebandSink->setMessageQueueToChannel(getInputMessageQueue()); diff --git a/plugins/channelrx/demodpager/pagerdemod.cpp b/plugins/channelrx/demodpager/pagerdemod.cpp index cc3666cba..73a0fc24c 100644 --- a/plugins/channelrx/demodpager/pagerdemod.cpp +++ b/plugins/channelrx/demodpager/pagerdemod.cpp @@ -47,6 +47,7 @@ PagerDemod::PagerDemod(DeviceAPI *deviceAPI) : m_centerFrequency(0) { setObjectName(m_channelId); + m_thread.setObjectName("PagerDemodBB"); m_basebandSink = new PagerDemodBaseband(); m_basebandSink->setMessageQueueToChannel(getInputMessageQueue()); diff --git a/plugins/channelrx/demodradiosonde/radiosondedemod.cpp b/plugins/channelrx/demodradiosonde/radiosondedemod.cpp index 2553f2a9c..bb8bab047 100644 --- a/plugins/channelrx/demodradiosonde/radiosondedemod.cpp +++ b/plugins/channelrx/demodradiosonde/radiosondedemod.cpp @@ -49,6 +49,7 @@ RadiosondeDemod::RadiosondeDemod(DeviceAPI *deviceAPI) : m_basebandSampleRate(0) { setObjectName(m_channelId); + m_thread.setObjectName("RadiosondeDeBB"); m_basebandSink = new RadiosondeDemodBaseband(this); m_basebandSink->setMessageQueueToChannel(getInputMessageQueue()); diff --git a/plugins/channelrx/demodrtty/rttydemod.cpp b/plugins/channelrx/demodrtty/rttydemod.cpp index b21062cac..d08906664 100644 --- a/plugins/channelrx/demodrtty/rttydemod.cpp +++ b/plugins/channelrx/demodrtty/rttydemod.cpp @@ -52,6 +52,7 @@ RttyDemod::RttyDemod(DeviceAPI *deviceAPI) : m_basebandSampleRate(0) { setObjectName(m_channelId); + m_thread.setObjectName("RttyDemodBB"); m_basebandSink = new RttyDemodBaseband(); m_basebandSink->setMessageQueueToChannel(getInputMessageQueue()); diff --git a/plugins/channelrx/demodssb/ssbdemod.cpp b/plugins/channelrx/demodssb/ssbdemod.cpp index d4cb23202..626636b1e 100644 --- a/plugins/channelrx/demodssb/ssbdemod.cpp +++ b/plugins/channelrx/demodssb/ssbdemod.cpp @@ -143,6 +143,7 @@ void SSBDemod::start() qDebug() << "SSBDemod::start"; m_thread = new QThread(); + m_thread->setObjectName("SSBDemod"); m_basebandSink = new SSBDemodBaseband(); m_basebandSink->setFifoLabel(QString("%1 [%2:%3]") .arg(m_channelId) diff --git a/plugins/channelrx/demodvor/vordemod.cpp b/plugins/channelrx/demodvor/vordemod.cpp index 3740b5a26..774969cd7 100644 --- a/plugins/channelrx/demodvor/vordemod.cpp +++ b/plugins/channelrx/demodvor/vordemod.cpp @@ -133,6 +133,7 @@ void VORDemod::start() qDebug("VORDemod::start"); m_thread = new QThread(); + m_thread->setObjectName("VORDemod"); m_basebandSink = new VORDemodBaseband(); m_basebandSink->setMessageQueueToChannel(getInputMessageQueue()); m_basebandSink->moveToThread(m_thread); diff --git a/plugins/channelrx/demodvormc/vordemodmc.cpp b/plugins/channelrx/demodvormc/vordemodmc.cpp index 315cf2edd..afe1d16d1 100644 --- a/plugins/channelrx/demodvormc/vordemodmc.cpp +++ b/plugins/channelrx/demodvormc/vordemodmc.cpp @@ -50,6 +50,7 @@ VORDemodMC::VORDemodMC(DeviceAPI *deviceAPI) : m_basebandSampleRate(0) { setObjectName(m_channelId); + m_thread.setObjectName("VORDemodMCBB"); m_basebandSink = new VORDemodMCBaseband(); m_basebandSink->moveToThread(&m_thread); diff --git a/plugins/channelrx/demodwfm/wfmdemod.cpp b/plugins/channelrx/demodwfm/wfmdemod.cpp index c60d72f2d..7776642fc 100644 --- a/plugins/channelrx/demodwfm/wfmdemod.cpp +++ b/plugins/channelrx/demodwfm/wfmdemod.cpp @@ -132,6 +132,7 @@ void WFMDemod::start() qDebug() << "WFMDemod::start"; m_thread = new QThread(this); + m_thread->setObjectName("WFMDemod"); m_basebandSink = new WFMDemodBaseband(); m_basebandSink->setChannel(this); m_basebandSink->moveToThread(m_thread); diff --git a/plugins/channelrx/filesink/filesink.cpp b/plugins/channelrx/filesink/filesink.cpp index 324a26fa1..87c1cd9d6 100644 --- a/plugins/channelrx/filesink/filesink.cpp +++ b/plugins/channelrx/filesink/filesink.cpp @@ -146,6 +146,7 @@ void FileSink::start() qDebug("FileSink::start"); m_thread = new QThread(); + m_thread->setObjectName("FileSink"); m_basebandSink = new FileSinkBaseband(); m_basebandSink->setFifoLabel(QString("%1 [%2:%3]") .arg(m_channelId) diff --git a/plugins/channelrx/freqscanner/freqscanner.cpp b/plugins/channelrx/freqscanner/freqscanner.cpp index 452639367..f02972633 100644 --- a/plugins/channelrx/freqscanner/freqscanner.cpp +++ b/plugins/channelrx/freqscanner/freqscanner.cpp @@ -154,6 +154,7 @@ void FreqScanner::start() qDebug("FreqScanner::start"); m_thread = new QThread(); + m_thread->setObjectName("FreqScanner"); m_basebandSink = new FreqScannerBaseband(this); m_basebandSink->setFifoLabel(QString("%1 [%2:%3]") .arg(m_channelId) diff --git a/plugins/channelrx/freqtracker/freqtracker.cpp b/plugins/channelrx/freqtracker/freqtracker.cpp index ac46b5095..86c814578 100644 --- a/plugins/channelrx/freqtracker/freqtracker.cpp +++ b/plugins/channelrx/freqtracker/freqtracker.cpp @@ -130,6 +130,7 @@ void FreqTracker::start() qDebug("FreqTracker::start"); m_thread = new QThread(this); + m_thread->setObjectName("FreqTracker"); m_basebandSink = new FreqTrackerBaseband(); m_basebandSink->setSpectrumSink(&m_spectrumVis); m_basebandSink->setMessageQueueToInput(getInputMessageQueue()); diff --git a/plugins/channelrx/heatmap/heatmap.cpp b/plugins/channelrx/heatmap/heatmap.cpp index e068f321d..78c1f7958 100644 --- a/plugins/channelrx/heatmap/heatmap.cpp +++ b/plugins/channelrx/heatmap/heatmap.cpp @@ -48,6 +48,7 @@ HeatMap::HeatMap(DeviceAPI *deviceAPI) : m_centerFrequency(0) { setObjectName(m_channelId); + m_thread.setObjectName("HeatMapBB"); m_basebandSink = new HeatMapBaseband(); m_basebandSink->setMessageQueueToChannel(getInputMessageQueue()); diff --git a/plugins/channelrx/localsink/localsink.cpp b/plugins/channelrx/localsink/localsink.cpp index fbd6a7b3f..ff5036366 100644 --- a/plugins/channelrx/localsink/localsink.cpp +++ b/plugins/channelrx/localsink/localsink.cpp @@ -148,6 +148,7 @@ void LocalSink::startProcessing() qDebug("LocalSink::startProcessing"); m_thread = new QThread(this); + m_thread->setObjectName("LocalSink"); m_basebandSink = new LocalSinkBaseband(); m_basebandSink->setSpectrumSink(&m_spectrumVis); m_basebandSink->moveToThread(m_thread); diff --git a/plugins/channelrx/localsink/localsinksink.cpp b/plugins/channelrx/localsink/localsinksink.cpp index d3dcf60ab..26fe15c7d 100644 --- a/plugins/channelrx/localsink/localsinksink.cpp +++ b/plugins/channelrx/localsink/localsinksink.cpp @@ -38,6 +38,7 @@ LocalSinkSink::LocalSinkSink() : m_sampleRate(48000), m_deviceSampleRate(48000) { + m_sinkWorkerThread.setObjectName("LocalSinkSinkWr"); m_sampleFifo.setSize(SampleSinkFifo::getSizePolicy(4000000)); // m_fftFilter = new fftfilt(0.1f, 0.4f, 1<setMessageQueueToChannel(getInputMessageQueue()); diff --git a/plugins/channelrx/radioastronomy/radioastronomy.cpp b/plugins/channelrx/radioastronomy/radioastronomy.cpp index 1d767fc85..0e7947eab 100644 --- a/plugins/channelrx/radioastronomy/radioastronomy.cpp +++ b/plugins/channelrx/radioastronomy/radioastronomy.cpp @@ -74,6 +74,8 @@ RadioAstronomy::RadioAstronomy(DeviceAPI *deviceAPI) : { qDebug("RadioAstronomy::RadioAstronomy"); setObjectName(m_channelId); + m_thread.setObjectName("RadioAstroBB"); + m_workerThread.setObjectName("RadioAstroWk"); m_basebandSink = new RadioAstronomyBaseband(this); m_basebandSink->setMessageQueueToChannel(getInputMessageQueue()); diff --git a/plugins/channelrx/radioclock/radioclock.cpp b/plugins/channelrx/radioclock/radioclock.cpp index 88b8da6ed..c2b16a5ca 100644 --- a/plugins/channelrx/radioclock/radioclock.cpp +++ b/plugins/channelrx/radioclock/radioclock.cpp @@ -51,6 +51,7 @@ RadioClock::RadioClock(DeviceAPI *deviceAPI) : m_centerFrequency(0) { setObjectName(m_channelId); + m_thread.setObjectName("RadioClockBB"); m_basebandSink = new RadioClockBaseband(); m_basebandSink->setMessageQueueToChannel(getInputMessageQueue()); diff --git a/plugins/channelrx/remotesink/remotesink.cpp b/plugins/channelrx/remotesink/remotesink.cpp index 54500050e..27c52ad1e 100644 --- a/plugins/channelrx/remotesink/remotesink.cpp +++ b/plugins/channelrx/remotesink/remotesink.cpp @@ -130,6 +130,7 @@ void RemoteSink::start() qDebug("RemoteSink::start: m_basebandSampleRate: %d", m_basebandSampleRate); m_thread = new QThread(); + m_thread->setObjectName("RemoteSink"); m_basebandSink = new RemoteSinkBaseband(); m_basebandSink->moveToThread(m_thread); diff --git a/plugins/channelrx/remotesink/remotesinksink.cpp b/plugins/channelrx/remotesink/remotesinksink.cpp index fbe19e9f3..60142cd3a 100644 --- a/plugins/channelrx/remotesink/remotesinksink.cpp +++ b/plugins/channelrx/remotesink/remotesinksink.cpp @@ -44,6 +44,7 @@ RemoteSinkSink::RemoteSinkSink() : m_dataPort(9090) { qDebug("RemoteSinkSink::RemoteSinkSink"); + m_senderThread.setObjectName("RmtSnkSnkSnd"); applySettings(QStringList(), m_settings, true); } diff --git a/plugins/channelrx/remotetcpsink/remotetcpsink.cpp b/plugins/channelrx/remotetcpsink/remotetcpsink.cpp index 75dd8e262..5cd5cf40f 100644 --- a/plugins/channelrx/remotetcpsink/remotetcpsink.cpp +++ b/plugins/channelrx/remotetcpsink/remotetcpsink.cpp @@ -59,6 +59,7 @@ RemoteTCPSink::RemoteTCPSink(DeviceAPI *deviceAPI) : m_removeRequest(nullptr) { setObjectName(m_channelId); + m_thread.setObjectName("RemoteTCPSinkBB"); m_basebandSink = new RemoteTCPSinkBaseband(); m_basebandSink->setMessageQueueToChannel(&m_inputMessageQueue); diff --git a/plugins/channelrx/remotetcpsink/remotetcpsinksettingsdialog.cpp b/plugins/channelrx/remotetcpsink/remotetcpsinksettingsdialog.cpp index 0b45356aa..76a0ff391 100644 --- a/plugins/channelrx/remotetcpsink/remotetcpsinksettingsdialog.cpp +++ b/plugins/channelrx/remotetcpsink/remotetcpsinksettingsdialog.cpp @@ -384,4 +384,4 @@ void RemoteTCPSinkSettingsDialog::updateRotatorList(const AvailableChannelOrFeat ui->rotator->blockSignals(false); displayEnabled(); -} \ No newline at end of file +} diff --git a/plugins/channelrx/sigmffilesink/sigmffilesink.cpp b/plugins/channelrx/sigmffilesink/sigmffilesink.cpp index 99243915d..c11b145d0 100644 --- a/plugins/channelrx/sigmffilesink/sigmffilesink.cpp +++ b/plugins/channelrx/sigmffilesink/sigmffilesink.cpp @@ -145,6 +145,7 @@ void SigMFFileSink::start() qDebug("SigMFFileSink::start"); m_thread = new QThread(); + m_thread->setObjectName("SigMFFileSink"); m_basebandSink = new SigMFFileSinkBaseband(); m_basebandSink->setFifoLabel(QString("%1 [%2:%3]") .arg(m_channelId) diff --git a/plugins/channelrx/udpsink/udpsink.cpp b/plugins/channelrx/udpsink/udpsink.cpp index 5cf65450a..38be11b03 100644 --- a/plugins/channelrx/udpsink/udpsink.cpp +++ b/plugins/channelrx/udpsink/udpsink.cpp @@ -57,6 +57,7 @@ UDPSink::UDPSink(DeviceAPI *deviceAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("UDPSink"); m_basebandSink = new UDPSinkBaseband(); m_basebandSink->setSpectrum(&m_spectrumVis); m_basebandSink->moveToThread(m_thread); diff --git a/plugins/channelrx/wdsprx/wdsprx.cpp b/plugins/channelrx/wdsprx/wdsprx.cpp index 70642ab15..a0628fb62 100644 --- a/plugins/channelrx/wdsprx/wdsprx.cpp +++ b/plugins/channelrx/wdsprx/wdsprx.cpp @@ -145,6 +145,7 @@ void WDSPRx::start() qDebug() << "WDSPRx::start"; m_thread = new QThread(); + m_thread->setObjectName("WDSPRx"); m_basebandSink = new WDSPRxBaseband(); m_basebandSink->setFifoLabel(QString("%1 [%2:%3]") .arg(m_channelId) diff --git a/plugins/channeltx/filesource/filesource.cpp b/plugins/channeltx/filesource/filesource.cpp index 61cafe420..0fab1982c 100644 --- a/plugins/channeltx/filesource/filesource.cpp +++ b/plugins/channeltx/filesource/filesource.cpp @@ -59,6 +59,7 @@ FileSource::FileSource(DeviceAPI *deviceAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("FileSource"); m_basebandSource = new FileSourceBaseband(); m_basebandSource->moveToThread(m_thread); diff --git a/plugins/channeltx/localsource/localsource.cpp b/plugins/channeltx/localsource/localsource.cpp index 2d0ba2d71..185a76824 100644 --- a/plugins/channeltx/localsource/localsource.cpp +++ b/plugins/channeltx/localsource/localsource.cpp @@ -53,6 +53,7 @@ LocalSource::LocalSource(DeviceAPI *deviceAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("LocalSource"); m_basebandSource = new LocalSourceBaseband(); m_basebandSource->moveToThread(m_thread); diff --git a/plugins/channeltx/localsource/localsourcesource.cpp b/plugins/channeltx/localsource/localsourcesource.cpp index 266abd0f2..e2ceb0158 100644 --- a/plugins/channeltx/localsource/localsourcesource.cpp +++ b/plugins/channeltx/localsource/localsourcesource.cpp @@ -26,7 +26,9 @@ LocalSourceSource::LocalSourceSource() : m_chunkSize(0), m_localSamplesIndex(0), m_localSamplesIndexOffset(0) -{} +{ + m_sinkWorkerThread.setObjectName("LocalSrcSrcWrk"); +} LocalSourceSource::~LocalSourceSource() {} diff --git a/plugins/channeltx/mod802.15.4/ieee_802_15_4_mod.cpp b/plugins/channeltx/mod802.15.4/ieee_802_15_4_mod.cpp index d6fddf69b..fe6501ddd 100644 --- a/plugins/channeltx/mod802.15.4/ieee_802_15_4_mod.cpp +++ b/plugins/channeltx/mod802.15.4/ieee_802_15_4_mod.cpp @@ -60,6 +60,7 @@ IEEE_802_15_4_Mod::IEEE_802_15_4_Mod(DeviceAPI *deviceAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("802_15_4_Mod"); m_basebandSource = new IEEE_802_15_4_ModBaseband(); m_basebandSource->setSpectrumSampleSink(&m_spectrumVis); m_basebandSource->moveToThread(m_thread); diff --git a/plugins/channeltx/modais/aismod.cpp b/plugins/channeltx/modais/aismod.cpp index a4e36e233..67259d112 100644 --- a/plugins/channeltx/modais/aismod.cpp +++ b/plugins/channeltx/modais/aismod.cpp @@ -62,6 +62,7 @@ AISMod::AISMod(DeviceAPI *deviceAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("AISMod"); m_basebandSource = new AISModBaseband(); m_basebandSource->setSpectrumSampleSink(&m_spectrumVis); m_basebandSource->setChannel(this); diff --git a/plugins/channeltx/modam/ammod.cpp b/plugins/channeltx/modam/ammod.cpp index b1b2f2c32..3d9984ef2 100644 --- a/plugins/channeltx/modam/ammod.cpp +++ b/plugins/channeltx/modam/ammod.cpp @@ -116,6 +116,7 @@ void AMMod::start() qDebug("AMMod::start"); m_thread = new QThread(this); + m_thread->setObjectName("AMMod"); m_basebandSource = new AMModBaseband(); m_basebandSource->setInputFileStream(&m_ifstream); m_basebandSource->setChannel(this); diff --git a/plugins/channeltx/modatv/atvmod.cpp b/plugins/channeltx/modatv/atvmod.cpp index 57a9858a8..5971dad98 100644 --- a/plugins/channeltx/modatv/atvmod.cpp +++ b/plugins/channeltx/modatv/atvmod.cpp @@ -62,6 +62,7 @@ ATVMod::ATVMod(DeviceAPI *deviceAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("ATVMod"); m_basebandSource = new ATVModBaseband(); m_basebandSource->moveToThread(m_thread); diff --git a/plugins/channeltx/modchirpchat/chirpchatmod.cpp b/plugins/channeltx/modchirpchat/chirpchatmod.cpp index 100ed308c..dd6854fe3 100644 --- a/plugins/channeltx/modchirpchat/chirpchatmod.cpp +++ b/plugins/channeltx/modchirpchat/chirpchatmod.cpp @@ -61,6 +61,7 @@ ChirpChatMod::ChirpChatMod(DeviceAPI *deviceAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("ChirpChatMod"); m_basebandSource = new ChirpChatModBaseband(); m_basebandSource->moveToThread(m_thread); diff --git a/plugins/channeltx/moddatv/datvmod.cpp b/plugins/channeltx/moddatv/datvmod.cpp index 9a6a8bb3b..924974a78 100644 --- a/plugins/channeltx/moddatv/datvmod.cpp +++ b/plugins/channeltx/moddatv/datvmod.cpp @@ -63,6 +63,7 @@ DATVMod::DATVMod(DeviceAPI *deviceAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("DATVMod"); m_basebandSource = new DATVModBaseband(); m_basebandSource->moveToThread(m_thread); diff --git a/plugins/channeltx/modfreedv/freedvmod.cpp b/plugins/channeltx/modfreedv/freedvmod.cpp index 52cb50f25..8ec927252 100644 --- a/plugins/channeltx/modfreedv/freedvmod.cpp +++ b/plugins/channeltx/modfreedv/freedvmod.cpp @@ -63,6 +63,7 @@ FreeDVMod::FreeDVMod(DeviceAPI *deviceAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("FreeDVMod"); m_basebandSource = new FreeDVModBaseband(); m_basebandSource->setSpectrumSampleSink(&m_spectrumVis); m_basebandSource->setInputFileStream(&m_ifstream); diff --git a/plugins/channeltx/modm17/m17mod.cpp b/plugins/channeltx/modm17/m17mod.cpp index 2dd1d4974..0d7ea0645 100644 --- a/plugins/channeltx/modm17/m17mod.cpp +++ b/plugins/channeltx/modm17/m17mod.cpp @@ -62,6 +62,7 @@ M17Mod::M17Mod(DeviceAPI *deviceAPI) : m_loopPacketTimer.setInterval(m_settings.m_loopPacketInterval*1000); m_thread = new QThread(this); + m_thread->setObjectName("M17Mod"); m_basebandSource = new M17ModBaseband(); m_basebandSource->setInputFileStream(&m_ifstream); m_basebandSource->setChannel(this); diff --git a/plugins/channeltx/modm17/m17modsource.cpp b/plugins/channeltx/modm17/m17modsource.cpp index 58aadd27d..888eab0e3 100644 --- a/plugins/channeltx/modm17/m17modsource.cpp +++ b/plugins/channeltx/modm17/m17modsource.cpp @@ -43,6 +43,7 @@ M17ModSource::M17ModSource() : m_preemphasisFilter(m_preemphasis*48000) { m_audioFifo.setLabel("M17ModSource.m_audioFifo"); + m_processorThread.setObjectName("M17ModSourceWrk"); m_feedbackAudioFifo.setLabel("M17ModSource.m_feedbackAudioFifo"); m_audioBuffer.resize(24000); m_audioBufferFill = 0; diff --git a/plugins/channeltx/modmeshcore/meshcoremod.cpp b/plugins/channeltx/modmeshcore/meshcoremod.cpp index 99dea0c39..b8f0cec08 100644 --- a/plugins/channeltx/modmeshcore/meshcoremod.cpp +++ b/plugins/channeltx/modmeshcore/meshcoremod.cpp @@ -66,6 +66,7 @@ MeshcoreMod::MeshcoreMod(DeviceAPI *deviceAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("MeshcoreMod"); m_basebandSource = new MeshcoreModBaseband(); m_basebandSource->moveToThread(m_thread); diff --git a/plugins/channeltx/modmeshtastic/meshtasticmod.cpp b/plugins/channeltx/modmeshtastic/meshtasticmod.cpp index d3703fdff..92d8aab76 100644 --- a/plugins/channeltx/modmeshtastic/meshtasticmod.cpp +++ b/plugins/channeltx/modmeshtastic/meshtasticmod.cpp @@ -64,6 +64,7 @@ MeshtasticMod::MeshtasticMod(DeviceAPI *deviceAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("MeshtasticMod"); m_basebandSource = new MeshtasticModBaseband(); m_basebandSource->moveToThread(m_thread); diff --git a/plugins/channeltx/modnfm/nfmmod.cpp b/plugins/channeltx/modnfm/nfmmod.cpp index d057b5257..fe0e8567a 100644 --- a/plugins/channeltx/modnfm/nfmmod.cpp +++ b/plugins/channeltx/modnfm/nfmmod.cpp @@ -113,6 +113,7 @@ void NFMMod::start() qDebug("NFMMod::start"); m_thread = new QThread(this); + m_thread->setObjectName("NFMMod"); m_basebandSource = new NFMModBaseband(); m_basebandSource->setInputFileStream(&m_ifstream); m_basebandSource->setChannel(this); diff --git a/plugins/channeltx/modpacket/packetmod.cpp b/plugins/channeltx/modpacket/packetmod.cpp index ea08d3e8a..29be8e9f6 100644 --- a/plugins/channeltx/modpacket/packetmod.cpp +++ b/plugins/channeltx/modpacket/packetmod.cpp @@ -64,6 +64,7 @@ PacketMod::PacketMod(DeviceAPI *deviceAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("PacketMod"); m_basebandSource = new PacketModBaseband(); m_basebandSource->setSpectrumSampleSink(&m_spectrumVis); m_basebandSource->setChannel(this); diff --git a/plugins/channeltx/modpsk31/psk31mod.cpp b/plugins/channeltx/modpsk31/psk31mod.cpp index 830327102..5ec40541c 100644 --- a/plugins/channeltx/modpsk31/psk31mod.cpp +++ b/plugins/channeltx/modpsk31/psk31mod.cpp @@ -60,6 +60,7 @@ PSK31::PSK31(DeviceAPI *deviceAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("PSK31"); m_basebandSource = new PSK31Baseband(); m_basebandSource->setSpectrumSampleSink(&m_spectrumVis); m_basebandSource->setChannel(this); diff --git a/plugins/channeltx/modrtty/rttymod.cpp b/plugins/channeltx/modrtty/rttymod.cpp index 90e06175c..96f404507 100644 --- a/plugins/channeltx/modrtty/rttymod.cpp +++ b/plugins/channeltx/modrtty/rttymod.cpp @@ -60,6 +60,7 @@ RttyMod::RttyMod(DeviceAPI *deviceAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("RttyMod"); m_basebandSource = new RttyModBaseband(); m_basebandSource->setSpectrumSampleSink(&m_spectrumVis); m_basebandSource->setChannel(this); diff --git a/plugins/channeltx/modssb/ssbmod.cpp b/plugins/channeltx/modssb/ssbmod.cpp index 24fb6fd03..22835ea8c 100644 --- a/plugins/channeltx/modssb/ssbmod.cpp +++ b/plugins/channeltx/modssb/ssbmod.cpp @@ -65,6 +65,7 @@ SSBMod::SSBMod(DeviceAPI *deviceAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("SSBMod"); m_basebandSource = new SSBModBaseband(); m_basebandSource->setSpectrumSink(&m_spectrumVis); m_basebandSource->setInputFileStream(&m_ifstream); diff --git a/plugins/channeltx/modwfm/wfmmod.cpp b/plugins/channeltx/modwfm/wfmmod.cpp index 4183fea3f..5a7278d4d 100644 --- a/plugins/channeltx/modwfm/wfmmod.cpp +++ b/plugins/channeltx/modwfm/wfmmod.cpp @@ -61,6 +61,7 @@ WFMMod::WFMMod(DeviceAPI *deviceAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("WFMMod"); m_basebandSource = new WFMModBaseband(); m_basebandSource->setInputFileStream(&m_ifstream); m_basebandSource->setChannel(this); diff --git a/plugins/channeltx/remotesource/remotesource.cpp b/plugins/channeltx/remotesource/remotesource.cpp index e64177c20..06227c80f 100644 --- a/plugins/channeltx/remotesource/remotesource.cpp +++ b/plugins/channeltx/remotesource/remotesource.cpp @@ -57,6 +57,7 @@ RemoteSource::RemoteSource(DeviceAPI *deviceAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("RemoteSource"); m_basebandSource = new RemoteSourceBaseband(); m_basebandSource->moveToThread(m_thread); diff --git a/plugins/channeltx/remotesource/remotesourcesource.cpp b/plugins/channeltx/remotesource/remotesourcesource.cpp index 05adf7db1..a500f1601 100644 --- a/plugins/channeltx/remotesource/remotesourcesource.cpp +++ b/plugins/channeltx/remotesource/remotesourcesource.cpp @@ -30,6 +30,7 @@ RemoteSourceSource::RemoteSourceSource() : m_nbUncorrectableErrors(0), m_channelSampleRate(48000) { + m_sourceWorkerThread.setObjectName("RmtSrcSrcWrk"); connect(&m_dataQueue, SIGNAL(dataBlockEnqueued()), this, SLOT(handleData()), Qt::QueuedConnection); m_cm256p = m_cm256.isInitialized() ? &m_cm256 : 0; m_currentMeta.init(); diff --git a/plugins/channeltx/udpsource/udpsource.cpp b/plugins/channeltx/udpsource/udpsource.cpp index b88d7ec95..7378869f3 100644 --- a/plugins/channeltx/udpsource/udpsource.cpp +++ b/plugins/channeltx/udpsource/udpsource.cpp @@ -50,6 +50,7 @@ UDPSource::UDPSource(DeviceAPI *deviceAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("UDPSource"); m_basebandSource = new UDPSourceBaseband(); m_basebandSource->setSpectrumSink(&m_spectrumVis); m_basebandSource->moveToThread(m_thread); diff --git a/plugins/feature/afc/afc.cpp b/plugins/feature/afc/afc.cpp index b697408e9..6c292bb14 100644 --- a/plugins/feature/afc/afc.cpp +++ b/plugins/feature/afc/afc.cpp @@ -95,6 +95,7 @@ void AFC::start() qDebug("AFC::start"); m_thread = new QThread(); + m_thread->setObjectName("AFC"); m_worker = new AFCWorker(getWebAPIAdapterInterface()); m_worker->moveToThread(m_thread); diff --git a/plugins/feature/ambe/ambeengine.cpp b/plugins/feature/ambe/ambeengine.cpp index ca8f66f61..03a9d4b8e 100644 --- a/plugins/feature/ambe/ambeengine.cpp +++ b/plugins/feature/ambe/ambeengine.cpp @@ -249,6 +249,7 @@ bool AMBEEngine::registerController(const std::string& deviceRef) m_controllers.push_back(AMBEController()); m_controllers.back().worker = worker; m_controllers.back().thread = new QThread(); + m_controllers.back().thread->setObjectName("AMBE:" + QString::fromStdString(deviceRef)); m_controllers.back().device = deviceRef; m_controllers.back().worker->moveToThread(m_controllers.back().thread); diff --git a/plugins/feature/aprs/aprs.cpp b/plugins/feature/aprs/aprs.cpp index ef19245fb..8025960a1 100644 --- a/plugins/feature/aprs/aprs.cpp +++ b/plugins/feature/aprs/aprs.cpp @@ -97,6 +97,7 @@ void APRS::start() { qDebug("APRS::start"); m_thread = new QThread(); + m_thread->setObjectName("APRS"); m_worker = new APRSWorker(this, m_webAPIAdapterInterface); m_worker->moveToThread(m_thread); diff --git a/plugins/feature/demodanalyzer/demodanalyzer.cpp b/plugins/feature/demodanalyzer/demodanalyzer.cpp index 3cf444119..013a2cc29 100644 --- a/plugins/feature/demodanalyzer/demodanalyzer.cpp +++ b/plugins/feature/demodanalyzer/demodanalyzer.cpp @@ -101,6 +101,7 @@ void DemodAnalyzer::start() qDebug("DemodAnalyzer::start"); m_thread = new QThread(); + m_thread->setObjectName("DemodAnalyzer"); m_worker = new DemodAnalyzerWorker(); m_worker->moveToThread(m_thread); diff --git a/plugins/feature/denoiser/denoiser.cpp b/plugins/feature/denoiser/denoiser.cpp index fed578526..8d038083b 100644 --- a/plugins/feature/denoiser/denoiser.cpp +++ b/plugins/feature/denoiser/denoiser.cpp @@ -140,6 +140,7 @@ void Denoiser::start() qDebug("Denoiser::start"); m_thread = new QThread(); + m_thread->setObjectName("Denoiser"); m_worker = new DenoiserWorker(); m_worker->moveToThread(m_thread); diff --git a/plugins/feature/gs232controller/gs232controller.cpp b/plugins/feature/gs232controller/gs232controller.cpp index 4394ade07..d27d4bbd0 100644 --- a/plugins/feature/gs232controller/gs232controller.cpp +++ b/plugins/feature/gs232controller/gs232controller.cpp @@ -120,6 +120,7 @@ void GS232Controller::start() qDebug("GS232Controller::start"); m_thread = new QThread(); + m_thread->setObjectName("GS232Controller"); m_worker = new GS232ControllerWorker(this); m_worker->moveToThread(m_thread); QObject::connect(m_thread, &QThread::started, m_worker, &GS232ControllerWorker::startWork); diff --git a/plugins/feature/map/data/README.txt b/plugins/feature/map/data/README.txt index e7075a745..685247222 100644 --- a/plugins/feature/map/data/README.txt +++ b/plugins/feature/map/data/README.txt @@ -1,23 +1,23 @@ -UK transmitter data: - -TxParamsAM.csv. TxParamsDAB.csv, TxParamsVHF.csv - https://www.ofcom.org.uk/spectrum/information/radio-tech-parameters - -700-plan-clearance.xlsx - https://www.ofcom.org.uk/spectrum/information/transmitter-frequency - -French transmitter data: - -sites-DAB-TII-v0.10.csv - https://extranet.arcom.fr/radio/index.php - - -WMM (World Magnetic Model): - -Download ERSI shapefiles from: https://data.ngdc.noaa.gov/geomag/wmm/wmm2025/shapefiles/ -Open D_2025.shp in QGIS: https://qgis.org/ -Layer > Open Attribute Table, Toggle Edit Mode, Delete unneeded contours (E.g. odd values). -Edit > Edit Geometry > Simplify feature, Draw box around all geometry, set tolerance to 0.1 and check reduction in number of verticies. -Layer > Save As... - -QGIS geojson export doesn't support styles (See: https://github.com/qgis/QGIS/issues/21195) so manually edit the geojson and insert: - - "stroke": "#ff0000" properties to set color. Negative blue, positive red, 0 green. - "stroke-width": 0.5, for contours that aren't multiples of 10 and 1.0 for those that are. +UK transmitter data: + +TxParamsAM.csv. TxParamsDAB.csv, TxParamsVHF.csv - https://www.ofcom.org.uk/spectrum/information/radio-tech-parameters + +700-plan-clearance.xlsx - https://www.ofcom.org.uk/spectrum/information/transmitter-frequency + +French transmitter data: + +sites-DAB-TII-v0.10.csv - https://extranet.arcom.fr/radio/index.php + + +WMM (World Magnetic Model): + +Download ERSI shapefiles from: https://data.ngdc.noaa.gov/geomag/wmm/wmm2025/shapefiles/ +Open D_2025.shp in QGIS: https://qgis.org/ +Layer > Open Attribute Table, Toggle Edit Mode, Delete unneeded contours (E.g. odd values). +Edit > Edit Geometry > Simplify feature, Draw box around all geometry, set tolerance to 0.1 and check reduction in number of verticies. +Layer > Save As... + +QGIS geojson export doesn't support styles (See: https://github.com/qgis/QGIS/issues/21195) so manually edit the geojson and insert: + + "stroke": "#ff0000" properties to set color. Negative blue, positive red, 0 green. + "stroke-width": 0.5, for contours that aren't multiples of 10 and 1.0 for those that are. diff --git a/plugins/feature/map/map/cockpit.js b/plugins/feature/map/map/cockpit.js index 1da72d86b..0214cb1a9 100644 --- a/plugins/feature/map/map/cockpit.js +++ b/plugins/feature/map/map/cockpit.js @@ -1,1463 +1,1463 @@ -// Airbus like PFD (Primary Flight Display) - -var icao; -var callsign; -var aircraftType; -var onSurface; -var wasOnSurface60SecsAgo; -var speed; -var modelSpeed; // Speed of 3D model in Cesium -var trueAirspeed; -var groundspeed; -var targetSpeed; -var altitude; -var targetAltitude; -var radioAltitude; -var verticalSpeed; // ft/m -var heading; // degrees mag -var targetHeading; -var track; // degrees true -var pressure; // mb -var mach; -var roll; -var autopilot; -var verticalMode; -var lateralMode; -var tcasMode; -var windSpeed; -var windDirection; -var staticAirTemperature; - -var mdoelSpeed; -var toga = false; -var rollOut = false; -var runwayAltitude; - -const grayColor = "#6A75AE"; -const greenColor = "#20E966"; -const cyanColor = "#2FF7FE"; -const yellowColor = "#F4F82F"; -const orangeColor = "#FEDA30"; -const skyColor = "#26C9FF"; -const groundColor = "#D35E34"; - -function setPFDData(forward, newICAO, newCallsign, newAircraftType, newOnSurface, newWasOnSurface60SecsAgo, newRunwayAltitudeEstimate, - newModelSpeed, newIndicatedAirspeed, newTrueAirspeed, newGroundspeed, newMach, newAltitude, newRadioAltitude, newQnh, newVerticalSpeed, - newHeading, newTrack, newRoll, newSelectedAltitude, newSelectedHeading, - newAutopilot, newVerticalMode, newLateralMode, newTCASMode, - newWindSpeed, newWindDirection, newStaticAirTemperature) { - - //console.log('PFD', newIndicatedAirspeed, newMach, newAltitude, newQnh, newVerticalSpeed, newHeading, newTrack, newRoll, newSelectedAltitude, newSelectedHeading); - - const newAircraft = icao !== newICAO; - - if (newAircraft) { - toga = false; - rollOut = false; - runwayAltitude = undefined; - } - - icao = newICAO; - callsign = newCallsign; - aircraftType = newAircraftType; - onSurface = newOnSurface; - wasOnSurface60SecsAgo = newWasOnSurface60SecsAgo; - modelSpeed = newModelSpeed; - if ((newIndicatedAirspeed === undefined) || (newOnSurface > 0)) { - // IAS not transmitted frequently. After landing will no longer be valid - if (newGroundspeed !== undefined) { - speed = newGroundspeed; - } else { - speed = newModelSpeed; - } - } else { - speed = newIndicatedAirspeed; - } - trueAirspeed = newTrueAirspeed; - groundspeed = newGroundspeed; - mach = newMach; - altitude = newAltitude; - radioAltitude = newRadioAltitude; - pressure = newQnh; - verticalSpeed = newVerticalSpeed; - if (newHeading === undefined) { - heading = newTrack; // Track more frequent than heading - } else { - heading = newHeading; - } - track = newTrack; - roll = newRoll; - targetAltitude = newSelectedAltitude; - targetHeading = newSelectedHeading; - if (newAutopilot === -1) { - autopilot = undefined; - } else { - autopilot = newAutopilot; - } - verticalMode = newVerticalMode; - lateralMode = newLateralMode; - tcasMode = newTCASMode; - windSpeed = newWindSpeed; - windDirection = newWindDirection; - staticAirTemperature = newStaticAirTemperature; - - // Correct altitude for QNH setting - if (pressure !== undefined) { - altitude += (pressure - 1013.25) * 30; - } - - if (!rollOut && forward && (wasOnSurface60SecsAgo === 0) && (onSurface > 0) && (modelSpeed >= 70)) { - rollOut = true; - } else if (rollOut && ((modelSpeed < 40) || (onSurface === 0))) { - rollOut = false; - } - - const accelerationHeight = 1500; - - if (!toga && !rollOut && forward && (onSurface > 0) && (modelSpeed >= 35)) { - toga = true; // Start take-off roll on surface - runwayAltitude = altitude; - } else if (!toga && !rollOut && (modelSpeed >= 35) && (runwayAltitude === undefined) && (wasOnSurface60SecsAgo > 0) && (newRunwayAltitudeEstimate !== undefined)) { - toga = true; // For when selecting an aircraft having just taken off - runwayAltitude = newRunwayAltitudeEstimate; - } else if (!toga && !rollOut && (onSurface === 0) && (wasOnSurface60SecsAgo > 0) && (altitude !== undefined) && (runwayAltitude !== undefined) && (altitude < runwayAltitude + accelerationHeight)) { - toga = true; // For when played in reverse - } else if (toga && (modelSpeed <= 20)) { - toga = false; - } else if (toga && (altitude !== undefined) && (runwayAltitude !== undefined) && (altitude >= runwayAltitude + accelerationHeight)) { - toga = false; - } - if (toga && (runwayAltitude === undefined) && (newRunwayAltitudeEstimate !== undefined)) { - runwayAltitude = newRunwayAltitudeEstimate; - } -} - -function isStd() { - return (pressure >= 1012) && (pressure < 1014); -} - -function drawAirspeedIndicator(ctx, fm20, fm30) { - // Airspeed indicator - - const speedIndWidth = 100; - const speedIndHeight = 500; - const speedIndLeft = 30; - const speedIndRight = speedIndLeft + speedIndWidth; - const speedIndTop = 250; - const speedIndBottom = speedIndTop + speedIndHeight; - const speedIndMid = speedIndTop + speedIndHeight / 2; - - // Background - ctx.fillStyle = grayColor; - ctx.fillRect(speedIndLeft, speedIndTop, speedIndWidth, speedIndHeight); - - // Clip speed tape - ctx.save(); - ctx.rect(speedIndLeft, speedIndTop, speedIndWidth, speedIndHeight); - ctx.clip(); - - // Speed tape markings every 10knts - const speedTapMinSpeed = 0; // A320 only starts drawning from 30knts, but we draw from 0 - const speedTapeLeft = speedIndRight - 20; - const speedTapeRight = speedIndRight; - const speedTapeSpacing = 60; - const speedTapeStep = 10; - const speedTextStep = 20; - const speedPerPixel = speedTapeSpacing / speedTapeStep; - const speedOffset = (speed % speedTextStep) * speedPerPixel; - ctx.beginPath(); - var speedTape = Math.round(speed - speed % speedTextStep + 6 * speedTapeStep); - for (var i = -6; i < 5; i++) { - if (speedTape >= speedTapMinSpeed) { - ctx.moveTo(speedTapeLeft, speedOffset + i * speedTapeSpacing + speedIndMid); - ctx.lineTo(speedTapeRight, speedOffset + i * speedTapeSpacing + speedIndMid); - } - speedTape -= speedTapeStep; - } - ctx.lineWidth = 2; - ctx.strokeStyle = "white"; - ctx.stroke(); - - // Speeds every 20knts - var speedText = Math.round(speed - speed % speedTextStep + 3 * speedTextStep); - for (var i = -3; i < 3; i++) { - ctx.font = "30px Arial"; - ctx.fillStyle = "white"; - if (speedText >= speedTapMinSpeed) { - const speedTextString = speedText.toString().padStart(3, '0'); - ctx.fillText(speedTextString, speedIndLeft + 20, speedOffset + i * speedTapeSpacing * 2 + speedIndMid + fm30.actualBoundingBoxAscent / 2); - } - speedText -= speedTextStep; - } - - // Disable clipping - ctx.restore(); - - ctx.beginPath(); - ctx.moveTo(speedIndLeft, speedIndTop); - ctx.lineTo(speedIndRight + 30, speedIndTop); - var speedIndRightLineHeight = speed / (speedIndHeight / 2 / speedPerPixel); // White line on right only drawn down to speedTapMinSpeed - if (speedIndRightLineHeight > 1) { - speedIndRightLineHeight = 1; - ctx.moveTo(speedIndLeft, speedIndTop + speedIndHeight); - ctx.lineTo(speedIndRight + 30, speedIndTop + speedIndHeight); - } - ctx.moveTo(speedIndRight, speedIndTop); - ctx.lineTo(speedIndRight, speedIndTop + speedIndRightLineHeight * (speedIndHeight / 2) + (speedIndHeight / 2)); - ctx.lineWidth = 2; - ctx.strokeStyle = "white"; - ctx.stroke(); - - // Speed indicator - ctx.beginPath(); - ctx.moveTo(speedIndLeft - 10, speedIndMid); - ctx.lineTo(speedIndLeft, speedIndMid); - ctx.moveTo(speedTapeLeft - 5, speedIndMid); - ctx.lineTo(speedTapeRight + 20, speedIndMid); - ctx.lineWidth = 2; - ctx.strokeStyle = yellowColor; - ctx.stroke(); - - ctx.beginPath(); - ctx.moveTo(speedTapeRight + 10, speedIndMid); - ctx.lineTo(speedTapeRight + 35, speedIndMid - 10); - ctx.lineTo(speedTapeRight + 35, speedIndMid + 10); - ctx.lineTo(speedTapeRight + 10, speedIndMid); - ctx.fillStyle = yellowColor; - ctx.fill(); - - // Target speed - - if (targetSpeed !== undefined) { - var targetSpeedY = (speed - targetSpeed) * speedPerPixel; - targetSpeedY = targetSpeedY + speedIndMid; - if (targetSpeedY < speedIndTop) { - // Target speed as text on top - ctx.font = "20px Arial"; - ctx.fillStyle = cyanColor; - const targetSpeedMetrics = ctx.measureText(targetSpeed); - ctx.fillText(targetSpeed, speedIndRight - targetSpeedMetrics.width / 2, speedIndTop - 4); - - } else if (targetSpeedY > speedIndBottom) { - // Target speed as text underneath - ctx.font = "20px Arial"; - ctx.fillStyle = cyanColor; - const targetSpeedMetrics = ctx.measureText(targetSpeed); - ctx.fillText(targetSpeed, speedIndRight - targetSpeedMetrics.width / 2, speedIndBottom + fm20.actualBoundingBoxAscent + 4); - } else { - // Cyan triangle on right side - const targetSpeedWidth = 40; - const targetSpeedHeight = 30; - const targetSpeedLeft = speedIndRight; - const targetSpeedRight = targetSpeedLeft + targetSpeedWidth; - - ctx.beginPath(); - ctx.moveTo(targetSpeedLeft, targetSpeedY); - ctx.lineTo(targetSpeedRight, targetSpeedY - targetSpeedHeight / 2); - ctx.lineTo(targetSpeedRight, targetSpeedY + targetSpeedHeight / 2); - ctx.lineTo(targetSpeedLeft, targetSpeedY); - ctx.lineWidth = 2; - ctx.strokeStyle = cyanColor; - ctx.stroke(); - } - } -} - -function drawAltitudeIndicator(ctx, fm20, fm30) { - // Altitude indicator - - const altitudeIndWidth = 70; - const altitudeIndHeight = 500; - const altitudeIndLeft = 750; - const altitudeIndRight = altitudeIndLeft + altitudeIndWidth; - const altitudeIndTop = 250; - const altitudeIndBottom = altitudeIndTop + altitudeIndHeight; - const altitudeIndMid = altitudeIndTop + altitudeIndHeight / 2; - - // Background - ctx.fillStyle = grayColor; - ctx.fillRect(altitudeIndLeft, altitudeIndTop, altitudeIndWidth, altitudeIndHeight); - - ctx.font = "30px Arial"; - const greaterThanMetrics = ctx.measureText(">"); - - // Mid point marker (for glideslope, but always visible) - ctx.fillStyle = yellowColor; - ctx.fillRect(altitudeIndLeft - 70, altitudeIndMid - 3, 50, 6); - - // Clip altitude tape - ctx.save(); - ctx.rect(altitudeIndLeft - greaterThanMetrics.width, altitudeIndTop, altitudeIndWidth + greaterThanMetrics.width, altitudeIndHeight); - ctx.clip(); - - // Altitude tape markings every 100 ft - const altitudeTapeLeft = altitudeIndRight - 10; - const altitudeTapeRight = altitudeIndRight; - const altitudeTapeSpacing = 40; - const altitudeTapeStep = 100; - const altitudeTextStep = 500; - const altitudePerPixel = altitudeTapeSpacing / altitudeTapeStep; // reciprocal - const altitudeOffset = (altitude % altitudeTextStep) * altitudePerPixel; - ctx.beginPath(); - var altitudeTape = Math.round(altitude - altitude % altitudeTextStep + 10 * altitudeTapeStep); - for (var i = -10; i < 7; i++) { - ctx.moveTo(altitudeTapeLeft, altitudeOffset + i * altitudeTapeSpacing + altitudeIndMid); - ctx.lineTo(altitudeTapeRight, altitudeOffset + i * altitudeTapeSpacing + altitudeIndMid); - altitudeTape -= altitudeTapeStep; - } - ctx.lineWidth = 2; - ctx.strokeStyle = "white"; - ctx.stroke(); - - // Flight level texts every 500ft - ctx.font = "30px Arial"; - ctx.fillStyle = "white"; - var altitudeText = Math.round(altitude - altitude % altitudeTextStep + 2 * altitudeTextStep); - for (var i = -2; i < 2; i++) { - const flightLevelText = Math.abs(altitudeText / 100); // Don't display - if negative - const flightLevelTextString = ">" + flightLevelText.toString().padStart(3, '0'); - ctx.fillText(flightLevelTextString, altitudeIndLeft - greaterThanMetrics.width, altitudeOffset + i * altitudeTapeSpacing * 5 + altitudeIndMid + fm30.actualBoundingBoxAscent / 2); - altitudeText -= altitudeTextStep; - } - - // Disable clipping - ctx.restore(); - - // White lines at top, bottom and on right - ctx.beginPath(); - ctx.moveTo(altitudeIndLeft, altitudeIndTop); - ctx.lineTo(altitudeIndRight + 30, altitudeIndTop); - ctx.moveTo(altitudeIndLeft, altitudeIndTop + altitudeIndHeight); - ctx.lineTo(altitudeIndRight + 30, altitudeIndTop + altitudeIndHeight); - ctx.moveTo(altitudeIndRight, altitudeIndTop); - ctx.lineTo(altitudeIndRight, altitudeIndTop + altitudeIndHeight); - ctx.lineWidth = 2; - ctx.strokeStyle = "white"; - ctx.stroke(); - - // Target altitude - - if (targetAltitude !== undefined) { - var targetAltitudeY = (altitude - targetAltitude) * altitudePerPixel; - targetAltitudeY = targetAltitudeY + altitudeIndMid; - - if (isStd()) { - targetAltitudeText = Math.round(targetAltitude / 100); - } else { - targetAltitudeText = Math.round(targetAltitude); - } - - if (targetAltitudeY < altitudeIndTop) { - // Target altitude as text on top - ctx.font = "30px Arial"; - ctx.fillStyle = cyanColor; - const targetAltitudeMetrics = ctx.measureText(targetAltitudeText); - if (isStd()) { - ctx.fillText("FL", altitudeIndLeft, altitudeIndTop - 4); - } - ctx.fillText(targetAltitudeText, altitudeIndRight - targetAltitudeMetrics.width / 2, altitudeIndTop - 4); - } else if (targetAltitudeY > altitudeIndBottom) { - // Target altitude as text underneath - ctx.font = "30px Arial"; - ctx.fillStyle = cyanColor; - const targetAltitudeMetrics = ctx.measureText(targetAltitudeText); - if (isStd()) { - ctx.fillText("FL", altitudeIndLeft, altitudeIndBottom + fm30.actualBoundingBoxAscent + 4); - } - ctx.fillText(targetAltitudeText, altitudeIndRight - targetAltitudeMetrics.width / 2, altitudeIndBottom + fm30.actualBoundingBoxAscent + 4); - } else { - - // Clip - ctx.save(); - ctx.rect(altitudeIndLeft - greaterThanMetrics.width, altitudeIndTop, altitudeIndWidth + greaterThanMetrics.width, altitudeIndHeight); - ctx.clip(); - - targetAltitudeText = targetAltitudeText.toString().padStart(3, '0'); - - ctx.font = "30px Arial"; - ctx.fillStyle = cyanColor; - const targetAltitudeMetrics = ctx.measureText(targetAltitudeText); - - // Cyan box - const targetAltitudeWidth = 30; - const targetAltitudeHeight = 3 * (fm30.actualBoundingBoxAscent + fm30.actualBoundingBoxDescent); - const targetAltitudeBoxHeight = 1.1 * (fm30.actualBoundingBoxAscent + fm30.actualBoundingBoxDescent); - const targetAltitudeLeft = altitudeIndLeft - 5; - const targetAltitudeRight = targetAltitudeLeft + targetAltitudeWidth; - - ctx.beginPath(); - ctx.moveTo(targetAltitudeLeft, targetAltitudeY - targetAltitudeHeight / 2); - ctx.lineTo(targetAltitudeLeft, targetAltitudeY - 5); - ctx.lineTo(targetAltitudeLeft + 5, targetAltitudeY); - ctx.lineTo(targetAltitudeLeft, targetAltitudeY + 5); - ctx.lineTo(targetAltitudeLeft, targetAltitudeY + targetAltitudeHeight / 2); - ctx.lineTo(targetAltitudeRight, targetAltitudeY + targetAltitudeHeight / 2); - ctx.lineTo(targetAltitudeRight, targetAltitudeY - targetAltitudeHeight / 2); - ctx.lineTo(targetAltitudeLeft, targetAltitudeY - targetAltitudeHeight / 2); - ctx.lineWidth = 2; - ctx.lineWidth = 2; - ctx.strokeStyle = cyanColor; - ctx.stroke(); - - ctx.fillStyle = 'black'; - ctx.fillRect(altitudeIndLeft, targetAltitudeY - targetAltitudeBoxHeight / 2, altitudeIndWidth - 2, targetAltitudeBoxHeight); - ctx.fillStyle = cyanColor; - ctx.fillText(targetAltitudeText, altitudeIndLeft, targetAltitudeY + fm30.actualBoundingBoxAscent / 2); - - // Disable clipping - ctx.restore(); - } - } - - // Altitude - - ctx.font = "34px Arial"; - const levelText = (altitude === undefined) || isNaN(altitude) ? "" : Math.floor(altitude / 100).toString(); - const levelTextMetrics = ctx.measureText(levelText); - const levelTextHeightMetrics = ctx.measureText("0"); - const border = 2; - const levelHeight = levelTextHeightMetrics.actualBoundingBoxAscent + levelTextHeightMetrics.actualBoundingBoxDescent + 8 * border; - - const subscaleHeight = 60; - const subscaleWidth = 30; - - // Black background box - ctx.fillStyle = 'black'; - ctx.fillRect(altitudeIndLeft, altitudeIndMid - levelHeight / 2, altitudeIndWidth + 1, levelHeight); - - // Current flight level - if (levelText !== "") { - ctx.fillStyle = greenColor; - ctx.fillText(levelText, altitudeIndRight - levelTextMetrics.width, altitudeIndMid + levelTextMetrics.actualBoundingBoxAscent / 2); - } - - // Yellow box - ctx.beginPath(); - ctx.moveTo(altitudeIndLeft, altitudeIndMid - levelHeight / 2); - ctx.lineTo(altitudeIndRight, altitudeIndMid - levelHeight / 2); - ctx.lineTo(altitudeIndRight, altitudeIndMid - subscaleHeight / 2); - ctx.lineTo(altitudeIndRight + subscaleWidth, altitudeIndMid - subscaleHeight / 2); - ctx.lineTo(altitudeIndRight + subscaleWidth, altitudeIndMid + subscaleHeight / 2); - ctx.lineTo(altitudeIndRight, altitudeIndMid + subscaleHeight / 2); - ctx.lineTo(altitudeIndRight, altitudeIndMid + levelHeight / 2); - ctx.lineTo(altitudeIndLeft, altitudeIndMid + levelHeight / 2); - ctx.lineWidth = 2; - if (Math.abs(verticalSpeed) >= 6000) { - ctx.strokeStyle = orangeColor; - } else { - ctx.strokeStyle = yellowColor; - } - ctx.stroke(); - - // Clip around subscale - ctx.save(); - ctx.rect(altitudeIndRight, altitudeIndMid - subscaleHeight / 2, subscaleWidth, subscaleHeight); - ctx.clip(); - - const subscaleStep = 20; - var subscaleText = (altitude % 100) + subscaleStep * 2; - var subscaleSpacing = fm20.actualBoundingBoxAscent + fm20.actualBoundingBoxDescent + 2; - const subscalePerPixel = subscaleSpacing / subscaleStep; // reciprocal - const subscaleOffset = (altitude % subscaleStep) * subscalePerPixel; - ctx.font = "20px Arial"; - for (var i = -2; i < 2; i++) { - const subscaleTextString = (Math.floor((subscaleText % 100) / subscaleStep) * subscaleStep).toString().padStart(2, '0'); - ctx.fillText(subscaleTextString, altitudeIndRight + 1, subscaleOffset + i * subscaleSpacing + altitudeIndMid + fm20.actualBoundingBoxAscent / 2); - subscaleText -= subscaleStep; - if (subscaleText < 0) { - subscaleText += 100; - } - } - - // Disable clipping - ctx.restore(); -} -function drawHeadingIndicator(ctx, fm20, fm30) { - - const headingIndWidth = 450; - const headingIndHeight = 60; - const headingIndLeft = 225; - const headingIndRight = headingIndLeft + headingIndWidth; - const headingIndTop = 890; - const headingIndBottom = headingIndTop + headingIndHeight; - const headingIndMid = headingIndLeft + headingIndWidth / 2; - - ctx.fillStyle = grayColor; - ctx.fillRect(headingIndLeft, headingIndTop, headingIndWidth, headingIndHeight); - - // White lines left, right and top - ctx.beginPath(); - ctx.moveTo(headingIndLeft, headingIndBottom); - ctx.lineTo(headingIndLeft, headingIndTop); - ctx.lineTo(headingIndRight, headingIndTop); - ctx.lineTo(headingIndRight, headingIndBottom); - ctx.lineWidth = 2; - ctx.strokeStyle = "white"; - ctx.stroke(); - - // Heading indicator line - ctx.beginPath(); - ctx.moveTo(headingIndMid, headingIndTop - 30); - ctx.lineTo(headingIndMid, headingIndTop); - ctx.lineWidth = 4; - ctx.strokeStyle = yellowColor; - ctx.stroke(); - - // Clip tape - ctx.save(); - ctx.rect(headingIndLeft, headingIndTop, headingIndWidth, headingIndHeight); - ctx.clip(); - - // Tape markings every 5 degrees - const headingTapeLeft = headingIndRight - 20; - const headingTapeRight = headingIndRight; - const headingTapeSpacing = 50; - const headingTapeStep = 5; - const headingTextStep = 10; - const headingPerPixel = headingTapeSpacing / headingTapeStep; - const headingOffset = - (heading % headingTextStep) * headingPerPixel; - ctx.beginPath(); - var headingTape = Math.round(heading - heading % headingTextStep - 6 * headingTapeStep); - for (var i = -6; i < 7; i++) { - ctx.moveTo(headingOffset + i * headingTapeSpacing + headingIndMid, headingIndTop); - if (headingTape % 10 != 0) { - ctx.lineTo(headingOffset + i * headingTapeSpacing + headingIndMid, headingIndTop + 10); - } else { - ctx.lineTo(headingOffset + i * headingTapeSpacing + headingIndMid, headingIndTop + 20); - } - headingTape += headingTapeStep; - } - ctx.lineWidth = 2; - ctx.strokeStyle = "white"; - ctx.stroke(); - - ctx.font = "30px Arial"; - ctx.fillStyle = "white"; - const headingMetricsBig = ctx.measureText("36"); - ctx.font = "24px Arial"; - ctx.fillStyle = "white"; - const headingMetricsSmall = ctx.measureText("36"); - - // Headings every 10 degrees - var headingText = Math.round(heading - heading % headingTextStep - 3 * headingTextStep); - for (var i = -3; i < 4; i++) { - const big = headingText % 30 == 0; - if (big) { - ctx.font = "30px Arial"; - } else { - ctx.font = "24px Arial"; - } - ctx.fillStyle = "white"; - var headingTextMod = Math.round(headingText / 10) % 36; - if (headingTextMod < 0) { - headingTextMod += 36; - } - const headingTextString = headingTextMod.toString(); - const headingMetrics = ctx.measureText(headingTextString); - - ctx.fillText(headingTextString, headingOffset + i * headingTapeSpacing * 2 + headingIndMid - headingMetrics.width / 2, headingIndTop + 30 + headingMetrics.actualBoundingBoxAscent); - headingText += headingTextStep; - } - - // Track diamond - - if (track !== undefined) { - const trackMid = headingIndMid + (track - heading) * headingPerPixel; - const trackSize = 20; - - ctx.beginPath(); - ctx.moveTo(trackMid, headingIndTop); - ctx.lineTo(trackMid - trackSize / 2, headingIndTop + trackSize / 2); - ctx.lineTo(trackMid, headingIndTop + trackSize); - ctx.lineTo(trackMid + trackSize / 2, headingIndTop + trackSize / 2); - ctx.lineTo(trackMid, headingIndTop); - ctx.lineWidth = 5; - ctx.strokeStyle = greenColor; - ctx.stroke(); - } - - // Disable clipping - ctx.restore(); - - // Target heading - - if (targetHeading !== undefined) { - var targetDiff = targetHeading - heading; - if (targetDiff > 180) { - targetDiff -= 360; - } - var targetMid = headingIndMid + targetDiff * headingPerPixel; - if (targetMid < headingIndLeft) { - - // Display target heading as text on left - ctx.font = "20px Arial"; - ctx.fillStyle = cyanColor; - const targetHeadingText = Math.round(targetHeading).toString().padStart(3, '0'); - const targetHeadingMetrics = ctx.measureText(targetHeadingText); - ctx.fillText(targetHeadingText, headingIndLeft, headingIndTop - 4); - - } else if (targetMid > headingIndRight) { - - // Display target heading as text on right - ctx.font = "20px Arial"; - ctx.fillStyle = cyanColor; - const targetHeadingText = Math.round(targetHeading).toString().padStart(3, '0'); - const targetHeadingMetrics = ctx.measureText(targetHeadingText); - ctx.fillText(targetHeadingText, headingIndRight - targetHeadingMetrics.width, headingIndTop - 4); - - } else { - // Target indicator triangle - - const targetWidth = 30; - const targetHeight = 40; - - ctx.beginPath(); - ctx.moveTo(targetMid, headingIndTop); - ctx.lineTo(targetMid - targetWidth / 2, headingIndTop - targetHeight); - ctx.lineTo(targetMid + targetWidth / 2, headingIndTop - targetHeight); - ctx.lineTo(targetMid, headingIndTop); - ctx.lineWidth = 2; - ctx.strokeStyle = cyanColor; - ctx.stroke(); - } - } -} - -function drawBankAngleBoxMarker(ctx, radius, height) { - ctx.beginPath(); - ctx.moveTo(-5, -radius); - ctx.lineTo(-5, -radius - height); - ctx.lineTo(5, -radius - height); - ctx.lineTo(5, -radius); - ctx.lineWidth = 2; - ctx.strokeStyle = 'white'; - ctx.stroke(); -} - -function drawBankAngleLineMarker(ctx, radius, height) { - ctx.beginPath(); - ctx.moveTo(0, -radius); - ctx.lineTo(0, -radius - height); - ctx.lineWidth = 2; - ctx.strokeStyle = 'white'; - ctx.stroke(); -} -function drawAttitudeIndicator(ctx, fm20, fm30) { - - if (roll === undefined) { - return; - } - - // Height the same as airspeed indicator - cropped width same as heading indicator - - const speedIndRight = 30 + 100; - const altitudeIndLeft = 750; - - const attitudeIndMidX = speedIndRight + ((altitudeIndLeft - speedIndRight) / 2); - //const attitudeIndLeft = 30 + 100; // speedIndRight - //const attitudeIndRight = 750; // altitudeIndLeft - const attitudeIndWidth = 500; // speedIndHeight = 500; // attitudeIndRight - attitudeIndLeft; - const attitudeIndTop = 250; - const attitudeIndLeft = attitudeIndMidX - attitudeIndWidth / 2; - const attitudeIndHeight = attitudeIndWidth; // It's a circle - const attitudeIndMidY = attitudeIndTop + attitudeIndHeight / 2; - const attitudeIndCrop = (attitudeIndWidth - 450) / 2; // headingIndWidth = 450 - - // Clip - ctx.save(); - //ctx.arc(attitudeIndMidX, attitudeIndMidY, attitudeIndWidth / 2, 0, 2 * Math.PI); - ctx.beginPath(); - ctx.arc(attitudeIndMidX, attitudeIndMidY, attitudeIndWidth / 2, Math.PI / 10 + Math.PI, Math.PI - Math.PI / 10 + Math.PI); - ctx.arc(attitudeIndMidX, attitudeIndMidY, attitudeIndWidth / 2, Math.PI / 10, Math.PI - Math.PI / 10); -// //ctx.rect(attitudeIndLeft + attitudeIndCrop, attitudeIndTop, attitudeIndWidth - 2 * attitudeIndCrop, attitudeIndWidth); - // ctx.rect(attitudeIndLeft + attitudeIndCrop, attitudeIndTop, attitudeIndWidth - 2 * attitudeIndCrop, attitudeIndWidth); - ctx.clip(); - - - // Background - //ctx.beginPath(); - //ctx.fillStyle = cyanColor; - //ctx.arc(attitudeIndMidX, attitudeIndMidY, attitudeIndWidth / 2, Math.PI / 10, Math.PI - Math.PI / 10); - //ctx.arc(attitudeIndMidX, attitudeIndMidY, attitudeIndWidth / 2, Math.PI / 10 + Math.PI, Math.PI - Math.PI / 10 + Math.PI); - //console.log(attitudeIndMidX, attitudeIndMidY, attitudeIndWidth / 2, 0, 2 * Math.PI); - //ctx.fill(); - - ctx.fillStyle = skyColor; - ctx.fillRect(attitudeIndLeft, attitudeIndTop, attitudeIndWidth, attitudeIndWidth); - - const rollRad = -roll * Math.PI / 180; - const radius = attitudeIndWidth / 2; - - ctx.fillStyle = groundColor; - ctx.beginPath(); - ctx.arc(attitudeIndMidX, attitudeIndMidY, radius, 0 + rollRad, Math.PI + rollRad); - ctx.fill(); - - //const offsetX = Math.cos(rollRad) * radius; - //const offsetY = Math.sin(rollRad) * radius; - //ctx.beginPath(); - //ctx.moveTo(attitudeIndMidX - offsetX, attitudeIndMidY - offsetY); - //ctx.lineTo(attitudeIndMidX + offsetX, attitudeIndMidY + offsetY); - //ctx.lineWidth = 2; - //ctx.strokeStyle = 'white'; - //ctx.stroke(); - - // Disable clipping - //ctx.restore(); - - const twoAndHalfDegOffset = 15; - const fiveDegOffset = twoAndHalfDegOffset * 2; - const tenDegOffset = twoAndHalfDegOffset * 4; - const fifteenDegOffset = twoAndHalfDegOffset * 2.5; - const spacing = 50; - - // ctx.save(); - - ctx.translate(attitudeIndMidX, attitudeIndMidY); - ctx.rotate(rollRad); - - ctx.beginPath(); - ctx.moveTo(-radius, 0); - ctx.lineTo(radius, 0); - for (var i = -2; i < 4; i++) { - ctx.moveTo(-twoAndHalfDegOffset, -i * spacing - spacing / 2); - ctx.lineTo(twoAndHalfDegOffset, -i * spacing - spacing / 2); - } - for (var i = -1; i < 5; i++) { - ctx.moveTo(-fiveDegOffset, -i * spacing); - ctx.lineTo(fiveDegOffset, -i * spacing); - } - for (var i = -1; i < 3; i++) { - ctx.moveTo(-tenDegOffset, -i * 2 * spacing); - ctx.lineTo(tenDegOffset, -i * 2 * spacing); - } - ctx.moveTo(-fifteenDegOffset, 2.75 * spacing); - ctx.lineTo(fifteenDegOffset, 2.75 * spacing); - ctx.moveTo(-tenDegOffset, 3.5 * spacing); - ctx.lineTo(tenDegOffset, 3.5 * spacing); - ctx.lineWidth = 2; - ctx.strokeStyle = 'white'; - ctx.stroke(); - - const greenThingWidth = 20; - ctx.beginPath(); - ctx.strokeStyle = greenColor; - ctx.moveTo(-fifteenDegOffset - greenThingWidth, 2.75 * spacing - 3); - ctx.lineTo(-fifteenDegOffset, 2.75 * spacing - 3); - ctx.moveTo(-fifteenDegOffset - greenThingWidth, 2.75 * spacing + 3); - ctx.lineTo(-fifteenDegOffset, 2.75 * spacing + 3); - ctx.moveTo(fifteenDegOffset + greenThingWidth, 2.75 * spacing - 3); - ctx.lineTo(fifteenDegOffset, 2.75 * spacing - 3); - ctx.moveTo(fifteenDegOffset + greenThingWidth, 2.75 * spacing + 3); - ctx.lineTo(fifteenDegOffset, 2.75 * spacing + 3); - ctx.stroke(); - - ctx.font = "20px Arial"; - ctx.fillStyle = 'white'; - const labelMetrics = ctx.measureText("20"); - const labelCenterY = labelMetrics.actualBoundingBoxAscent / 2; - const labelOffset = tenDegOffset + 10; - - ctx.fillText("10", labelOffset, spacing * 2 + labelCenterY); - ctx.fillText("10", -labelOffset - labelMetrics.width, spacing * 2 + labelCenterY); - ctx.fillText("10", labelOffset, -spacing * 2 + labelCenterY); - ctx.fillText("10", -labelOffset - labelMetrics.width, -spacing * 2 + labelCenterY); - ctx.fillText("20", labelOffset, -spacing * 4 + labelCenterY); - ctx.fillText("20", -labelOffset - labelMetrics.width, -spacing * 4 + labelCenterY); - ctx.fillText("20", labelOffset, spacing * 3.5 + labelCenterY); - ctx.fillText("20", -labelOffset - labelMetrics.width, spacing * 3.5 + labelCenterY); - - const rollBig = 18; - const rollSmall = 10; - - const rollTriangleOffet = 4; - - ctx.beginPath(); - ctx.moveTo(0, -radius + rollTriangleOffet); - ctx.lineTo(rollBig, -radius + rollBig + rollTriangleOffet); - ctx.lineTo(-rollBig, -radius + rollBig + rollTriangleOffet); - ctx.lineTo(0, -radius + rollTriangleOffet); - ctx.lineWidth = 2; - ctx.strokeStyle = yellowColor; - ctx.stroke(); - - const rollTrapX1 = 20; - const rollTrapX2 = 30; - const rollTrapY1 = -radius + rollBig + rollTriangleOffet + 5; - const rollTrapY2 = rollTrapY1 + 10; - - ctx.beginPath(); - ctx.moveTo(-rollTrapX1, rollTrapY1); - ctx.lineTo(rollTrapX1, rollTrapY1); - ctx.lineTo(rollTrapX2, rollTrapY2); - ctx.lineTo(-rollTrapX2, rollTrapY2); - ctx.lineTo(-rollTrapX1, rollTrapY1); - ctx.lineWidth = 2; - ctx.strokeStyle = yellowColor; - ctx.stroke(); - - ctx.restore(); - - // Roll scale - - ctx.save(); - ctx.translate(attitudeIndMidX, attitudeIndMidY); - - ctx.beginPath(); - ctx.rect(-radius, -radius - 2 *rollBig , radius * 2, radius); - ctx.clip(); - - ctx.beginPath(); - ctx.moveTo(0, -radius); - ctx.lineTo(rollBig, -radius - rollBig); - ctx.lineTo(-rollBig, -radius - rollBig); - ctx.lineTo(0, -radius); - ctx.lineWidth = 2; - ctx.strokeStyle = yellowColor; - ctx.stroke(); - - ctx.beginPath(); - ctx.arc(0, 0, radius, (240 - 2) * Math.PI / 180, (300 + 2) * Math.PI / 180); - ctx.lineWidth = 2; - ctx.strokeStyle = 'white'; - ctx.stroke(); - - ctx.rotate(45 * Math.PI / 180); - drawBankAngleLineMarker(ctx, radius, rollBig); - ctx.rotate(-15 * Math.PI / 180); - drawBankAngleBoxMarker(ctx, radius, rollBig); - ctx.rotate(-10 * Math.PI / 180); - drawBankAngleBoxMarker(ctx, radius, 10); - ctx.rotate(-10 * Math.PI / 180); - drawBankAngleBoxMarker(ctx, radius, 10); - ctx.rotate(-10 * Math.PI / 180); - - ctx.rotate(-10 * Math.PI / 180); - drawBankAngleBoxMarker(ctx, radius, 10); - ctx.rotate(-10 * Math.PI / 180); - drawBankAngleBoxMarker(ctx, radius, 10); - ctx.rotate(-10 * Math.PI / 180); - drawBankAngleBoxMarker(ctx, radius, rollBig); - ctx.rotate(-15 * Math.PI / 180); - drawBankAngleLineMarker(ctx, radius, rollBig); - - - // ctx.rotate(-rollRad); - // ctx.translate(-attitudeIndMidX, -attitudeIndMidY); - - ctx.restore(); - - // Wings - const wingThickness = 14; - const wingHeight = 35; - const wingWidth = 90; - const wingOffset = 130; - - ctx.beginPath(); - ctx.moveTo(attitudeIndMidX - wingOffset - wingWidth, attitudeIndMidY - wingThickness / 2); - ctx.lineTo(attitudeIndMidX - wingOffset, attitudeIndMidY - wingThickness / 2); - ctx.lineTo(attitudeIndMidX - wingOffset, attitudeIndMidY + wingHeight); - ctx.lineTo(attitudeIndMidX - wingOffset - wingThickness, attitudeIndMidY + wingHeight); - ctx.lineTo(attitudeIndMidX - wingOffset - wingThickness, attitudeIndMidY + wingThickness / 2); - ctx.lineTo(attitudeIndMidX - wingOffset - wingWidth, attitudeIndMidY + wingThickness / 2); - ctx.lineTo(attitudeIndMidX - wingOffset - wingWidth, attitudeIndMidY - wingThickness / 2); - ctx.lineWidth = 4; - ctx.fillStyle = 'black'; - ctx.strokeStyle = yellowColor; - ctx.stroke(); - ctx.fill(); - - ctx.beginPath(); - ctx.moveTo(attitudeIndMidX + wingOffset + wingWidth, attitudeIndMidY - wingThickness / 2); - ctx.lineTo(attitudeIndMidX + wingOffset, attitudeIndMidY - wingThickness / 2); - ctx.lineTo(attitudeIndMidX + wingOffset, attitudeIndMidY + wingHeight); - ctx.lineTo(attitudeIndMidX + wingOffset + wingThickness, attitudeIndMidY + wingHeight); - ctx.lineTo(attitudeIndMidX + wingOffset + wingThickness, attitudeIndMidY + wingThickness / 2); - ctx.lineTo(attitudeIndMidX + wingOffset + wingWidth, attitudeIndMidY + wingThickness / 2); - ctx.lineTo(attitudeIndMidX + wingOffset + wingWidth, attitudeIndMidY - wingThickness / 2); - ctx.lineWidth = 4; - ctx.fillStyle = 'black'; - ctx.strokeStyle = yellowColor; - ctx.stroke(); - ctx.fill(); - - ctx.strokeRect(attitudeIndMidX - wingThickness / 2, attitudeIndMidY - wingThickness / 2, wingThickness, wingThickness); - - // Radio altitude - if ((radioAltitude !== undefined) && (radioAltitude <= 2500)) { - ctx.font = "30px Arial"; - if (radioAltitude < 100) { - ctx.fillStyle = orangeColor; - } else { - ctx.fillStyle = greenColor; - } - const raText = Math.round(radioAltitude).toString(); - const raTextMetrics = ctx.measureText(raText); - ctx.fillText(raText, attitudeIndMidX - raTextMetrics.width / 2, attitudeIndTop + attitudeIndHeight - 4); - } -} - -function drawPressure(ctx, fm20, fm30) { - - if (pressure !== undefined) { - - const pressureLeft = 750; // Righthand side of altitude indicator - const pressureMidX = 750 + 80; // Lefthand side of altitude indicator - const pressureMidY = 850; - - const pressureInt = Math.round(pressure); - - if (isStd()) { - - const border = 3; - ctx.font = "30px Arial"; - ctx.fillStyle = cyanColor; - const pressureText = "STD"; - const pressureMetrics = ctx.measureText(pressureText); - const height = pressureMetrics.actualBoundingBoxAscent + pressureMetrics.actualBoundingBoxDescent + 2 * border; - ctx.fillText(pressureText, pressureMidX - pressureMetrics.width / 2, pressureMidY); - - ctx.lineWidth = 2; - ctx.strokeStyle = yellowColor; - ctx.strokeRect(pressureMidX - pressureMetrics.width / 2 - border, pressureMidY - pressureMetrics.actualBoundingBoxAscent - 2 * border, pressureMetrics.width + border * 2, height + border * 2); - - } else { - ctx.font = "30px Arial"; - ctx.fillStyle = "white"; - ctx.fillText("QNH", pressureLeft, pressureMidY); - - ctx.fillStyle = cyanColor; - const pressureText = pressureInt.toString(); - ctx.fillText(pressureText, pressureMidX, pressureMidY); - } - } -} - -function drawMachIndicator(ctx) { - if (mach !== undefined) { - if (mach >= 0.45) { // Actually comes on at .5 and goes off at 0.45 - - ctx.font = "38px Arial"; - ctx.fillStyle = greenColor; - var machString; - if (mach < 1) { - machString = mach.toFixed(3).substring(1); // No leading 0 - } else { - machString = mach.toFixed(2); - } - - ctx.fillText(machString, 40, 840); - } - } -} -function drawVerticalSpeedIndicator(ctx, fm20, fm30) { - - const verticalSpeedIndWidth = 50; - const verticalSpeedIndHeight = 620; - const verticalSpeedIndLeft = 900; - const verticalSpeedIndTop = 190; - const verticalSpeedIndBottom = verticalSpeedIndTop + verticalSpeedIndHeight; - const verticalSpeedIndMidY = verticalSpeedIndTop + + verticalSpeedIndHeight / 2; - const verticalSpeedIndMidX = verticalSpeedIndLeft + verticalSpeedIndWidth / 2; - const verticalSpeedIndRight = verticalSpeedIndLeft + verticalSpeedIndWidth; - const verticalSpeedBevel = 80; - const verticalSpeedMarkerSpacing = 35; - const verticalSpeedMarkerWidth = verticalSpeedIndWidth / 4; - const verticalSpeedMarkerLeft = verticalSpeedIndLeft + verticalSpeedMarkerWidth; - const verticalSpeedIndText = verticalSpeedIndLeft + 1; - const verticalSpeedLineRight = verticalSpeedIndRight + 30; - const verticalSpeedLineLeft = verticalSpeedIndMidX - 5; - - - // Background - ctx.beginPath(); - ctx.moveTo(verticalSpeedIndLeft, verticalSpeedIndTop); - ctx.lineTo(verticalSpeedIndMidX, verticalSpeedIndTop); - ctx.lineTo(verticalSpeedIndRight, verticalSpeedIndTop + verticalSpeedBevel); - ctx.lineTo(verticalSpeedIndRight, verticalSpeedIndBottom - verticalSpeedBevel); - ctx.lineTo(verticalSpeedIndMidX, verticalSpeedIndBottom); - ctx.lineTo(verticalSpeedIndLeft, verticalSpeedIndBottom); - ctx.lineTo(verticalSpeedIndLeft, verticalSpeedIndTop); - ctx.fillStyle = grayColor; - ctx.fill(); - - // Labels - ctx.font = "20px Arial"; - ctx.fillStyle = 'white'; - ctx.fillText("6", verticalSpeedIndText, verticalSpeedIndMidY - 8 * verticalSpeedMarkerSpacing + fm20.actualBoundingBoxAscent / 2); - ctx.fillText("2", verticalSpeedIndText, verticalSpeedIndMidY - 6 * verticalSpeedMarkerSpacing + fm20.actualBoundingBoxAscent / 2); - ctx.fillText("1", verticalSpeedIndText, verticalSpeedIndMidY - 4 * verticalSpeedMarkerSpacing + fm20.actualBoundingBoxAscent / 2); - ctx.fillText("1", verticalSpeedIndText, verticalSpeedIndMidY + 4 * verticalSpeedMarkerSpacing + fm20.actualBoundingBoxAscent / 2); - ctx.fillText("2", verticalSpeedIndText, verticalSpeedIndMidY + 6 * verticalSpeedMarkerSpacing + fm20.actualBoundingBoxAscent / 2); - ctx.fillText("6", verticalSpeedIndText, verticalSpeedIndMidY + 8 * verticalSpeedMarkerSpacing + fm20.actualBoundingBoxAscent / 2); - - // Markers - ctx.fillStyle = 'white'; - for (var i = -8; i <= 8; i++) - { - const j = Math.abs(i); - if (!((j == 1) || (j == 3))) { - var height; - if ((j == 4) || (j == 6) || (j == 8)) { - height = 6; - } else { - height = 2; - } - ctx.fillRect(verticalSpeedMarkerLeft, verticalSpeedIndMidY - i * verticalSpeedMarkerSpacing - height / 2, verticalSpeedMarkerWidth, height); - } - } - - // 0 marker - ctx.fillStyle = yellowColor; - ctx.fillRect(verticalSpeedIndLeft, verticalSpeedIndMidY - 3, verticalSpeedIndWidth / 2, 6); - - // Indicator line - - const verticalSpeedAbsolute = Math.abs(verticalSpeed); - var verticalOffset; - var color = greenColor; - - if (verticalSpeedAbsolute <= 1000) { - verticalOffset = verticalSpeedAbsolute / 1000 * 4 * verticalSpeedMarkerSpacing; - } else if (verticalSpeedAbsolute < 2000) { - verticalOffset = (verticalSpeedAbsolute - 1000) / 1000 * 2 * verticalSpeedMarkerSpacing + 4 * verticalSpeedMarkerSpacing; - } else if (verticalSpeedAbsolute < 6000) { - verticalOffset = (verticalSpeedAbsolute - 2000) / 4000 * 2 * verticalSpeedMarkerSpacing + 6 * verticalSpeedMarkerSpacing; - } else { - verticalOffset = 8 * verticalSpeedMarkerSpacing; - color = orangeColor; - } - - const verticalSpeedLineY = verticalSpeedIndMidY - verticalOffset * Math.sign(verticalSpeed); - - ctx.beginPath(); - ctx.moveTo(verticalSpeedLineRight, verticalSpeedIndMidY); - ctx.lineTo(verticalSpeedLineLeft, verticalSpeedLineY); - ctx.lineWidth = 4; - ctx.strokeStyle = color; - ctx.stroke(); - - // Text - if (verticalSpeedAbsolute > 200) { - - const verticalSpeedTextX = verticalSpeedLineLeft + 3; - const verticalSpeedTextHeight = fm20.actualBoundingBoxAscent + fm20.actualBoundingBoxDescent + 2; - const verticalSpeedText = Math.round(verticalSpeedAbsolute / 100); - const verticalSpeedTextString = verticalSpeedText.toString().padStart(2, '0'); - - // Background - ctx.fillStyle = 'black'; - if (verticalSpeed > 0) { - ctx.fillRect(verticalSpeedTextX, verticalSpeedLineY - verticalSpeedTextHeight, verticalSpeedIndWidth / 2, verticalSpeedTextHeight); - } else { - ctx.fillRect(verticalSpeedTextX, verticalSpeedLineY, verticalSpeedIndWidth / 2, verticalSpeedTextHeight); - } - - ctx.fillStyle = color; - if (verticalSpeed > 0) { - ctx.fillText(verticalSpeedTextString, verticalSpeedTextX, verticalSpeedLineY - fm20.actualBoundingBoxDescent - 1); - } else { - ctx.fillText(verticalSpeedTextString, verticalSpeedTextX, verticalSpeedLineY + fm20.actualBoundingBoxAscent + 1); - } - - } - -} - -// For testing only -var speedInc = 0.1; -var headingInc = 0.1; -var altitudeInc = 1; -var verticalSpeedInc = 10; -var rollInc = 0.1; -function animatePFD() { - if (speed === undefined) { - speed = 0; - targetSpeed = 200; - } else if (speed <= 0) { - speedInc = 0.1; - } else if (speed >= 350) { - speedInc = -0.1; - } - if (heading === undefined) { - heading = 0; - targetHeading = 180; - } else if (heading <= 0) { - headingInc = 0.1; - } else if (heading >= 360) { - headingInc = -0.1; - } - if (altitude === undefined) { - altitude = 0; - targetAltitude = 1000; - } else if (altitude <= 0) { - altitudeInc = 1; - } else if (altitude >= 45000) { - altitudeInc = -1; - } - if (verticalSpeed === undefined) { - verticalSpeed = -7000; - } else if (verticalSpeed <= -7000) { - verticalSpeedInc = 10; - } else if (verticalSpeed >= 7000) { - verticalSpeedInc = -10; - } - if (roll === undefined) { - roll = 45; - } else if (roll <= -45) { - rollInc = 0.1; - } else if (roll >= 45) { - rollInc = -0.1; - } - speed = speed + speedInc; - groundspeed = 150; - trueAirspeed = 130; - heading = heading + headingInc; - altitude = altitude + altitudeInc; - altitude = 39; - radioAltitude = 1720; - onSurface = 0; - verticalSpeed = verticalSpeed + verticalSpeedInc; - roll = roll + rollInc; - callsign = "BAW123G"; - aircraftType = "A320"; - windDirection = 85; - windSpeed = 15; - staticAirTemperature = 7; - verticalMode = 3; - lateralMode = 2; - autopilot = 1; - tcasMode = 1; - pressure = 1013; - //pressure = 1018; -} -function drawPFD() { - - const canvas = document.getElementById("pfdCanvas"); - const ctx = canvas.getContext("2d"); - - ctx.font = "20px Arial"; - const fm20 = ctx.measureText("180"); - ctx.font = "30px Arial"; - const fm30 = ctx.measureText("180"); - - // Background - - ctx.fillStyle = "black"; - ctx.fillRect(0, 0, 1000, 1000); - - // Airspeed indicator - - drawAirspeedIndicator(ctx, fm20, fm30); - - // Attitude indicator - - drawAttitudeIndicator(ctx, fm20, fm30); - - // Altimeter - - drawAltitudeIndicator(ctx, fm20, fm30); - - // Vertical speed indicator - - drawVerticalSpeedIndicator(ctx, fm20, fm30); - - // Heading indicator - - drawHeadingIndicator(ctx, fm20, fm30); - - // Pressure setting - - drawPressure(ctx, fm20, fm30); - - // Mach indicator - - drawMachIndicator(ctx); - - // Flight mode announciators - - ctx.beginPath(); - ctx.moveTo(220, 5); - ctx.lineTo(220, 140); - ctx.lineWidth = 1; - ctx.strokeStyle = "white"; - ctx.stroke(); - if (targetSpeed !== undefined) { - ctx.font = "30px Arial"; - ctx.fillStyle = greenColor; - ctx.fillText("SPEED", 55, 50); // THR CLB is climbing? - } else if (toga) { - ctx.font = "30px Arial"; - ctx.fillStyle = "white"; - ctx.fillText("TOGA", 70, 50); - } - - // FIXME: - //ctx.font = "30px Arial"; - //ctx.fillStyle = "white"; - //ctx.fillText("toga " + toga + " roll " + rollOut + " Surf " + onSurface + " wasSurf " + wasOnSurface60SecsAgo + " MS " + modelSpeed + " r/w Alt " + runwayAltitude, 50, 150); - - var landing = false; - if (verticalMode !== undefined) { - ctx.font = "30px Arial"; - ctx.fillStyle = greenColor; - if (verticalMode == 1) { - if (verticalSpeed !== undefined) { - if (verticalSpeed > 0) { - ctx.fillText("CLB", 290, 50); - } else if (verticalSpeed < 0) { - ctx.fillText("DES", 290, 50); - } else { - ctx.fillText("ALT", 290, 50); - } - } else if (targetAltitude !== undefined && altitude !== undefined) { - if (targetAltitude > altitude) { - ctx.fillText("CLB", 290, 50); - } else if (targetAltitude < altitude) { - ctx.fillText("DES", 290, 50); - } else { - ctx.fillText("ALT", 290, 50); - } - } - } else if (verticalMode == 2) { - ctx.fillText("ALT", 290, 50); - } else if (verticalMode == 3) { - if (rollOut) { - ctx.fillText("ROLL OUT", 370, 50); - landing = true; - } else if ((onSurface === 0) && (radioAltitude < 40)) { - ctx.fillText("FLARE", 390, 50); - landing = true; - } else if ((onSurface === 0) && (radioAltitude < 400)) { - ctx.fillText("LAND", 400, 50); - landing = true; - } else { - ctx.fillText("G/S", 290, 50); - } - } - } - if (!landing) { - ctx.beginPath(); - ctx.moveTo(420, 5); - ctx.lineTo(420, 140); - ctx.lineWidth = 1; - ctx.strokeStyle = "white"; - ctx.stroke(); - } - - ctx.beginPath(); - ctx.moveTo(660, 5); - ctx.lineTo(660, 140); - ctx.lineWidth = 1; - ctx.strokeStyle = "white"; - ctx.stroke(); - if (lateralMode !== undefined) { - ctx.font = "30px Arial"; - ctx.fillStyle = greenColor; - if (lateralMode == 1) { - ctx.fillText("NAV", 510, 50); - } else if (lateralMode == 2) { - if (!landing) { - ctx.fillText("LOC", 510, 50); - } - } - } - - ctx.beginPath(); - ctx.moveTo(850, 5); - ctx.lineTo(850, 140); - ctx.lineWidth = 1; - ctx.strokeStyle = "white"; - ctx.stroke(); - ctx.font = "30px Arial"; - ctx.fillStyle = "white"; - if (autopilot !== undefined) { - if (autopilot) { - if (verticalMode == 3) { - // We can't tell whether both APs are enabled - but they typically would be - ctx.fillText("AP1+2", 870, 40); - ctx.fillText("CAT3", 720, 40); - ctx.fillText("DUAL", 720, 85); - } else { - ctx.fillText("AP1", 890, 40); - } - } - } - ctx.fillText("1 FD 2", 870, 85); - if (((targetSpeed !== undefined) || autopilot) && !rollOut) { - ctx.fillText("A/THR", 870, 130); - } - - // Aircraft callsign and type - - ctx.fillStyle = "white"; - ctx.font = "30px Arial"; - if (callsign !== undefined) { - ctx.fillText(callsign, 20, 940); - } - ctx.font = "21px Arial"; - if (aircraftType !== undefined) { - ctx.fillText(aircraftType, 20, 980); - } - - const dataLeft = 750; // Aligned with QNH - const dataTop = 890; - - // TCAS - As displayed on ND/ECAM - if (tcasMode === 1) { - ctx.fillStyle = orangeColor; - ctx.font = "21px Arial"; - ctx.fillText("TCAS STBY", dataLeft, dataTop); - } else if (tcasMode === 2) { - ctx.fillStyle = "white"; - ctx.font = "21px Arial"; - ctx.fillText("TA ONLY", dataLeft, dataTop); - } - - // Groundspeed and TAS as displayed on ND - if ((groundspeed !== undefined) || (trueAirspeed !== undefined)) { - ctx.font = "21px Arial"; - if (groundspeed !== undefined) { - ctx.fillStyle = "white"; - ctx.fillText("GS", dataLeft, dataTop + 30); - ctx.fillStyle = greenColor; - ctx.fillText(Math.round(groundspeed).toString(), dataLeft + 40, dataTop + 30); - } - if (trueAirspeed !== undefined) { - ctx.fillStyle = "white"; - ctx.fillText("TAS", dataLeft + 90, dataTop + 30); - ctx.fillStyle = greenColor; - ctx.fillText(Math.round(trueAirspeed).toString(), dataLeft + 140, dataTop + 30); - } - } - - // Wind speed and direction as displayed on ND - if ((windSpeed !== undefined) && (windDirection !== undefined)) { - const windText = pad(Math.round(windDirection), 3) + "/" + Math.round(windSpeed); - ctx.fillStyle = greenColor; - ctx.font = "21px Arial"; - ctx.fillText(windText, dataLeft, dataTop + 60); - - if (heading !== undefined) { - // An arrow showing wind direction relative to heading - var angle = (windDirection - heading) * Math.PI / 180; - - ctx.save(); - ctx.translate(dataLeft + 80, dataTop + 53); - ctx.rotate(angle); - - ctx.strokeStyle = greenColor; - ctx.beginPath(); - ctx.moveTo(0, -10); - ctx.lineTo(0, 10); - ctx.lineTo(-5, 7); - ctx.moveTo(0, 10); - ctx.lineTo(5, 7); - ctx.stroke(); - - ctx.restore(); - } - } - - // Static air temperature as displayed on lower ECAM - if (staticAirTemperature !== undefined) { - var satText; - if (staticAirTemperature > 0) { - satText = "+" + Math.round(staticAirTemperature); - } else { - satText = Math.round(staticAirTemperature).toString(); - } - - ctx.font = "21px Arial"; - ctx.fillStyle = "white"; - ctx.fillText("SAT", dataLeft, dataTop + 90); - ctx.fillStyle = greenColor; - ctx.fillText(satText, dataLeft + 60, dataTop + 90); - ctx.fillStyle = cyanColor; - ctx.fillText("\u00B0C", dataLeft + 100, dataTop + 90); - } -} - -const canvas = document.getElementById('pfdCanvas'); -canvas.onmousedown = pfdMouseDown; -canvas.onmouseup = pfdMouseUp; -canvas.onmousemove = pfdMouseMove; -canvas.onmouseleave = pfdMouseLeave; -canvas.onmouseenter = pfdMouseEnter; -var docMouseMove = null; -var docMouseUp = null; -var movePFD = false; -var scalePFD = false; -var posX = 0; -var posY = 0; -var canvasWidth = 0; -var canvasHeight = 0; - -function pad(num, size) { - num = num.toString(); - while (num.length < size) num = "0" + num; - return num; -} - -function pfdMouseDown(e) { - e.preventDefault(); - e.stopPropagation(); - const r = canvas.getBoundingClientRect(); - posX = r.left; - posY = r.top; - canvasWidth = r.width; - canvasHeight = r.height; - if ((e.offsetX > 0.95 * canvasWidth) && (e.offsetY > 0.95 * canvasHeight)) { - scalePFD = true; - } else { - movePFD = true; - } -} -function pfdMouseUp(e) { - e.preventDefault(); - e.stopPropagation(); - movePFD = false; - scalePFD = false; - pfdRestoreDocMouse(); -} -function pfdMouseMove(e) { - e.preventDefault(); - e.stopPropagation(); - if (movePFD) { - posX = posX + e.movementX; - posY = posY + e.movementY; - canvas.style.position = "absolute"; - canvas.style.left = posX + "px"; - canvas.style.top = posY + "px"; - } else if (scalePFD) { - canvasWidth = canvasWidth + e.movementX; - canvasHeight = canvasHeight + e.movementY; - const constrainedWidth = Math.max(canvasWidth, 250); - const constrainedHeight = Math.max(canvasHeight, 250); - canvas.style.width = constrainedWidth + "px"; - canvas.style.height = constrainedHeight + "px"; - } -} - -function pfdMouseLeave(e) { - //movePFD = false; - //scalePFD = false; - if (scalePFD || movePFD) { - docMouseUp = document.onmouseup; - docMouseMove = document.onmousemove; - document.onmouseup = pfdMouseUp; - document.onmousemove = pfdMouseMove; - } -} - -function pfdRestoreDocMouse() { - if (docMouseUp) { - document.onmouseup = docMouseUp; - document.onmousemove = docMouseMove; - docMouseDown = null; - docMouseMove = null; - } -} -function pfdMouseEnter(e) { - pfdRestoreDocMouse(); -} +// Airbus like PFD (Primary Flight Display) + +var icao; +var callsign; +var aircraftType; +var onSurface; +var wasOnSurface60SecsAgo; +var speed; +var modelSpeed; // Speed of 3D model in Cesium +var trueAirspeed; +var groundspeed; +var targetSpeed; +var altitude; +var targetAltitude; +var radioAltitude; +var verticalSpeed; // ft/m +var heading; // degrees mag +var targetHeading; +var track; // degrees true +var pressure; // mb +var mach; +var roll; +var autopilot; +var verticalMode; +var lateralMode; +var tcasMode; +var windSpeed; +var windDirection; +var staticAirTemperature; + +var mdoelSpeed; +var toga = false; +var rollOut = false; +var runwayAltitude; + +const grayColor = "#6A75AE"; +const greenColor = "#20E966"; +const cyanColor = "#2FF7FE"; +const yellowColor = "#F4F82F"; +const orangeColor = "#FEDA30"; +const skyColor = "#26C9FF"; +const groundColor = "#D35E34"; + +function setPFDData(forward, newICAO, newCallsign, newAircraftType, newOnSurface, newWasOnSurface60SecsAgo, newRunwayAltitudeEstimate, + newModelSpeed, newIndicatedAirspeed, newTrueAirspeed, newGroundspeed, newMach, newAltitude, newRadioAltitude, newQnh, newVerticalSpeed, + newHeading, newTrack, newRoll, newSelectedAltitude, newSelectedHeading, + newAutopilot, newVerticalMode, newLateralMode, newTCASMode, + newWindSpeed, newWindDirection, newStaticAirTemperature) { + + //console.log('PFD', newIndicatedAirspeed, newMach, newAltitude, newQnh, newVerticalSpeed, newHeading, newTrack, newRoll, newSelectedAltitude, newSelectedHeading); + + const newAircraft = icao !== newICAO; + + if (newAircraft) { + toga = false; + rollOut = false; + runwayAltitude = undefined; + } + + icao = newICAO; + callsign = newCallsign; + aircraftType = newAircraftType; + onSurface = newOnSurface; + wasOnSurface60SecsAgo = newWasOnSurface60SecsAgo; + modelSpeed = newModelSpeed; + if ((newIndicatedAirspeed === undefined) || (newOnSurface > 0)) { + // IAS not transmitted frequently. After landing will no longer be valid + if (newGroundspeed !== undefined) { + speed = newGroundspeed; + } else { + speed = newModelSpeed; + } + } else { + speed = newIndicatedAirspeed; + } + trueAirspeed = newTrueAirspeed; + groundspeed = newGroundspeed; + mach = newMach; + altitude = newAltitude; + radioAltitude = newRadioAltitude; + pressure = newQnh; + verticalSpeed = newVerticalSpeed; + if (newHeading === undefined) { + heading = newTrack; // Track more frequent than heading + } else { + heading = newHeading; + } + track = newTrack; + roll = newRoll; + targetAltitude = newSelectedAltitude; + targetHeading = newSelectedHeading; + if (newAutopilot === -1) { + autopilot = undefined; + } else { + autopilot = newAutopilot; + } + verticalMode = newVerticalMode; + lateralMode = newLateralMode; + tcasMode = newTCASMode; + windSpeed = newWindSpeed; + windDirection = newWindDirection; + staticAirTemperature = newStaticAirTemperature; + + // Correct altitude for QNH setting + if (pressure !== undefined) { + altitude += (pressure - 1013.25) * 30; + } + + if (!rollOut && forward && (wasOnSurface60SecsAgo === 0) && (onSurface > 0) && (modelSpeed >= 70)) { + rollOut = true; + } else if (rollOut && ((modelSpeed < 40) || (onSurface === 0))) { + rollOut = false; + } + + const accelerationHeight = 1500; + + if (!toga && !rollOut && forward && (onSurface > 0) && (modelSpeed >= 35)) { + toga = true; // Start take-off roll on surface + runwayAltitude = altitude; + } else if (!toga && !rollOut && (modelSpeed >= 35) && (runwayAltitude === undefined) && (wasOnSurface60SecsAgo > 0) && (newRunwayAltitudeEstimate !== undefined)) { + toga = true; // For when selecting an aircraft having just taken off + runwayAltitude = newRunwayAltitudeEstimate; + } else if (!toga && !rollOut && (onSurface === 0) && (wasOnSurface60SecsAgo > 0) && (altitude !== undefined) && (runwayAltitude !== undefined) && (altitude < runwayAltitude + accelerationHeight)) { + toga = true; // For when played in reverse + } else if (toga && (modelSpeed <= 20)) { + toga = false; + } else if (toga && (altitude !== undefined) && (runwayAltitude !== undefined) && (altitude >= runwayAltitude + accelerationHeight)) { + toga = false; + } + if (toga && (runwayAltitude === undefined) && (newRunwayAltitudeEstimate !== undefined)) { + runwayAltitude = newRunwayAltitudeEstimate; + } +} + +function isStd() { + return (pressure >= 1012) && (pressure < 1014); +} + +function drawAirspeedIndicator(ctx, fm20, fm30) { + // Airspeed indicator + + const speedIndWidth = 100; + const speedIndHeight = 500; + const speedIndLeft = 30; + const speedIndRight = speedIndLeft + speedIndWidth; + const speedIndTop = 250; + const speedIndBottom = speedIndTop + speedIndHeight; + const speedIndMid = speedIndTop + speedIndHeight / 2; + + // Background + ctx.fillStyle = grayColor; + ctx.fillRect(speedIndLeft, speedIndTop, speedIndWidth, speedIndHeight); + + // Clip speed tape + ctx.save(); + ctx.rect(speedIndLeft, speedIndTop, speedIndWidth, speedIndHeight); + ctx.clip(); + + // Speed tape markings every 10knts + const speedTapMinSpeed = 0; // A320 only starts drawning from 30knts, but we draw from 0 + const speedTapeLeft = speedIndRight - 20; + const speedTapeRight = speedIndRight; + const speedTapeSpacing = 60; + const speedTapeStep = 10; + const speedTextStep = 20; + const speedPerPixel = speedTapeSpacing / speedTapeStep; + const speedOffset = (speed % speedTextStep) * speedPerPixel; + ctx.beginPath(); + var speedTape = Math.round(speed - speed % speedTextStep + 6 * speedTapeStep); + for (var i = -6; i < 5; i++) { + if (speedTape >= speedTapMinSpeed) { + ctx.moveTo(speedTapeLeft, speedOffset + i * speedTapeSpacing + speedIndMid); + ctx.lineTo(speedTapeRight, speedOffset + i * speedTapeSpacing + speedIndMid); + } + speedTape -= speedTapeStep; + } + ctx.lineWidth = 2; + ctx.strokeStyle = "white"; + ctx.stroke(); + + // Speeds every 20knts + var speedText = Math.round(speed - speed % speedTextStep + 3 * speedTextStep); + for (var i = -3; i < 3; i++) { + ctx.font = "30px Arial"; + ctx.fillStyle = "white"; + if (speedText >= speedTapMinSpeed) { + const speedTextString = speedText.toString().padStart(3, '0'); + ctx.fillText(speedTextString, speedIndLeft + 20, speedOffset + i * speedTapeSpacing * 2 + speedIndMid + fm30.actualBoundingBoxAscent / 2); + } + speedText -= speedTextStep; + } + + // Disable clipping + ctx.restore(); + + ctx.beginPath(); + ctx.moveTo(speedIndLeft, speedIndTop); + ctx.lineTo(speedIndRight + 30, speedIndTop); + var speedIndRightLineHeight = speed / (speedIndHeight / 2 / speedPerPixel); // White line on right only drawn down to speedTapMinSpeed + if (speedIndRightLineHeight > 1) { + speedIndRightLineHeight = 1; + ctx.moveTo(speedIndLeft, speedIndTop + speedIndHeight); + ctx.lineTo(speedIndRight + 30, speedIndTop + speedIndHeight); + } + ctx.moveTo(speedIndRight, speedIndTop); + ctx.lineTo(speedIndRight, speedIndTop + speedIndRightLineHeight * (speedIndHeight / 2) + (speedIndHeight / 2)); + ctx.lineWidth = 2; + ctx.strokeStyle = "white"; + ctx.stroke(); + + // Speed indicator + ctx.beginPath(); + ctx.moveTo(speedIndLeft - 10, speedIndMid); + ctx.lineTo(speedIndLeft, speedIndMid); + ctx.moveTo(speedTapeLeft - 5, speedIndMid); + ctx.lineTo(speedTapeRight + 20, speedIndMid); + ctx.lineWidth = 2; + ctx.strokeStyle = yellowColor; + ctx.stroke(); + + ctx.beginPath(); + ctx.moveTo(speedTapeRight + 10, speedIndMid); + ctx.lineTo(speedTapeRight + 35, speedIndMid - 10); + ctx.lineTo(speedTapeRight + 35, speedIndMid + 10); + ctx.lineTo(speedTapeRight + 10, speedIndMid); + ctx.fillStyle = yellowColor; + ctx.fill(); + + // Target speed + + if (targetSpeed !== undefined) { + var targetSpeedY = (speed - targetSpeed) * speedPerPixel; + targetSpeedY = targetSpeedY + speedIndMid; + if (targetSpeedY < speedIndTop) { + // Target speed as text on top + ctx.font = "20px Arial"; + ctx.fillStyle = cyanColor; + const targetSpeedMetrics = ctx.measureText(targetSpeed); + ctx.fillText(targetSpeed, speedIndRight - targetSpeedMetrics.width / 2, speedIndTop - 4); + + } else if (targetSpeedY > speedIndBottom) { + // Target speed as text underneath + ctx.font = "20px Arial"; + ctx.fillStyle = cyanColor; + const targetSpeedMetrics = ctx.measureText(targetSpeed); + ctx.fillText(targetSpeed, speedIndRight - targetSpeedMetrics.width / 2, speedIndBottom + fm20.actualBoundingBoxAscent + 4); + } else { + // Cyan triangle on right side + const targetSpeedWidth = 40; + const targetSpeedHeight = 30; + const targetSpeedLeft = speedIndRight; + const targetSpeedRight = targetSpeedLeft + targetSpeedWidth; + + ctx.beginPath(); + ctx.moveTo(targetSpeedLeft, targetSpeedY); + ctx.lineTo(targetSpeedRight, targetSpeedY - targetSpeedHeight / 2); + ctx.lineTo(targetSpeedRight, targetSpeedY + targetSpeedHeight / 2); + ctx.lineTo(targetSpeedLeft, targetSpeedY); + ctx.lineWidth = 2; + ctx.strokeStyle = cyanColor; + ctx.stroke(); + } + } +} + +function drawAltitudeIndicator(ctx, fm20, fm30) { + // Altitude indicator + + const altitudeIndWidth = 70; + const altitudeIndHeight = 500; + const altitudeIndLeft = 750; + const altitudeIndRight = altitudeIndLeft + altitudeIndWidth; + const altitudeIndTop = 250; + const altitudeIndBottom = altitudeIndTop + altitudeIndHeight; + const altitudeIndMid = altitudeIndTop + altitudeIndHeight / 2; + + // Background + ctx.fillStyle = grayColor; + ctx.fillRect(altitudeIndLeft, altitudeIndTop, altitudeIndWidth, altitudeIndHeight); + + ctx.font = "30px Arial"; + const greaterThanMetrics = ctx.measureText(">"); + + // Mid point marker (for glideslope, but always visible) + ctx.fillStyle = yellowColor; + ctx.fillRect(altitudeIndLeft - 70, altitudeIndMid - 3, 50, 6); + + // Clip altitude tape + ctx.save(); + ctx.rect(altitudeIndLeft - greaterThanMetrics.width, altitudeIndTop, altitudeIndWidth + greaterThanMetrics.width, altitudeIndHeight); + ctx.clip(); + + // Altitude tape markings every 100 ft + const altitudeTapeLeft = altitudeIndRight - 10; + const altitudeTapeRight = altitudeIndRight; + const altitudeTapeSpacing = 40; + const altitudeTapeStep = 100; + const altitudeTextStep = 500; + const altitudePerPixel = altitudeTapeSpacing / altitudeTapeStep; // reciprocal + const altitudeOffset = (altitude % altitudeTextStep) * altitudePerPixel; + ctx.beginPath(); + var altitudeTape = Math.round(altitude - altitude % altitudeTextStep + 10 * altitudeTapeStep); + for (var i = -10; i < 7; i++) { + ctx.moveTo(altitudeTapeLeft, altitudeOffset + i * altitudeTapeSpacing + altitudeIndMid); + ctx.lineTo(altitudeTapeRight, altitudeOffset + i * altitudeTapeSpacing + altitudeIndMid); + altitudeTape -= altitudeTapeStep; + } + ctx.lineWidth = 2; + ctx.strokeStyle = "white"; + ctx.stroke(); + + // Flight level texts every 500ft + ctx.font = "30px Arial"; + ctx.fillStyle = "white"; + var altitudeText = Math.round(altitude - altitude % altitudeTextStep + 2 * altitudeTextStep); + for (var i = -2; i < 2; i++) { + const flightLevelText = Math.abs(altitudeText / 100); // Don't display - if negative + const flightLevelTextString = ">" + flightLevelText.toString().padStart(3, '0'); + ctx.fillText(flightLevelTextString, altitudeIndLeft - greaterThanMetrics.width, altitudeOffset + i * altitudeTapeSpacing * 5 + altitudeIndMid + fm30.actualBoundingBoxAscent / 2); + altitudeText -= altitudeTextStep; + } + + // Disable clipping + ctx.restore(); + + // White lines at top, bottom and on right + ctx.beginPath(); + ctx.moveTo(altitudeIndLeft, altitudeIndTop); + ctx.lineTo(altitudeIndRight + 30, altitudeIndTop); + ctx.moveTo(altitudeIndLeft, altitudeIndTop + altitudeIndHeight); + ctx.lineTo(altitudeIndRight + 30, altitudeIndTop + altitudeIndHeight); + ctx.moveTo(altitudeIndRight, altitudeIndTop); + ctx.lineTo(altitudeIndRight, altitudeIndTop + altitudeIndHeight); + ctx.lineWidth = 2; + ctx.strokeStyle = "white"; + ctx.stroke(); + + // Target altitude + + if (targetAltitude !== undefined) { + var targetAltitudeY = (altitude - targetAltitude) * altitudePerPixel; + targetAltitudeY = targetAltitudeY + altitudeIndMid; + + if (isStd()) { + targetAltitudeText = Math.round(targetAltitude / 100); + } else { + targetAltitudeText = Math.round(targetAltitude); + } + + if (targetAltitudeY < altitudeIndTop) { + // Target altitude as text on top + ctx.font = "30px Arial"; + ctx.fillStyle = cyanColor; + const targetAltitudeMetrics = ctx.measureText(targetAltitudeText); + if (isStd()) { + ctx.fillText("FL", altitudeIndLeft, altitudeIndTop - 4); + } + ctx.fillText(targetAltitudeText, altitudeIndRight - targetAltitudeMetrics.width / 2, altitudeIndTop - 4); + } else if (targetAltitudeY > altitudeIndBottom) { + // Target altitude as text underneath + ctx.font = "30px Arial"; + ctx.fillStyle = cyanColor; + const targetAltitudeMetrics = ctx.measureText(targetAltitudeText); + if (isStd()) { + ctx.fillText("FL", altitudeIndLeft, altitudeIndBottom + fm30.actualBoundingBoxAscent + 4); + } + ctx.fillText(targetAltitudeText, altitudeIndRight - targetAltitudeMetrics.width / 2, altitudeIndBottom + fm30.actualBoundingBoxAscent + 4); + } else { + + // Clip + ctx.save(); + ctx.rect(altitudeIndLeft - greaterThanMetrics.width, altitudeIndTop, altitudeIndWidth + greaterThanMetrics.width, altitudeIndHeight); + ctx.clip(); + + targetAltitudeText = targetAltitudeText.toString().padStart(3, '0'); + + ctx.font = "30px Arial"; + ctx.fillStyle = cyanColor; + const targetAltitudeMetrics = ctx.measureText(targetAltitudeText); + + // Cyan box + const targetAltitudeWidth = 30; + const targetAltitudeHeight = 3 * (fm30.actualBoundingBoxAscent + fm30.actualBoundingBoxDescent); + const targetAltitudeBoxHeight = 1.1 * (fm30.actualBoundingBoxAscent + fm30.actualBoundingBoxDescent); + const targetAltitudeLeft = altitudeIndLeft - 5; + const targetAltitudeRight = targetAltitudeLeft + targetAltitudeWidth; + + ctx.beginPath(); + ctx.moveTo(targetAltitudeLeft, targetAltitudeY - targetAltitudeHeight / 2); + ctx.lineTo(targetAltitudeLeft, targetAltitudeY - 5); + ctx.lineTo(targetAltitudeLeft + 5, targetAltitudeY); + ctx.lineTo(targetAltitudeLeft, targetAltitudeY + 5); + ctx.lineTo(targetAltitudeLeft, targetAltitudeY + targetAltitudeHeight / 2); + ctx.lineTo(targetAltitudeRight, targetAltitudeY + targetAltitudeHeight / 2); + ctx.lineTo(targetAltitudeRight, targetAltitudeY - targetAltitudeHeight / 2); + ctx.lineTo(targetAltitudeLeft, targetAltitudeY - targetAltitudeHeight / 2); + ctx.lineWidth = 2; + ctx.lineWidth = 2; + ctx.strokeStyle = cyanColor; + ctx.stroke(); + + ctx.fillStyle = 'black'; + ctx.fillRect(altitudeIndLeft, targetAltitudeY - targetAltitudeBoxHeight / 2, altitudeIndWidth - 2, targetAltitudeBoxHeight); + ctx.fillStyle = cyanColor; + ctx.fillText(targetAltitudeText, altitudeIndLeft, targetAltitudeY + fm30.actualBoundingBoxAscent / 2); + + // Disable clipping + ctx.restore(); + } + } + + // Altitude + + ctx.font = "34px Arial"; + const levelText = (altitude === undefined) || isNaN(altitude) ? "" : Math.floor(altitude / 100).toString(); + const levelTextMetrics = ctx.measureText(levelText); + const levelTextHeightMetrics = ctx.measureText("0"); + const border = 2; + const levelHeight = levelTextHeightMetrics.actualBoundingBoxAscent + levelTextHeightMetrics.actualBoundingBoxDescent + 8 * border; + + const subscaleHeight = 60; + const subscaleWidth = 30; + + // Black background box + ctx.fillStyle = 'black'; + ctx.fillRect(altitudeIndLeft, altitudeIndMid - levelHeight / 2, altitudeIndWidth + 1, levelHeight); + + // Current flight level + if (levelText !== "") { + ctx.fillStyle = greenColor; + ctx.fillText(levelText, altitudeIndRight - levelTextMetrics.width, altitudeIndMid + levelTextMetrics.actualBoundingBoxAscent / 2); + } + + // Yellow box + ctx.beginPath(); + ctx.moveTo(altitudeIndLeft, altitudeIndMid - levelHeight / 2); + ctx.lineTo(altitudeIndRight, altitudeIndMid - levelHeight / 2); + ctx.lineTo(altitudeIndRight, altitudeIndMid - subscaleHeight / 2); + ctx.lineTo(altitudeIndRight + subscaleWidth, altitudeIndMid - subscaleHeight / 2); + ctx.lineTo(altitudeIndRight + subscaleWidth, altitudeIndMid + subscaleHeight / 2); + ctx.lineTo(altitudeIndRight, altitudeIndMid + subscaleHeight / 2); + ctx.lineTo(altitudeIndRight, altitudeIndMid + levelHeight / 2); + ctx.lineTo(altitudeIndLeft, altitudeIndMid + levelHeight / 2); + ctx.lineWidth = 2; + if (Math.abs(verticalSpeed) >= 6000) { + ctx.strokeStyle = orangeColor; + } else { + ctx.strokeStyle = yellowColor; + } + ctx.stroke(); + + // Clip around subscale + ctx.save(); + ctx.rect(altitudeIndRight, altitudeIndMid - subscaleHeight / 2, subscaleWidth, subscaleHeight); + ctx.clip(); + + const subscaleStep = 20; + var subscaleText = (altitude % 100) + subscaleStep * 2; + var subscaleSpacing = fm20.actualBoundingBoxAscent + fm20.actualBoundingBoxDescent + 2; + const subscalePerPixel = subscaleSpacing / subscaleStep; // reciprocal + const subscaleOffset = (altitude % subscaleStep) * subscalePerPixel; + ctx.font = "20px Arial"; + for (var i = -2; i < 2; i++) { + const subscaleTextString = (Math.floor((subscaleText % 100) / subscaleStep) * subscaleStep).toString().padStart(2, '0'); + ctx.fillText(subscaleTextString, altitudeIndRight + 1, subscaleOffset + i * subscaleSpacing + altitudeIndMid + fm20.actualBoundingBoxAscent / 2); + subscaleText -= subscaleStep; + if (subscaleText < 0) { + subscaleText += 100; + } + } + + // Disable clipping + ctx.restore(); +} +function drawHeadingIndicator(ctx, fm20, fm30) { + + const headingIndWidth = 450; + const headingIndHeight = 60; + const headingIndLeft = 225; + const headingIndRight = headingIndLeft + headingIndWidth; + const headingIndTop = 890; + const headingIndBottom = headingIndTop + headingIndHeight; + const headingIndMid = headingIndLeft + headingIndWidth / 2; + + ctx.fillStyle = grayColor; + ctx.fillRect(headingIndLeft, headingIndTop, headingIndWidth, headingIndHeight); + + // White lines left, right and top + ctx.beginPath(); + ctx.moveTo(headingIndLeft, headingIndBottom); + ctx.lineTo(headingIndLeft, headingIndTop); + ctx.lineTo(headingIndRight, headingIndTop); + ctx.lineTo(headingIndRight, headingIndBottom); + ctx.lineWidth = 2; + ctx.strokeStyle = "white"; + ctx.stroke(); + + // Heading indicator line + ctx.beginPath(); + ctx.moveTo(headingIndMid, headingIndTop - 30); + ctx.lineTo(headingIndMid, headingIndTop); + ctx.lineWidth = 4; + ctx.strokeStyle = yellowColor; + ctx.stroke(); + + // Clip tape + ctx.save(); + ctx.rect(headingIndLeft, headingIndTop, headingIndWidth, headingIndHeight); + ctx.clip(); + + // Tape markings every 5 degrees + const headingTapeLeft = headingIndRight - 20; + const headingTapeRight = headingIndRight; + const headingTapeSpacing = 50; + const headingTapeStep = 5; + const headingTextStep = 10; + const headingPerPixel = headingTapeSpacing / headingTapeStep; + const headingOffset = - (heading % headingTextStep) * headingPerPixel; + ctx.beginPath(); + var headingTape = Math.round(heading - heading % headingTextStep - 6 * headingTapeStep); + for (var i = -6; i < 7; i++) { + ctx.moveTo(headingOffset + i * headingTapeSpacing + headingIndMid, headingIndTop); + if (headingTape % 10 != 0) { + ctx.lineTo(headingOffset + i * headingTapeSpacing + headingIndMid, headingIndTop + 10); + } else { + ctx.lineTo(headingOffset + i * headingTapeSpacing + headingIndMid, headingIndTop + 20); + } + headingTape += headingTapeStep; + } + ctx.lineWidth = 2; + ctx.strokeStyle = "white"; + ctx.stroke(); + + ctx.font = "30px Arial"; + ctx.fillStyle = "white"; + const headingMetricsBig = ctx.measureText("36"); + ctx.font = "24px Arial"; + ctx.fillStyle = "white"; + const headingMetricsSmall = ctx.measureText("36"); + + // Headings every 10 degrees + var headingText = Math.round(heading - heading % headingTextStep - 3 * headingTextStep); + for (var i = -3; i < 4; i++) { + const big = headingText % 30 == 0; + if (big) { + ctx.font = "30px Arial"; + } else { + ctx.font = "24px Arial"; + } + ctx.fillStyle = "white"; + var headingTextMod = Math.round(headingText / 10) % 36; + if (headingTextMod < 0) { + headingTextMod += 36; + } + const headingTextString = headingTextMod.toString(); + const headingMetrics = ctx.measureText(headingTextString); + + ctx.fillText(headingTextString, headingOffset + i * headingTapeSpacing * 2 + headingIndMid - headingMetrics.width / 2, headingIndTop + 30 + headingMetrics.actualBoundingBoxAscent); + headingText += headingTextStep; + } + + // Track diamond + + if (track !== undefined) { + const trackMid = headingIndMid + (track - heading) * headingPerPixel; + const trackSize = 20; + + ctx.beginPath(); + ctx.moveTo(trackMid, headingIndTop); + ctx.lineTo(trackMid - trackSize / 2, headingIndTop + trackSize / 2); + ctx.lineTo(trackMid, headingIndTop + trackSize); + ctx.lineTo(trackMid + trackSize / 2, headingIndTop + trackSize / 2); + ctx.lineTo(trackMid, headingIndTop); + ctx.lineWidth = 5; + ctx.strokeStyle = greenColor; + ctx.stroke(); + } + + // Disable clipping + ctx.restore(); + + // Target heading + + if (targetHeading !== undefined) { + var targetDiff = targetHeading - heading; + if (targetDiff > 180) { + targetDiff -= 360; + } + var targetMid = headingIndMid + targetDiff * headingPerPixel; + if (targetMid < headingIndLeft) { + + // Display target heading as text on left + ctx.font = "20px Arial"; + ctx.fillStyle = cyanColor; + const targetHeadingText = Math.round(targetHeading).toString().padStart(3, '0'); + const targetHeadingMetrics = ctx.measureText(targetHeadingText); + ctx.fillText(targetHeadingText, headingIndLeft, headingIndTop - 4); + + } else if (targetMid > headingIndRight) { + + // Display target heading as text on right + ctx.font = "20px Arial"; + ctx.fillStyle = cyanColor; + const targetHeadingText = Math.round(targetHeading).toString().padStart(3, '0'); + const targetHeadingMetrics = ctx.measureText(targetHeadingText); + ctx.fillText(targetHeadingText, headingIndRight - targetHeadingMetrics.width, headingIndTop - 4); + + } else { + // Target indicator triangle + + const targetWidth = 30; + const targetHeight = 40; + + ctx.beginPath(); + ctx.moveTo(targetMid, headingIndTop); + ctx.lineTo(targetMid - targetWidth / 2, headingIndTop - targetHeight); + ctx.lineTo(targetMid + targetWidth / 2, headingIndTop - targetHeight); + ctx.lineTo(targetMid, headingIndTop); + ctx.lineWidth = 2; + ctx.strokeStyle = cyanColor; + ctx.stroke(); + } + } +} + +function drawBankAngleBoxMarker(ctx, radius, height) { + ctx.beginPath(); + ctx.moveTo(-5, -radius); + ctx.lineTo(-5, -radius - height); + ctx.lineTo(5, -radius - height); + ctx.lineTo(5, -radius); + ctx.lineWidth = 2; + ctx.strokeStyle = 'white'; + ctx.stroke(); +} + +function drawBankAngleLineMarker(ctx, radius, height) { + ctx.beginPath(); + ctx.moveTo(0, -radius); + ctx.lineTo(0, -radius - height); + ctx.lineWidth = 2; + ctx.strokeStyle = 'white'; + ctx.stroke(); +} +function drawAttitudeIndicator(ctx, fm20, fm30) { + + if (roll === undefined) { + return; + } + + // Height the same as airspeed indicator - cropped width same as heading indicator + + const speedIndRight = 30 + 100; + const altitudeIndLeft = 750; + + const attitudeIndMidX = speedIndRight + ((altitudeIndLeft - speedIndRight) / 2); + //const attitudeIndLeft = 30 + 100; // speedIndRight + //const attitudeIndRight = 750; // altitudeIndLeft + const attitudeIndWidth = 500; // speedIndHeight = 500; // attitudeIndRight - attitudeIndLeft; + const attitudeIndTop = 250; + const attitudeIndLeft = attitudeIndMidX - attitudeIndWidth / 2; + const attitudeIndHeight = attitudeIndWidth; // It's a circle + const attitudeIndMidY = attitudeIndTop + attitudeIndHeight / 2; + const attitudeIndCrop = (attitudeIndWidth - 450) / 2; // headingIndWidth = 450 + + // Clip + ctx.save(); + //ctx.arc(attitudeIndMidX, attitudeIndMidY, attitudeIndWidth / 2, 0, 2 * Math.PI); + ctx.beginPath(); + ctx.arc(attitudeIndMidX, attitudeIndMidY, attitudeIndWidth / 2, Math.PI / 10 + Math.PI, Math.PI - Math.PI / 10 + Math.PI); + ctx.arc(attitudeIndMidX, attitudeIndMidY, attitudeIndWidth / 2, Math.PI / 10, Math.PI - Math.PI / 10); +// //ctx.rect(attitudeIndLeft + attitudeIndCrop, attitudeIndTop, attitudeIndWidth - 2 * attitudeIndCrop, attitudeIndWidth); + // ctx.rect(attitudeIndLeft + attitudeIndCrop, attitudeIndTop, attitudeIndWidth - 2 * attitudeIndCrop, attitudeIndWidth); + ctx.clip(); + + + // Background + //ctx.beginPath(); + //ctx.fillStyle = cyanColor; + //ctx.arc(attitudeIndMidX, attitudeIndMidY, attitudeIndWidth / 2, Math.PI / 10, Math.PI - Math.PI / 10); + //ctx.arc(attitudeIndMidX, attitudeIndMidY, attitudeIndWidth / 2, Math.PI / 10 + Math.PI, Math.PI - Math.PI / 10 + Math.PI); + //console.log(attitudeIndMidX, attitudeIndMidY, attitudeIndWidth / 2, 0, 2 * Math.PI); + //ctx.fill(); + + ctx.fillStyle = skyColor; + ctx.fillRect(attitudeIndLeft, attitudeIndTop, attitudeIndWidth, attitudeIndWidth); + + const rollRad = -roll * Math.PI / 180; + const radius = attitudeIndWidth / 2; + + ctx.fillStyle = groundColor; + ctx.beginPath(); + ctx.arc(attitudeIndMidX, attitudeIndMidY, radius, 0 + rollRad, Math.PI + rollRad); + ctx.fill(); + + //const offsetX = Math.cos(rollRad) * radius; + //const offsetY = Math.sin(rollRad) * radius; + //ctx.beginPath(); + //ctx.moveTo(attitudeIndMidX - offsetX, attitudeIndMidY - offsetY); + //ctx.lineTo(attitudeIndMidX + offsetX, attitudeIndMidY + offsetY); + //ctx.lineWidth = 2; + //ctx.strokeStyle = 'white'; + //ctx.stroke(); + + // Disable clipping + //ctx.restore(); + + const twoAndHalfDegOffset = 15; + const fiveDegOffset = twoAndHalfDegOffset * 2; + const tenDegOffset = twoAndHalfDegOffset * 4; + const fifteenDegOffset = twoAndHalfDegOffset * 2.5; + const spacing = 50; + + // ctx.save(); + + ctx.translate(attitudeIndMidX, attitudeIndMidY); + ctx.rotate(rollRad); + + ctx.beginPath(); + ctx.moveTo(-radius, 0); + ctx.lineTo(radius, 0); + for (var i = -2; i < 4; i++) { + ctx.moveTo(-twoAndHalfDegOffset, -i * spacing - spacing / 2); + ctx.lineTo(twoAndHalfDegOffset, -i * spacing - spacing / 2); + } + for (var i = -1; i < 5; i++) { + ctx.moveTo(-fiveDegOffset, -i * spacing); + ctx.lineTo(fiveDegOffset, -i * spacing); + } + for (var i = -1; i < 3; i++) { + ctx.moveTo(-tenDegOffset, -i * 2 * spacing); + ctx.lineTo(tenDegOffset, -i * 2 * spacing); + } + ctx.moveTo(-fifteenDegOffset, 2.75 * spacing); + ctx.lineTo(fifteenDegOffset, 2.75 * spacing); + ctx.moveTo(-tenDegOffset, 3.5 * spacing); + ctx.lineTo(tenDegOffset, 3.5 * spacing); + ctx.lineWidth = 2; + ctx.strokeStyle = 'white'; + ctx.stroke(); + + const greenThingWidth = 20; + ctx.beginPath(); + ctx.strokeStyle = greenColor; + ctx.moveTo(-fifteenDegOffset - greenThingWidth, 2.75 * spacing - 3); + ctx.lineTo(-fifteenDegOffset, 2.75 * spacing - 3); + ctx.moveTo(-fifteenDegOffset - greenThingWidth, 2.75 * spacing + 3); + ctx.lineTo(-fifteenDegOffset, 2.75 * spacing + 3); + ctx.moveTo(fifteenDegOffset + greenThingWidth, 2.75 * spacing - 3); + ctx.lineTo(fifteenDegOffset, 2.75 * spacing - 3); + ctx.moveTo(fifteenDegOffset + greenThingWidth, 2.75 * spacing + 3); + ctx.lineTo(fifteenDegOffset, 2.75 * spacing + 3); + ctx.stroke(); + + ctx.font = "20px Arial"; + ctx.fillStyle = 'white'; + const labelMetrics = ctx.measureText("20"); + const labelCenterY = labelMetrics.actualBoundingBoxAscent / 2; + const labelOffset = tenDegOffset + 10; + + ctx.fillText("10", labelOffset, spacing * 2 + labelCenterY); + ctx.fillText("10", -labelOffset - labelMetrics.width, spacing * 2 + labelCenterY); + ctx.fillText("10", labelOffset, -spacing * 2 + labelCenterY); + ctx.fillText("10", -labelOffset - labelMetrics.width, -spacing * 2 + labelCenterY); + ctx.fillText("20", labelOffset, -spacing * 4 + labelCenterY); + ctx.fillText("20", -labelOffset - labelMetrics.width, -spacing * 4 + labelCenterY); + ctx.fillText("20", labelOffset, spacing * 3.5 + labelCenterY); + ctx.fillText("20", -labelOffset - labelMetrics.width, spacing * 3.5 + labelCenterY); + + const rollBig = 18; + const rollSmall = 10; + + const rollTriangleOffet = 4; + + ctx.beginPath(); + ctx.moveTo(0, -radius + rollTriangleOffet); + ctx.lineTo(rollBig, -radius + rollBig + rollTriangleOffet); + ctx.lineTo(-rollBig, -radius + rollBig + rollTriangleOffet); + ctx.lineTo(0, -radius + rollTriangleOffet); + ctx.lineWidth = 2; + ctx.strokeStyle = yellowColor; + ctx.stroke(); + + const rollTrapX1 = 20; + const rollTrapX2 = 30; + const rollTrapY1 = -radius + rollBig + rollTriangleOffet + 5; + const rollTrapY2 = rollTrapY1 + 10; + + ctx.beginPath(); + ctx.moveTo(-rollTrapX1, rollTrapY1); + ctx.lineTo(rollTrapX1, rollTrapY1); + ctx.lineTo(rollTrapX2, rollTrapY2); + ctx.lineTo(-rollTrapX2, rollTrapY2); + ctx.lineTo(-rollTrapX1, rollTrapY1); + ctx.lineWidth = 2; + ctx.strokeStyle = yellowColor; + ctx.stroke(); + + ctx.restore(); + + // Roll scale + + ctx.save(); + ctx.translate(attitudeIndMidX, attitudeIndMidY); + + ctx.beginPath(); + ctx.rect(-radius, -radius - 2 *rollBig , radius * 2, radius); + ctx.clip(); + + ctx.beginPath(); + ctx.moveTo(0, -radius); + ctx.lineTo(rollBig, -radius - rollBig); + ctx.lineTo(-rollBig, -radius - rollBig); + ctx.lineTo(0, -radius); + ctx.lineWidth = 2; + ctx.strokeStyle = yellowColor; + ctx.stroke(); + + ctx.beginPath(); + ctx.arc(0, 0, radius, (240 - 2) * Math.PI / 180, (300 + 2) * Math.PI / 180); + ctx.lineWidth = 2; + ctx.strokeStyle = 'white'; + ctx.stroke(); + + ctx.rotate(45 * Math.PI / 180); + drawBankAngleLineMarker(ctx, radius, rollBig); + ctx.rotate(-15 * Math.PI / 180); + drawBankAngleBoxMarker(ctx, radius, rollBig); + ctx.rotate(-10 * Math.PI / 180); + drawBankAngleBoxMarker(ctx, radius, 10); + ctx.rotate(-10 * Math.PI / 180); + drawBankAngleBoxMarker(ctx, radius, 10); + ctx.rotate(-10 * Math.PI / 180); + + ctx.rotate(-10 * Math.PI / 180); + drawBankAngleBoxMarker(ctx, radius, 10); + ctx.rotate(-10 * Math.PI / 180); + drawBankAngleBoxMarker(ctx, radius, 10); + ctx.rotate(-10 * Math.PI / 180); + drawBankAngleBoxMarker(ctx, radius, rollBig); + ctx.rotate(-15 * Math.PI / 180); + drawBankAngleLineMarker(ctx, radius, rollBig); + + + // ctx.rotate(-rollRad); + // ctx.translate(-attitudeIndMidX, -attitudeIndMidY); + + ctx.restore(); + + // Wings + const wingThickness = 14; + const wingHeight = 35; + const wingWidth = 90; + const wingOffset = 130; + + ctx.beginPath(); + ctx.moveTo(attitudeIndMidX - wingOffset - wingWidth, attitudeIndMidY - wingThickness / 2); + ctx.lineTo(attitudeIndMidX - wingOffset, attitudeIndMidY - wingThickness / 2); + ctx.lineTo(attitudeIndMidX - wingOffset, attitudeIndMidY + wingHeight); + ctx.lineTo(attitudeIndMidX - wingOffset - wingThickness, attitudeIndMidY + wingHeight); + ctx.lineTo(attitudeIndMidX - wingOffset - wingThickness, attitudeIndMidY + wingThickness / 2); + ctx.lineTo(attitudeIndMidX - wingOffset - wingWidth, attitudeIndMidY + wingThickness / 2); + ctx.lineTo(attitudeIndMidX - wingOffset - wingWidth, attitudeIndMidY - wingThickness / 2); + ctx.lineWidth = 4; + ctx.fillStyle = 'black'; + ctx.strokeStyle = yellowColor; + ctx.stroke(); + ctx.fill(); + + ctx.beginPath(); + ctx.moveTo(attitudeIndMidX + wingOffset + wingWidth, attitudeIndMidY - wingThickness / 2); + ctx.lineTo(attitudeIndMidX + wingOffset, attitudeIndMidY - wingThickness / 2); + ctx.lineTo(attitudeIndMidX + wingOffset, attitudeIndMidY + wingHeight); + ctx.lineTo(attitudeIndMidX + wingOffset + wingThickness, attitudeIndMidY + wingHeight); + ctx.lineTo(attitudeIndMidX + wingOffset + wingThickness, attitudeIndMidY + wingThickness / 2); + ctx.lineTo(attitudeIndMidX + wingOffset + wingWidth, attitudeIndMidY + wingThickness / 2); + ctx.lineTo(attitudeIndMidX + wingOffset + wingWidth, attitudeIndMidY - wingThickness / 2); + ctx.lineWidth = 4; + ctx.fillStyle = 'black'; + ctx.strokeStyle = yellowColor; + ctx.stroke(); + ctx.fill(); + + ctx.strokeRect(attitudeIndMidX - wingThickness / 2, attitudeIndMidY - wingThickness / 2, wingThickness, wingThickness); + + // Radio altitude + if ((radioAltitude !== undefined) && (radioAltitude <= 2500)) { + ctx.font = "30px Arial"; + if (radioAltitude < 100) { + ctx.fillStyle = orangeColor; + } else { + ctx.fillStyle = greenColor; + } + const raText = Math.round(radioAltitude).toString(); + const raTextMetrics = ctx.measureText(raText); + ctx.fillText(raText, attitudeIndMidX - raTextMetrics.width / 2, attitudeIndTop + attitudeIndHeight - 4); + } +} + +function drawPressure(ctx, fm20, fm30) { + + if (pressure !== undefined) { + + const pressureLeft = 750; // Righthand side of altitude indicator + const pressureMidX = 750 + 80; // Lefthand side of altitude indicator + const pressureMidY = 850; + + const pressureInt = Math.round(pressure); + + if (isStd()) { + + const border = 3; + ctx.font = "30px Arial"; + ctx.fillStyle = cyanColor; + const pressureText = "STD"; + const pressureMetrics = ctx.measureText(pressureText); + const height = pressureMetrics.actualBoundingBoxAscent + pressureMetrics.actualBoundingBoxDescent + 2 * border; + ctx.fillText(pressureText, pressureMidX - pressureMetrics.width / 2, pressureMidY); + + ctx.lineWidth = 2; + ctx.strokeStyle = yellowColor; + ctx.strokeRect(pressureMidX - pressureMetrics.width / 2 - border, pressureMidY - pressureMetrics.actualBoundingBoxAscent - 2 * border, pressureMetrics.width + border * 2, height + border * 2); + + } else { + ctx.font = "30px Arial"; + ctx.fillStyle = "white"; + ctx.fillText("QNH", pressureLeft, pressureMidY); + + ctx.fillStyle = cyanColor; + const pressureText = pressureInt.toString(); + ctx.fillText(pressureText, pressureMidX, pressureMidY); + } + } +} + +function drawMachIndicator(ctx) { + if (mach !== undefined) { + if (mach >= 0.45) { // Actually comes on at .5 and goes off at 0.45 + + ctx.font = "38px Arial"; + ctx.fillStyle = greenColor; + var machString; + if (mach < 1) { + machString = mach.toFixed(3).substring(1); // No leading 0 + } else { + machString = mach.toFixed(2); + } + + ctx.fillText(machString, 40, 840); + } + } +} +function drawVerticalSpeedIndicator(ctx, fm20, fm30) { + + const verticalSpeedIndWidth = 50; + const verticalSpeedIndHeight = 620; + const verticalSpeedIndLeft = 900; + const verticalSpeedIndTop = 190; + const verticalSpeedIndBottom = verticalSpeedIndTop + verticalSpeedIndHeight; + const verticalSpeedIndMidY = verticalSpeedIndTop + + verticalSpeedIndHeight / 2; + const verticalSpeedIndMidX = verticalSpeedIndLeft + verticalSpeedIndWidth / 2; + const verticalSpeedIndRight = verticalSpeedIndLeft + verticalSpeedIndWidth; + const verticalSpeedBevel = 80; + const verticalSpeedMarkerSpacing = 35; + const verticalSpeedMarkerWidth = verticalSpeedIndWidth / 4; + const verticalSpeedMarkerLeft = verticalSpeedIndLeft + verticalSpeedMarkerWidth; + const verticalSpeedIndText = verticalSpeedIndLeft + 1; + const verticalSpeedLineRight = verticalSpeedIndRight + 30; + const verticalSpeedLineLeft = verticalSpeedIndMidX - 5; + + + // Background + ctx.beginPath(); + ctx.moveTo(verticalSpeedIndLeft, verticalSpeedIndTop); + ctx.lineTo(verticalSpeedIndMidX, verticalSpeedIndTop); + ctx.lineTo(verticalSpeedIndRight, verticalSpeedIndTop + verticalSpeedBevel); + ctx.lineTo(verticalSpeedIndRight, verticalSpeedIndBottom - verticalSpeedBevel); + ctx.lineTo(verticalSpeedIndMidX, verticalSpeedIndBottom); + ctx.lineTo(verticalSpeedIndLeft, verticalSpeedIndBottom); + ctx.lineTo(verticalSpeedIndLeft, verticalSpeedIndTop); + ctx.fillStyle = grayColor; + ctx.fill(); + + // Labels + ctx.font = "20px Arial"; + ctx.fillStyle = 'white'; + ctx.fillText("6", verticalSpeedIndText, verticalSpeedIndMidY - 8 * verticalSpeedMarkerSpacing + fm20.actualBoundingBoxAscent / 2); + ctx.fillText("2", verticalSpeedIndText, verticalSpeedIndMidY - 6 * verticalSpeedMarkerSpacing + fm20.actualBoundingBoxAscent / 2); + ctx.fillText("1", verticalSpeedIndText, verticalSpeedIndMidY - 4 * verticalSpeedMarkerSpacing + fm20.actualBoundingBoxAscent / 2); + ctx.fillText("1", verticalSpeedIndText, verticalSpeedIndMidY + 4 * verticalSpeedMarkerSpacing + fm20.actualBoundingBoxAscent / 2); + ctx.fillText("2", verticalSpeedIndText, verticalSpeedIndMidY + 6 * verticalSpeedMarkerSpacing + fm20.actualBoundingBoxAscent / 2); + ctx.fillText("6", verticalSpeedIndText, verticalSpeedIndMidY + 8 * verticalSpeedMarkerSpacing + fm20.actualBoundingBoxAscent / 2); + + // Markers + ctx.fillStyle = 'white'; + for (var i = -8; i <= 8; i++) + { + const j = Math.abs(i); + if (!((j == 1) || (j == 3))) { + var height; + if ((j == 4) || (j == 6) || (j == 8)) { + height = 6; + } else { + height = 2; + } + ctx.fillRect(verticalSpeedMarkerLeft, verticalSpeedIndMidY - i * verticalSpeedMarkerSpacing - height / 2, verticalSpeedMarkerWidth, height); + } + } + + // 0 marker + ctx.fillStyle = yellowColor; + ctx.fillRect(verticalSpeedIndLeft, verticalSpeedIndMidY - 3, verticalSpeedIndWidth / 2, 6); + + // Indicator line + + const verticalSpeedAbsolute = Math.abs(verticalSpeed); + var verticalOffset; + var color = greenColor; + + if (verticalSpeedAbsolute <= 1000) { + verticalOffset = verticalSpeedAbsolute / 1000 * 4 * verticalSpeedMarkerSpacing; + } else if (verticalSpeedAbsolute < 2000) { + verticalOffset = (verticalSpeedAbsolute - 1000) / 1000 * 2 * verticalSpeedMarkerSpacing + 4 * verticalSpeedMarkerSpacing; + } else if (verticalSpeedAbsolute < 6000) { + verticalOffset = (verticalSpeedAbsolute - 2000) / 4000 * 2 * verticalSpeedMarkerSpacing + 6 * verticalSpeedMarkerSpacing; + } else { + verticalOffset = 8 * verticalSpeedMarkerSpacing; + color = orangeColor; + } + + const verticalSpeedLineY = verticalSpeedIndMidY - verticalOffset * Math.sign(verticalSpeed); + + ctx.beginPath(); + ctx.moveTo(verticalSpeedLineRight, verticalSpeedIndMidY); + ctx.lineTo(verticalSpeedLineLeft, verticalSpeedLineY); + ctx.lineWidth = 4; + ctx.strokeStyle = color; + ctx.stroke(); + + // Text + if (verticalSpeedAbsolute > 200) { + + const verticalSpeedTextX = verticalSpeedLineLeft + 3; + const verticalSpeedTextHeight = fm20.actualBoundingBoxAscent + fm20.actualBoundingBoxDescent + 2; + const verticalSpeedText = Math.round(verticalSpeedAbsolute / 100); + const verticalSpeedTextString = verticalSpeedText.toString().padStart(2, '0'); + + // Background + ctx.fillStyle = 'black'; + if (verticalSpeed > 0) { + ctx.fillRect(verticalSpeedTextX, verticalSpeedLineY - verticalSpeedTextHeight, verticalSpeedIndWidth / 2, verticalSpeedTextHeight); + } else { + ctx.fillRect(verticalSpeedTextX, verticalSpeedLineY, verticalSpeedIndWidth / 2, verticalSpeedTextHeight); + } + + ctx.fillStyle = color; + if (verticalSpeed > 0) { + ctx.fillText(verticalSpeedTextString, verticalSpeedTextX, verticalSpeedLineY - fm20.actualBoundingBoxDescent - 1); + } else { + ctx.fillText(verticalSpeedTextString, verticalSpeedTextX, verticalSpeedLineY + fm20.actualBoundingBoxAscent + 1); + } + + } + +} + +// For testing only +var speedInc = 0.1; +var headingInc = 0.1; +var altitudeInc = 1; +var verticalSpeedInc = 10; +var rollInc = 0.1; +function animatePFD() { + if (speed === undefined) { + speed = 0; + targetSpeed = 200; + } else if (speed <= 0) { + speedInc = 0.1; + } else if (speed >= 350) { + speedInc = -0.1; + } + if (heading === undefined) { + heading = 0; + targetHeading = 180; + } else if (heading <= 0) { + headingInc = 0.1; + } else if (heading >= 360) { + headingInc = -0.1; + } + if (altitude === undefined) { + altitude = 0; + targetAltitude = 1000; + } else if (altitude <= 0) { + altitudeInc = 1; + } else if (altitude >= 45000) { + altitudeInc = -1; + } + if (verticalSpeed === undefined) { + verticalSpeed = -7000; + } else if (verticalSpeed <= -7000) { + verticalSpeedInc = 10; + } else if (verticalSpeed >= 7000) { + verticalSpeedInc = -10; + } + if (roll === undefined) { + roll = 45; + } else if (roll <= -45) { + rollInc = 0.1; + } else if (roll >= 45) { + rollInc = -0.1; + } + speed = speed + speedInc; + groundspeed = 150; + trueAirspeed = 130; + heading = heading + headingInc; + altitude = altitude + altitudeInc; + altitude = 39; + radioAltitude = 1720; + onSurface = 0; + verticalSpeed = verticalSpeed + verticalSpeedInc; + roll = roll + rollInc; + callsign = "BAW123G"; + aircraftType = "A320"; + windDirection = 85; + windSpeed = 15; + staticAirTemperature = 7; + verticalMode = 3; + lateralMode = 2; + autopilot = 1; + tcasMode = 1; + pressure = 1013; + //pressure = 1018; +} +function drawPFD() { + + const canvas = document.getElementById("pfdCanvas"); + const ctx = canvas.getContext("2d"); + + ctx.font = "20px Arial"; + const fm20 = ctx.measureText("180"); + ctx.font = "30px Arial"; + const fm30 = ctx.measureText("180"); + + // Background + + ctx.fillStyle = "black"; + ctx.fillRect(0, 0, 1000, 1000); + + // Airspeed indicator + + drawAirspeedIndicator(ctx, fm20, fm30); + + // Attitude indicator + + drawAttitudeIndicator(ctx, fm20, fm30); + + // Altimeter + + drawAltitudeIndicator(ctx, fm20, fm30); + + // Vertical speed indicator + + drawVerticalSpeedIndicator(ctx, fm20, fm30); + + // Heading indicator + + drawHeadingIndicator(ctx, fm20, fm30); + + // Pressure setting + + drawPressure(ctx, fm20, fm30); + + // Mach indicator + + drawMachIndicator(ctx); + + // Flight mode announciators + + ctx.beginPath(); + ctx.moveTo(220, 5); + ctx.lineTo(220, 140); + ctx.lineWidth = 1; + ctx.strokeStyle = "white"; + ctx.stroke(); + if (targetSpeed !== undefined) { + ctx.font = "30px Arial"; + ctx.fillStyle = greenColor; + ctx.fillText("SPEED", 55, 50); // THR CLB is climbing? + } else if (toga) { + ctx.font = "30px Arial"; + ctx.fillStyle = "white"; + ctx.fillText("TOGA", 70, 50); + } + + // FIXME: + //ctx.font = "30px Arial"; + //ctx.fillStyle = "white"; + //ctx.fillText("toga " + toga + " roll " + rollOut + " Surf " + onSurface + " wasSurf " + wasOnSurface60SecsAgo + " MS " + modelSpeed + " r/w Alt " + runwayAltitude, 50, 150); + + var landing = false; + if (verticalMode !== undefined) { + ctx.font = "30px Arial"; + ctx.fillStyle = greenColor; + if (verticalMode == 1) { + if (verticalSpeed !== undefined) { + if (verticalSpeed > 0) { + ctx.fillText("CLB", 290, 50); + } else if (verticalSpeed < 0) { + ctx.fillText("DES", 290, 50); + } else { + ctx.fillText("ALT", 290, 50); + } + } else if (targetAltitude !== undefined && altitude !== undefined) { + if (targetAltitude > altitude) { + ctx.fillText("CLB", 290, 50); + } else if (targetAltitude < altitude) { + ctx.fillText("DES", 290, 50); + } else { + ctx.fillText("ALT", 290, 50); + } + } + } else if (verticalMode == 2) { + ctx.fillText("ALT", 290, 50); + } else if (verticalMode == 3) { + if (rollOut) { + ctx.fillText("ROLL OUT", 370, 50); + landing = true; + } else if ((onSurface === 0) && (radioAltitude < 40)) { + ctx.fillText("FLARE", 390, 50); + landing = true; + } else if ((onSurface === 0) && (radioAltitude < 400)) { + ctx.fillText("LAND", 400, 50); + landing = true; + } else { + ctx.fillText("G/S", 290, 50); + } + } + } + if (!landing) { + ctx.beginPath(); + ctx.moveTo(420, 5); + ctx.lineTo(420, 140); + ctx.lineWidth = 1; + ctx.strokeStyle = "white"; + ctx.stroke(); + } + + ctx.beginPath(); + ctx.moveTo(660, 5); + ctx.lineTo(660, 140); + ctx.lineWidth = 1; + ctx.strokeStyle = "white"; + ctx.stroke(); + if (lateralMode !== undefined) { + ctx.font = "30px Arial"; + ctx.fillStyle = greenColor; + if (lateralMode == 1) { + ctx.fillText("NAV", 510, 50); + } else if (lateralMode == 2) { + if (!landing) { + ctx.fillText("LOC", 510, 50); + } + } + } + + ctx.beginPath(); + ctx.moveTo(850, 5); + ctx.lineTo(850, 140); + ctx.lineWidth = 1; + ctx.strokeStyle = "white"; + ctx.stroke(); + ctx.font = "30px Arial"; + ctx.fillStyle = "white"; + if (autopilot !== undefined) { + if (autopilot) { + if (verticalMode == 3) { + // We can't tell whether both APs are enabled - but they typically would be + ctx.fillText("AP1+2", 870, 40); + ctx.fillText("CAT3", 720, 40); + ctx.fillText("DUAL", 720, 85); + } else { + ctx.fillText("AP1", 890, 40); + } + } + } + ctx.fillText("1 FD 2", 870, 85); + if (((targetSpeed !== undefined) || autopilot) && !rollOut) { + ctx.fillText("A/THR", 870, 130); + } + + // Aircraft callsign and type + + ctx.fillStyle = "white"; + ctx.font = "30px Arial"; + if (callsign !== undefined) { + ctx.fillText(callsign, 20, 940); + } + ctx.font = "21px Arial"; + if (aircraftType !== undefined) { + ctx.fillText(aircraftType, 20, 980); + } + + const dataLeft = 750; // Aligned with QNH + const dataTop = 890; + + // TCAS - As displayed on ND/ECAM + if (tcasMode === 1) { + ctx.fillStyle = orangeColor; + ctx.font = "21px Arial"; + ctx.fillText("TCAS STBY", dataLeft, dataTop); + } else if (tcasMode === 2) { + ctx.fillStyle = "white"; + ctx.font = "21px Arial"; + ctx.fillText("TA ONLY", dataLeft, dataTop); + } + + // Groundspeed and TAS as displayed on ND + if ((groundspeed !== undefined) || (trueAirspeed !== undefined)) { + ctx.font = "21px Arial"; + if (groundspeed !== undefined) { + ctx.fillStyle = "white"; + ctx.fillText("GS", dataLeft, dataTop + 30); + ctx.fillStyle = greenColor; + ctx.fillText(Math.round(groundspeed).toString(), dataLeft + 40, dataTop + 30); + } + if (trueAirspeed !== undefined) { + ctx.fillStyle = "white"; + ctx.fillText("TAS", dataLeft + 90, dataTop + 30); + ctx.fillStyle = greenColor; + ctx.fillText(Math.round(trueAirspeed).toString(), dataLeft + 140, dataTop + 30); + } + } + + // Wind speed and direction as displayed on ND + if ((windSpeed !== undefined) && (windDirection !== undefined)) { + const windText = pad(Math.round(windDirection), 3) + "/" + Math.round(windSpeed); + ctx.fillStyle = greenColor; + ctx.font = "21px Arial"; + ctx.fillText(windText, dataLeft, dataTop + 60); + + if (heading !== undefined) { + // An arrow showing wind direction relative to heading + var angle = (windDirection - heading) * Math.PI / 180; + + ctx.save(); + ctx.translate(dataLeft + 80, dataTop + 53); + ctx.rotate(angle); + + ctx.strokeStyle = greenColor; + ctx.beginPath(); + ctx.moveTo(0, -10); + ctx.lineTo(0, 10); + ctx.lineTo(-5, 7); + ctx.moveTo(0, 10); + ctx.lineTo(5, 7); + ctx.stroke(); + + ctx.restore(); + } + } + + // Static air temperature as displayed on lower ECAM + if (staticAirTemperature !== undefined) { + var satText; + if (staticAirTemperature > 0) { + satText = "+" + Math.round(staticAirTemperature); + } else { + satText = Math.round(staticAirTemperature).toString(); + } + + ctx.font = "21px Arial"; + ctx.fillStyle = "white"; + ctx.fillText("SAT", dataLeft, dataTop + 90); + ctx.fillStyle = greenColor; + ctx.fillText(satText, dataLeft + 60, dataTop + 90); + ctx.fillStyle = cyanColor; + ctx.fillText("\u00B0C", dataLeft + 100, dataTop + 90); + } +} + +const canvas = document.getElementById('pfdCanvas'); +canvas.onmousedown = pfdMouseDown; +canvas.onmouseup = pfdMouseUp; +canvas.onmousemove = pfdMouseMove; +canvas.onmouseleave = pfdMouseLeave; +canvas.onmouseenter = pfdMouseEnter; +var docMouseMove = null; +var docMouseUp = null; +var movePFD = false; +var scalePFD = false; +var posX = 0; +var posY = 0; +var canvasWidth = 0; +var canvasHeight = 0; + +function pad(num, size) { + num = num.toString(); + while (num.length < size) num = "0" + num; + return num; +} + +function pfdMouseDown(e) { + e.preventDefault(); + e.stopPropagation(); + const r = canvas.getBoundingClientRect(); + posX = r.left; + posY = r.top; + canvasWidth = r.width; + canvasHeight = r.height; + if ((e.offsetX > 0.95 * canvasWidth) && (e.offsetY > 0.95 * canvasHeight)) { + scalePFD = true; + } else { + movePFD = true; + } +} +function pfdMouseUp(e) { + e.preventDefault(); + e.stopPropagation(); + movePFD = false; + scalePFD = false; + pfdRestoreDocMouse(); +} +function pfdMouseMove(e) { + e.preventDefault(); + e.stopPropagation(); + if (movePFD) { + posX = posX + e.movementX; + posY = posY + e.movementY; + canvas.style.position = "absolute"; + canvas.style.left = posX + "px"; + canvas.style.top = posY + "px"; + } else if (scalePFD) { + canvasWidth = canvasWidth + e.movementX; + canvasHeight = canvasHeight + e.movementY; + const constrainedWidth = Math.max(canvasWidth, 250); + const constrainedHeight = Math.max(canvasHeight, 250); + canvas.style.width = constrainedWidth + "px"; + canvas.style.height = constrainedHeight + "px"; + } +} + +function pfdMouseLeave(e) { + //movePFD = false; + //scalePFD = false; + if (scalePFD || movePFD) { + docMouseUp = document.onmouseup; + docMouseMove = document.onmousemove; + document.onmouseup = pfdMouseUp; + document.onmousemove = pfdMouseMove; + } +} + +function pfdRestoreDocMouse() { + if (docMouseUp) { + document.onmouseup = docMouseUp; + document.onmousemove = docMouseMove; + docMouseDown = null; + docMouseMove = null; + } +} +function pfdMouseEnter(e) { + pfdRestoreDocMouse(); +} diff --git a/plugins/feature/map/map/grid.js b/plugins/feature/map/map/grid.js index c9b94963b..742292390 100644 --- a/plugins/feature/map/map/grid.js +++ b/plugins/feature/map/map/grid.js @@ -1,165 +1,165 @@ -// Maidenhead grid for Cesium - -const polylines = new Cesium.PolylineCollection(); -const polylinesFine = new Cesium.PolylineCollection(); - -const labels = new Cesium.LabelCollection(); -const labelsFine = new Cesium.LabelCollection(); - -const segLen = 2; - -const gridMaterial = Cesium.Material.fromType('Color'); -gridMaterial.uniforms.color = new Cesium.Color(0.6, 0.6, 0.6, 1.0); -const gridLabelColor = new Cesium.Color(1, 1, 1, 1.0); - -function createLat() { - for (var lon = -180; lon < 180; lon += 20) { - const array = []; - for (var lat = -90; lat <= 90; lat += segLen) { - array.push(lon); - array.push(lat); - } - polylines.add({ - positions: Cesium.Cartesian3.fromDegreesArray(array), - width: 1, - material: gridMaterial - }); - - } -} - -function createLatFine() { - for (var lon = -180; lon < 180; lon += 2) { - if (lon % 20 != 0) { - const array = []; - for (var lat = -90; lat <= 90; lat += segLen) { - array.push(lon); - array.push(lat); - } - polylinesFine.add({ - positions: Cesium.Cartesian3.fromDegreesArray(array), - width: 1, - material: gridMaterial - }); - } - } -} - -function createLon() { - for (var lat = -80; lat <= 80; lat += 10) { - const array = []; - for (var lon = -180; lon <= 180; lon += segLen) { - array.push(lon); - array.push(lat); - } - polylines.add({ - positions: Cesium.Cartesian3.fromDegreesArray(array), - width: 1, - material: gridMaterial - }); - } -} - -function createLonFine() { - for (var lat = -80; lat <= 80; lat += 1) { - if (lat % 10 != 0) { - const array = []; - for (var lon = -180; lon <= 180; lon += segLen) { - array.push(lon); - array.push(lat); - } - polylinesFine.add({ - positions: Cesium.Cartesian3.fromDegreesArray(array), - width: 1, - material: gridMaterial - }); - } - } -} - -function createLabels() { - var latField = 'B'.charCodeAt(0); - for (var lat = -80; lat <= 80; lat += 10) { - var lonField = 'A'.charCodeAt(0); - for (var lon = -180; lon < 180; lon += 20) { - labels.add({ - position: Cesium.Cartesian3.fromDegrees(lon + 0.5, lat + 0.5, 0.0), - text: String.fromCharCode(lonField) + String.fromCharCode(latField), - fillColor: gridLabelColor, - font: '20px sans-serif' - }); - lonField++; - } - latField++; - } -} - -function createLabelsFine() { - var latField = 'B'.charCodeAt(0); - for (var lat = -80; lat <= 80; lat += 1) { - var latSq = '0'.charCodeAt(0) + mod(lat, 10); - var lonField = 'A'.charCodeAt(0); - for (var lon = -180; lon < 180; lon += 2) { - var lonSq = '0'.charCodeAt(0) + mod(lon, 20) / 2; - labelsFine.add({ - position: Cesium.Cartesian3.fromDegrees(lon + 0.05, lat + 0.05, 0.0), - text: String.fromCharCode(lonField) + String.fromCharCode(latField) + String.fromCharCode(lonSq) + String.fromCharCode(latSq), - fillColor: gridLabelColor, - font: '20px sans-serif' - }); - if (mod(lon, 20) == 18) { - lonField++; - } - } - if (mod(lat, 10) == 9) { - latField++; - } - } -} -function mod(n, m) { - return ((n % m) + m) % m; -} - -function showGridByDistance() { - - var cameraHeight = viewer.scene.ellipsoid.cartesianToCartographic(viewer.scene.camera.position).height; - - const showFine = cameraHeight < 1500000; - - polylinesFine.show = showFine; - labels.show = !showFine; - labelsFine.show = showFine; -} - -function createGrid(viewer) { - - createLatFine(); - createLat(); - createLonFine(); - createLon(); - polylinesFine.show = false; - viewer.scene.primitives.add(polylines); - viewer.scene.primitives.add(polylinesFine); - - createLabels(); - createLabelsFine(); - labelsFine.show = false; - viewer.scene.primitives.add(labels); - viewer.scene.primitives.add(labelsFine); -} - -function showGrid(show) { - if (show) { - if (polylines.length == 0) { - createGrid(viewer); - } - polylines.show = true; - viewer.clock.onTick.addEventListener(showGridByDistance); - } else { - viewer.clock.onTick.removeEventListener(showGridByDistance); - polylines.show = false; - polylinesFine.show = false; - labels.show = false; - labelsFine.show = false; - } -} +// Maidenhead grid for Cesium + +const polylines = new Cesium.PolylineCollection(); +const polylinesFine = new Cesium.PolylineCollection(); + +const labels = new Cesium.LabelCollection(); +const labelsFine = new Cesium.LabelCollection(); + +const segLen = 2; + +const gridMaterial = Cesium.Material.fromType('Color'); +gridMaterial.uniforms.color = new Cesium.Color(0.6, 0.6, 0.6, 1.0); +const gridLabelColor = new Cesium.Color(1, 1, 1, 1.0); + +function createLat() { + for (var lon = -180; lon < 180; lon += 20) { + const array = []; + for (var lat = -90; lat <= 90; lat += segLen) { + array.push(lon); + array.push(lat); + } + polylines.add({ + positions: Cesium.Cartesian3.fromDegreesArray(array), + width: 1, + material: gridMaterial + }); + + } +} + +function createLatFine() { + for (var lon = -180; lon < 180; lon += 2) { + if (lon % 20 != 0) { + const array = []; + for (var lat = -90; lat <= 90; lat += segLen) { + array.push(lon); + array.push(lat); + } + polylinesFine.add({ + positions: Cesium.Cartesian3.fromDegreesArray(array), + width: 1, + material: gridMaterial + }); + } + } +} + +function createLon() { + for (var lat = -80; lat <= 80; lat += 10) { + const array = []; + for (var lon = -180; lon <= 180; lon += segLen) { + array.push(lon); + array.push(lat); + } + polylines.add({ + positions: Cesium.Cartesian3.fromDegreesArray(array), + width: 1, + material: gridMaterial + }); + } +} + +function createLonFine() { + for (var lat = -80; lat <= 80; lat += 1) { + if (lat % 10 != 0) { + const array = []; + for (var lon = -180; lon <= 180; lon += segLen) { + array.push(lon); + array.push(lat); + } + polylinesFine.add({ + positions: Cesium.Cartesian3.fromDegreesArray(array), + width: 1, + material: gridMaterial + }); + } + } +} + +function createLabels() { + var latField = 'B'.charCodeAt(0); + for (var lat = -80; lat <= 80; lat += 10) { + var lonField = 'A'.charCodeAt(0); + for (var lon = -180; lon < 180; lon += 20) { + labels.add({ + position: Cesium.Cartesian3.fromDegrees(lon + 0.5, lat + 0.5, 0.0), + text: String.fromCharCode(lonField) + String.fromCharCode(latField), + fillColor: gridLabelColor, + font: '20px sans-serif' + }); + lonField++; + } + latField++; + } +} + +function createLabelsFine() { + var latField = 'B'.charCodeAt(0); + for (var lat = -80; lat <= 80; lat += 1) { + var latSq = '0'.charCodeAt(0) + mod(lat, 10); + var lonField = 'A'.charCodeAt(0); + for (var lon = -180; lon < 180; lon += 2) { + var lonSq = '0'.charCodeAt(0) + mod(lon, 20) / 2; + labelsFine.add({ + position: Cesium.Cartesian3.fromDegrees(lon + 0.05, lat + 0.05, 0.0), + text: String.fromCharCode(lonField) + String.fromCharCode(latField) + String.fromCharCode(lonSq) + String.fromCharCode(latSq), + fillColor: gridLabelColor, + font: '20px sans-serif' + }); + if (mod(lon, 20) == 18) { + lonField++; + } + } + if (mod(lat, 10) == 9) { + latField++; + } + } +} +function mod(n, m) { + return ((n % m) + m) % m; +} + +function showGridByDistance() { + + var cameraHeight = viewer.scene.ellipsoid.cartesianToCartographic(viewer.scene.camera.position).height; + + const showFine = cameraHeight < 1500000; + + polylinesFine.show = showFine; + labels.show = !showFine; + labelsFine.show = showFine; +} + +function createGrid(viewer) { + + createLatFine(); + createLat(); + createLonFine(); + createLon(); + polylinesFine.show = false; + viewer.scene.primitives.add(polylines); + viewer.scene.primitives.add(polylinesFine); + + createLabels(); + createLabelsFine(); + labelsFine.show = false; + viewer.scene.primitives.add(labels); + viewer.scene.primitives.add(labelsFine); +} + +function showGrid(show) { + if (show) { + if (polylines.length == 0) { + createGrid(viewer); + } + polylines.show = true; + viewer.clock.onTick.addEventListener(showGridByDistance); + } else { + viewer.clock.onTick.removeEventListener(showGridByDistance); + polylines.show = false; + polylinesFine.show = false; + labels.show = false; + labelsFine.show = false; + } +} diff --git a/plugins/feature/map/map/map3d.html b/plugins/feature/map/map/map3d.html index da0cda347..79d7df997 100644 --- a/plugins/feature/map/map/map3d.html +++ b/plugins/feature/map/map/map3d.html @@ -1,1348 +1,1348 @@ - - - - - - - - - -
- - - - - - - - - + + + + + + + + + +
+ + + + + + + + + diff --git a/plugins/feature/mcpserver/bridge/CMakeLists.txt b/plugins/feature/mcpserver/bridge/CMakeLists.txt index 8fa612378..23f9d996c 100644 --- a/plugins/feature/mcpserver/bridge/CMakeLists.txt +++ b/plugins/feature/mcpserver/bridge/CMakeLists.txt @@ -1,129 +1,135 @@ -project(sdrangelmcpbridge) - -# A standalone executable, deliberately free of Qt and of the rest of SDRangel: it is -# shipped inside a Claude Desktop extension bundle, where nothing else is on the library -# path, so it must run with only the C++ runtime. - -set(mcpbridge_SOURCES - main.cpp - httpclient.cpp - jsonscan.cpp - ssereader.cpp -) - -set(mcpbridge_HEADERS - httpclient.h - jsonscan.h - ssereader.h -) - -add_executable(sdrangel-mcp-bridge ${mcpbridge_SOURCES} ${mcpbridge_HEADERS}) - -# There is no Qt here, so the project wide automatic moc, uic and rcc have nothing to do -set_target_properties(sdrangel-mcp-bridge PROPERTIES AUTOMOC OFF AUTOUIC OFF AUTORCC OFF) - -target_compile_definitions(sdrangel-mcp-bridge PRIVATE - SDRANGEL_MCP_BRIDGE_VERSION="${CPACK_PACKAGE_VERSION}" -) - -find_package(Threads REQUIRED) -target_link_libraries(sdrangel-mcp-bridge Threads::Threads) - -if(WIN32) - target_link_libraries(sdrangel-mcp-bridge ws2_32) - # Static runtime, so the bundle does not depend on the redistributable being present - set_property(TARGET sdrangel-mcp-bridge PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") -endif() - -install(TARGETS sdrangel-mcp-bridge DESTINATION ${INSTALL_BIN_DIR}) - -# A .mcpb is a zip with manifest.json at its root, so CMake can build one on its own. The -# mcpb CLI only adds validation and signing, and requiring npm to build SDRangel would be a -# poor trade for that. -if(BUILD_MCP_BUNDLE) - if(WIN32) - set(MCPBRIDGE_BUNDLE_PLATFORM "win32") - elseif(APPLE) - set(MCPBRIDGE_BUNDLE_PLATFORM "darwin") - else() - set(MCPBRIDGE_BUNDLE_PLATFORM "linux") - endif() - - # A bundle claiming a version that is already installed is not unpacked again, which - # silently leaves the previous one in place, so every build needs a version of its own. - # A release is exactly its tag; anything else carries the git describe suffix and the time - # it was configured, since rebuilds between commits would otherwise all claim the same - # version. Both are valid semantic version prereleases, and the added identifier makes a - # rebuild sort above what it replaces rather than below it - if(sdrangel_VERSION_SUFFIX STREQUAL "") - set(MCPBRIDGE_BUNDLE_VERSION "${CPACK_PACKAGE_VERSION}") - else() - string(TIMESTAMP MCPBRIDGE_BUILD_TIME "%Y%m%dT%H%M%S" UTC) - set(MCPBRIDGE_BUNDLE_VERSION "${CPACK_PACKAGE_VERSION}.${MCPBRIDGE_BUILD_TIME}") - endif() - - # The tool list the bundle carries comes from the server itself, built here by a host tool - # that constructs the real registry. Sources are named by path rather than reusing the - # plugin target, which is a Qt plugin module and cannot be linked into an executable - set(MCPTOOLSDUMP_DIR "${CMAKE_SOURCE_DIR}/plugins/feature/mcpserver") - - add_executable(sdrangel-mcp-tools-dump - "${MCPTOOLSDUMP_DIR}/toolsdump.cpp" - "${MCPTOOLSDUMP_DIR}/mcptools.cpp" - "${MCPTOOLSDUMP_DIR}/mcpdocs.cpp" - "${MCPTOOLSDUMP_DIR}/mcpdatafeed.cpp" - "${MCPTOOLSDUMP_DIR}/mcpcapture.cpp" - "${MCPTOOLSDUMP_DIR}/mcpaudiocapture.cpp" - "${MCPTOOLSDUMP_DIR}/mcpstreams.cpp" - ) - - target_include_directories(sdrangel-mcp-tools-dump PRIVATE - "${MCPTOOLSDUMP_DIR}" - "${CMAKE_SOURCE_DIR}/sdrbase" - "${CMAKE_SOURCE_DIR}/exports" - "${CMAKE_SOURCE_DIR}/httpserver" - "${CMAKE_SOURCE_DIR}/swagger/sdrangel/code/qt5/client" - ) - - target_link_libraries(sdrangel-mcp-tools-dump PRIVATE Qt::Core sdrbase httpserver) - - set(MCPBRIDGE_BUNDLE_DIR "${CMAKE_CURRENT_BINARY_DIR}/bundle") - # Alongside the built binaries, which is bin/ on Windows and the build directory itself - # elsewhere. That is also where the running application looks for it in a build tree - set(MCPBRIDGE_BUNDLE_FILE "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/sdrangel-${MCPBRIDGE_BUNDLE_VERSION}-${MCPBRIDGE_BUNDLE_PLATFORM}.mcpb") - - configure_file(manifest.json.in "${MCPBRIDGE_BUNDLE_DIR}/manifest.json" @ONLY) - - # Part of ALL, so that turning the option on is enough: the packaging step installs the - # bundle if it is there, and silently leaves it out if it is not, which would be a hard - # thing to notice in a finished installer - add_custom_target(mcpbundle ALL - COMMAND ${CMAKE_COMMAND} -E make_directory "${MCPBRIDGE_BUNDLE_DIR}/server" - COMMAND ${CMAKE_COMMAND} -E copy $ "${MCPBRIDGE_BUNDLE_DIR}/server/" - COMMAND ${CMAKE_COMMAND} -E copy "${CMAKE_SOURCE_DIR}/cmake/cpack/sdrangel_icon.png" "${MCPBRIDGE_BUNDLE_DIR}/icon.png" - # The tool list, straight from the server's own registry, beside the bridge that serves - # it when SDRangel is not up - COMMAND $ "${MCPBRIDGE_BUNDLE_DIR}/server/tools.json" - COMMAND ${CMAKE_COMMAND} -E rm -f "${MCPBRIDGE_BUNDLE_FILE}" - # Relative paths and a working directory, so that manifest.json lands at the root of - # the archive, which is where the installer looks for it - COMMAND ${CMAKE_COMMAND} -E tar cf "${MCPBRIDGE_BUNDLE_FILE}" --format=zip -- manifest.json icon.png server - WORKING_DIRECTORY "${MCPBRIDGE_BUNDLE_DIR}" - DEPENDS sdrangel-mcp-bridge sdrangel-mcp-tools-dump "${MCPBRIDGE_BUNDLE_DIR}/manifest.json" - COMMENT "Packaging ${MCPBRIDGE_BUNDLE_FILE}" - VERBATIM - ) - - # The installer needs the name, and cmake/cpack is configured after this directory - set(MCPBRIDGE_BUNDLE_NAME "sdrangel-${MCPBRIDGE_BUNDLE_VERSION}-${MCPBRIDGE_BUNDLE_PLATFORM}.mcpb" - CACHE INTERNAL "File name of the Claude Desktop extension bundle") - - # Not OPTIONAL: mcpbundle is part of ALL, so the bundle is always there by the time the - # install rules run. Should packaging ever break, failing here is far better than an - # installer that quietly ships without the extension - install(FILES "${MCPBRIDGE_BUNDLE_FILE}" DESTINATION ${INSTALL_BIN_DIR}) - - # Beside the installed bridge as well, for anyone pointing a client straight at it rather - # than installing the extension - install(FILES "${MCPBRIDGE_BUNDLE_DIR}/server/tools.json" DESTINATION ${INSTALL_BIN_DIR}) -endif() +project(sdrangelmcpbridge) + +# A standalone executable, deliberately free of Qt and of the rest of SDRangel: it is +# shipped inside a Claude Desktop extension bundle, where nothing else is on the library +# path, so it must run with only the C++ runtime. + +set(mcpbridge_SOURCES + main.cpp + httpclient.cpp + jsonscan.cpp + ssereader.cpp +) + +set(mcpbridge_HEADERS + httpclient.h + jsonscan.h + ssereader.h +) + +add_executable(sdrangel-mcp-bridge ${mcpbridge_SOURCES} ${mcpbridge_HEADERS}) + +# There is no Qt here, so the project wide automatic moc, uic and rcc have nothing to do +set_target_properties(sdrangel-mcp-bridge PROPERTIES AUTOMOC OFF AUTOUIC OFF AUTORCC OFF) + +target_compile_definitions(sdrangel-mcp-bridge PRIVATE + SDRANGEL_MCP_BRIDGE_VERSION="${CPACK_PACKAGE_VERSION}" +) + +find_package(Threads REQUIRED) +target_link_libraries(sdrangel-mcp-bridge Threads::Threads) + +if(WIN32) + target_link_libraries(sdrangel-mcp-bridge ws2_32) + # Static runtime, so the bundle does not depend on the redistributable being present + set_property(TARGET sdrangel-mcp-bridge PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") +endif() + +install(TARGETS sdrangel-mcp-bridge DESTINATION ${INSTALL_BIN_DIR}) + +# A .mcpb is a zip with manifest.json at its root, so CMake can build one on its own. The +# mcpb CLI only adds validation and signing, and requiring npm to build SDRangel would be a +# poor trade for that. +if(BUILD_MCP_BUNDLE) + if(WIN32) + set(MCPBRIDGE_BUNDLE_PLATFORM "win32") + elseif(APPLE) + set(MCPBRIDGE_BUNDLE_PLATFORM "darwin") + else() + set(MCPBRIDGE_BUNDLE_PLATFORM "linux") + endif() + + # A bundle claiming a version that is already installed is not unpacked again, which + # silently leaves the previous one in place, so every build needs a version of its own. + # A release is exactly its tag; anything else carries the git describe suffix and the time + # it was configured, since rebuilds between commits would otherwise all claim the same + # version. Both are valid semantic version prereleases, and the added identifier makes a + # rebuild sort above what it replaces rather than below it + if(sdrangel_VERSION_SUFFIX STREQUAL "") + set(MCPBRIDGE_BUNDLE_VERSION "${CPACK_PACKAGE_VERSION}") + else() + string(TIMESTAMP MCPBRIDGE_BUILD_TIME "%Y%m%dT%H%M%S" UTC) + set(MCPBRIDGE_BUNDLE_VERSION "${CPACK_PACKAGE_VERSION}.${MCPBRIDGE_BUILD_TIME}") + endif() + + # The tool list the bundle carries comes from the server itself, built here by a host tool + # that constructs the real registry. Sources are named by path rather than reusing the + # plugin target, which is a Qt plugin module and cannot be linked into an executable + set(MCPTOOLSDUMP_DIR "${CMAKE_SOURCE_DIR}/plugins/feature/mcpserver") + + add_executable(sdrangel-mcp-tools-dump + "${MCPTOOLSDUMP_DIR}/toolsdump.cpp" + "${MCPTOOLSDUMP_DIR}/mcptools.cpp" + "${MCPTOOLSDUMP_DIR}/mcpdocs.cpp" + "${MCPTOOLSDUMP_DIR}/mcpdatafeed.cpp" + "${MCPTOOLSDUMP_DIR}/mcpcapture.cpp" + "${MCPTOOLSDUMP_DIR}/mcpaudiocapture.cpp" + "${MCPTOOLSDUMP_DIR}/mcpstreams.cpp" + ) + + target_include_directories(sdrangel-mcp-tools-dump PRIVATE + "${MCPTOOLSDUMP_DIR}" + "${CMAKE_SOURCE_DIR}/sdrbase" + "${CMAKE_SOURCE_DIR}/exports" + "${CMAKE_SOURCE_DIR}/httpserver" + "${CMAKE_SOURCE_DIR}/swagger/sdrangel/code/qt5/client" + ) + + target_link_libraries(sdrangel-mcp-tools-dump PRIVATE Qt::Core sdrbase httpserver) + + if(APPLE) + # This helper runs during the build, before macOS packaging rewrites library paths for + # the app bundle, so it needs the external-library build directories on its own rpath. + set_target_properties(sdrangel-mcp-tools-dump PROPERTIES BUILD_RPATH "${MACOS_EXTERNAL_LIBS_FIXUP}") + endif() + + set(MCPBRIDGE_BUNDLE_DIR "${CMAKE_CURRENT_BINARY_DIR}/bundle") + # Alongside the built binaries, which is bin/ on Windows and the build directory itself + # elsewhere. That is also where the running application looks for it in a build tree + set(MCPBRIDGE_BUNDLE_FILE "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/sdrangel-${MCPBRIDGE_BUNDLE_VERSION}-${MCPBRIDGE_BUNDLE_PLATFORM}.mcpb") + + configure_file(manifest.json.in "${MCPBRIDGE_BUNDLE_DIR}/manifest.json" @ONLY) + + # Part of ALL, so that turning the option on is enough: the packaging step installs the + # bundle if it is there, and silently leaves it out if it is not, which would be a hard + # thing to notice in a finished installer + add_custom_target(mcpbundle ALL + COMMAND ${CMAKE_COMMAND} -E make_directory "${MCPBRIDGE_BUNDLE_DIR}/server" + COMMAND ${CMAKE_COMMAND} -E copy $ "${MCPBRIDGE_BUNDLE_DIR}/server/" + COMMAND ${CMAKE_COMMAND} -E copy "${CMAKE_SOURCE_DIR}/cmake/cpack/sdrangel_icon.png" "${MCPBRIDGE_BUNDLE_DIR}/icon.png" + # The tool list, straight from the server's own registry, beside the bridge that serves + # it when SDRangel is not up + COMMAND $ "${MCPBRIDGE_BUNDLE_DIR}/server/tools.json" + COMMAND ${CMAKE_COMMAND} -E rm -f "${MCPBRIDGE_BUNDLE_FILE}" + # Relative paths and a working directory, so that manifest.json lands at the root of + # the archive, which is where the installer looks for it + COMMAND ${CMAKE_COMMAND} -E tar cf "${MCPBRIDGE_BUNDLE_FILE}" --format=zip -- manifest.json icon.png server + WORKING_DIRECTORY "${MCPBRIDGE_BUNDLE_DIR}" + DEPENDS sdrangel-mcp-bridge sdrangel-mcp-tools-dump "${MCPBRIDGE_BUNDLE_DIR}/manifest.json" + COMMENT "Packaging ${MCPBRIDGE_BUNDLE_FILE}" + VERBATIM + ) + + # The installer needs the name, and cmake/cpack is configured after this directory + set(MCPBRIDGE_BUNDLE_NAME "sdrangel-${MCPBRIDGE_BUNDLE_VERSION}-${MCPBRIDGE_BUNDLE_PLATFORM}.mcpb" + CACHE INTERNAL "File name of the Claude Desktop extension bundle") + + # Not OPTIONAL: mcpbundle is part of ALL, so the bundle is always there by the time the + # install rules run. Should packaging ever break, failing here is far better than an + # installer that quietly ships without the extension + install(FILES "${MCPBRIDGE_BUNDLE_FILE}" DESTINATION ${INSTALL_BIN_DIR}) + + # Beside the installed bridge as well, for anyone pointing a client straight at it rather + # than installing the extension + install(FILES "${MCPBRIDGE_BUNDLE_DIR}/server/tools.json" DESTINATION ${INSTALL_BIN_DIR}) +endif() diff --git a/plugins/feature/mcpserver/bridge/httpclient.cpp b/plugins/feature/mcpserver/bridge/httpclient.cpp index 827c32c21..79372dca6 100644 --- a/plugins/feature/mcpserver/bridge/httpclient.cpp +++ b/plugins/feature/mcpserver/bridge/httpclient.cpp @@ -1,494 +1,494 @@ -/////////////////////////////////////////////////////////////////////////////////// -// Copyright (C) 2026 Jon Beniston, M7RCE // -// Some code by AI // -// // -// This program is free software; you can redistribute it and/or modify // -// it under the terms of the GNU General Public License as published by // -// the Free Software Foundation as version 3 of the License, or // -// (at your option) any later version. // -// // -// This program is distributed in the hope that it will be useful, // -// but WITHOUT ANY WARRANTY; without even the implied warranty of // -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // -// GNU General Public License V3 for more details. // -// // -// You should have received a copy of the GNU General Public License // -// along with this program. If not, see . // -/////////////////////////////////////////////////////////////////////////////////// - -#include "httpclient.h" - -#include -#include -#include -#include -#include - -#ifdef _WIN32 -#include -#include -#else -#include -#include -#include -#include -#include -#include -#include -#include -#endif - -namespace -{ - -std::string lowered(const std::string& text) -{ - std::string result(text); - - std::transform(result.begin(), result.end(), result.begin(), - [](unsigned char c) { return static_cast(std::tolower(c)); }); - return result; -} - -std::string trimmed(const std::string& text) -{ - size_t begin = text.find_first_not_of(" \t\r\n"); - - if (begin == std::string::npos) { - return std::string(); - } - - size_t end = text.find_last_not_of(" \t\r\n"); - return text.substr(begin, end - begin + 1); -} - -std::string socketError() -{ -#ifdef _WIN32 - int code = WSAGetLastError(); - - switch (code) - { - case WSAECONNREFUSED: return "connection refused"; - case WSAETIMEDOUT: return "timed out"; - case WSAECONNRESET: return "connection reset"; - case WSAEHOSTUNREACH: return "host unreachable"; - default: return "socket error " + std::to_string(code); - } -#else - // A receive timeout set with SO_RCVTIMEO comes back as EAGAIN, whose text says nothing - // about time - if ((errno == EAGAIN) || (errno == EWOULDBLOCK)) { - return "timed out"; - } - - return std::strerror(errno); -#endif -} - -} // namespace - -HttpClient::Socket HttpClient::invalidSocket() -{ -#ifdef _WIN32 - return INVALID_SOCKET; -#else - return -1; -#endif -} - -std::string HttpClient::Head::header(const std::string& name) const -{ - std::string wanted = lowered(name); - - for (const auto& header : m_headers) - { - if (lowered(header.first) == wanted) { - return header.second; - } - } - - return std::string(); -} - -bool HttpClient::startup(std::string& error) -{ -#ifdef _WIN32 - WSADATA data; - int result = WSAStartup(MAKEWORD(2, 2), &data); - - if (result != 0) - { - error = "WSAStartup failed with " + std::to_string(result); - return false; - } -#else - (void) error; -#endif - return true; -} - -void HttpClient::cleanup() -{ -#ifdef _WIN32 - WSACleanup(); -#endif -} - -HttpClient::~HttpClient() -{ - close(); -} - -bool HttpClient::open(const std::string& host, int port, int timeoutMs, std::string& error) -{ - close(); - - addrinfo hints; - std::memset(&hints, 0, sizeof(hints)); - hints.ai_family = AF_UNSPEC; - hints.ai_socktype = SOCK_STREAM; - hints.ai_protocol = IPPROTO_TCP; - - addrinfo *addresses = nullptr; - std::string service = std::to_string(port); - - if (getaddrinfo(host.c_str(), service.c_str(), &hints, &addresses) != 0) - { - error = "cannot resolve " + host; - return false; - } - - std::string reason; - - for (addrinfo *address = addresses; address != nullptr; address = address->ai_next) - { - Socket handle = socket(address->ai_family, address->ai_socktype, address->ai_protocol); - - if (handle == invalidSocket()) { - continue; - } - - if (connect(handle, address->ai_addr, static_cast(address->ai_addrlen)) == 0) - { - m_socket = handle; - break; - } - - // Read before closing the socket and freeing the addresses, either of which - // replaces the last error with one of its own - reason = socketError(); - -#ifdef _WIN32 - closesocket(handle); -#else - ::close(handle); -#endif - } - - freeaddrinfo(addresses); - - if (m_socket == invalidSocket()) - { - error = reason.empty() ? "no usable address" : reason; - return false; - } - - // Nagle would hold small JSON-RPC messages back waiting for more to send - int flag = 1; - setsockopt(m_socket, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast(&flag), sizeof(flag)); - -#ifdef SO_NOSIGPIPE - // A send on a connection the server has closed must fail, not raise SIGPIPE and end the - // process. Linux has no such option and uses MSG_NOSIGNAL on the send instead - setsockopt(m_socket, SOL_SOCKET, SO_NOSIGPIPE, &flag, sizeof(flag)); -#endif - - if (timeoutMs > 0) - { -#ifdef _WIN32 - DWORD timeout = static_cast(timeoutMs); - setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast(&timeout), sizeof(timeout)); - setsockopt(m_socket, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast(&timeout), sizeof(timeout)); -#else - timeval timeout; - timeout.tv_sec = timeoutMs / 1000; - timeout.tv_usec = (timeoutMs % 1000) * 1000; - setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)); - setsockopt(m_socket, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)); -#endif - } - - m_buffer.clear(); - m_eof = false; - return true; -} - -void HttpClient::interrupt() -{ - if (m_socket != invalidSocket()) - { -#ifdef _WIN32 - shutdown(m_socket, SD_BOTH); -#else - shutdown(m_socket, SHUT_RDWR); -#endif - } -} - -void HttpClient::close() -{ - if (m_socket != invalidSocket()) - { -#ifdef _WIN32 - closesocket(m_socket); -#else - ::close(m_socket); -#endif - m_socket = invalidSocket(); - } - - m_buffer.clear(); - m_eof = false; -} - -bool HttpClient::sendAll(const std::string& data, std::string& error) -{ - size_t sent = 0; - - while (sent < data.size()) - { -#ifdef MSG_NOSIGNAL - const int flags = MSG_NOSIGNAL; -#else - const int flags = 0; -#endif - int count = ::send(m_socket, data.data() + sent, static_cast(data.size() - sent), flags); - - if (count <= 0) - { - error = "send failed (" + socketError() + ")"; - return false; - } - - sent += static_cast(count); - } - - return true; -} - -bool HttpClient::send(const std::string& method, const std::string& path, const std::vector
& headers, - const std::string& body, std::string& error) -{ - std::string request = method + " " + path + " HTTP/1.1\r\n"; - - for (const auto& header : headers) { - request += header.first + ": " + header.second + "\r\n"; - } - - // One request per connection keeps the response framing simple: no pipelining to unpick, - // and a body with neither Content-Length nor chunking ends at the close - request += "Connection: close\r\n"; - request += "Content-Length: " + std::to_string(body.size()) + "\r\n"; - request += "\r\n"; - request += body; - - return sendAll(request, error); -} - -bool HttpClient::fill(std::string& error) -{ - char block[8192]; - int count = recv(m_socket, block, sizeof(block), 0); - - if (count == 0) - { - m_eof = true; - return false; - } - - if (count < 0) - { - error = "read failed (" + socketError() + ")"; - m_eof = true; - return false; - } - - m_buffer.append(block, static_cast(count)); - return true; -} - -bool HttpClient::readLine(std::string& line, std::string& error) -{ - for (;;) - { - size_t end = m_buffer.find("\r\n"); - - if (end != std::string::npos) - { - line = m_buffer.substr(0, end); - m_buffer.erase(0, end + 2); - return true; - } - - if (!fill(error)) - { - if (error.empty()) { - error = "connection closed while reading a line"; - } - - return false; - } - } -} - -bool HttpClient::readExactly(size_t count, std::string& out, std::string& error) -{ - while (m_buffer.size() < count) - { - if (!fill(error)) - { - if (error.empty()) { - error = "connection closed with " + std::to_string(count - m_buffer.size()) + " bytes still to read"; - } - - return false; - } - } - - out = m_buffer.substr(0, count); - m_buffer.erase(0, count); - return true; -} - -bool HttpClient::readHead(Head& head, std::string& error) -{ - std::string line; - - if (!readLine(line, error)) { - return false; - } - - // HTTP/1.1 200 OK - size_t firstSpace = line.find(' '); - - if ((firstSpace == std::string::npos) || (line.compare(0, 5, "HTTP/") != 0)) - { - error = "not an HTTP response: " + line; - return false; - } - - size_t secondSpace = line.find(' ', firstSpace + 1); - head.m_status = std::atoi(line.substr(firstSpace + 1).c_str()); - head.m_reason = (secondSpace == std::string::npos) ? std::string() : trimmed(line.substr(secondSpace + 1)); - - for (;;) - { - if (!readLine(line, error)) { - return false; - } - - if (line.empty()) { - break; - } - - size_t colon = line.find(':'); - - if (colon == std::string::npos) { - continue; - } - - head.m_headers.emplace_back(trimmed(line.substr(0, colon)), trimmed(line.substr(colon + 1))); - } - - std::string length = head.header("Content-Length"); - - if (!length.empty()) { - head.m_contentLength = std::atoll(length.c_str()); - } - - head.m_chunked = (lowered(head.header("Transfer-Encoding")).find("chunked") != std::string::npos); - return true; -} - -bool HttpClient::readChunk(std::string& chunk, std::string& error) -{ - std::string line; - - if (!readLine(line, error)) { - return false; - } - - // The size line may carry chunk extensions after a semicolon - size_t semicolon = line.find(';'); - std::string sizeText = trimmed((semicolon == std::string::npos) ? line : line.substr(0, semicolon)); - size_t size = static_cast(std::strtoul(sizeText.c_str(), nullptr, 16)); - - if (size == 0) - { - // Trailers, then the final blank line. The body is complete, which is not an error - for (;;) - { - std::string trailer; - - if (!readLine(trailer, error) || trailer.empty()) { - break; - } - } - - error.clear(); - return false; - } - - if (!readExactly(size, chunk, error)) { - return false; - } - - std::string terminator; - return readLine(terminator, error); -} - -bool HttpClient::readSome(std::string& data, std::string& error) -{ - if (m_buffer.empty() && !fill(error)) { - return false; - } - - data.clear(); - data.swap(m_buffer); - return true; -} - -bool HttpClient::readBody(const Head& head, std::string& body, std::string& error) -{ - body.clear(); - - if (head.m_chunked) - { - std::string chunk; - - while (readChunk(chunk, error)) { - body += chunk; - } - - return error.empty(); - } - - if (head.m_contentLength >= 0) - { - if (head.m_contentLength == 0) { - return true; - } - - return readExactly(static_cast(head.m_contentLength), body, error); - } - - // Neither framing: the body runs to the close, which Connection: close guarantees - while (fill(error)) { - // keep reading - } - - body.swap(m_buffer); - m_buffer.clear(); - return error.empty(); -} +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// (at your option) any later version. // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include "httpclient.h" + +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#include +#else +#include +#include +#include +#include +#include +#include +#include +#include +#endif + +namespace +{ + +std::string lowered(const std::string& text) +{ + std::string result(text); + + std::transform(result.begin(), result.end(), result.begin(), + [](unsigned char c) { return static_cast(std::tolower(c)); }); + return result; +} + +std::string trimmed(const std::string& text) +{ + size_t begin = text.find_first_not_of(" \t\r\n"); + + if (begin == std::string::npos) { + return std::string(); + } + + size_t end = text.find_last_not_of(" \t\r\n"); + return text.substr(begin, end - begin + 1); +} + +std::string socketError() +{ +#ifdef _WIN32 + int code = WSAGetLastError(); + + switch (code) + { + case WSAECONNREFUSED: return "connection refused"; + case WSAETIMEDOUT: return "timed out"; + case WSAECONNRESET: return "connection reset"; + case WSAEHOSTUNREACH: return "host unreachable"; + default: return "socket error " + std::to_string(code); + } +#else + // A receive timeout set with SO_RCVTIMEO comes back as EAGAIN, whose text says nothing + // about time + if ((errno == EAGAIN) || (errno == EWOULDBLOCK)) { + return "timed out"; + } + + return std::strerror(errno); +#endif +} + +} // namespace + +HttpClient::Socket HttpClient::invalidSocket() +{ +#ifdef _WIN32 + return INVALID_SOCKET; +#else + return -1; +#endif +} + +std::string HttpClient::Head::header(const std::string& name) const +{ + std::string wanted = lowered(name); + + for (const auto& header : m_headers) + { + if (lowered(header.first) == wanted) { + return header.second; + } + } + + return std::string(); +} + +bool HttpClient::startup(std::string& error) +{ +#ifdef _WIN32 + WSADATA data; + int result = WSAStartup(MAKEWORD(2, 2), &data); + + if (result != 0) + { + error = "WSAStartup failed with " + std::to_string(result); + return false; + } +#else + (void) error; +#endif + return true; +} + +void HttpClient::cleanup() +{ +#ifdef _WIN32 + WSACleanup(); +#endif +} + +HttpClient::~HttpClient() +{ + close(); +} + +bool HttpClient::open(const std::string& host, int port, int timeoutMs, std::string& error) +{ + close(); + + addrinfo hints; + std::memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + hints.ai_protocol = IPPROTO_TCP; + + addrinfo *addresses = nullptr; + std::string service = std::to_string(port); + + if (getaddrinfo(host.c_str(), service.c_str(), &hints, &addresses) != 0) + { + error = "cannot resolve " + host; + return false; + } + + std::string reason; + + for (addrinfo *address = addresses; address != nullptr; address = address->ai_next) + { + Socket handle = socket(address->ai_family, address->ai_socktype, address->ai_protocol); + + if (handle == invalidSocket()) { + continue; + } + + if (connect(handle, address->ai_addr, static_cast(address->ai_addrlen)) == 0) + { + m_socket = handle; + break; + } + + // Read before closing the socket and freeing the addresses, either of which + // replaces the last error with one of its own + reason = socketError(); + +#ifdef _WIN32 + closesocket(handle); +#else + ::close(handle); +#endif + } + + freeaddrinfo(addresses); + + if (m_socket == invalidSocket()) + { + error = reason.empty() ? "no usable address" : reason; + return false; + } + + // Nagle would hold small JSON-RPC messages back waiting for more to send + int flag = 1; + setsockopt(m_socket, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast(&flag), sizeof(flag)); + +#ifdef SO_NOSIGPIPE + // A send on a connection the server has closed must fail, not raise SIGPIPE and end the + // process. Linux has no such option and uses MSG_NOSIGNAL on the send instead + setsockopt(m_socket, SOL_SOCKET, SO_NOSIGPIPE, &flag, sizeof(flag)); +#endif + + if (timeoutMs > 0) + { +#ifdef _WIN32 + DWORD timeout = static_cast(timeoutMs); + setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast(&timeout), sizeof(timeout)); + setsockopt(m_socket, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast(&timeout), sizeof(timeout)); +#else + timeval timeout; + timeout.tv_sec = timeoutMs / 1000; + timeout.tv_usec = (timeoutMs % 1000) * 1000; + setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)); + setsockopt(m_socket, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)); +#endif + } + + m_buffer.clear(); + m_eof = false; + return true; +} + +void HttpClient::interrupt() +{ + if (m_socket != invalidSocket()) + { +#ifdef _WIN32 + shutdown(m_socket, SD_BOTH); +#else + shutdown(m_socket, SHUT_RDWR); +#endif + } +} + +void HttpClient::close() +{ + if (m_socket != invalidSocket()) + { +#ifdef _WIN32 + closesocket(m_socket); +#else + ::close(m_socket); +#endif + m_socket = invalidSocket(); + } + + m_buffer.clear(); + m_eof = false; +} + +bool HttpClient::sendAll(const std::string& data, std::string& error) +{ + size_t sent = 0; + + while (sent < data.size()) + { +#ifdef MSG_NOSIGNAL + const int flags = MSG_NOSIGNAL; +#else + const int flags = 0; +#endif + int count = ::send(m_socket, data.data() + sent, static_cast(data.size() - sent), flags); + + if (count <= 0) + { + error = "send failed (" + socketError() + ")"; + return false; + } + + sent += static_cast(count); + } + + return true; +} + +bool HttpClient::send(const std::string& method, const std::string& path, const std::vector
& headers, + const std::string& body, std::string& error) +{ + std::string request = method + " " + path + " HTTP/1.1\r\n"; + + for (const auto& header : headers) { + request += header.first + ": " + header.second + "\r\n"; + } + + // One request per connection keeps the response framing simple: no pipelining to unpick, + // and a body with neither Content-Length nor chunking ends at the close + request += "Connection: close\r\n"; + request += "Content-Length: " + std::to_string(body.size()) + "\r\n"; + request += "\r\n"; + request += body; + + return sendAll(request, error); +} + +bool HttpClient::fill(std::string& error) +{ + char block[8192]; + int count = recv(m_socket, block, sizeof(block), 0); + + if (count == 0) + { + m_eof = true; + return false; + } + + if (count < 0) + { + error = "read failed (" + socketError() + ")"; + m_eof = true; + return false; + } + + m_buffer.append(block, static_cast(count)); + return true; +} + +bool HttpClient::readLine(std::string& line, std::string& error) +{ + for (;;) + { + size_t end = m_buffer.find("\r\n"); + + if (end != std::string::npos) + { + line = m_buffer.substr(0, end); + m_buffer.erase(0, end + 2); + return true; + } + + if (!fill(error)) + { + if (error.empty()) { + error = "connection closed while reading a line"; + } + + return false; + } + } +} + +bool HttpClient::readExactly(size_t count, std::string& out, std::string& error) +{ + while (m_buffer.size() < count) + { + if (!fill(error)) + { + if (error.empty()) { + error = "connection closed with " + std::to_string(count - m_buffer.size()) + " bytes still to read"; + } + + return false; + } + } + + out = m_buffer.substr(0, count); + m_buffer.erase(0, count); + return true; +} + +bool HttpClient::readHead(Head& head, std::string& error) +{ + std::string line; + + if (!readLine(line, error)) { + return false; + } + + // HTTP/1.1 200 OK + size_t firstSpace = line.find(' '); + + if ((firstSpace == std::string::npos) || (line.compare(0, 5, "HTTP/") != 0)) + { + error = "not an HTTP response: " + line; + return false; + } + + size_t secondSpace = line.find(' ', firstSpace + 1); + head.m_status = std::atoi(line.substr(firstSpace + 1).c_str()); + head.m_reason = (secondSpace == std::string::npos) ? std::string() : trimmed(line.substr(secondSpace + 1)); + + for (;;) + { + if (!readLine(line, error)) { + return false; + } + + if (line.empty()) { + break; + } + + size_t colon = line.find(':'); + + if (colon == std::string::npos) { + continue; + } + + head.m_headers.emplace_back(trimmed(line.substr(0, colon)), trimmed(line.substr(colon + 1))); + } + + std::string length = head.header("Content-Length"); + + if (!length.empty()) { + head.m_contentLength = std::atoll(length.c_str()); + } + + head.m_chunked = (lowered(head.header("Transfer-Encoding")).find("chunked") != std::string::npos); + return true; +} + +bool HttpClient::readChunk(std::string& chunk, std::string& error) +{ + std::string line; + + if (!readLine(line, error)) { + return false; + } + + // The size line may carry chunk extensions after a semicolon + size_t semicolon = line.find(';'); + std::string sizeText = trimmed((semicolon == std::string::npos) ? line : line.substr(0, semicolon)); + size_t size = static_cast(std::strtoul(sizeText.c_str(), nullptr, 16)); + + if (size == 0) + { + // Trailers, then the final blank line. The body is complete, which is not an error + for (;;) + { + std::string trailer; + + if (!readLine(trailer, error) || trailer.empty()) { + break; + } + } + + error.clear(); + return false; + } + + if (!readExactly(size, chunk, error)) { + return false; + } + + std::string terminator; + return readLine(terminator, error); +} + +bool HttpClient::readSome(std::string& data, std::string& error) +{ + if (m_buffer.empty() && !fill(error)) { + return false; + } + + data.clear(); + data.swap(m_buffer); + return true; +} + +bool HttpClient::readBody(const Head& head, std::string& body, std::string& error) +{ + body.clear(); + + if (head.m_chunked) + { + std::string chunk; + + while (readChunk(chunk, error)) { + body += chunk; + } + + return error.empty(); + } + + if (head.m_contentLength >= 0) + { + if (head.m_contentLength == 0) { + return true; + } + + return readExactly(static_cast(head.m_contentLength), body, error); + } + + // Neither framing: the body runs to the close, which Connection: close guarantees + while (fill(error)) { + // keep reading + } + + body.swap(m_buffer); + m_buffer.clear(); + return error.empty(); +} diff --git a/plugins/feature/mcpserver/bridge/httpclient.h b/plugins/feature/mcpserver/bridge/httpclient.h index 38c6b6d76..f16a2c24b 100644 --- a/plugins/feature/mcpserver/bridge/httpclient.h +++ b/plugins/feature/mcpserver/bridge/httpclient.h @@ -1,101 +1,101 @@ -/////////////////////////////////////////////////////////////////////////////////// -// Copyright (C) 2026 Jon Beniston, M7RCE // -// Some code by AI // -// // -// This program is free software; you can redistribute it and/or modify // -// it under the terms of the GNU General Public License as published by // -// the Free Software Foundation as version 3 of the License, or // -// (at your option) any later version. // -// // -// This program is distributed in the hope that it will be useful, // -// but WITHOUT ANY WARRANTY; without even the implied warranty of // -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // -// GNU General Public License V3 for more details. // -// // -// You should have received a copy of the GNU General Public License // -// along with this program. If not, see . // -/////////////////////////////////////////////////////////////////////////////////// - -#ifndef INCLUDE_MCPBRIDGE_HTTPCLIENT_H_ -#define INCLUDE_MCPBRIDGE_HTTPCLIENT_H_ - -#include -#include -#include - -//!< Just enough HTTP/1.1 to talk to SDRangel's MCP server: one request per connection, -//!< no TLS, no redirects, no keep alive. Bodies arrive either with a Content-Length or -//!< chunked, and a chunked body can be read incrementally so that the event stream can -//!< be followed as it arrives. -class HttpClient -{ -public: - using Header = std::pair; - - struct Head - { - int m_status = 0; - std::string m_reason; - std::vector
m_headers; - long long m_contentLength = -1; //!< -1 when there is no Content-Length - bool m_chunked = false; - - //!< Case insensitive lookup, empty when the header is absent - std::string header(const std::string& name) const; - }; - - HttpClient() = default; - ~HttpClient(); - - HttpClient(const HttpClient&) = delete; - HttpClient& operator=(const HttpClient&) = delete; - - static bool startup(std::string& error); //!< WSAStartup on Windows, nothing elsewhere - static void cleanup(); - - bool open(const std::string& host, int port, int timeoutMs, std::string& error); - void close(); - //!< Wakes a read blocked on this socket from another thread. Only the socket is touched: - //!< the buffer and the rest belong to the thread reading, which closes when its read - //!< returns. Closing from the other thread would not wake a read on Linux, and frees a - //!< descriptor number the reader still holds - void interrupt(); - bool isOpen() const { return m_socket != invalidSocket(); } - - //!< Sends the request and its body. An empty method body is fine. - bool send(const std::string& method, const std::string& path, const std::vector
& headers, - const std::string& body, std::string& error); - - bool readHead(Head& head, std::string& error); - - //!< Reads the whole body, however it is framed. Not for the event stream, which never ends. - bool readBody(const Head& head, std::string& body, std::string& error); - - //!< One piece of a chunked body, for following a stream. Returns false at the end of the - //!< body or on error, with error empty when the end was reached cleanly. - bool readChunk(std::string& chunk, std::string& error); - - //!< Whatever has arrived of a body that is delimited by the connection closing rather - //!< than chunked, which is how the event stream comes back. Same false at the end. - bool readSome(std::string& data, std::string& error); - -private: -#ifdef _WIN32 - using Socket = unsigned long long; //!< SOCKET, kept out of the header so windows.h is not needed here -#else - using Socket = int; -#endif - - static Socket invalidSocket(); - - bool fill(std::string& error); //!< One read into m_buffer - bool readLine(std::string& line, std::string& error); - bool readExactly(size_t count, std::string& out, std::string& error); - bool sendAll(const std::string& data, std::string& error); - - Socket m_socket = invalidSocket(); - std::string m_buffer; //!< Bytes read from the socket but not yet consumed - bool m_eof = false; -}; - -#endif // INCLUDE_MCPBRIDGE_HTTPCLIENT_H_ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// (at your option) any later version. // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_MCPBRIDGE_HTTPCLIENT_H_ +#define INCLUDE_MCPBRIDGE_HTTPCLIENT_H_ + +#include +#include +#include + +//!< Just enough HTTP/1.1 to talk to SDRangel's MCP server: one request per connection, +//!< no TLS, no redirects, no keep alive. Bodies arrive either with a Content-Length or +//!< chunked, and a chunked body can be read incrementally so that the event stream can +//!< be followed as it arrives. +class HttpClient +{ +public: + using Header = std::pair; + + struct Head + { + int m_status = 0; + std::string m_reason; + std::vector
m_headers; + long long m_contentLength = -1; //!< -1 when there is no Content-Length + bool m_chunked = false; + + //!< Case insensitive lookup, empty when the header is absent + std::string header(const std::string& name) const; + }; + + HttpClient() = default; + ~HttpClient(); + + HttpClient(const HttpClient&) = delete; + HttpClient& operator=(const HttpClient&) = delete; + + static bool startup(std::string& error); //!< WSAStartup on Windows, nothing elsewhere + static void cleanup(); + + bool open(const std::string& host, int port, int timeoutMs, std::string& error); + void close(); + //!< Wakes a read blocked on this socket from another thread. Only the socket is touched: + //!< the buffer and the rest belong to the thread reading, which closes when its read + //!< returns. Closing from the other thread would not wake a read on Linux, and frees a + //!< descriptor number the reader still holds + void interrupt(); + bool isOpen() const { return m_socket != invalidSocket(); } + + //!< Sends the request and its body. An empty method body is fine. + bool send(const std::string& method, const std::string& path, const std::vector
& headers, + const std::string& body, std::string& error); + + bool readHead(Head& head, std::string& error); + + //!< Reads the whole body, however it is framed. Not for the event stream, which never ends. + bool readBody(const Head& head, std::string& body, std::string& error); + + //!< One piece of a chunked body, for following a stream. Returns false at the end of the + //!< body or on error, with error empty when the end was reached cleanly. + bool readChunk(std::string& chunk, std::string& error); + + //!< Whatever has arrived of a body that is delimited by the connection closing rather + //!< than chunked, which is how the event stream comes back. Same false at the end. + bool readSome(std::string& data, std::string& error); + +private: +#ifdef _WIN32 + using Socket = unsigned long long; //!< SOCKET, kept out of the header so windows.h is not needed here +#else + using Socket = int; +#endif + + static Socket invalidSocket(); + + bool fill(std::string& error); //!< One read into m_buffer + bool readLine(std::string& line, std::string& error); + bool readExactly(size_t count, std::string& out, std::string& error); + bool sendAll(const std::string& data, std::string& error); + + Socket m_socket = invalidSocket(); + std::string m_buffer; //!< Bytes read from the socket but not yet consumed + bool m_eof = false; +}; + +#endif // INCLUDE_MCPBRIDGE_HTTPCLIENT_H_ diff --git a/plugins/feature/mcpserver/bridge/main.cpp b/plugins/feature/mcpserver/bridge/main.cpp index a0631cb3d..6211064c1 100644 --- a/plugins/feature/mcpserver/bridge/main.cpp +++ b/plugins/feature/mcpserver/bridge/main.cpp @@ -1,1085 +1,1085 @@ -/////////////////////////////////////////////////////////////////////////////////// -// Copyright (C) 2026 Jon Beniston, M7RCE // -// Some code by AI // -// // -// This program is free software; you can redistribute it and/or modify // -// it under the terms of the GNU General Public License as published by // -// the Free Software Foundation as version 3 of the License, or // -// (at your option) any later version. // -// // -// This program is distributed in the hope that it will be useful, // -// but WITHOUT ANY WARRANTY; without even the implied warranty of // -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // -// GNU General Public License V3 for more details. // -// // -// You should have received a copy of the GNU General Public License // -// along with this program. If not, see . // -/////////////////////////////////////////////////////////////////////////////////// - -// Bridges the MCP stdio transport to SDRangel's Streamable HTTP MCP server, for clients -// such as Claude Desktop that can only launch a local server on stdin and stdout. -// JSON-RPC messages are passed through untouched: this program understands the transport, -// not the protocol. - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef _WIN32 -#include -#include -#include -#endif - -#include "httpclient.h" -#include "jsonscan.h" -#include "ssereader.h" - -namespace -{ - -const char *versionText = "sdrangel-mcp-bridge " SDRANGEL_MCP_BRIDGE_VERSION; - -struct Options -{ - std::string m_host = "127.0.0.1"; - int m_port = 8092; - std::string m_path = "/mcp"; - std::string m_token; - bool m_verbose = false; -}; - -void note(const Options& options, const std::string& message) -{ - if (options.m_verbose) { - std::fprintf(stderr, "sdrangel-mcp-bridge: %s\n", message.c_str()); - } -} - -void warn(const std::string& message) -{ - std::fprintf(stderr, "sdrangel-mcp-bridge: %s\n", message.c_str()); -} - -//!< An extension bundle cannot leave an argument out, so a user_config value the user did not -//!< set can reach us as the placeholder text itself. Treated as "not given" rather than taken -//!< literally, which would mean a nonsense port or a token the server never issued. -bool isPlaceholder(const std::string& value) -{ - return (value.size() > 3) && (value.compare(0, 2, "${") == 0) && (value.back() == '}'); -} - -//!< The tool list this build of SDRangel provides, written beside the bridge when the -//!< extension was packaged. A client reads the tool list once when a conversation begins and -//!< does not ask again, so a conversation that starts before SDRangel is up would have no -//!< tools for its whole life if the bridge could only answer with what it had seen. Shipping -//!< the list means it is right the first time the extension is ever used, and it comes from -//!< the server's own registry, so it cannot drift from what the tools really are. -std::string toolsFile(const char *program) -{ - std::string path; - -#ifdef _WIN32 - char module[MAX_PATH]; - - if (GetModuleFileNameA(nullptr, module, MAX_PATH) > 0) { - path = module; - } -#endif - - if (path.empty() && program) { - path = program; - } - - size_t slash = path.find_last_of("/\\"); - return (slash == std::string::npos) ? std::string("tools.json") : path.substr(0, slash + 1) + "tools.json"; -} - -std::string readFile(const std::string& path) -{ - std::ifstream file(path, std::ios::binary); - - if (!file) { - return std::string(); - } - - return std::string((std::istreambuf_iterator(file)), std::istreambuf_iterator()); -} - -//!< JSON string escaping for the messages this program generates itself -std::string escaped(const std::string& text) -{ - std::string result; - - for (char c : text) - { - switch (c) - { - case '"': result += "\\\""; break; - case '\\': result += "\\\\"; break; - case '\n': result += "\\n"; break; - case '\r': result += "\\r"; break; - case '\t': result += "\\t"; break; - default: - if (static_cast(c) < 0x20) { - result += ' '; - } else { - result += c; - } - } - } - - return result; -} - -} // namespace - -class Bridge -{ -public: - Bridge(const Options& options, const std::string& shippedTools) : - m_options(options), - m_shippedTools(shippedTools) - { - } - - int run(); - -private: - void handle(const std::string& message); - void post(const std::string& message); - bool exchange(const std::string& message, HttpClient::Head& head, std::string& body, std::string& error); - void noteSession(const HttpClient::Head& head); - bool reinitialize(const std::string& staleSession); - bool answerLocally(const std::string& id, const std::string& method, const std::string& message); - bool openSession(); - //!< Subscribes again to the resources the client had subscribed to, on a session just built - void replaySubscriptions(); - void settleHandshake(); - void waitForHandshake(); - void streamLoop(); - void startStream(); - void stopStream(); - void endSession(); - - std::vector headers(bool eventStream) const; - void writeMessage(const std::string& message); - void writeError(const std::string& id, int code, const std::string& reason); - - std::string sessionId() const; - - const Options m_options; - mutable std::mutex m_stateMutex; - std::string m_sessionId; - std::string m_protocolVersion; - std::string m_initializeMessage; //!< Kept so the session can be rebuilt without the client - std::set m_subscriptions; //!< Resource URIs the client subscribed to, to carry over to a new session - std::mutex m_reinitMutex; //!< One rebuild at a time, however many calls failed at once - std::atomic m_degraded { false }; //!< Handshake answered without SDRangel: it was not up - std::string m_shippedTools; //!< tools/list result packaged with the bridge, may be empty - - // Every request but the handshake itself waits for the handshake to finish. Whether - // SDRangel was reachable decides how the listings are answered, and a request that - // overtook the handshake would be answered on a state that had not been worked out yet - std::mutex m_handshakeMutex; - std::condition_variable m_handshakeReady; - bool m_handshakeSettled { false }; - - std::mutex m_outputMutex; - - static constexpr int m_retryMinMs = 1000; //!< First wait before reopening the event stream - static constexpr int m_retryMaxMs = 60000; //!< And the longest, once it keeps failing - - // Socket timeouts, so that a SDRangel that has stopped answering cannot hold a worker - // for ever: run() joins every worker once the client closes stdin, and one that never - // returns would keep this process alive after the client has given up on it. - // A call may legitimately run for over a minute: scan watches for up to 30 s after - // measuring its threshold for up to 15 s, and listen may tune the gain first - static constexpr int m_callTimeoutMs = 180000; - // The server writes a keepalive comment every 15 s while the stream is open - static constexpr int m_streamTimeoutMs = 60000; - static constexpr int m_shutdownTimeoutMs = 5000; - - std::atomic m_running { true }; - std::atomic m_streamWanted { false }; - std::thread m_streamThread; - std::mutex m_streamMutex; - HttpClient *m_streamClient = nullptr; //!< Owned by the stream thread, closed from ours to unblock it -}; - -std::string Bridge::sessionId() const -{ - std::lock_guard lock(m_stateMutex); - return m_sessionId; -} - -std::vector Bridge::headers(bool eventStream) const -{ - std::vector result; - result.emplace_back("Host", m_options.m_host + ":" + std::to_string(m_options.m_port)); - result.emplace_back("User-Agent", versionText); - result.emplace_back("Accept", eventStream ? "text/event-stream" : "application/json, text/event-stream"); - - if (!eventStream) { - result.emplace_back("Content-Type", "application/json"); - } - - if (!m_options.m_token.empty()) { - result.emplace_back("Authorization", "Bearer " + m_options.m_token); - } - - std::string session; - std::string version; - { - std::lock_guard lock(m_stateMutex); - session = m_sessionId; - version = m_protocolVersion; - } - - if (!session.empty()) { - result.emplace_back("Mcp-Session-Id", session); - } - - // Sent on every request after initialize, as the Streamable HTTP transport requires - if (!version.empty()) { - result.emplace_back("MCP-Protocol-Version", version); - } - - return result; -} - -void Bridge::writeMessage(const std::string& message) -{ - // One JSON-RPC message per line. Compact JSON has no raw newlines in it, so nothing - // here can break the framing, but a stray carriage return would confuse a strict reader - std::string line(message); - line.erase(std::remove(line.begin(), line.end(), '\n'), line.end()); - line.erase(std::remove(line.begin(), line.end(), '\r'), line.end()); - - std::lock_guard lock(m_outputMutex); - std::fwrite(line.data(), 1, line.size(), stdout); - std::fputc('\n', stdout); - std::fflush(stdout); -} - -void Bridge::writeError(const std::string& id, int code, const std::string& reason) -{ - // An absent or unreadable id becomes null, which is what JSON-RPC asks for when the - // request could not be identified. The client cannot match it to a call, so the text - // has to stand on its own in the log - std::string identifier = id.empty() ? "null" : id; - writeMessage("{\"jsonrpc\":\"2.0\",\"id\":" + identifier - + ",\"error\":{\"code\":" + std::to_string(code) - + ",\"message\":\"" + escaped(reason) + "\"}}"); -} - -void Bridge::handle(const std::string& message) -{ - post(message); -} - -//!< One request and its whole reply. The error is ready to hand to the client as it is. -bool Bridge::exchange(const std::string& message, HttpClient::Head& head, std::string& body, std::string& error) -{ - HttpClient client; - - if (!client.open(m_options.m_host, m_options.m_port, m_callTimeoutMs, error)) - { - error = "Cannot reach SDRangel's MCP server at " + m_options.m_host + ":" - + std::to_string(m_options.m_port) + ": " + error + ". Start SDRangel, add the MCP Server " - "feature and start it, then try again."; - return false; - } - - if (!client.send("POST", m_options.m_path, headers(false), message, error)) - { - error = "Sending to SDRangel failed: " + error; - return false; - } - - if (!client.readHead(head, error)) - { - error = "No reply from SDRangel: " + error; - return false; - } - - if (!client.readBody(head, body, error)) - { - error = "Truncated reply from SDRangel: " + error; - return false; - } - - return true; -} - -void Bridge::noteSession(const HttpClient::Head& head) -{ - std::string session = head.header("Mcp-Session-Id"); - - if (session.empty() || (session == sessionId())) { - return; - } - - { - std::lock_guard lock(m_stateMutex); - m_sessionId = session; - } - - note(m_options, "session " + session); - startStream(); // no effect once it is running: it picks the new session up on its own -} - -//!< Replays the client's initialize to get a working session again. SDRangel forgets every -//!< session it has issued when it restarts, and answers 404 to the ones it used to know. The -//!< client will not initialize a second time on its own, and the bridge outlives many runs of -//!< SDRangel, so without this the connector is dead until the client restarts it. -bool Bridge::reinitialize(const std::string& staleSession) -{ - std::lock_guard lock(m_reinitMutex); - - if (sessionId() != staleSession) { - return true; // another call rebuilt it while this one waited - } - - std::string initialize; - { - std::lock_guard stateLock(m_stateMutex); - initialize = m_initializeMessage; - m_sessionId.clear(); // or the replay carries the dead id and is refused in its turn - } - - if (initialize.empty()) { - return false; - } - - HttpClient::Head head; - std::string body; - std::string error; - - if (!exchange(initialize, head, body, error)) - { - note(m_options, "could not start a new session: " + error); - return false; - } - - if ((head.m_status < 200) || (head.m_status > 299)) - { - note(m_options, "could not start a new session: HTTP " + std::to_string(head.m_status)); - return false; - } - - noteSession(head); - - std::string version = jsonStringMember(jsonMember(body, "result"), "protocolVersion"); - - if (!version.empty()) - { - std::lock_guard stateLock(m_stateMutex); - m_protocolVersion = version; - } - - // This server does nothing with it, but a client that has initialized sends it, and the - // reply is of no interest either way - HttpClient::Head ignoredHead; - std::string ignoredBody; - std::string ignoredError; - exchange("{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}", ignoredHead, ignoredBody, ignoredError); - - if (sessionId().empty()) { - return false; - } - - replaySubscriptions(); - return true; -} - -//!< A subscription lives in the session it was made in, so a session the server has forgotten -//!< took the client's subscriptions with it. The client is not told: the updates it asked for -//!< carry on arriving as before. The replies are answers to requests the client never made, so -//!< they are not passed on -void Bridge::replaySubscriptions() -{ - std::set uris; - { - std::lock_guard lock(m_stateMutex); - uris = m_subscriptions; - } - - int n = 0; - - for (const std::string& uri : uris) - { - HttpClient::Head head; - std::string body; - std::string error; - std::string message = "{\"jsonrpc\":\"2.0\",\"id\":\"bridge-subscribe-" + std::to_string(++n) - + "\",\"method\":\"resources/subscribe\",\"params\":{\"uri\":\"" + escaped(uri) + "\"}}"; - - if (!exchange(message, head, body, error) || (head.m_status < 200) || (head.m_status > 299)) { - note(m_options, "could not subscribe again to " + uri); - } - } - - if (n > 0) { - note(m_options, "subscribed again to " + std::to_string(n) + " resource(s)"); - } -} - -//!< Answers what the bridge can answer on its own. Returns true when it has replied. -//!< -//!< A stdio server's health is judged by the client from this conversation, and the bridge is -//!< healthy whether or not SDRangel happens to be running: it is a long lived process that -//!< outlives many runs of the application behind it. Letting SDRangel's absence turn into -//!< failed pings or a failed handshake makes the client give up on the bridge for good, since -//!< it will not restart it until the application itself is restarted. -bool Bridge::answerLocally(const std::string& id, const std::string& method, const std::string& message) -{ - if (!m_degraded.load()) { - return false; - } - - // SDRangel was not up for the handshake, so there is nothing to list yet. An empty list - // keeps the client working; it is told to ask again as soon as SDRangel appears - static const char *emptyListings[][2] = { - {"tools/list", "tools"}, - {"resources/list", "resources"}, - {"resources/templates/list", "resourceTemplates"}, - {"prompts/list", "prompts"}, - }; - - for (const auto& listing : emptyListings) - { - if (method == listing[0]) - { - // The tools are shipped with the bridge; resources and prompts are whatever the - // running instance happens to hold, so those stay empty until it is reachable - std::string result = (method == "tools/list") && !m_shippedTools.empty() - ? m_shippedTools - : std::string("{\"") + listing[1] + "\":[]}"; - - writeMessage("{\"jsonrpc\":\"2.0\",\"id\":" + (id.empty() ? "null" : id) - + ",\"result\":" + result + "}"); - return true; - } - } - - (void) message; - return false; -} - -//!< Establishes a session upstream by replaying the client's initialize. Tells the client to -//!< ask for the tools again if the handshake had to be answered without SDRangel. -bool Bridge::openSession() -{ - if (!sessionId().empty()) { - return true; - } - - // One session at a time, however many callers found none: the stream thread and every - // worker with a call in hand arrive here together when SDRangel comes back, and each - // would otherwise open a session of its own, with the stream on one and the calls on - // another. Whoever waited finds the session the first one made - std::lock_guard lock(m_reinitMutex); - - if (!sessionId().empty()) { - return true; - } - - std::string initialize; - { - std::lock_guard lock(m_stateMutex); - initialize = m_initializeMessage; - } - - if (initialize.empty()) { - return false; - } - - HttpClient::Head head; - std::string body; - std::string error; - - if (!exchange(initialize, head, body, error) || (head.m_status < 200) || (head.m_status > 299)) { - return false; - } - - noteSession(head); - - if (sessionId().empty()) { - return false; - } - - std::string version = jsonStringMember(jsonMember(body, "result"), "protocolVersion"); - - if (!version.empty()) - { - std::lock_guard lock(m_stateMutex); - m_protocolVersion = version; - } - - replaySubscriptions(); - - if (m_degraded.exchange(false)) - { - note(m_options, "SDRangel is up, telling the client to list again"); - writeMessage("{\"jsonrpc\":\"2.0\",\"method\":\"notifications/tools/list_changed\"}"); - writeMessage("{\"jsonrpc\":\"2.0\",\"method\":\"notifications/resources/list_changed\"}"); - writeMessage("{\"jsonrpc\":\"2.0\",\"method\":\"notifications/prompts/list_changed\"}"); - } - - return true; -} - -void Bridge::settleHandshake() -{ - { - std::lock_guard lock(m_handshakeMutex); - m_handshakeSettled = true; - } - - m_handshakeReady.notify_all(); -} - -void Bridge::waitForHandshake() -{ - std::unique_lock lock(m_handshakeMutex); - - // Bounded, so that a client which never gets as far as initialize cannot wedge the bridge - m_handshakeReady.wait_for(lock, std::chrono::seconds(20), [this]() { return m_handshakeSettled; }); -} - -void Bridge::post(const std::string& message) -{ - std::string id = jsonMember(message, "id"); - std::string method = jsonStringMember(message, "method"); - - // Whether this process is alive has nothing to do with the handshake or with SDRangel - if (method == "ping") - { - writeMessage("{\"jsonrpc\":\"2.0\",\"id\":" + (id.empty() ? "null" : id) + ",\"result\":{}}"); - return; - } - - if (method == "initialize") - { - std::lock_guard lock(m_stateMutex); - m_initializeMessage = message; - } - else - { - waitForHandshake(); - } - - if (answerLocally(id, method, message)) { - return; - } - - // A call arriving while there is no session, because SDRangel was away: try to build one - // rather than failing on a stale or absent session - if ((method != "initialize") && sessionId().empty()) { - openSession(); - } - - // Releases anything waiting on the handshake however this call ends - struct Settle - { - Bridge *bridge; - bool wanted; - ~Settle() { if (wanted) { bridge->settleHandshake(); } } - } settle { this, method == "initialize" }; - - HttpClient::Head head; - std::string body; - std::string error; - - if (!exchange(message, head, body, error)) - { - // A notification has no id and takes no reply, failed or not: an error against a - // null id is a response to a call the client never made - if (id.empty() && (method != "initialize")) - { - note(m_options, "dropped " + method + ": " + error); - return; - } - - // The handshake must not fail, whatever SDRangel is doing: a client that is told the - // server is broken during initialize never comes back to it - if (method == "initialize") - { - note(m_options, "SDRangel is not up: answering the handshake without it"); - m_degraded.store(true); - startStream(); // watches for SDRangel and lists again once it is there - - std::string requested = jsonStringMember(jsonMember(message, "params"), "protocolVersion"); - - if (requested.empty()) { - requested = "2025-06-18"; - } - - writeMessage("{\"jsonrpc\":\"2.0\",\"id\":" + (id.empty() ? "null" : id) - + ",\"result\":{\"protocolVersion\":\"" + escaped(requested) + "\"" - ",\"capabilities\":{\"tools\":{\"listChanged\":true}" - ",\"resources\":{\"listChanged\":true,\"subscribe\":true}" - ",\"prompts\":{\"listChanged\":true}}" - ",\"serverInfo\":{\"name\":\"SDRangel\",\"version\":\"" + escaped(SDRANGEL_MCP_BRIDGE_VERSION) + "\"}" - // Written in the past tense: the client reads this once, when the - // conversation starts, and never again, so anything phrased as the state - // right now is wrong within seconds of SDRangel being started - ",\"instructions\":\"SDRangel is a software defined radio (SDR) application. This " - "server controls it.\\n\\nSDRangel was not running when this conversation started, so " - "these tools are the ones shipped with it rather than a listing from the running " - "instance. They work as soon as SDRangel is running with the MCP Server feature added " - "and started, with nothing to restart. Until then a call reports that it cannot reach " - "it.\"}}"); - return; - } - - writeError(id, -32001, error); - return; - } - - noteSession(head); - - // A session the server has never heard of: it has been restarted, or the session was - // expired. Rebuild it and send the call again, so that neither the client nor the user - // has to know anything happened - std::string session = sessionId(); - - if ((head.m_status == 404) && !session.empty() && (method != "initialize")) - { - note(m_options, "session refused, starting a new one"); - - if (reinitialize(session)) - { - HttpClient::Head retryHead; - std::string retryBody; - std::string retryError; - - if (exchange(message, retryHead, retryBody, retryError)) - { - head = retryHead; - body = retryBody; - noteSession(head); - } - } - } - - if (head.m_status == 202) { - return; // a notification or a response of our own: nothing comes back - } - - if ((head.m_status < 200) || (head.m_status > 299)) - { - // The server's own errors are {"error": "..."} rather than JSON-RPC - std::string detail = jsonStringMember(body, "error"); - - if (detail.empty()) { - detail = head.m_reason.empty() ? body : head.m_reason; - } - - writeError(id, -32001, "SDRangel returned HTTP " + std::to_string(head.m_status) + ": " + detail); - return; - } - - if (body.empty()) - { - writeError(id, -32001, "SDRangel returned an empty reply"); - return; - } - - if (method == "initialize") - { - std::string version = jsonStringMember(jsonMember(body, "result"), "protocolVersion"); - - if (!version.empty()) - { - std::lock_guard lock(m_stateMutex); - m_protocolVersion = version; - } - } - - // Remembered only once the server has accepted it, so that a refused subscription is not - // replayed on the next session - if (((method == "resources/subscribe") || (method == "resources/unsubscribe")) && jsonMember(body, "error").empty()) - { - std::string uri = jsonStringMember(jsonMember(message, "params"), "uri"); - - if (!uri.empty()) - { - std::lock_guard lock(m_stateMutex); - - if (method == "resources/subscribe") { - m_subscriptions.insert(uri); - } else { - m_subscriptions.erase(uri); - } - } - } - - writeMessage(body); -} - -void Bridge::startStream() -{ - bool expected = false; - - if (!m_streamWanted.compare_exchange_strong(expected, true)) { - return; // already running - } - - m_streamThread = std::thread([this]() { streamLoop(); }); -} - -void Bridge::stopStream() -{ - if (!m_streamWanted.load()) { - return; - } - - { - // Shutting the socket down under the thread is what unblocks its read; the thread - // then closes it itself - std::lock_guard lock(m_streamMutex); - - if (m_streamClient) { - m_streamClient->interrupt(); - } - } - - if (m_streamThread.joinable()) { - m_streamThread.join(); - } -} - -void Bridge::streamLoop() -{ - // The server closes the stream when its lifetime backstop expires, so this reopens it - // for as long as the bridge is running. It is also what notices SDRangel coming back - // after the handshake had to be answered without it. - // - // Retries back off. A client that is sitting idle sends nothing, so nothing else here - // ever notices that something is wrong, and a fixed one second retry turns an - // unreachable or unhappy server into hundreds of log lines a minute, for hours. - int retryMs = m_retryMinMs; - - while (m_running.load()) - { - HttpClient client; - std::string error; - bool opened = false; - - if (sessionId().empty() && !openSession()) - { - // Nothing to stream from yet: wait and look again - for (int waited = 0; m_running.load() && (waited < retryMs); waited += 50) { - std::this_thread::sleep_for(std::chrono::milliseconds(50)); - } - - retryMs = std::min(retryMs * 2, m_retryMaxMs); - continue; - } - - if (!client.open(m_options.m_host, m_options.m_port, m_streamTimeoutMs, error)) - { - note(m_options, "event stream cannot connect: " + error); - } - else - { - { - std::lock_guard lock(m_streamMutex); - m_streamClient = &client; - } - - if (client.send("GET", m_options.m_path, headers(true), std::string(), error)) - { - HttpClient::Head head; - - if (!client.readHead(head, error)) - { - note(m_options, "event stream failed: " + error); - } - else if (head.m_status == 404) - { - // The session has been forgotten, which SDRangel restarting does to all of - // them. Only calls coming from the client recovered this before, so an idle - // client left the stream asking after a session that would never come back - note(m_options, "event stream session refused, starting a new one"); - - std::string stale = sessionId(); - - if (!stale.empty()) { - reinitialize(stale); - } - } - else if (head.m_status != 200) - { - note(m_options, "event stream refused with HTTP " + std::to_string(head.m_status)); - } - else - { - note(m_options, "event stream open"); - opened = true; - retryMs = m_retryMinMs; - SseReader reader; - std::string chunk; - - // The server delimits the stream by closing the connection rather than - // chunking it, but a proxy or a later server might chunk, so follow - // whichever framing the response actually used - while (head.m_chunked ? client.readChunk(chunk, error) : client.readSome(chunk, error)) - { - for (const auto& event : reader.feed(chunk)) - { - if (!event.empty()) { - writeMessage(event); - } - } - } - - if (!error.empty()) { - note(m_options, "event stream ended: " + error); - } - } - } - - { - std::lock_guard lock(m_streamMutex); - m_streamClient = nullptr; - } - } - - // Reopening immediately would spin if the server has gone away - for (int waited = 0; m_running.load() && (waited < retryMs); waited += 50) { - std::this_thread::sleep_for(std::chrono::milliseconds(50)); - } - - // A stream that opened and then ended is the normal lifetime backstop, so that starts - // again promptly; anything else waits longer each time - retryMs = opened ? m_retryMinMs : std::min(retryMs * 2, m_retryMaxMs); - } -} - -void Bridge::endSession() -{ - std::string session = sessionId(); - - if (session.empty()) { - return; - } - - HttpClient client; - std::string error; - - if (!client.open(m_options.m_host, m_options.m_port, m_shutdownTimeoutMs, error)) { - return; // going away anyway, and the server expires idle sessions - } - - if (client.send("DELETE", m_options.m_path, headers(false), std::string(), error)) - { - HttpClient::Head head; - std::string body; - - if (client.readHead(head, error)) { - client.readBody(head, body, error); - } - } - - note(m_options, "session ended"); -} - -int Bridge::run() -{ - std::string error; - - if (!HttpClient::startup(error)) - { - warn(error); - return 1; - } - - note(m_options, std::string("relaying to http://") + m_options.m_host + ":" - + std::to_string(m_options.m_port) + m_options.m_path); - - // A worker, and the flag it raises once it has run to completion. A thread that is still - // working is joinable too, so joinable() cannot tell the loop below which of them it is able - // to reap without blocking - struct Worker - { - std::thread m_thread; - std::shared_ptr> m_finished; - }; - - std::vector workers; - std::string line; - - while (std::getline(std::cin, line)) - { - if (!line.empty() && (line.back() == '\r')) { - line.pop_back(); - } - - if (line.empty()) { - continue; - } - - // A thread each, so that a long call such as record_iq does not hold up the - // messages that follow it, cancellation among them - auto finished = std::make_shared>(false); - workers.push_back(Worker{ - std::thread([this, line, finished]() { - handle(line); - finished->store(true); - }), - finished}); - - // Reap only the ones that have finished. Joining a worker that is still inside a - // record_iq, listen, scan or audio call would stop this loop reading input for as long as - // that call runs, which is exactly when a cancellation needs to get through - for (auto worker = workers.begin(); worker != workers.end(); ) - { - if (worker->m_finished->load()) - { - worker->m_thread.join(); - worker = workers.erase(worker); - } - else - { - ++worker; - } - } - } - - note(m_options, "input closed"); - m_running.store(false); - - for (auto& worker : workers) - { - if (worker.m_thread.joinable()) { - worker.m_thread.join(); - } - } - - stopStream(); - endSession(); - HttpClient::cleanup(); - return 0; -} - -int main(int argc, char *argv[]) -{ -#ifndef _WIN32 - // A write to a socket or pipe whose other end has gone must fail, not end the process - signal(SIGPIPE, SIG_IGN); -#endif - - Options options; - - for (int i = 1; i < argc; i++) - { - std::string argument(argv[i]); - auto value = [&](const char *name) -> std::string - { - if (i + 1 >= argc) - { - warn(std::string(name) + " needs a value"); - std::exit(2); - } - - return std::string(argv[++i]); - }; - - if (argument == "--host") - { - std::string host = value("--host"); - - if (!isPlaceholder(host) && !host.empty()) { - options.m_host = host; - } - } - else if (argument == "--port") - { - std::string port = value("--port"); - - if (!isPlaceholder(port) && !port.empty()) { - options.m_port = std::atoi(port.c_str()); - } - } - else if (argument == "--path") - { - std::string path = value("--path"); - - if (!isPlaceholder(path) && !path.empty()) { - options.m_path = path; - } - } - else if (argument == "--token") - { - std::string token = value("--token"); - - // "" is how a shell or a manifest spells an empty value it could not omit - if (!isPlaceholder(token) && (token != "\"\"")) { - options.m_token = token; - } - } - else if (argument == "--verbose") { - options.m_verbose = true; - } else if ((argument == "--version") || (argument == "-v")) { - std::printf("%s\n", versionText); - return 0; - } else if ((argument == "--help") || (argument == "-h")) { - std::printf("%s\n\n", versionText); - std::printf("Relays the MCP stdio transport to SDRangel's HTTP MCP server.\n\n"); - std::printf(" --host
SDRangel's MCP server address (default 127.0.0.1)\n"); - std::printf(" --port SDRangel's MCP server port (default 8092)\n"); - std::printf(" --path Endpoint path (default /mcp)\n"); - std::printf(" --token Bearer token, if the server has one set\n"); - std::printf(" --verbose Report what it is doing on stderr\n"); - return 0; - } else { - warn("unknown argument " + argument); - return 2; - } - } - - if ((options.m_port <= 0) || (options.m_port > 65535)) - { - warn("port must be between 1 and 65535"); - return 2; - } - -#ifdef _WIN32 - // Without this the C runtime turns \n into \r\n on the way out and eats \r on the way - // in, either of which corrupts the message framing - _setmode(_fileno(stdin), _O_BINARY); - _setmode(_fileno(stdout), _O_BINARY); -#endif - - std::ios::sync_with_stdio(false); - - std::string shippedTools = readFile(toolsFile(argv[0])); - - // Trim, so that a trailing newline cannot land in the middle of a JSON-RPC message - while (!shippedTools.empty() && ((shippedTools.back() == '\n') || (shippedTools.back() == '\r'))) { - shippedTools.pop_back(); - } - - if (options.m_verbose && shippedTools.empty()) { - warn("no tools.json beside the executable: no tools until SDRangel is reachable"); - } - - Bridge bridge(options, shippedTools); - return bridge.run(); -} +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// (at your option) any later version. // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +// Bridges the MCP stdio transport to SDRangel's Streamable HTTP MCP server, for clients +// such as Claude Desktop that can only launch a local server on stdin and stdout. +// JSON-RPC messages are passed through untouched: this program understands the transport, +// not the protocol. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#include +#include +#endif + +#include "httpclient.h" +#include "jsonscan.h" +#include "ssereader.h" + +namespace +{ + +const char *versionText = "sdrangel-mcp-bridge " SDRANGEL_MCP_BRIDGE_VERSION; + +struct Options +{ + std::string m_host = "127.0.0.1"; + int m_port = 8092; + std::string m_path = "/mcp"; + std::string m_token; + bool m_verbose = false; +}; + +void note(const Options& options, const std::string& message) +{ + if (options.m_verbose) { + std::fprintf(stderr, "sdrangel-mcp-bridge: %s\n", message.c_str()); + } +} + +void warn(const std::string& message) +{ + std::fprintf(stderr, "sdrangel-mcp-bridge: %s\n", message.c_str()); +} + +//!< An extension bundle cannot leave an argument out, so a user_config value the user did not +//!< set can reach us as the placeholder text itself. Treated as "not given" rather than taken +//!< literally, which would mean a nonsense port or a token the server never issued. +bool isPlaceholder(const std::string& value) +{ + return (value.size() > 3) && (value.compare(0, 2, "${") == 0) && (value.back() == '}'); +} + +//!< The tool list this build of SDRangel provides, written beside the bridge when the +//!< extension was packaged. A client reads the tool list once when a conversation begins and +//!< does not ask again, so a conversation that starts before SDRangel is up would have no +//!< tools for its whole life if the bridge could only answer with what it had seen. Shipping +//!< the list means it is right the first time the extension is ever used, and it comes from +//!< the server's own registry, so it cannot drift from what the tools really are. +std::string toolsFile(const char *program) +{ + std::string path; + +#ifdef _WIN32 + char module[MAX_PATH]; + + if (GetModuleFileNameA(nullptr, module, MAX_PATH) > 0) { + path = module; + } +#endif + + if (path.empty() && program) { + path = program; + } + + size_t slash = path.find_last_of("/\\"); + return (slash == std::string::npos) ? std::string("tools.json") : path.substr(0, slash + 1) + "tools.json"; +} + +std::string readFile(const std::string& path) +{ + std::ifstream file(path, std::ios::binary); + + if (!file) { + return std::string(); + } + + return std::string((std::istreambuf_iterator(file)), std::istreambuf_iterator()); +} + +//!< JSON string escaping for the messages this program generates itself +std::string escaped(const std::string& text) +{ + std::string result; + + for (char c : text) + { + switch (c) + { + case '"': result += "\\\""; break; + case '\\': result += "\\\\"; break; + case '\n': result += "\\n"; break; + case '\r': result += "\\r"; break; + case '\t': result += "\\t"; break; + default: + if (static_cast(c) < 0x20) { + result += ' '; + } else { + result += c; + } + } + } + + return result; +} + +} // namespace + +class Bridge +{ +public: + Bridge(const Options& options, const std::string& shippedTools) : + m_options(options), + m_shippedTools(shippedTools) + { + } + + int run(); + +private: + void handle(const std::string& message); + void post(const std::string& message); + bool exchange(const std::string& message, HttpClient::Head& head, std::string& body, std::string& error); + void noteSession(const HttpClient::Head& head); + bool reinitialize(const std::string& staleSession); + bool answerLocally(const std::string& id, const std::string& method, const std::string& message); + bool openSession(); + //!< Subscribes again to the resources the client had subscribed to, on a session just built + void replaySubscriptions(); + void settleHandshake(); + void waitForHandshake(); + void streamLoop(); + void startStream(); + void stopStream(); + void endSession(); + + std::vector headers(bool eventStream) const; + void writeMessage(const std::string& message); + void writeError(const std::string& id, int code, const std::string& reason); + + std::string sessionId() const; + + const Options m_options; + mutable std::mutex m_stateMutex; + std::string m_sessionId; + std::string m_protocolVersion; + std::string m_initializeMessage; //!< Kept so the session can be rebuilt without the client + std::set m_subscriptions; //!< Resource URIs the client subscribed to, to carry over to a new session + std::mutex m_reinitMutex; //!< One rebuild at a time, however many calls failed at once + std::atomic m_degraded { false }; //!< Handshake answered without SDRangel: it was not up + std::string m_shippedTools; //!< tools/list result packaged with the bridge, may be empty + + // Every request but the handshake itself waits for the handshake to finish. Whether + // SDRangel was reachable decides how the listings are answered, and a request that + // overtook the handshake would be answered on a state that had not been worked out yet + std::mutex m_handshakeMutex; + std::condition_variable m_handshakeReady; + bool m_handshakeSettled { false }; + + std::mutex m_outputMutex; + + static constexpr int m_retryMinMs = 1000; //!< First wait before reopening the event stream + static constexpr int m_retryMaxMs = 60000; //!< And the longest, once it keeps failing + + // Socket timeouts, so that a SDRangel that has stopped answering cannot hold a worker + // for ever: run() joins every worker once the client closes stdin, and one that never + // returns would keep this process alive after the client has given up on it. + // A call may legitimately run for over a minute: scan watches for up to 30 s after + // measuring its threshold for up to 15 s, and listen may tune the gain first + static constexpr int m_callTimeoutMs = 180000; + // The server writes a keepalive comment every 15 s while the stream is open + static constexpr int m_streamTimeoutMs = 60000; + static constexpr int m_shutdownTimeoutMs = 5000; + + std::atomic m_running { true }; + std::atomic m_streamWanted { false }; + std::thread m_streamThread; + std::mutex m_streamMutex; + HttpClient *m_streamClient = nullptr; //!< Owned by the stream thread, closed from ours to unblock it +}; + +std::string Bridge::sessionId() const +{ + std::lock_guard lock(m_stateMutex); + return m_sessionId; +} + +std::vector Bridge::headers(bool eventStream) const +{ + std::vector result; + result.emplace_back("Host", m_options.m_host + ":" + std::to_string(m_options.m_port)); + result.emplace_back("User-Agent", versionText); + result.emplace_back("Accept", eventStream ? "text/event-stream" : "application/json, text/event-stream"); + + if (!eventStream) { + result.emplace_back("Content-Type", "application/json"); + } + + if (!m_options.m_token.empty()) { + result.emplace_back("Authorization", "Bearer " + m_options.m_token); + } + + std::string session; + std::string version; + { + std::lock_guard lock(m_stateMutex); + session = m_sessionId; + version = m_protocolVersion; + } + + if (!session.empty()) { + result.emplace_back("Mcp-Session-Id", session); + } + + // Sent on every request after initialize, as the Streamable HTTP transport requires + if (!version.empty()) { + result.emplace_back("MCP-Protocol-Version", version); + } + + return result; +} + +void Bridge::writeMessage(const std::string& message) +{ + // One JSON-RPC message per line. Compact JSON has no raw newlines in it, so nothing + // here can break the framing, but a stray carriage return would confuse a strict reader + std::string line(message); + line.erase(std::remove(line.begin(), line.end(), '\n'), line.end()); + line.erase(std::remove(line.begin(), line.end(), '\r'), line.end()); + + std::lock_guard lock(m_outputMutex); + std::fwrite(line.data(), 1, line.size(), stdout); + std::fputc('\n', stdout); + std::fflush(stdout); +} + +void Bridge::writeError(const std::string& id, int code, const std::string& reason) +{ + // An absent or unreadable id becomes null, which is what JSON-RPC asks for when the + // request could not be identified. The client cannot match it to a call, so the text + // has to stand on its own in the log + std::string identifier = id.empty() ? "null" : id; + writeMessage("{\"jsonrpc\":\"2.0\",\"id\":" + identifier + + ",\"error\":{\"code\":" + std::to_string(code) + + ",\"message\":\"" + escaped(reason) + "\"}}"); +} + +void Bridge::handle(const std::string& message) +{ + post(message); +} + +//!< One request and its whole reply. The error is ready to hand to the client as it is. +bool Bridge::exchange(const std::string& message, HttpClient::Head& head, std::string& body, std::string& error) +{ + HttpClient client; + + if (!client.open(m_options.m_host, m_options.m_port, m_callTimeoutMs, error)) + { + error = "Cannot reach SDRangel's MCP server at " + m_options.m_host + ":" + + std::to_string(m_options.m_port) + ": " + error + ". Start SDRangel, add the MCP Server " + "feature and start it, then try again."; + return false; + } + + if (!client.send("POST", m_options.m_path, headers(false), message, error)) + { + error = "Sending to SDRangel failed: " + error; + return false; + } + + if (!client.readHead(head, error)) + { + error = "No reply from SDRangel: " + error; + return false; + } + + if (!client.readBody(head, body, error)) + { + error = "Truncated reply from SDRangel: " + error; + return false; + } + + return true; +} + +void Bridge::noteSession(const HttpClient::Head& head) +{ + std::string session = head.header("Mcp-Session-Id"); + + if (session.empty() || (session == sessionId())) { + return; + } + + { + std::lock_guard lock(m_stateMutex); + m_sessionId = session; + } + + note(m_options, "session " + session); + startStream(); // no effect once it is running: it picks the new session up on its own +} + +//!< Replays the client's initialize to get a working session again. SDRangel forgets every +//!< session it has issued when it restarts, and answers 404 to the ones it used to know. The +//!< client will not initialize a second time on its own, and the bridge outlives many runs of +//!< SDRangel, so without this the connector is dead until the client restarts it. +bool Bridge::reinitialize(const std::string& staleSession) +{ + std::lock_guard lock(m_reinitMutex); + + if (sessionId() != staleSession) { + return true; // another call rebuilt it while this one waited + } + + std::string initialize; + { + std::lock_guard stateLock(m_stateMutex); + initialize = m_initializeMessage; + m_sessionId.clear(); // or the replay carries the dead id and is refused in its turn + } + + if (initialize.empty()) { + return false; + } + + HttpClient::Head head; + std::string body; + std::string error; + + if (!exchange(initialize, head, body, error)) + { + note(m_options, "could not start a new session: " + error); + return false; + } + + if ((head.m_status < 200) || (head.m_status > 299)) + { + note(m_options, "could not start a new session: HTTP " + std::to_string(head.m_status)); + return false; + } + + noteSession(head); + + std::string version = jsonStringMember(jsonMember(body, "result"), "protocolVersion"); + + if (!version.empty()) + { + std::lock_guard stateLock(m_stateMutex); + m_protocolVersion = version; + } + + // This server does nothing with it, but a client that has initialized sends it, and the + // reply is of no interest either way + HttpClient::Head ignoredHead; + std::string ignoredBody; + std::string ignoredError; + exchange("{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}", ignoredHead, ignoredBody, ignoredError); + + if (sessionId().empty()) { + return false; + } + + replaySubscriptions(); + return true; +} + +//!< A subscription lives in the session it was made in, so a session the server has forgotten +//!< took the client's subscriptions with it. The client is not told: the updates it asked for +//!< carry on arriving as before. The replies are answers to requests the client never made, so +//!< they are not passed on +void Bridge::replaySubscriptions() +{ + std::set uris; + { + std::lock_guard lock(m_stateMutex); + uris = m_subscriptions; + } + + int n = 0; + + for (const std::string& uri : uris) + { + HttpClient::Head head; + std::string body; + std::string error; + std::string message = "{\"jsonrpc\":\"2.0\",\"id\":\"bridge-subscribe-" + std::to_string(++n) + + "\",\"method\":\"resources/subscribe\",\"params\":{\"uri\":\"" + escaped(uri) + "\"}}"; + + if (!exchange(message, head, body, error) || (head.m_status < 200) || (head.m_status > 299)) { + note(m_options, "could not subscribe again to " + uri); + } + } + + if (n > 0) { + note(m_options, "subscribed again to " + std::to_string(n) + " resource(s)"); + } +} + +//!< Answers what the bridge can answer on its own. Returns true when it has replied. +//!< +//!< A stdio server's health is judged by the client from this conversation, and the bridge is +//!< healthy whether or not SDRangel happens to be running: it is a long lived process that +//!< outlives many runs of the application behind it. Letting SDRangel's absence turn into +//!< failed pings or a failed handshake makes the client give up on the bridge for good, since +//!< it will not restart it until the application itself is restarted. +bool Bridge::answerLocally(const std::string& id, const std::string& method, const std::string& message) +{ + if (!m_degraded.load()) { + return false; + } + + // SDRangel was not up for the handshake, so there is nothing to list yet. An empty list + // keeps the client working; it is told to ask again as soon as SDRangel appears + static const char *emptyListings[][2] = { + {"tools/list", "tools"}, + {"resources/list", "resources"}, + {"resources/templates/list", "resourceTemplates"}, + {"prompts/list", "prompts"}, + }; + + for (const auto& listing : emptyListings) + { + if (method == listing[0]) + { + // The tools are shipped with the bridge; resources and prompts are whatever the + // running instance happens to hold, so those stay empty until it is reachable + std::string result = (method == "tools/list") && !m_shippedTools.empty() + ? m_shippedTools + : std::string("{\"") + listing[1] + "\":[]}"; + + writeMessage("{\"jsonrpc\":\"2.0\",\"id\":" + (id.empty() ? "null" : id) + + ",\"result\":" + result + "}"); + return true; + } + } + + (void) message; + return false; +} + +//!< Establishes a session upstream by replaying the client's initialize. Tells the client to +//!< ask for the tools again if the handshake had to be answered without SDRangel. +bool Bridge::openSession() +{ + if (!sessionId().empty()) { + return true; + } + + // One session at a time, however many callers found none: the stream thread and every + // worker with a call in hand arrive here together when SDRangel comes back, and each + // would otherwise open a session of its own, with the stream on one and the calls on + // another. Whoever waited finds the session the first one made + std::lock_guard lock(m_reinitMutex); + + if (!sessionId().empty()) { + return true; + } + + std::string initialize; + { + std::lock_guard lock(m_stateMutex); + initialize = m_initializeMessage; + } + + if (initialize.empty()) { + return false; + } + + HttpClient::Head head; + std::string body; + std::string error; + + if (!exchange(initialize, head, body, error) || (head.m_status < 200) || (head.m_status > 299)) { + return false; + } + + noteSession(head); + + if (sessionId().empty()) { + return false; + } + + std::string version = jsonStringMember(jsonMember(body, "result"), "protocolVersion"); + + if (!version.empty()) + { + std::lock_guard lock(m_stateMutex); + m_protocolVersion = version; + } + + replaySubscriptions(); + + if (m_degraded.exchange(false)) + { + note(m_options, "SDRangel is up, telling the client to list again"); + writeMessage("{\"jsonrpc\":\"2.0\",\"method\":\"notifications/tools/list_changed\"}"); + writeMessage("{\"jsonrpc\":\"2.0\",\"method\":\"notifications/resources/list_changed\"}"); + writeMessage("{\"jsonrpc\":\"2.0\",\"method\":\"notifications/prompts/list_changed\"}"); + } + + return true; +} + +void Bridge::settleHandshake() +{ + { + std::lock_guard lock(m_handshakeMutex); + m_handshakeSettled = true; + } + + m_handshakeReady.notify_all(); +} + +void Bridge::waitForHandshake() +{ + std::unique_lock lock(m_handshakeMutex); + + // Bounded, so that a client which never gets as far as initialize cannot wedge the bridge + m_handshakeReady.wait_for(lock, std::chrono::seconds(20), [this]() { return m_handshakeSettled; }); +} + +void Bridge::post(const std::string& message) +{ + std::string id = jsonMember(message, "id"); + std::string method = jsonStringMember(message, "method"); + + // Whether this process is alive has nothing to do with the handshake or with SDRangel + if (method == "ping") + { + writeMessage("{\"jsonrpc\":\"2.0\",\"id\":" + (id.empty() ? "null" : id) + ",\"result\":{}}"); + return; + } + + if (method == "initialize") + { + std::lock_guard lock(m_stateMutex); + m_initializeMessage = message; + } + else + { + waitForHandshake(); + } + + if (answerLocally(id, method, message)) { + return; + } + + // A call arriving while there is no session, because SDRangel was away: try to build one + // rather than failing on a stale or absent session + if ((method != "initialize") && sessionId().empty()) { + openSession(); + } + + // Releases anything waiting on the handshake however this call ends + struct Settle + { + Bridge *bridge; + bool wanted; + ~Settle() { if (wanted) { bridge->settleHandshake(); } } + } settle { this, method == "initialize" }; + + HttpClient::Head head; + std::string body; + std::string error; + + if (!exchange(message, head, body, error)) + { + // A notification has no id and takes no reply, failed or not: an error against a + // null id is a response to a call the client never made + if (id.empty() && (method != "initialize")) + { + note(m_options, "dropped " + method + ": " + error); + return; + } + + // The handshake must not fail, whatever SDRangel is doing: a client that is told the + // server is broken during initialize never comes back to it + if (method == "initialize") + { + note(m_options, "SDRangel is not up: answering the handshake without it"); + m_degraded.store(true); + startStream(); // watches for SDRangel and lists again once it is there + + std::string requested = jsonStringMember(jsonMember(message, "params"), "protocolVersion"); + + if (requested.empty()) { + requested = "2025-06-18"; + } + + writeMessage("{\"jsonrpc\":\"2.0\",\"id\":" + (id.empty() ? "null" : id) + + ",\"result\":{\"protocolVersion\":\"" + escaped(requested) + "\"" + ",\"capabilities\":{\"tools\":{\"listChanged\":true}" + ",\"resources\":{\"listChanged\":true,\"subscribe\":true}" + ",\"prompts\":{\"listChanged\":true}}" + ",\"serverInfo\":{\"name\":\"SDRangel\",\"version\":\"" + escaped(SDRANGEL_MCP_BRIDGE_VERSION) + "\"}" + // Written in the past tense: the client reads this once, when the + // conversation starts, and never again, so anything phrased as the state + // right now is wrong within seconds of SDRangel being started + ",\"instructions\":\"SDRangel is a software defined radio (SDR) application. This " + "server controls it.\\n\\nSDRangel was not running when this conversation started, so " + "these tools are the ones shipped with it rather than a listing from the running " + "instance. They work as soon as SDRangel is running with the MCP Server feature added " + "and started, with nothing to restart. Until then a call reports that it cannot reach " + "it.\"}}"); + return; + } + + writeError(id, -32001, error); + return; + } + + noteSession(head); + + // A session the server has never heard of: it has been restarted, or the session was + // expired. Rebuild it and send the call again, so that neither the client nor the user + // has to know anything happened + std::string session = sessionId(); + + if ((head.m_status == 404) && !session.empty() && (method != "initialize")) + { + note(m_options, "session refused, starting a new one"); + + if (reinitialize(session)) + { + HttpClient::Head retryHead; + std::string retryBody; + std::string retryError; + + if (exchange(message, retryHead, retryBody, retryError)) + { + head = retryHead; + body = retryBody; + noteSession(head); + } + } + } + + if (head.m_status == 202) { + return; // a notification or a response of our own: nothing comes back + } + + if ((head.m_status < 200) || (head.m_status > 299)) + { + // The server's own errors are {"error": "..."} rather than JSON-RPC + std::string detail = jsonStringMember(body, "error"); + + if (detail.empty()) { + detail = head.m_reason.empty() ? body : head.m_reason; + } + + writeError(id, -32001, "SDRangel returned HTTP " + std::to_string(head.m_status) + ": " + detail); + return; + } + + if (body.empty()) + { + writeError(id, -32001, "SDRangel returned an empty reply"); + return; + } + + if (method == "initialize") + { + std::string version = jsonStringMember(jsonMember(body, "result"), "protocolVersion"); + + if (!version.empty()) + { + std::lock_guard lock(m_stateMutex); + m_protocolVersion = version; + } + } + + // Remembered only once the server has accepted it, so that a refused subscription is not + // replayed on the next session + if (((method == "resources/subscribe") || (method == "resources/unsubscribe")) && jsonMember(body, "error").empty()) + { + std::string uri = jsonStringMember(jsonMember(message, "params"), "uri"); + + if (!uri.empty()) + { + std::lock_guard lock(m_stateMutex); + + if (method == "resources/subscribe") { + m_subscriptions.insert(uri); + } else { + m_subscriptions.erase(uri); + } + } + } + + writeMessage(body); +} + +void Bridge::startStream() +{ + bool expected = false; + + if (!m_streamWanted.compare_exchange_strong(expected, true)) { + return; // already running + } + + m_streamThread = std::thread([this]() { streamLoop(); }); +} + +void Bridge::stopStream() +{ + if (!m_streamWanted.load()) { + return; + } + + { + // Shutting the socket down under the thread is what unblocks its read; the thread + // then closes it itself + std::lock_guard lock(m_streamMutex); + + if (m_streamClient) { + m_streamClient->interrupt(); + } + } + + if (m_streamThread.joinable()) { + m_streamThread.join(); + } +} + +void Bridge::streamLoop() +{ + // The server closes the stream when its lifetime backstop expires, so this reopens it + // for as long as the bridge is running. It is also what notices SDRangel coming back + // after the handshake had to be answered without it. + // + // Retries back off. A client that is sitting idle sends nothing, so nothing else here + // ever notices that something is wrong, and a fixed one second retry turns an + // unreachable or unhappy server into hundreds of log lines a minute, for hours. + int retryMs = m_retryMinMs; + + while (m_running.load()) + { + HttpClient client; + std::string error; + bool opened = false; + + if (sessionId().empty() && !openSession()) + { + // Nothing to stream from yet: wait and look again + for (int waited = 0; m_running.load() && (waited < retryMs); waited += 50) { + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + } + + retryMs = std::min(retryMs * 2, m_retryMaxMs); + continue; + } + + if (!client.open(m_options.m_host, m_options.m_port, m_streamTimeoutMs, error)) + { + note(m_options, "event stream cannot connect: " + error); + } + else + { + { + std::lock_guard lock(m_streamMutex); + m_streamClient = &client; + } + + if (client.send("GET", m_options.m_path, headers(true), std::string(), error)) + { + HttpClient::Head head; + + if (!client.readHead(head, error)) + { + note(m_options, "event stream failed: " + error); + } + else if (head.m_status == 404) + { + // The session has been forgotten, which SDRangel restarting does to all of + // them. Only calls coming from the client recovered this before, so an idle + // client left the stream asking after a session that would never come back + note(m_options, "event stream session refused, starting a new one"); + + std::string stale = sessionId(); + + if (!stale.empty()) { + reinitialize(stale); + } + } + else if (head.m_status != 200) + { + note(m_options, "event stream refused with HTTP " + std::to_string(head.m_status)); + } + else + { + note(m_options, "event stream open"); + opened = true; + retryMs = m_retryMinMs; + SseReader reader; + std::string chunk; + + // The server delimits the stream by closing the connection rather than + // chunking it, but a proxy or a later server might chunk, so follow + // whichever framing the response actually used + while (head.m_chunked ? client.readChunk(chunk, error) : client.readSome(chunk, error)) + { + for (const auto& event : reader.feed(chunk)) + { + if (!event.empty()) { + writeMessage(event); + } + } + } + + if (!error.empty()) { + note(m_options, "event stream ended: " + error); + } + } + } + + { + std::lock_guard lock(m_streamMutex); + m_streamClient = nullptr; + } + } + + // Reopening immediately would spin if the server has gone away + for (int waited = 0; m_running.load() && (waited < retryMs); waited += 50) { + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + } + + // A stream that opened and then ended is the normal lifetime backstop, so that starts + // again promptly; anything else waits longer each time + retryMs = opened ? m_retryMinMs : std::min(retryMs * 2, m_retryMaxMs); + } +} + +void Bridge::endSession() +{ + std::string session = sessionId(); + + if (session.empty()) { + return; + } + + HttpClient client; + std::string error; + + if (!client.open(m_options.m_host, m_options.m_port, m_shutdownTimeoutMs, error)) { + return; // going away anyway, and the server expires idle sessions + } + + if (client.send("DELETE", m_options.m_path, headers(false), std::string(), error)) + { + HttpClient::Head head; + std::string body; + + if (client.readHead(head, error)) { + client.readBody(head, body, error); + } + } + + note(m_options, "session ended"); +} + +int Bridge::run() +{ + std::string error; + + if (!HttpClient::startup(error)) + { + warn(error); + return 1; + } + + note(m_options, std::string("relaying to http://") + m_options.m_host + ":" + + std::to_string(m_options.m_port) + m_options.m_path); + + // A worker, and the flag it raises once it has run to completion. A thread that is still + // working is joinable too, so joinable() cannot tell the loop below which of them it is able + // to reap without blocking + struct Worker + { + std::thread m_thread; + std::shared_ptr> m_finished; + }; + + std::vector workers; + std::string line; + + while (std::getline(std::cin, line)) + { + if (!line.empty() && (line.back() == '\r')) { + line.pop_back(); + } + + if (line.empty()) { + continue; + } + + // A thread each, so that a long call such as record_iq does not hold up the + // messages that follow it, cancellation among them + auto finished = std::make_shared>(false); + workers.push_back(Worker{ + std::thread([this, line, finished]() { + handle(line); + finished->store(true); + }), + finished}); + + // Reap only the ones that have finished. Joining a worker that is still inside a + // record_iq, listen, scan or audio call would stop this loop reading input for as long as + // that call runs, which is exactly when a cancellation needs to get through + for (auto worker = workers.begin(); worker != workers.end(); ) + { + if (worker->m_finished->load()) + { + worker->m_thread.join(); + worker = workers.erase(worker); + } + else + { + ++worker; + } + } + } + + note(m_options, "input closed"); + m_running.store(false); + + for (auto& worker : workers) + { + if (worker.m_thread.joinable()) { + worker.m_thread.join(); + } + } + + stopStream(); + endSession(); + HttpClient::cleanup(); + return 0; +} + +int main(int argc, char *argv[]) +{ +#ifndef _WIN32 + // A write to a socket or pipe whose other end has gone must fail, not end the process + signal(SIGPIPE, SIG_IGN); +#endif + + Options options; + + for (int i = 1; i < argc; i++) + { + std::string argument(argv[i]); + auto value = [&](const char *name) -> std::string + { + if (i + 1 >= argc) + { + warn(std::string(name) + " needs a value"); + std::exit(2); + } + + return std::string(argv[++i]); + }; + + if (argument == "--host") + { + std::string host = value("--host"); + + if (!isPlaceholder(host) && !host.empty()) { + options.m_host = host; + } + } + else if (argument == "--port") + { + std::string port = value("--port"); + + if (!isPlaceholder(port) && !port.empty()) { + options.m_port = std::atoi(port.c_str()); + } + } + else if (argument == "--path") + { + std::string path = value("--path"); + + if (!isPlaceholder(path) && !path.empty()) { + options.m_path = path; + } + } + else if (argument == "--token") + { + std::string token = value("--token"); + + // "" is how a shell or a manifest spells an empty value it could not omit + if (!isPlaceholder(token) && (token != "\"\"")) { + options.m_token = token; + } + } + else if (argument == "--verbose") { + options.m_verbose = true; + } else if ((argument == "--version") || (argument == "-v")) { + std::printf("%s\n", versionText); + return 0; + } else if ((argument == "--help") || (argument == "-h")) { + std::printf("%s\n\n", versionText); + std::printf("Relays the MCP stdio transport to SDRangel's HTTP MCP server.\n\n"); + std::printf(" --host
SDRangel's MCP server address (default 127.0.0.1)\n"); + std::printf(" --port SDRangel's MCP server port (default 8092)\n"); + std::printf(" --path Endpoint path (default /mcp)\n"); + std::printf(" --token Bearer token, if the server has one set\n"); + std::printf(" --verbose Report what it is doing on stderr\n"); + return 0; + } else { + warn("unknown argument " + argument); + return 2; + } + } + + if ((options.m_port <= 0) || (options.m_port > 65535)) + { + warn("port must be between 1 and 65535"); + return 2; + } + +#ifdef _WIN32 + // Without this the C runtime turns \n into \r\n on the way out and eats \r on the way + // in, either of which corrupts the message framing + _setmode(_fileno(stdin), _O_BINARY); + _setmode(_fileno(stdout), _O_BINARY); +#endif + + std::ios::sync_with_stdio(false); + + std::string shippedTools = readFile(toolsFile(argv[0])); + + // Trim, so that a trailing newline cannot land in the middle of a JSON-RPC message + while (!shippedTools.empty() && ((shippedTools.back() == '\n') || (shippedTools.back() == '\r'))) { + shippedTools.pop_back(); + } + + if (options.m_verbose && shippedTools.empty()) { + warn("no tools.json beside the executable: no tools until SDRangel is reachable"); + } + + Bridge bridge(options, shippedTools); + return bridge.run(); +} diff --git a/plugins/feature/mcpserver/bridge/readme.md b/plugins/feature/mcpserver/bridge/readme.md index a8ecb025e..bed9d79ae 100644 --- a/plugins/feature/mcpserver/bridge/readme.md +++ b/plugins/feature/mcpserver/bridge/readme.md @@ -1,88 +1,88 @@ -

SDRangel MCP stdio bridge

- -

Introduction

- -Relays the MCP stdio transport to the HTTP transport of the [MCP Server feature](../readme.md), for -clients that can only launch a local server on stdin and stdout. Claude Desktop is the one that -matters: it has no way to connect to an MCP server on `http://127.0.0.1`, since its custom connectors -are fetched from Anthropic's cloud, which cannot reach your machine. - -Without it, those clients need `npx mcp-remote`, which means installing Node.js and hand editing a -JSON configuration file. The bridge is a single executable with no dependencies beyond the C++ -runtime, so it can be shipped inside a Claude Desktop extension bundle (`.mcpb`) and installed with -a double click. - -JSON-RPC messages pass through untouched. This program understands the transport, not the protocol, -so it needs no changes when tools are added or the schema changes. - -

Building

- -It is not built by default, as only a release that ships an extension bundle needs it: - - cmake -S . -B build -DBUILD_MCP_BRIDGE=ON - cmake --build build --target sdrangel-mcp-bridge - -There is no Qt and no SDRangel library in it, and on Windows it links the static runtime, so the -executable stands alone. - -

Packaging

- - cmake -S . -B build -DBUILD_MCP_BUNDLE=ON - cmake --build build --target mcpbundle - -produces `bin/sdrangel--.mcpb`, a Claude Desktop extension holding this -executable, the manifest and an icon. A `.mcpb` is a zip with `manifest.json` at its root, so -CMake builds one on its own; the `mcpb` CLI only adds validation and signing, and requiring -npm to build SDRangel would be a poor trade for that. The bundle is not signed, so Claude -warns that the publisher is unverified when it is installed. - -Both options default to off, so a normal build is untouched. With `BUILD_MCP_BUNDLE=ON` the -bundle is part of `all`, so building the Windows installer picks it up with nothing else to -remember: - - cmake --build build --target package - -

Running

- - sdrangel-mcp-bridge [--host
] [--port ] [--path ] [--token ] [--verbose] - -The defaults match the MCP Server feature's own: `127.0.0.1`, port 8092, path `/mcp` and no token. -`--verbose` reports what it is doing on stderr, which Claude Desktop collects in its logs. - -To use it without an extension bundle, in `%APPDATA%\Claude\claude_desktop_config.json`: - - "mcpServers": { - "sdrangel": { - "command": "C:\\Program Files\\SDRangel\\sdrangel-mcp-bridge.exe", - "args": ["--port", "8092"] - } - } - -

How it works

- -Each line arriving on stdin is one JSON-RPC message, and is POSTed to the server on its own -connection and its own thread, so that a long call such as `record_iq` does not hold up the messages -that follow it. Replies are written back to stdout, one line each. - -The server's session id, returned as a header on the reply to `initialize`, is sent on every request -after it, and the negotiated protocol version with it. Once there is a session, a GET is held open -for the server to client event stream, which is where `notifications/resources/updated` arrives for -anything subscribed to with `resources/subscribe`. The server closes that stream when its lifetime -backstop expires, so it is reopened for as long as the bridge runs. When stdin closes, the session is -ended with a DELETE. SDRangel forgets every session when it restarts: the bridge then replays the -client's `initialize` to get a new one, and subscribes again to every resource the client had -subscribed to, so the client sees neither the restart nor a gap in its updates. - -Anything that goes wrong with the transport becomes a JSON-RPC error against the id of the request -that provoked it, rather than a dropped message. The one users will meet is SDRangel not running, -which says so in as many words. - -

Testing

- -The bridge can be driven by hand, which is the quickest way to check it against a running SDRangel: - - echo {"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test","version":"0"}}} | sdrangel-mcp-bridge --verbose - -Worth covering when changing it: a tool call that takes tens of seconds arriving before a quick one, -a `resources/subscribe` followed by a change in SDRangel, and starting the bridge with nothing -listening on the port. +

SDRangel MCP stdio bridge

+ +

Introduction

+ +Relays the MCP stdio transport to the HTTP transport of the [MCP Server feature](../readme.md), for +clients that can only launch a local server on stdin and stdout. Claude Desktop is the one that +matters: it has no way to connect to an MCP server on `http://127.0.0.1`, since its custom connectors +are fetched from Anthropic's cloud, which cannot reach your machine. + +Without it, those clients need `npx mcp-remote`, which means installing Node.js and hand editing a +JSON configuration file. The bridge is a single executable with no dependencies beyond the C++ +runtime, so it can be shipped inside a Claude Desktop extension bundle (`.mcpb`) and installed with +a double click. + +JSON-RPC messages pass through untouched. This program understands the transport, not the protocol, +so it needs no changes when tools are added or the schema changes. + +

Building

+ +It is not built by default, as only a release that ships an extension bundle needs it: + + cmake -S . -B build -DBUILD_MCP_BRIDGE=ON + cmake --build build --target sdrangel-mcp-bridge + +There is no Qt and no SDRangel library in it, and on Windows it links the static runtime, so the +executable stands alone. + +

Packaging

+ + cmake -S . -B build -DBUILD_MCP_BUNDLE=ON + cmake --build build --target mcpbundle + +produces `bin/sdrangel--.mcpb`, a Claude Desktop extension holding this +executable, the manifest and an icon. A `.mcpb` is a zip with `manifest.json` at its root, so +CMake builds one on its own; the `mcpb` CLI only adds validation and signing, and requiring +npm to build SDRangel would be a poor trade for that. The bundle is not signed, so Claude +warns that the publisher is unverified when it is installed. + +Both options default to off, so a normal build is untouched. With `BUILD_MCP_BUNDLE=ON` the +bundle is part of `all`, so building the Windows installer picks it up with nothing else to +remember: + + cmake --build build --target package + +

Running

+ + sdrangel-mcp-bridge [--host
] [--port ] [--path ] [--token ] [--verbose] + +The defaults match the MCP Server feature's own: `127.0.0.1`, port 8092, path `/mcp` and no token. +`--verbose` reports what it is doing on stderr, which Claude Desktop collects in its logs. + +To use it without an extension bundle, in `%APPDATA%\Claude\claude_desktop_config.json`: + + "mcpServers": { + "sdrangel": { + "command": "C:\\Program Files\\SDRangel\\sdrangel-mcp-bridge.exe", + "args": ["--port", "8092"] + } + } + +

How it works

+ +Each line arriving on stdin is one JSON-RPC message, and is POSTed to the server on its own +connection and its own thread, so that a long call such as `record_iq` does not hold up the messages +that follow it. Replies are written back to stdout, one line each. + +The server's session id, returned as a header on the reply to `initialize`, is sent on every request +after it, and the negotiated protocol version with it. Once there is a session, a GET is held open +for the server to client event stream, which is where `notifications/resources/updated` arrives for +anything subscribed to with `resources/subscribe`. The server closes that stream when its lifetime +backstop expires, so it is reopened for as long as the bridge runs. When stdin closes, the session is +ended with a DELETE. SDRangel forgets every session when it restarts: the bridge then replays the +client's `initialize` to get a new one, and subscribes again to every resource the client had +subscribed to, so the client sees neither the restart nor a gap in its updates. + +Anything that goes wrong with the transport becomes a JSON-RPC error against the id of the request +that provoked it, rather than a dropped message. The one users will meet is SDRangel not running, +which says so in as many words. + +

Testing

+ +The bridge can be driven by hand, which is the quickest way to check it against a running SDRangel: + + echo {"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test","version":"0"}}} | sdrangel-mcp-bridge --verbose + +Worth covering when changing it: a tool call that takes tens of seconds arriving before a quick one, +a `resources/subscribe` followed by a change in SDRangel, and starting the bridge with nothing +listening on the port. diff --git a/plugins/feature/mcpserver/mcpservergui.cpp b/plugins/feature/mcpserver/mcpservergui.cpp index 9f1b08e5e..3a4d437d4 100644 --- a/plugins/feature/mcpserver/mcpservergui.cpp +++ b/plugins/feature/mcpserver/mcpservergui.cpp @@ -1,340 +1,340 @@ -/////////////////////////////////////////////////////////////////////////////////// -// Copyright (C) 2026 Jon Beniston, M7RCE // -// Some code by AI // -// // -// This program is free software; you can redistribute it and/or modify // -// it under the terms of the GNU General Public License as published by // -// the Free Software Foundation as version 3 of the License, or // -// (at your option) any later version. // -// // -// This program is distributed in the hope that it will be useful, // -// but WITHOUT ANY WARRANTY; without even the implied warranty of // -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // -// GNU General Public License V3 for more details. // -// // -// You should have received a copy of the GNU General Public License // -// along with this program. If not, see . // -/////////////////////////////////////////////////////////////////////////////////// - -#include -#include - -#include "feature/featureuiset.h" -#include "gui/basicfeaturesettingsdialog.h" -#include "gui/dialogpositioner.h" - -#include "ui_mcpservergui.h" -#include "mcpserver.h" -#include "mcpservergui.h" -#include "mcpcodexconfig.h" -#include "mcpclaudeextension.h" - -MCPServerGUI* MCPServerGUI::create(PluginAPI* pluginAPI, FeatureUISet *featureUISet, Feature *feature) -{ - MCPServerGUI* gui = new MCPServerGUI(pluginAPI, featureUISet, feature); - return gui; -} - -void MCPServerGUI::destroy() -{ - delete this; -} - -void MCPServerGUI::resetToDefaults() -{ - m_settings.resetToDefaults(); - displaySettings(); - applySettings(true); -} - -QByteArray MCPServerGUI::serialize() const -{ - return m_settings.serialize(); -} - -bool MCPServerGUI::deserialize(const QByteArray& data) -{ - if (m_settings.deserialize(data)) - { - m_feature->setWorkspaceIndex(m_settings.m_workspaceIndex); - displaySettings(); - applySettings(true); - return true; - } - else - { - resetToDefaults(); - return false; - } -} - -bool MCPServerGUI::handleMessage(const Message& message) -{ - if (MCPServer::MsgConfigureMCPServer::match(message)) - { - qDebug("MCPServerGUI::handleMessage: MCPServer::MsgConfigureMCPServer"); - const MCPServer::MsgConfigureMCPServer& cfg = (MCPServer::MsgConfigureMCPServer&) message; - - if (cfg.getForce()) { - m_settings = cfg.getSettings(); - } else { - m_settings.applySettings(cfg.getSettingsKeys(), cfg.getSettings()); - } - - blockApplySettings(true); - displaySettings(); - blockApplySettings(false); - - return true; - } - - return false; -} - -void MCPServerGUI::handleInputMessages() -{ - Message* message; - - while ((message = getInputMessageQueue()->pop())) - { - if (handleMessage(*message)) { - delete message; - } - } -} - -void MCPServerGUI::onWidgetRolled(QWidget* widget, bool rollDown) -{ - (void) widget; - (void) rollDown; - - getRollupContents()->saveState(m_rollupState); -} - -MCPServerGUI::MCPServerGUI(PluginAPI* pluginAPI, FeatureUISet *featureUISet, Feature *feature, QWidget* parent) : - FeatureGUI(parent), - ui(new Ui::MCPServerGUI), - m_pluginAPI(pluginAPI), - m_featureUISet(featureUISet), - m_doApplySettings(true) -{ - m_feature = feature; - setAttribute(Qt::WA_DeleteOnClose, true); - m_helpURL = "plugins/feature/mcpserver/readme.md"; - RollupContents *rollupContents = getRollupContents(); - ui->setupUi(rollupContents); - rollupContents->arrangeRollups(); - connect(rollupContents, SIGNAL(widgetRolled(QWidget*,bool)), this, SLOT(onWidgetRolled(QWidget*,bool))); - - m_mcpServer = reinterpret_cast(feature); - m_mcpServer->setMessageQueueToGUI(&m_inputMessageQueue); - - m_settings.setRollupState(&m_rollupState); - - connect(this, &MCPServerGUI::customContextMenuRequested, this, &MCPServerGUI::onMenuDialogCalled); - connect(getInputMessageQueue(), &MessageQueue::messageEnqueued, this, &MCPServerGUI::handleInputMessages); - connect(m_mcpServer, &Feature::stateChanged, this, &MCPServerGUI::updateFeatureState); - - connect(&m_statisticsTimer, &QTimer::timeout, this, &MCPServerGUI::updateStatistics); - m_statisticsTimer.start(1000); - - displaySettings(); - applySettings(true); - makeUIConnections(); - updateFeatureState(); - updateStatistics(); - m_resizer.enableChildMouseTracking(); -} - -MCPServerGUI::~MCPServerGUI() -{ - delete ui; -} - -void MCPServerGUI::setWorkspaceIndex(int index) -{ - m_settings.m_workspaceIndex = index; - m_settingsKeys.append("workspaceIndex"); - m_feature->setWorkspaceIndex(index); -} - -void MCPServerGUI::blockApplySettings(bool block) -{ - m_doApplySettings = !block; -} - -void MCPServerGUI::displaySettings() -{ - setTitleColor(m_settings.m_rgbColor); - setWindowTitle(m_settings.m_title); - setTitle(m_settings.m_title); - blockApplySettings(true); - ui->address->setText(m_settings.m_address); - ui->port->setValue(m_settings.m_port); - ui->token->setText(m_settings.m_token); - ui->captureDir->setText(m_settings.m_captureDir); - ui->url->setText(m_mcpServer->getServerURL()); - getRollupContents()->restoreState(m_rollupState); - blockApplySettings(false); -} - -void MCPServerGUI::onMenuDialogCalled(const QPoint &p) -{ - if (m_contextMenuType == ContextMenuType::ContextMenuChannelSettings) - { - BasicFeatureSettingsDialog dialog(this); - dialog.setTitle(m_settings.m_title); - dialog.setUseReverseAPI(m_settings.m_useReverseAPI); - dialog.setReverseAPIAddress(m_settings.m_reverseAPIAddress); - dialog.setReverseAPIPort(m_settings.m_reverseAPIPort); - dialog.setReverseAPIFeatureSetIndex(m_settings.m_reverseAPIFeatureSetIndex); - dialog.setReverseAPIFeatureIndex(m_settings.m_reverseAPIFeatureIndex); - dialog.setDefaultTitle(m_displayedName); - - dialog.move(p); - new DialogPositioner(&dialog, false); - dialog.exec(); - - m_settings.m_title = dialog.getTitle(); - m_settings.m_useReverseAPI = dialog.useReverseAPI(); - m_settings.m_reverseAPIAddress = dialog.getReverseAPIAddress(); - m_settings.m_reverseAPIPort = dialog.getReverseAPIPort(); - m_settings.m_reverseAPIFeatureSetIndex = dialog.getReverseAPIFeatureSetIndex(); - m_settings.m_reverseAPIFeatureIndex = dialog.getReverseAPIFeatureIndex(); - - setTitle(m_settings.m_title); - setTitleColor(m_settings.m_rgbColor); - - m_settingsKeys.append("title"); - m_settingsKeys.append("rgbColor"); - m_settingsKeys.append("useReverseAPI"); - m_settingsKeys.append("reverseAPIAddress"); - m_settingsKeys.append("reverseAPIPort"); - m_settingsKeys.append("reverseAPIFeatureSetIndex"); - m_settingsKeys.append("reverseAPIFeatureIndex"); - - applySettings(); - } - - resetContextMenuType(); -} - -void MCPServerGUI::on_startStop_toggled(bool checked) -{ - if (m_doApplySettings) - { - MCPServer::MsgStartStop *message = MCPServer::MsgStartStop::create(checked); - m_mcpServer->getInputMessageQueue()->push(message); - } -} - -void MCPServerGUI::on_address_editingFinished() -{ - m_settings.m_address = ui->address->text().trimmed(); - m_settingsKeys.append("address"); - ui->url->setText(QString("http://%1:%2/mcp").arg(m_settings.m_address.isEmpty() ? "0.0.0.0" : m_settings.m_address).arg(m_settings.m_port)); - applySettings(); -} - -void MCPServerGUI::on_port_valueChanged(int value) -{ - m_settings.m_port = value; - m_settingsKeys.append("port"); - ui->url->setText(QString("http://%1:%2/mcp").arg(m_settings.m_address.isEmpty() ? "0.0.0.0" : m_settings.m_address).arg(m_settings.m_port)); - applySettings(); -} - -void MCPServerGUI::on_token_editingFinished() -{ - m_settings.m_token = ui->token->text().trimmed(); - m_settingsKeys.append("token"); - applySettings(); -} - -void MCPServerGUI::on_captureDir_editingFinished() -{ - m_settings.m_captureDir = ui->captureDir->text().trimmed(); - m_settingsKeys.append("captureDir"); - applySettings(); -} - -void MCPServerGUI::on_captureDirBrowse_clicked() -{ - QString dir = QFileDialog::getExistingDirectory(this, tr("Capture directory"), m_settings.m_captureDir); - - if (!dir.isEmpty()) - { - m_settings.m_captureDir = dir; - ui->captureDir->setText(dir); - m_settingsKeys.append("captureDir"); - applySettings(); - } -} - -void MCPServerGUI::on_addToCodex_clicked() -{ - // The settings hold what the server is configured with, which is what a client has to use - const QString url = MCPCodexConfig::serverUrl(m_settings.m_address, m_settings.m_port); - QString message; - MCPCodexConfig::Result result = MCPCodexConfig::addServer("sdrangel", url, m_settings.m_token, message); - - if (result == MCPCodexConfig::Failed) - { - QMessageBox::critical(this, tr("Add to Codex"), message); - } - else - { - // Codex reads its configuration once, at startup - QMessageBox::information(this, tr("Add to Codex"), - tr("%1\n\nRestart Codex for it to see the server.").arg(message)); - } -} - -void MCPServerGUI::on_addToClaude_clicked() -{ - QString message; - MCPClaudeExtension::Result result = MCPClaudeExtension::install(message); - - if (result == MCPClaudeExtension::Launched) { - QMessageBox::information(this, tr("Add to Claude Desktop"), message); - } else { - QMessageBox::warning(this, tr("Add to Claude Desktop"), message); - } -} - -void MCPServerGUI::updateFeatureState() -{ - updateStartStopButton(ui->startStop); -} - -void MCPServerGUI::updateStatistics() -{ - int streams = m_mcpServer->getStreamCount(); - ui->requests->setText(streams > 0 - ? QString("Requests: %1 Streams: %2").arg(m_mcpServer->getRequestCount()).arg(streams) - : QString("Requests: %1").arg(m_mcpServer->getRequestCount())); - ui->lastRequest->setText(m_mcpServer->getLastRequest()); -} - -void MCPServerGUI::applySettings(bool force) -{ - if (m_doApplySettings) - { - MCPServer::MsgConfigureMCPServer* message = MCPServer::MsgConfigureMCPServer::create(m_settings, m_settingsKeys, force); - m_mcpServer->getInputMessageQueue()->push(message); - } - - m_settingsKeys.clear(); -} - -void MCPServerGUI::makeUIConnections() -{ - QObject::connect(ui->startStop, &ButtonSwitch::toggled, this, &MCPServerGUI::on_startStop_toggled); - QObject::connect(ui->address, &QLineEdit::editingFinished, this, &MCPServerGUI::on_address_editingFinished); - QObject::connect(ui->port, qOverload(&QSpinBox::valueChanged), this, &MCPServerGUI::on_port_valueChanged); - QObject::connect(ui->token, &QLineEdit::editingFinished, this, &MCPServerGUI::on_token_editingFinished); - QObject::connect(ui->captureDir, &QLineEdit::editingFinished, this, &MCPServerGUI::on_captureDir_editingFinished); - QObject::connect(ui->captureDirBrowse, &QToolButton::clicked, this, &MCPServerGUI::on_captureDirBrowse_clicked); - QObject::connect(ui->addToCodex, &QPushButton::clicked, this, &MCPServerGUI::on_addToCodex_clicked); - QObject::connect(ui->addToClaude, &QPushButton::clicked, this, &MCPServerGUI::on_addToClaude_clicked); -} +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// (at your option) any later version. // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include +#include + +#include "feature/featureuiset.h" +#include "gui/basicfeaturesettingsdialog.h" +#include "gui/dialogpositioner.h" + +#include "ui_mcpservergui.h" +#include "mcpserver.h" +#include "mcpservergui.h" +#include "mcpcodexconfig.h" +#include "mcpclaudeextension.h" + +MCPServerGUI* MCPServerGUI::create(PluginAPI* pluginAPI, FeatureUISet *featureUISet, Feature *feature) +{ + MCPServerGUI* gui = new MCPServerGUI(pluginAPI, featureUISet, feature); + return gui; +} + +void MCPServerGUI::destroy() +{ + delete this; +} + +void MCPServerGUI::resetToDefaults() +{ + m_settings.resetToDefaults(); + displaySettings(); + applySettings(true); +} + +QByteArray MCPServerGUI::serialize() const +{ + return m_settings.serialize(); +} + +bool MCPServerGUI::deserialize(const QByteArray& data) +{ + if (m_settings.deserialize(data)) + { + m_feature->setWorkspaceIndex(m_settings.m_workspaceIndex); + displaySettings(); + applySettings(true); + return true; + } + else + { + resetToDefaults(); + return false; + } +} + +bool MCPServerGUI::handleMessage(const Message& message) +{ + if (MCPServer::MsgConfigureMCPServer::match(message)) + { + qDebug("MCPServerGUI::handleMessage: MCPServer::MsgConfigureMCPServer"); + const MCPServer::MsgConfigureMCPServer& cfg = (MCPServer::MsgConfigureMCPServer&) message; + + if (cfg.getForce()) { + m_settings = cfg.getSettings(); + } else { + m_settings.applySettings(cfg.getSettingsKeys(), cfg.getSettings()); + } + + blockApplySettings(true); + displaySettings(); + blockApplySettings(false); + + return true; + } + + return false; +} + +void MCPServerGUI::handleInputMessages() +{ + Message* message; + + while ((message = getInputMessageQueue()->pop())) + { + if (handleMessage(*message)) { + delete message; + } + } +} + +void MCPServerGUI::onWidgetRolled(QWidget* widget, bool rollDown) +{ + (void) widget; + (void) rollDown; + + getRollupContents()->saveState(m_rollupState); +} + +MCPServerGUI::MCPServerGUI(PluginAPI* pluginAPI, FeatureUISet *featureUISet, Feature *feature, QWidget* parent) : + FeatureGUI(parent), + ui(new Ui::MCPServerGUI), + m_pluginAPI(pluginAPI), + m_featureUISet(featureUISet), + m_doApplySettings(true) +{ + m_feature = feature; + setAttribute(Qt::WA_DeleteOnClose, true); + m_helpURL = "plugins/feature/mcpserver/readme.md"; + RollupContents *rollupContents = getRollupContents(); + ui->setupUi(rollupContents); + rollupContents->arrangeRollups(); + connect(rollupContents, SIGNAL(widgetRolled(QWidget*,bool)), this, SLOT(onWidgetRolled(QWidget*,bool))); + + m_mcpServer = reinterpret_cast(feature); + m_mcpServer->setMessageQueueToGUI(&m_inputMessageQueue); + + m_settings.setRollupState(&m_rollupState); + + connect(this, &MCPServerGUI::customContextMenuRequested, this, &MCPServerGUI::onMenuDialogCalled); + connect(getInputMessageQueue(), &MessageQueue::messageEnqueued, this, &MCPServerGUI::handleInputMessages); + connect(m_mcpServer, &Feature::stateChanged, this, &MCPServerGUI::updateFeatureState); + + connect(&m_statisticsTimer, &QTimer::timeout, this, &MCPServerGUI::updateStatistics); + m_statisticsTimer.start(1000); + + displaySettings(); + applySettings(true); + makeUIConnections(); + updateFeatureState(); + updateStatistics(); + m_resizer.enableChildMouseTracking(); +} + +MCPServerGUI::~MCPServerGUI() +{ + delete ui; +} + +void MCPServerGUI::setWorkspaceIndex(int index) +{ + m_settings.m_workspaceIndex = index; + m_settingsKeys.append("workspaceIndex"); + m_feature->setWorkspaceIndex(index); +} + +void MCPServerGUI::blockApplySettings(bool block) +{ + m_doApplySettings = !block; +} + +void MCPServerGUI::displaySettings() +{ + setTitleColor(m_settings.m_rgbColor); + setWindowTitle(m_settings.m_title); + setTitle(m_settings.m_title); + blockApplySettings(true); + ui->address->setText(m_settings.m_address); + ui->port->setValue(m_settings.m_port); + ui->token->setText(m_settings.m_token); + ui->captureDir->setText(m_settings.m_captureDir); + ui->url->setText(m_mcpServer->getServerURL()); + getRollupContents()->restoreState(m_rollupState); + blockApplySettings(false); +} + +void MCPServerGUI::onMenuDialogCalled(const QPoint &p) +{ + if (m_contextMenuType == ContextMenuType::ContextMenuChannelSettings) + { + BasicFeatureSettingsDialog dialog(this); + dialog.setTitle(m_settings.m_title); + dialog.setUseReverseAPI(m_settings.m_useReverseAPI); + dialog.setReverseAPIAddress(m_settings.m_reverseAPIAddress); + dialog.setReverseAPIPort(m_settings.m_reverseAPIPort); + dialog.setReverseAPIFeatureSetIndex(m_settings.m_reverseAPIFeatureSetIndex); + dialog.setReverseAPIFeatureIndex(m_settings.m_reverseAPIFeatureIndex); + dialog.setDefaultTitle(m_displayedName); + + dialog.move(p); + new DialogPositioner(&dialog, false); + dialog.exec(); + + m_settings.m_title = dialog.getTitle(); + m_settings.m_useReverseAPI = dialog.useReverseAPI(); + m_settings.m_reverseAPIAddress = dialog.getReverseAPIAddress(); + m_settings.m_reverseAPIPort = dialog.getReverseAPIPort(); + m_settings.m_reverseAPIFeatureSetIndex = dialog.getReverseAPIFeatureSetIndex(); + m_settings.m_reverseAPIFeatureIndex = dialog.getReverseAPIFeatureIndex(); + + setTitle(m_settings.m_title); + setTitleColor(m_settings.m_rgbColor); + + m_settingsKeys.append("title"); + m_settingsKeys.append("rgbColor"); + m_settingsKeys.append("useReverseAPI"); + m_settingsKeys.append("reverseAPIAddress"); + m_settingsKeys.append("reverseAPIPort"); + m_settingsKeys.append("reverseAPIFeatureSetIndex"); + m_settingsKeys.append("reverseAPIFeatureIndex"); + + applySettings(); + } + + resetContextMenuType(); +} + +void MCPServerGUI::on_startStop_toggled(bool checked) +{ + if (m_doApplySettings) + { + MCPServer::MsgStartStop *message = MCPServer::MsgStartStop::create(checked); + m_mcpServer->getInputMessageQueue()->push(message); + } +} + +void MCPServerGUI::on_address_editingFinished() +{ + m_settings.m_address = ui->address->text().trimmed(); + m_settingsKeys.append("address"); + ui->url->setText(QString("http://%1:%2/mcp").arg(m_settings.m_address.isEmpty() ? "0.0.0.0" : m_settings.m_address).arg(m_settings.m_port)); + applySettings(); +} + +void MCPServerGUI::on_port_valueChanged(int value) +{ + m_settings.m_port = value; + m_settingsKeys.append("port"); + ui->url->setText(QString("http://%1:%2/mcp").arg(m_settings.m_address.isEmpty() ? "0.0.0.0" : m_settings.m_address).arg(m_settings.m_port)); + applySettings(); +} + +void MCPServerGUI::on_token_editingFinished() +{ + m_settings.m_token = ui->token->text().trimmed(); + m_settingsKeys.append("token"); + applySettings(); +} + +void MCPServerGUI::on_captureDir_editingFinished() +{ + m_settings.m_captureDir = ui->captureDir->text().trimmed(); + m_settingsKeys.append("captureDir"); + applySettings(); +} + +void MCPServerGUI::on_captureDirBrowse_clicked() +{ + QString dir = QFileDialog::getExistingDirectory(this, tr("Capture directory"), m_settings.m_captureDir); + + if (!dir.isEmpty()) + { + m_settings.m_captureDir = dir; + ui->captureDir->setText(dir); + m_settingsKeys.append("captureDir"); + applySettings(); + } +} + +void MCPServerGUI::on_addToCodex_clicked() +{ + // The settings hold what the server is configured with, which is what a client has to use + const QString url = MCPCodexConfig::serverUrl(m_settings.m_address, m_settings.m_port); + QString message; + MCPCodexConfig::Result result = MCPCodexConfig::addServer("sdrangel", url, m_settings.m_token, message); + + if (result == MCPCodexConfig::Failed) + { + QMessageBox::critical(this, tr("Add to Codex"), message); + } + else + { + // Codex reads its configuration once, at startup + QMessageBox::information(this, tr("Add to Codex"), + tr("%1\n\nRestart Codex for it to see the server.").arg(message)); + } +} + +void MCPServerGUI::on_addToClaude_clicked() +{ + QString message; + MCPClaudeExtension::Result result = MCPClaudeExtension::install(message); + + if (result == MCPClaudeExtension::Launched) { + QMessageBox::information(this, tr("Add to Claude Desktop"), message); + } else { + QMessageBox::warning(this, tr("Add to Claude Desktop"), message); + } +} + +void MCPServerGUI::updateFeatureState() +{ + updateStartStopButton(ui->startStop); +} + +void MCPServerGUI::updateStatistics() +{ + int streams = m_mcpServer->getStreamCount(); + ui->requests->setText(streams > 0 + ? QString("Requests: %1 Streams: %2").arg(m_mcpServer->getRequestCount()).arg(streams) + : QString("Requests: %1").arg(m_mcpServer->getRequestCount())); + ui->lastRequest->setText(m_mcpServer->getLastRequest()); +} + +void MCPServerGUI::applySettings(bool force) +{ + if (m_doApplySettings) + { + MCPServer::MsgConfigureMCPServer* message = MCPServer::MsgConfigureMCPServer::create(m_settings, m_settingsKeys, force); + m_mcpServer->getInputMessageQueue()->push(message); + } + + m_settingsKeys.clear(); +} + +void MCPServerGUI::makeUIConnections() +{ + QObject::connect(ui->startStop, &ButtonSwitch::toggled, this, &MCPServerGUI::on_startStop_toggled); + QObject::connect(ui->address, &QLineEdit::editingFinished, this, &MCPServerGUI::on_address_editingFinished); + QObject::connect(ui->port, qOverload(&QSpinBox::valueChanged), this, &MCPServerGUI::on_port_valueChanged); + QObject::connect(ui->token, &QLineEdit::editingFinished, this, &MCPServerGUI::on_token_editingFinished); + QObject::connect(ui->captureDir, &QLineEdit::editingFinished, this, &MCPServerGUI::on_captureDir_editingFinished); + QObject::connect(ui->captureDirBrowse, &QToolButton::clicked, this, &MCPServerGUI::on_captureDirBrowse_clicked); + QObject::connect(ui->addToCodex, &QPushButton::clicked, this, &MCPServerGUI::on_addToCodex_clicked); + QObject::connect(ui->addToClaude, &QPushButton::clicked, this, &MCPServerGUI::on_addToClaude_clicked); +} diff --git a/plugins/feature/mcpserver/mcptools.cpp b/plugins/feature/mcpserver/mcptools.cpp index 8d30765f0..1c838bc2f 100644 --- a/plugins/feature/mcpserver/mcptools.cpp +++ b/plugins/feature/mcpserver/mcptools.cpp @@ -1,6184 +1,6184 @@ -/////////////////////////////////////////////////////////////////////////////////// -// Copyright (C) 2026 Jon Beniston, M7RCE // -// Some code by AI // -// // -// This program is free software; you can redistribute it and/or modify // -// it under the terms of the GNU General Public License as published by // -// the Free Software Foundation as version 3 of the License, or // -// (at your option) any later version. // -// // -// This program is distributed in the hope that it will be useful, // -// but WITHOUT ANY WARRANTY; without even the implied warranty of // -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // -// GNU General Public License V3 for more details. // -// // -// You should have received a copy of the GNU General Public License // -// along with this program. If not, see . // -/////////////////////////////////////////////////////////////////////////////////// - -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include "SWGErrorResponse.h" -#include "SWGSuccessResponse.h" -#include "SWGInstanceSummaryResponse.h" -#include "SWGInstanceDevicesResponse.h" -#include "SWGInstanceChannelsResponse.h" -#include "SWGInstanceFeaturesResponse.h" -#include "SWGDeviceSetList.h" -#include "SWGDeviceSet.h" -#include "SWGDeviceListItem.h" -#include "SWGDeviceSettings.h" -#include "SWGDeviceState.h" -#include "SWGDeviceReport.h" -#include "SWGDeviceActions.h" -#include "SWGChannelSettings.h" -#include "SWGChannelReport.h" -#include "SWGChannelActions.h" -#include "SWGChannelsDetail.h" -#include "SWGFeatureSet.h" -#include "SWGFeatureSettings.h" -#include "SWGFeatureReport.h" -#include "SWGFeatureActions.h" -#include "SWGPresets.h" -#include "SWGPresetGroup.h" -#include "SWGPresetItem.h" -#include "SWGPresetTransfer.h" -#include "SWGPresetIdentifier.h" -#include "SWGConfigurations.h" -#include "SWGConfigurationIdentifier.h" -#include "SWGWorkspaceInfo.h" -#include "SWGWorkspaceActions.h" -#include "SWGWindowList.h" -#include "SWGGLSpectrum.h" -#include "SWGGLSpectrumReport.h" -#include "SWGSpectrumActions.h" -#include "SWGGLSpectrumData.h" -#include "SWGGLSpectrumHistory.h" -#include "SWGSpectrumHistorySignal.h" -#include "SWGAudioDevices.h" -#include "SWGLocationInformation.h" - -#include "maincore.h" -#include "device/deviceset.h" -#include "channel/channelapi.h" -#include "device/deviceapi.h" -#include "feature/feature.h" -#include "feature/featureset.h" -#include "webapi/webapiadapterinterface.h" -#include "webapi/webapiutils.h" - -#include "mcpstreams.h" -#include "mcptools.h" - -// --------------------------------------------------------------------------- -// Helpers -// --------------------------------------------------------------------------- - -namespace { - -QJsonObject toJson(SWGSDRangel::SWGObject& object) -{ - QJsonObject *obj = object.asJsonObject(); - QJsonObject result = *obj; - delete obj; - return result; -} - -QString compact(const QJsonValue& value) -{ - if (value.isObject()) { - return QString(QJsonDocument(value.toObject()).toJson(QJsonDocument::Compact)); - } else if (value.isArray()) { - return QString(QJsonDocument(value.toArray()).toJson(QJsonDocument::Compact)); - } else if (value.isString()) { - return value.toString(); - } else { - return QString(QJsonDocument(QJsonArray({value})).toJson(QJsonDocument::Compact)); - } -} - -// Throws if the Web API call failed -void check(int httpRC, SWGSDRangel::SWGErrorResponse& error, const QString& what) -{ - if (httpRC / 100 != 2) - { - QString message = error.getMessage() ? *error.getMessage() : QString(); - throw MCPToolError(QString("%1 failed (HTTP %2)%3").arg(what).arg(httpRC).arg(message.isEmpty() ? "" : ": " + message)); - } -} - -// Argument access. Accepts numbers given as strings, as models sometimes do. -bool hasArg(const QJsonObject& args, const QString& key) -{ - return args.contains(key) && !args[key].isNull() && !args[key].isUndefined(); -} - -// Models write booleans as JSON booleans mostly, but also as "true"/"false" strings and as 0/1, -// and QJsonValue::toBool answers its default for anything but a JSON boolean, which turned -// replace "false" into true. Absent, null and anything unreadable give the default -bool argBool(const QJsonObject& args, const QString& key, bool defaultValue) -{ - if (!hasArg(args, key)) { - return defaultValue; - } - - const QJsonValue value = args.value(key); - - if (value.isBool()) { - return value.toBool(); - } - - if (value.isDouble()) { - return value.toDouble() != 0.0; - } - - if (value.isString()) - { - const QString text = value.toString().trimmed().toLower(); - - if ((text == "true") || (text == "1") || (text == "yes") || (text == "on")) { - return true; - } - - if ((text == "false") || (text == "0") || (text == "no") || (text == "off") || text.isEmpty()) { - return false; - } - } - - return defaultValue; -} - -int argInt(const QJsonObject& args, const QString& key, bool required = true, int defaultValue = 0) -{ - if (!hasArg(args, key)) - { - if (required) { - throw MCPToolError(QString("Missing required argument: %1").arg(key)); - } - - return defaultValue; - } - - QJsonValue value = args[key]; - - if (value.isDouble()) { - return (int) value.toDouble(); - } - - bool ok; - int result = value.toString().trimmed().toInt(&ok); - - if (!ok) - { - double d = value.toString().trimmed().toDouble(&ok); - - if (ok) { - return (int) d; - } - - throw MCPToolError(QString("Argument %1 must be an integer").arg(key)); - } - - return result; -} - -qint64 argInt64(const QJsonObject& args, const QString& key, bool required = true, qint64 defaultValue = 0) -{ - if (!hasArg(args, key)) - { - if (required) { - throw MCPToolError(QString("Missing required argument: %1").arg(key)); - } - - return defaultValue; - } - - QJsonValue value = args[key]; - - if (value.isDouble()) { - return (qint64) value.toDouble(); - } - - bool ok; - double d = value.toString().trimmed().toDouble(&ok); - - if (!ok) { - throw MCPToolError(QString("Argument %1 must be a number").arg(key)); - } - - return (qint64) d; -} - -double argDouble(const QJsonObject& args, const QString& key, bool required = true, double defaultValue = 0.0) -{ - if (!hasArg(args, key)) - { - if (required) { - throw MCPToolError(QString("Missing required argument: %1").arg(key)); - } - - return defaultValue; - } - - QJsonValue value = args[key]; - - if (value.isDouble()) { - return value.toDouble(); - } - - bool ok; - double d = value.toString().trimmed().toDouble(&ok); - - if (!ok) { - throw MCPToolError(QString("Argument %1 must be a number").arg(key)); - } - - return d; -} - -QString argString(const QJsonObject& args, const QString& key, bool required = true, const QString& defaultValue = QString()) -{ - if (!hasArg(args, key)) - { - if (required) { - throw MCPToolError(QString("Missing required argument: %1").arg(key)); - } - - return defaultValue; - } - - QJsonValue value = args[key]; - - if (value.isString()) { - return value.toString(); - } else if (value.isDouble()) { - return QString::number(value.toDouble(), 'g', 15); - } else { - return compact(value); - } -} - -QJsonObject argObject(const QJsonObject& args, const QString& key, bool required = true) -{ - if (!hasArg(args, key)) - { - if (required) { - throw MCPToolError(QString("Missing required argument: %1").arg(key)); - } - - return QJsonObject(); - } - - QJsonValue value = args[key]; - - if (value.isObject()) { - return value.toObject(); - } - - // Tolerate an object passed as a JSON string - if (value.isString()) - { - QJsonDocument doc = QJsonDocument::fromJson(value.toString().toUtf8()); - - if (doc.isObject()) { - return doc.object(); - } - } - - throw MCPToolError(QString("Argument %1 must be a JSON object").arg(key)); -} - -// direction: "rx" / "tx" / "mimo" or 0 / 1 / 2 -int argDirection(const QJsonObject& args, const QString& key = "direction", bool required = false, int defaultValue = 0) -{ - if (!hasArg(args, key)) - { - if (required) { - throw MCPToolError(QString("Missing required argument: %1").arg(key)); - } - - return defaultValue; - } - - QJsonValue value = args[key]; - - if (value.isDouble()) { - return (int) value.toDouble(); - } - - QString s = value.toString().trimmed().toLower(); - - if ((s == "rx") || (s == "0") || (s == "receive") || (s == "source")) { - return 0; - } else if ((s == "tx") || (s == "1") || (s == "transmit") || (s == "sink")) { - return 1; - } else if ((s == "mimo") || (s == "2")) { - return 2; - } - - throw MCPToolError(QString("Argument %1 must be \"rx\", \"tx\" or \"mimo\"").arg(key)); -} - -QString directionName(int direction) -{ - switch (direction) - { - case 0: return "rx"; - case 1: return "tx"; - case 2: return "mimo"; - default: return QString::number(direction); - } -} - -// JSON schema builders -QJsonObject prop(const QString& type, const QString& description) -{ - QJsonObject p; - p["type"] = type; - p["description"] = description; - return p; -} - -QJsonObject intProp(const QString& description) { return prop("integer", description); } -QJsonObject numProp(const QString& description) { return prop("number", description); } -QJsonObject strProp(const QString& description) { return prop("string", description); } -QJsonObject objProp(const QString& description) { return prop("object", description); } - -QJsonObject enumProp(const QString& description, const QStringList& values) -{ - QJsonObject p = strProp(description); - p["enum"] = QJsonArray::fromStringList(values); - return p; -} - -QJsonObject directionProp(const QString& description) -{ - return enumProp(description, {"rx", "tx", "mimo"}); -} - -// Adds the bounds a handler enforces at runtime to the schema, so a client can see them -QJsonObject bounded(QJsonObject property, double minimum, double maximum) -{ - property["minimum"] = minimum; - property["maximum"] = maximum; - return property; -} - -QJsonObject schema(const QJsonObject& properties, const QStringList& required = QStringList()) -{ - QJsonObject s; - s["type"] = "object"; - s["properties"] = properties; - s["required"] = QJsonArray::fromStringList(required); - s["additionalProperties"] = false; - return s; -} - -const QJsonObject deviceSetIndexProp = intProp("Index of the device set (0 for R0, the first device set)"); -const QJsonObject channelIndexProp = intProp("Index of the channel within the device set"); -const QJsonObject featureIndexProp = intProp("Index of the feature within the feature set"); - -// Settings keys in the form used by the Web API PATCH: nested keys are dotted, array elements indexed -void extractKeys(const QJsonObject& json, QStringList& keys, const QString& prefix = QString()) -{ - for (const QString& key : json.keys()) - { - QString full = prefix.isEmpty() ? key : prefix + "." + key; - keys.append(full); - - if (json[key].isObject()) - { - extractKeys(json[key].toObject(), keys, full); - } - else if (json[key].isArray()) - { - QJsonArray array = json[key].toArray(); - - for (int i = 0; i < array.count(); i++) - { - QString element = QString("%1[%2]").arg(full).arg(i); - keys.append(element); - - if (array.at(i).isObject()) { - extractKeys(array.at(i).toObject(), keys, element); - } - } - } - } -} - -// Applies patch on top of target. Objects are merged recursively, everything else replaced. -// Keys absent from target are reported (they may still be valid: empty strings are not serialized). -void mergeInto(QJsonObject& target, const QJsonObject& patch, QStringList& unknownKeys, const QString& prefix = QString()) -{ - for (const QString& key : patch.keys()) - { - QString full = prefix.isEmpty() ? key : prefix + "." + key; - - if (!target.contains(key)) { - unknownKeys.append(full); - } - - if (patch[key].isObject() && target[key].isObject()) - { - QJsonObject sub = target[key].toObject(); - mergeInto(sub, patch[key].toObject(), unknownKeys, full); - target[key] = sub; - } - else - { - target[key] = patch[key]; - } - } -} - -int leadingSpaces(const QString& line) -{ - int count = 0; - - while ((count < line.length()) && (line.at(count) == ' ')) { - count++; - } - - return count; -} - -// Reads the property names and types out of one swagger definition. Only the properties of the -// definition itself are taken: the attributes of a property sit two spaces further in, so an -// items: block of an array cannot be mistaken for the array's own type. -SettingsSchema parseSettingsSchema(const QString& yaml) -{ - SettingsSchema schema; - int propertiesIndent = -1; - int nameIndent = -1; - QString property; - - for (const QString& line : yaml.split('\n')) - { - QString text = line.trimmed(); - - if (text.isEmpty() || text.startsWith('#')) { - continue; - } - - int indent = leadingSpaces(line); - - if (propertiesIndent < 0) - { - if (text == "properties:") { - propertiesIndent = indent; - } - - continue; - } - - if (indent <= propertiesIndent) { - break; // out of the properties block and into the next section of the definition - } - - if (nameIndent < 0) { - nameIndent = indent; - } - - if (indent == nameIndent) - { - if (text.endsWith(':')) - { - property = text.left(text.length() - 1); - schema.m_types.insert(property, QString()); - } - else - { - property.clear(); - } - } - else if ((indent == nameIndent + 2) && !property.isEmpty()) - { - if (text.startsWith("type:")) { - schema.m_types[property] = text.mid(5).trimmed(); - } else if (text.startsWith("$ref:") && schema.m_types.value(property).isEmpty()) { - schema.m_types[property] = "object"; - } - } - } - - schema.m_known = !schema.m_types.isEmpty(); - return schema; -} - -// Checks a patch against the schema and returns it with the one conversion worth making. Values -// are checked here rather than left to the SWG object, whose setValue() turns a string into zero -// without complaint: "rfBandwidth": "wide" would otherwise stop the channel demodulating and be -// reported as a successful change. -QJsonObject checkAgainstSchema(const QJsonObject& patch, const SettingsSchema& schema, - QStringList& unknownKeys, QStringList& typeErrors) -{ - QJsonObject checked; - - for (const QString& key : patch.keys()) - { - QJsonValue value = patch[key]; - - if (!schema.m_types.contains(key)) - { - unknownKeys.append(key); - checked[key] = value; - continue; - } - - QString type = schema.m_types[key]; - bool numeric = (type == "integer") || (type == "number"); - - if (numeric && value.isBool()) - { - // Unambiguous and lossless, and the natural way to write a 0/1 flag - checked[key] = value.toBool() ? 1 : 0; - continue; - } - - bool ok = true; - - if (numeric) { - ok = value.isDouble(); - } else if (type == "string") { - ok = value.isString(); - } else if (type == "array") { - ok = value.isArray(); - } else if (type == "object") { - ok = value.isObject(); - } - - if (!ok) - { - QString got = value.isString() ? "string" : - value.isDouble() ? "number" : - value.isBool() ? "boolean" : - value.isArray() ? "array" : - value.isObject() ? "object" : "null"; - typeErrors.append(QString("%1 expects %2 but was given a %3 (%4)") - .arg(key).arg(type).arg(got).arg(compact(QJsonObject{{key, value}}))); - } - - checked[key] = value; - } - - return checked; -} - -// The key holding the type specific settings, e.g. "rtlSdrSettings" or "ADSBDemodSettings" -QString findSettingsKey(const QJsonObject& json) -{ - for (const QString& key : json.keys()) - { - if (key.endsWith("Settings") && json[key].isObject()) { - return key; - } - } - - return QString(); -} - -// Generic settings patch: read current settings, merge the partial object given by the model -// into the type specific sub-object, then PATCH with the list of changed keys. -template -QJsonObject applySettingsPatch( - const std::function& get, - const std::function& put, - const QJsonObject& partial, - const QString& what, - const std::function& schemaFor) -{ - SWGSDRangel::SWGErrorResponse error; - error.init(); - SWG current; - check(get(current, error), error, "Get " + what); - QJsonObject json = toJson(current); - QString settingsKey = findSettingsKey(json); - - if (settingsKey.isEmpty()) { - throw MCPToolError(QString("Cannot find settings object in current %1: %2").arg(what).arg(compact(json))); - } - - QJsonObject subPartial; - - if (partial.contains(settingsKey)) - { - subPartial = partial[settingsKey].toObject(); - } - else - { - for (const QString& key : partial.keys()) - { - if (key.endsWith("Settings") && partial[key].isObject()) { - throw MCPToolError(QString("Settings object key %1 does not match the current type. Expected %2 or the bare settings object").arg(key).arg(settingsKey)); - } - } - - subPartial = partial; - } - - if (subPartial.isEmpty()) { - throw MCPToolError("No settings given"); - } - - QStringList unknownKeys; - SettingsSchema schema = schemaFor(settingsKey); - - if (schema.m_known) - { - QStringList typeErrors; - subPartial = checkAgainstSchema(subPartial, schema, unknownKeys, typeErrors); - - if (!typeErrors.isEmpty()) - { - throw MCPToolError(QString("Wrong value type for %1: %2. Numbers must be given as JSON " - "numbers, not strings. Nothing was changed.").arg(settingsKey).arg(typeErrors.join("; "))); - } - } - - QJsonObject sub = json[settingsKey].toObject(); - QStringList merged; - mergeInto(sub, subPartial, merged); - json[settingsKey] = sub; - - if (!schema.m_known) - { - // Without a schema the only test left is whether the key is in the current settings, which - // misses any string setting that is currently empty. Better than nothing, but not by much - unknownKeys = merged; - } - - QStringList keys; - extractKeys(subPartial, keys); - - SWG request; - request.fromJsonObject(json); - error.init(); - check(put(keys, request, error), error, "Set " + what); - - // Reply with only what was asked for, read back from the object that was sent. Echoing - // the whole settings block cost a client about 500 tokens per call, carried for the rest - // of the conversation, to confirm a one key change. - QJsonObject after = toJson(request)[settingsKey].toObject(); - QJsonObject changed; - - for (const QString& key : subPartial.keys()) - { - if (after.contains(key)) { - changed[key] = after[key]; - } - } - - QJsonObject result; - result["changed"] = changed; - - if (!unknownKeys.isEmpty()) { - result["warning"] = QString("Ignored unknown keys: %1. describe_settings lists the valid ones.").arg(unknownKeys.join(", ")); - } - - return result; -} - -QString capitalize(const QString& s) -{ - return s.isEmpty() ? s : s.at(0).toUpper() + s.mid(1); -} - -// The plugin lists carry a URI, a version and an index per entry that no caller needs. Each -// becomes one string: the id the other tools take, with the display name in brackets when it -// says something the id does not. -// Features with no run state: they work from the moment they are configured. Some answer the run -// request with 501 and the rest accept it and stay idle, so neither the request nor the state that -// follows it tells them apart from a feature that is slow to start -const QStringList passiveFeatureTypes = { - "AIS", "AMBE", "AntennaTools", "APRS", "FreqDisplay", "LimeRFE", "Map", "Radiosonde", - "RemoteControl", "SkyMap" -}; - -bool isPassiveFeature(const QString& featureType) -{ - return passiveFeatureTypes.contains(featureType); -} - -QJsonArray idsAndNames(const QJsonArray& plugins) -{ - QJsonArray out; - - for (const QJsonValue& v : plugins) - { - QJsonObject p = v.toObject(); - QString id = p["id"].toString(); - QString name = p["name"].toString(); - - if (!name.isEmpty() && (name.compare(id, Qt::CaseInsensitive) != 0)) { - out.append(QString("%1 (%2)").arg(id).arg(name)); - } else { - out.append(id); - } - } - - return out; -} - -} // namespace - -// --------------------------------------------------------------------------- -// Event counter -// --------------------------------------------------------------------------- - -MCPEventCounter::MCPEventCounter() : - m_deviceSetAdded(0), - m_deviceSetRemoved(0), - m_deviceChanged(0), - m_channelAdded(0), - m_channelRemoved(0), - m_featureAdded(0), - m_featureRemoved(0) -{ - MainCore *mainCore = MainCore::instance(); - connect(mainCore, &MainCore::deviceSetAdded, this, &MCPEventCounter::onDeviceSetAdded); - connect(mainCore, &MainCore::deviceSetRemoved, this, &MCPEventCounter::onDeviceSetRemoved); - connect(mainCore, &MainCore::deviceChanged, this, &MCPEventCounter::onDeviceChanged); - connect(mainCore, &MainCore::channelAdded, this, &MCPEventCounter::onChannelAdded); - connect(mainCore, &MainCore::channelRemoved, this, &MCPEventCounter::onChannelRemoved); - connect(mainCore, &MainCore::featureAdded, this, &MCPEventCounter::onFeatureAdded); - connect(mainCore, &MainCore::featureRemoved, this, &MCPEventCounter::onFeatureRemoved); -} - -void MCPEventCounter::onDeviceSetAdded(int index, DeviceAPI *device) -{ - (void) index; - (void) device; - m_deviceSetAdded.fetchAndAddRelease(1); -} - -void MCPEventCounter::onDeviceSetRemoved(int index) -{ - (void) index; - m_deviceSetRemoved.fetchAndAddRelease(1); -} - -void MCPEventCounter::onDeviceChanged(int index) -{ - (void) index; - m_deviceChanged.fetchAndAddRelease(1); -} - -void MCPEventCounter::onChannelAdded(int deviceSetIndex, ChannelAPI *channel) -{ - (void) deviceSetIndex; - (void) channel; - m_channelAdded.fetchAndAddRelease(1); -} - -void MCPEventCounter::onChannelRemoved(int deviceSetIndex, ChannelAPI *channel) -{ - (void) deviceSetIndex; - (void) channel; - m_channelRemoved.fetchAndAddRelease(1); -} - -void MCPEventCounter::onFeatureAdded(int featureSetIndex, Feature *feature) -{ - (void) featureSetIndex; - (void) feature; - m_featureAdded.fetchAndAddRelease(1); -} - -void MCPEventCounter::onFeatureRemoved(int featureSetIndex, Feature *feature) -{ - (void) featureSetIndex; - (void) feature; - m_featureRemoved.fetchAndAddRelease(1); -} - -// --------------------------------------------------------------------------- -// Registry -// --------------------------------------------------------------------------- - -MCPTools::MCPTools(WebAPIAdapterInterface *webAPIAdapterInterface) : - m_adapter(webAPIAdapterInterface), - m_capture(webAPIAdapterInterface), - m_streams(nullptr), - m_ownerFeature(nullptr), - m_stopping(0), - m_yamlLoaded(false) -{ - registerInstanceTools(); - registerDeviceSetTools(); - registerChannelTools(); - registerFeatureTools(); - registerPresetTools(); - registerWorkspaceTools(); - registerCaptureTools(); - registerIntentTools(); -} - -void MCPTools::setStopping(bool stopping) -{ - m_stopping.storeRelease(stopping ? 1 : 0); - m_capture.setStopping(stopping); -} - -// The tools run on HTTP threads and wait for work that completes on the main thread. When the -// server stops, the main thread waits for the HTTP threads instead, so a wait that carried on -// would hold it for its whole timeout, or for ever where the main thread itself is what is -// waited for. Every wait therefore gives up at once when a stop is under way -bool MCPTools::waitFor(const std::function& condition, int timeoutMs) const -{ - QElapsedTimer timer; - timer.start(); - - while (!condition()) - { - if (m_stopping.loadAcquire()) { - throw MCPToolError("The MCP server is stopping, so this call was abandoned"); - } - - if (timer.elapsed() > timeoutMs) { - return false; - } - - QThread::msleep(20); - } - - return true; -} - -void MCPTools::pause(int ms) const -{ - QElapsedTimer timer; - timer.start(); - - for (;;) - { - if (m_stopping.loadAcquire()) { - throw MCPToolError("The MCP server is stopping, so this call was abandoned"); - } - - // Read once: read again for the sleep, the limit could pass in between and a negative - // remainder become an unsigned sleep of weeks - const qint64 remaining = ms - timer.elapsed(); - - if (remaining <= 0) { - return; - } - - QThread::msleep((unsigned long) std::min(50, remaining)); - } -} - -// Per tool behaviour. The MCP hints are narrower than they look: destructiveHint false means -// the tool is additive only, so anything that overwrites existing state is destructive, and -// openWorldHint true means the tool can reach beyond this application, which covers commanding -// the radio, features that talk to network services, and data arriving from unknown transmitters. -struct ToolBehaviour -{ - bool m_readOnly; - bool m_destructive; - bool m_idempotent; - bool m_openWorld; -}; - -static ToolBehaviour behaviourFor(const QString& name) -{ - // Reads of this instance's own configuration and of documentation compiled into the plugin - static const QStringList localReads = { - "get_instance_summary", "list_available_devices", "list_channel_types", "list_feature_types", - "describe_settings", "get_receiving_guide", "list_docs", "get_docs", "list_audio_devices", - "get_location", "get_deviceset", "get_device_settings", - "get_spectrum_settings", "get_spectrum_report", "get_spectrum_data", "get_channel_settings", "get_feature_settings", - "list_presets", "list_configurations", "get_server_status", "get_status" - }; - - // Reads that return data received off the air, from transmitters this instance does not - // control, or from the network services some features talk to. Reports carry it as well as - // the dedicated data feeds do: an ADS-B report, for instance, lists the aircraft heard. - static const QStringList offAirReads = { - "get_packets", "get_map_items", "get_channel_report", - "get_device_report", "get_feature_report" - }; - - // Purely additive: they create something new and overwrite nothing - static const QStringList additive = { - "add_deviceset", "add_channel", "add_feature", "add_workspace", "add_annotation" - }; - - if (localReads.contains(name)) { - return {true, false, true, false}; - } - - if (offAirReads.contains(name)) { - return {true, false, true, true}; - } - - if (additive.contains(name)) { - return {false, false, false, true}; - } - - // Everything else changes or removes state. Only the workspace moves and the settings writes - // land in the same place when repeated; captures, actions and creation do not. - bool idempotent = name.startsWith("set_") || name.startsWith("stop_") || (name == "clear_packets"); - return {false, true, idempotent, true}; -} - -void MCPTools::add(const QString& name, const QString& description, const QJsonObject& inputSchema, - std::function handler) -{ - Tool tool; - tool.name = name; - tool.description = description; - tool.inputSchema = inputSchema; - tool.handler = handler; - m_tools.append(tool); -} - -QJsonArray MCPTools::listTools() const -{ - QJsonArray tools; - - for (const Tool& tool : m_tools) - { - QJsonObject t; - t["name"] = tool.name; - t["description"] = tool.description; - t["inputSchema"] = tool.inputSchema; - ToolBehaviour behaviour = behaviourFor(tool.name); - // Clients carry the whole tool list on every turn, so only say what differs from the - // defaults the MCP schema gives an absent hint (read-write, destructive, not - // idempotent, open world), and no title, which would repeat the description - QJsonObject annotations; - if (behaviour.m_readOnly) { annotations["readOnlyHint"] = true; } - if (!behaviour.m_destructive) { annotations["destructiveHint"] = false; } - if (behaviour.m_idempotent) { annotations["idempotentHint"] = true; } - if (!behaviour.m_openWorld) { annotations["openWorldHint"] = false; } - if (!annotations.isEmpty()) { t["annotations"] = annotations; } - tools.append(t); - } - - return tools; -} - -QJsonObject MCPTools::callTool(const QString& name, const QJsonObject& arguments) -{ - const Tool *tool = nullptr; - - for (const Tool& t : m_tools) - { - if (t.name == name) - { - tool = &t; - break; - } - } - - if (!tool) { - throw MCPError(-32602, QString("Unknown tool: %1").arg(name)); - } - - QJsonObject result; - QJsonArray content; - - try - { - // Every input schema says additionalProperties: false, so an argument a tool does not - // define is a mistake worth reporting. Dropping it silently turns a wrong call into a - // plausible wrong answer: get_packets, which filters on source and type, looks as though - // it is ignoring a deviceSetIndex and channelIndex filter it never had - QJsonObject properties = tool->inputSchema.value("properties").toObject(); - QStringList unknown; - - for (const QString& key : arguments.keys()) - { - if (!properties.contains(key)) { - unknown.append(key); - } - } - - if (!unknown.isEmpty()) - { - QStringList accepted = properties.keys(); - throw MCPToolError(QString("%1 does not take %2. It accepts: %3") - .arg(name) - .arg(unknown.join(", ")) - .arg(accepted.isEmpty() ? QString("no arguments") : accepted.join(", "))); - } - - QJsonValue value = tool->handler(arguments); - - // A handler that has a picture to show puts it under _image, which becomes an image - // content item beside the text rather than a base64 blob in it - QJsonObject image; - - if (value.isObject() && value.toObject().contains("_image")) - { - QJsonObject object = value.toObject(); - image = object.take("_image").toObject(); - value = object; - } - - QJsonObject text; - text["type"] = "text"; - text["text"] = compact(value); - content.append(text); - - if (!image.isEmpty()) - { - QJsonObject item; - item["type"] = "image"; - item["data"] = image["data"]; - item["mimeType"] = image["mimeType"]; - content.append(item); - } - - if (value.isObject()) { - result["structuredContent"] = value; - } - - result["isError"] = false; - } - catch (const MCPToolError& e) - { - qDebug() << "MCPTools::callTool:" << name << "error:" << e.message; - QJsonObject text; - text["type"] = "text"; - text["text"] = "Error: " + e.message; - content.append(text); - result["isError"] = true; - } - - result["content"] = content; - return result; -} - -// --------------------------------------------------------------------------- -// Instance level data -// --------------------------------------------------------------------------- - -QJsonObject MCPTools::getInstanceSummary() -{ - SWGSDRangel::SWGInstanceSummaryResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->instanceSummary(response, error), error, "Get instance summary"); - return toJson(response); -} - -QJsonObject MCPTools::getAvailableDevices(int direction) -{ - QJsonObject result; - - for (int dir = 0; dir < 3; dir++) - { - if ((direction >= 0) && (direction != dir)) { - continue; - } - - SWGSDRangel::SWGInstanceDevicesResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->instanceDevices(dir, response, error), error, "List devices"); - result[directionName(dir)] = toJson(response)["devices"].toArray(); - } - - return result; -} - -QJsonObject MCPTools::getAvailableChannels(int direction) -{ - QJsonObject result; - - for (int dir = 0; dir < 3; dir++) - { - if ((direction >= 0) && (direction != dir)) { - continue; - } - - SWGSDRangel::SWGInstanceChannelsResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->instanceChannels(dir, response, error), error, "List channel types"); - result[directionName(dir)] = idsAndNames(toJson(response)["channels"].toArray()); - } - - return result; -} - -QJsonObject MCPTools::getAvailableFeatures() -{ - SWGSDRangel::SWGInstanceFeaturesResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->instanceFeatures(response, error), error, "List feature types"); - QJsonObject result; - QJsonArray features; - - for (const QJsonValue& v : toJson(response)["features"].toArray()) - { - QString entry = v.toObject()["id"].toString(); - features.append(isPassiveFeature(entry) - ? QString("%1 [passive: no run state, do not start it]").arg(idsAndNames(QJsonArray{v}).first().toString()) - : idsAndNames(QJsonArray{v}).first().toString()); - } - - result["features"] = features; - return result; -} - -QJsonObject MCPTools::getPresets() -{ - SWGSDRangel::SWGPresets response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->instancePresetsGet(response, error), error, "List presets"); - return toJson(response); -} - -QJsonObject MCPTools::getConfigurations() -{ - SWGSDRangel::SWGConfigurations response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->instanceConfigurationsGet(response, error), error, "List configurations"); - return toJson(response); -} - -QJsonObject MCPTools::getDeviceSet(int deviceSetIndex) -{ - SWGSDRangel::SWGDeviceSet response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->devicesetGet(deviceSetIndex, response, error), error, QString("Get device set %1").arg(deviceSetIndex)); - return toJson(response); -} - -void MCPTools::loadYamlDefinitions() -{ - if (m_yamlLoaded) { - return; - } - - m_yamlLoaded = true; - QDir dir(":/webapi/doc/swagger/include"); - QRegularExpression definitionStart("^([A-Za-z0-9_]+):\\s*$"); - - for (const QString& fileName : dir.entryList(QStringList("*.yaml"), QDir::Files)) - { - QFile file(dir.filePath(fileName)); - - if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { - continue; - } - - QString name; - QStringList block; - - for (const QString& line : QString::fromUtf8(file.readAll()).split('\n')) - { - QRegularExpressionMatch match = definitionStart.match(line); - - if (match.hasMatch()) - { - if (!name.isEmpty()) { - m_yamlDefinitions[name] = block.join('\n').trimmed(); - } - - name = match.captured(1); - block.clear(); - } - - block.append(line); - } - - if (!name.isEmpty()) { - m_yamlDefinitions[name] = block.join('\n').trimmed(); - } - } - - for (auto name = m_yamlDefinitions.keyBegin(); name != m_yamlDefinitions.keyEnd(); ++name) { - m_yamlDefinitionsByLower.insert(name->toLower(), *name); - } - - qDebug("MCPTools::loadYamlDefinitions: %d definitions", (int) m_yamlDefinitions.size()); -} - -// The JSON settings key does not always capitalise the way its swagger definition does: -// testSourceSettings comes from TestSourceSettings, and sdrPlayV3Settings from SDRPlayV3Settings. -// Only the case ever differs, so a name that does not match exactly is looked up without it. -// Returns an empty string when there is no such definition -QString MCPTools::resolveDefinition(const QString& name) -{ - loadYamlDefinitions(); - - if (m_yamlDefinitions.contains(name)) { - return name; - } - - return m_yamlDefinitionsByLower.value(name.toLower()); -} - -QString MCPTools::describeType(const QString& typeIn, const QString& kindIn) -{ - QMutexLocker schemaLock(&m_schemaMutex); - loadYamlDefinitions(); - QString type = typeIn.trimmed(); - QString kind = kindIn.trimmed().toLower(); - // (settings JSON key, description of what matched) - QList> matches; - - // The spectrum display is not a type: its definitions are named after it directly - const QString lower = type.toLower(); - - if ((kind == "spectrum") || (lower == "spectrum") || (lower == "glspectrum")) - { - QStringList out; - out.append("# main spectrum display of a device set\n# get_spectrum_settings / set_spectrum_settings, get_spectrum_report, spectrum_action\n" - "# get_docs spectrum explains the display and its controls\n"); - - for (const QString& definition : {"GLSpectrum", "GLSpectrumReport", "SpectrumActions"}) - { - if (m_yamlDefinitions.contains(definition)) - { - out.append(m_yamlDefinitions[definition]); - out.append(""); - } - } - - return out.join('\n'); - } - - if (kind.isEmpty() || (kind == "channel")) - { - if (WebAPIUtils::m_channelTypeToSettingsKey.contains(type)) { - matches.append({WebAPIUtils::m_channelTypeToSettingsKey[type], "channel type " + type}); - } - } - - if (kind.isEmpty() || (kind == "device")) - { - if (WebAPIUtils::m_sourceDeviceHwIdToSettingsKey.contains(type)) { - matches.append({WebAPIUtils::m_sourceDeviceHwIdToSettingsKey[type], "rx device " + type}); - } - if (WebAPIUtils::m_sinkDeviceHwIdToSettingsKey.contains(type)) { - matches.append({WebAPIUtils::m_sinkDeviceHwIdToSettingsKey[type], "tx device " + type}); - } - if (WebAPIUtils::m_mimoDeviceHwIdToSettingsKey.contains(type)) { - matches.append({WebAPIUtils::m_mimoDeviceHwIdToSettingsKey[type], "mimo device " + type}); - } - } - - if (kind.isEmpty() || (kind == "feature")) - { - if (WebAPIUtils::m_featureTypeToSettingsKey.contains(type)) { - matches.append({WebAPIUtils::m_featureTypeToSettingsKey[type], "feature type " + type}); - } - } - - // Also accept a definition name given directly, e.g. "RtlSdrSettings" or "RtlSdr" - if (matches.isEmpty()) - { - if (!resolveDefinition(type + "Settings").isEmpty()) { - matches.append({type + "Settings", type}); - } else if (!resolveDefinition(type).isEmpty()) { - matches.append({type, type}); - } - } - - if (matches.isEmpty()) - { - throw MCPToolError(QString("Unknown type %1. Use the id values returned by list_channel_types, list_feature_types " - "or the hwType values returned by list_available_devices").arg(type)); - } - - QStringList out; - - for (const auto& match : matches) - { - QString settingsKey = match.first; - QString base = capitalize(settingsKey); - - if (base.endsWith("Settings")) { - base.chop(QString("Settings").size()); - } - - out.append(QString("# %1\n# Settings JSON key: %2\n").arg(match.second).arg(settingsKey)); - bool found = false; - - // A definition given by its own name that is not a Settings one, such as a Report or a - // marker, is what was asked for and is not reached by the suffixes below - if (!settingsKey.endsWith("Settings") && m_yamlDefinitions.contains(resolveDefinition(settingsKey))) - { - out.append(m_yamlDefinitions[resolveDefinition(settingsKey)]); - out.append(""); - found = true; - } - - for (const QString suffix : {"Settings", "Report", "Actions"}) - { - QString definition = resolveDefinition(base + suffix); - - if (!definition.isEmpty()) - { - out.append(m_yamlDefinitions[definition]); - out.append(""); - found = true; - } - } - - if (!found) { - out.append(QString("No documentation found for %1").arg(base)); - } - } - - return out.join('\n'); -} - -// --------------------------------------------------------------------------- -// Device set helpers -// --------------------------------------------------------------------------- - -int MCPTools::deviceSetCount() const -{ - return (int) MainCore::instance()->getDeviceSets().size(); -} - -int MCPTools::channelCount(int deviceSetIndex) const -{ - const std::vector& deviceSets = MainCore::instance()->getDeviceSets(); - - if ((deviceSetIndex < 0) || (deviceSetIndex >= (int) deviceSets.size())) { - return -1; - } - - return deviceSets[deviceSetIndex]->getNumberOfChannels(); -} - -int MCPTools::featureCount() const -{ - const std::vector& featureSets = MainCore::instance()->getFeatureeSets(); - - if (featureSets.empty()) { - return -1; - } - - return featureSets[0]->getNumberOfFeatures(); -} - -int MCPTools::deviceSetDirection(int deviceSetIndex) -{ - QJsonObject deviceSet = getDeviceSet(deviceSetIndex); - return deviceSet["samplingDevice"].toObject()["direction"].toInt(0); -} - -// Selects the sampling device of a device set from hwType / serial / sequence / displayedName / deviceIndex -// and waits for SDRangel to switch to it. -QJsonObject MCPTools::selectDevice(int deviceSetIndex, const QJsonObject& args) -{ - int direction = deviceSetDirection(deviceSetIndex); - QString hwType = argString(args, "hwType", false); - QString serial = argString(args, "serial", false); - QString displayedName = argString(args, "displayedName", false); - int sequence = argInt(args, "sequence", false, -1); - int streamIndex = argInt(args, "deviceStreamIndex", false, -1); - - if (hasArg(args, "deviceIndex")) - { - // Resolve the index in the available devices list to concrete identifiers - int deviceIndex = argInt(args, "deviceIndex"); - QJsonArray devices = getAvailableDevices(direction)[directionName(direction)].toArray(); - bool found = false; - - for (const auto& value : devices) - { - QJsonObject device = value.toObject(); - - if (device["index"].toInt(-1) == deviceIndex) - { - hwType = device["hwType"].toString(); - serial = device["serial"].toString(); - sequence = device["sequence"].toInt(-1); - streamIndex = device["deviceStreamIndex"].toInt(-1); - displayedName = device["displayedName"].toString(); - found = true; - break; - } - } - - if (!found) { - throw MCPToolError(QString("No %1 device with index %2 in the available devices list").arg(directionName(direction)).arg(deviceIndex)); - } - } - - if (hwType.isEmpty() && serial.isEmpty() && displayedName.isEmpty()) { - throw MCPToolError("Specify at least one of hwType, serial, displayedName or deviceIndex to select a device"); - } - - SWGSDRangel::SWGDeviceListItem query; - query.setDirection(direction); - query.setIndex(-1); - query.setSequence(sequence); - query.setDeviceStreamIndex(streamIndex); - - if (!hwType.isEmpty()) { - query.setHwType(new QString(hwType)); - } - if (!serial.isEmpty()) { - query.setSerial(new QString(serial)); - } - if (!displayedName.isEmpty()) { - query.setDisplayedName(new QString(displayedName)); - } - - SWGSDRangel::SWGDeviceListItem response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - int changedBefore = m_events.m_deviceChanged.loadAcquire(); - check(m_adapter->devicesetDevicePut(deviceSetIndex, query, response, error), error, "Select device"); - - QJsonObject selected = toJson(response); - QString wantHwType = selected["hwType"].toString(); - QString wantSerial = selected["serial"].toString(); - int wantSequence = selected["sequence"].toInt(-1); - - // The change completes on the main thread and is signalled by MainCore::deviceChanged - QJsonObject deviceSet; - bool done = waitFor([&]() - { - if (m_events.m_deviceChanged.loadAcquire() == changedBefore) { - return false; - } - - deviceSet = getDeviceSet(deviceSetIndex); - QJsonObject sampling = deviceSet["samplingDevice"].toObject(); - return (sampling["hwType"].toString() == wantHwType) - && (wantSerial.isEmpty() || (sampling["serial"].toString() == wantSerial)) - && ((wantSequence < 0) || (sampling["sequence"].toInt(-1) == wantSequence)); - }); - - QJsonObject result; - result["deviceSetIndex"] = deviceSetIndex; - result["selectedDevice"] = selected; - result["deviceSet"] = deviceSet; - - if (!done) { - result["warning"] = "Timed out waiting for the device change to complete. Call get_deviceset to check."; - } - - return result; -} - -QJsonObject MCPTools::getDeviceSettings(int deviceSetIndex) -{ - SWGSDRangel::SWGDeviceSettings response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->devicesetDeviceSettingsGet(deviceSetIndex, response, error), error, "Get device settings"); - return toJson(response); -} - -QJsonObject MCPTools::patchDeviceSettings(int deviceSetIndex, const QJsonObject& partial) -{ - return applySettingsPatch( - [&](SWGSDRangel::SWGDeviceSettings& r, SWGSDRangel::SWGErrorResponse& e) { - return m_adapter->devicesetDeviceSettingsGet(deviceSetIndex, r, e); - }, - [&](const QStringList& keys, SWGSDRangel::SWGDeviceSettings& r, SWGSDRangel::SWGErrorResponse& e) { - return m_adapter->devicesetDeviceSettingsPutPatch(deviceSetIndex, false, keys, r, e); - }, - partial, QString("device settings of device set %1").arg(deviceSetIndex), - [this](const QString& definition) { return settingsSchema(definition); }); -} - -QSet MCPTools::channelUids(int deviceSetIndex) const -{ - QSet result; - const std::vector& deviceSets = MainCore::instance()->getDeviceSets(); - - if ((deviceSetIndex < 0) || (deviceSetIndex >= (int) deviceSets.size())) { - return result; - } - - DeviceSet *deviceSet = deviceSets[deviceSetIndex]; - - for (int i = 0; i < deviceSet->getNumberOfChannels(); i++) - { - const ChannelAPI *channel = deviceSet->getChannelAt(i); - - if (channel) { - result.insert(channel->getUID()); - } - } - - return result; -} - -QSet MCPTools::featureUids() const -{ - QSet result; - const std::vector& featureSets = MainCore::instance()->getFeatureeSets(); - - if (featureSets.empty()) { - return result; - } - - for (int i = 0; i < featureSets[0]->getNumberOfFeatures(); i++) - { - const Feature *feature = featureSets[0]->getFeatureAt(i); - - if (feature) { - result.insert(feature->getUID()); - } - } - - return result; -} - -QSet MCPTools::deviceSetPointers() const -{ - QSet result; - - for (DeviceSet *deviceSet : MainCore::instance()->getDeviceSets()) { - result.insert(deviceSet); - } - - return result; -} - -// Adds a channel and waits for SDRangel to create it (which happens on the main thread), -// returning its index. The channel is ready to accept settings when this returns. -// -// The new channel is found by identity rather than by taking the last index: the GUI or -// another request can create a channel at the same time, and picking the highest index would -// then configure or delete somebody else's channel. -int MCPTools::addChannelAndWait(int deviceSetIndex, const QString& channelType) -{ - QMutexLocker creationLock(&m_creationMutex); - int direction = deviceSetDirection(deviceSetIndex); - int before = channelCount(deviceSetIndex); - - // A MIMO device set takes receive and transmit channels as well as MIMO ones, and the - // adapter looks the type up in the list the direction names, so the direction has to be - // the channel's rather than the device set's - if (direction == 2) - { - if (channelTypeIds(0).contains(channelType)) { - direction = 0; - } else if (channelTypeIds(1).contains(channelType)) { - direction = 1; - } - } - - if (before < 0) { - throw MCPToolError(QString("No device set with index %1").arg(deviceSetIndex)); - } - - QSet existing = channelUids(deviceSetIndex); - SWGSDRangel::SWGChannelSettings query; - query.setDirection(direction); - query.setChannelType(new QString(channelType)); - SWGSDRangel::SWGSuccessResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - int addedBefore = m_events.m_channelAdded.loadAcquire(); - check(m_adapter->devicesetChannelPost(deviceSetIndex, query, response, error), error, QString("Add channel %1").arg(channelType)); - - int channelIndex = -1; - bool created = waitFor([&]() - { - if (m_events.m_channelAdded.loadAcquire() <= addedBefore) { - return false; - } - - const std::vector& deviceSets = MainCore::instance()->getDeviceSets(); - - if ((deviceSetIndex < 0) || (deviceSetIndex >= (int) deviceSets.size())) { - return false; - } - - DeviceSet *deviceSet = deviceSets[deviceSetIndex]; - - for (int i = 0; i < deviceSet->getNumberOfChannels(); i++) - { - ChannelAPI *channel = deviceSet->getChannelAt(i); - - if (!channel || existing.contains(channel->getUID())) { - continue; - } - - QString id; - channel->getIdentifier(id); - - if (id == channelType) - { - channelIndex = i; - return true; - } - } - - return false; - }); - - if (!created || (channelIndex < 0)) { - throw MCPToolError(QString("Timed out waiting for the %1 channel to be created").arg(channelType)); - } - - // The channel needs a moment before it can accept settings - waitFor([&]() - { - SWGSDRangel::SWGChannelSettings s; - SWGSDRangel::SWGErrorResponse e; - e.init(); - return m_adapter->devicesetChannelSettingsGet(deviceSetIndex, channelIndex, s, e) / 100 == 2; - }, 2000); - - return channelIndex; -} - -// As for channels, the new feature is found by identity so that a feature created at the same -// time by the GUI or another request is never mistaken for this one. -int MCPTools::addFeatureAndWait(const QString& featureType) -{ - QMutexLocker creationLock(&m_creationMutex); - if (featureCount() < 0) { - throw MCPToolError("No feature set available"); - } - - QSet existing = featureUids(); - SWGSDRangel::SWGFeatureSettings query; - query.setFeatureType(new QString(featureType)); - SWGSDRangel::SWGSuccessResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - int addedBefore = m_events.m_featureAdded.loadAcquire(); - check(m_adapter->featuresetFeaturePost(0, query, response, error), error, QString("Add feature %1").arg(featureType)); - - int featureIndex = -1; - auto findNew = [&]() - { - const std::vector& featureSets = MainCore::instance()->getFeatureeSets(); - - if (featureSets.empty()) { - return -1; - } - - for (int i = 0; i < featureSets[0]->getNumberOfFeatures(); i++) - { - Feature *feature = featureSets[0]->getFeatureAt(i); - - if (!feature || existing.contains(feature->getUID())) { - continue; - } - - if (feature->getIdentifier() == featureType) { - return i; - } - } - - return -1; - }; - - // The wait ends as soon as the feature appears, so a longer limit only costs time when one - // genuinely fails to be created. The Map takes a while: it brings up a web engine - waitFor([&]() - { - if (m_events.m_featureAdded.loadAcquire() <= addedBefore) { - return false; - } - - featureIndex = findNew(); - return featureIndex >= 0; - }, 15000); - - if (featureIndex < 0) - { - // Look once more before reporting a failure. A caller told that creation failed when it - // did not will retry, and every retry builds another one - featureIndex = findNew(); - } - - if (featureIndex < 0) { - throw MCPToolError(QString("Timed out waiting for the %1 feature to be created").arg(featureType)); - } - - // The feature needs a moment before it can accept settings - waitFor([&]() - { - SWGSDRangel::SWGFeatureSettings s; - SWGSDRangel::SWGErrorResponse e; - e.init(); - return m_adapter->featuresetFeatureSettingsGet(0, featureIndex, s, e) / 100 == 2; - }, 2000); - - return featureIndex; -} - -// Device set creation runs as a state machine on the main thread; MainCore::deviceSetAdded -// marks the end. The new set is identified by pointer for the same reason as above. -int MCPTools::addDeviceSetAndWait(int direction) -{ - QMutexLocker creationLock(&m_creationMutex); - QSet existing = deviceSetPointers(); - int before = m_events.m_deviceSetAdded.loadAcquire(); - SWGSDRangel::SWGSuccessResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->instanceDeviceSetPost(direction, response, error), error, "Add device set"); - - int deviceSetIndex = -1; - bool created = waitFor([&]() - { - if (m_events.m_deviceSetAdded.loadAcquire() <= before) { - return false; - } - - const std::vector& deviceSets = MainCore::instance()->getDeviceSets(); - - for (int i = 0; i < (int) deviceSets.size(); i++) - { - if (!existing.contains(deviceSets[i])) - { - deviceSetIndex = i; - return true; - } - } - - return false; - }); - - if (!created || (deviceSetIndex < 0)) { - throw MCPToolError("Timed out waiting for the device set to be created"); - } - - return deviceSetIndex; -} - -// Deletes a channel and waits for SDRangel to remove it -// Watches the channel itself disappear rather than the removed signal, which is not emitted -// for the last channel of a device set -void MCPTools::deleteChannelAndWait(int deviceSetIndex, int channelIndex) -{ - QMutexLocker deletionLock(&m_deletionMutex); - deleteChannelLocked(deviceSetIndex, channelIndex); -} - -void MCPTools::deleteChannelLocked(int deviceSetIndex, int channelIndex) -{ - const uint64_t target = channelUidAt(deviceSetIndex, channelIndex); - SWGSDRangel::SWGSuccessResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->devicesetChannelDelete(deviceSetIndex, channelIndex, response, error), error, "Delete channel"); - - if (!waitFor([&]() { return !channelUids(deviceSetIndex).contains(target); })) { - throw MCPToolError(QString("Timed out waiting for channel %1:%2 to be removed").arg(deviceSetIndex).arg(channelIndex)); - } - - m_capture.forgetRecording(target); -} - -// Deletes a channel identified by its UID. A caller that waited, for instance for a -// recording to finish, cannot rely on the index it started with: deleting a lower numbered -// channel meanwhile renumbers everything above it. -void MCPTools::deleteChannelObjectAndWait(uint64_t channelUid) -{ - // The lookup and the delete under one lock, or another call's delete in between renumbers - // the index just found - QMutexLocker deletionLock(&m_deletionMutex); - int deviceSetIndex = -1; - int channelIndex = -1; - - if (!MCPCapture::locateChannel(channelUid, deviceSetIndex, channelIndex)) - { - m_capture.forgetRecording(channelUid); - return; // already gone, which is what was asked for - } - - deleteChannelLocked(deviceSetIndex, channelIndex); -} - -uint64_t MCPTools::deviceSetIdentity(int deviceSetIndex) const -{ - const std::vector& deviceSets = MainCore::instance()->getDeviceSets(); - - if ((deviceSetIndex < 0) || (deviceSetIndex >= (int) deviceSets.size()) || !deviceSets[deviceSetIndex]) { - return 0; - } - - const DeviceSet *deviceSet = deviceSets[deviceSetIndex]; - const uint64_t engine = deviceSet->m_deviceAPI ? deviceSet->m_deviceAPI->getDeviceUID() : 0; - return (engine << 32) ^ reinterpret_cast(deviceSet); -} - -void MCPTools::discardNewDeviceSet(int deviceSetIndex, uint64_t identity) -{ - try - { - QMutexLocker deletionLock(&m_deletionMutex); - - // Only the last device set can be removed, and only when it is still the one made - // here: another call may have added one since, or removed this one and put another - // at the same index while this call slept, and then what is there is left for the user - if ((deviceSetIndex < 0) || (deviceSetIndex != deviceSetCount() - 1) - || (identity == 0) || (deviceSetIdentity(deviceSetIndex) != identity)) { - return; - } - - int before = m_events.m_deviceSetRemoved.loadAcquire(); - SWGSDRangel::SWGSuccessResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->instanceDeviceSetDelete(response, error), error, "Remove device set"); - waitFor([&]() { return m_events.m_deviceSetRemoved.loadAcquire() > before; }); - } - catch (const MCPToolError&) {} -} - -const void *MCPTools::featureAt(int featureIndex) const -{ - const std::vector& featureSets = MainCore::instance()->getFeatureeSets(); - - if (featureSets.empty() || (featureIndex < 0) || (featureIndex >= featureSets[0]->getNumberOfFeatures())) { - return nullptr; - } - - return featureSets[0]->getFeatureAt(featureIndex); -} - -uint64_t MCPTools::featureUidAt(int featureIndex) const -{ - const Feature *feature = static_cast(featureAt(featureIndex)); - return feature ? feature->getUID() : 0; -} - -uint64_t MCPTools::channelUidAt(int deviceSetIndex, int channelIndex) const -{ - return MCPCapture::channelUidAt(deviceSetIndex, channelIndex); -} - -// Deleting or stopping the feature that is serving this request would tear down the HTTP -// listener from inside its own handler, so it is refused rather than attempted. -void MCPTools::requireNotSelf(int featureIndex, const QString& action) const -{ - if (m_ownerFeature && (featureAt(featureIndex) == m_ownerFeature)) - { - throw MCPToolError(QString("Feature %1 is the MCP Server serving this request and cannot be %2 through it. " - "Use the SDRangel GUI or the REST API instead.").arg(featureIndex).arg(action)); - } -} - -QJsonObject MCPTools::getChannelSettings(int deviceSetIndex, int channelIndex) -{ - SWGSDRangel::SWGChannelSettings response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->devicesetChannelSettingsGet(deviceSetIndex, channelIndex, response, error), error, "Get channel settings"); - return toJson(response); -} - -SettingsSchema MCPTools::settingsSchema(const QString& definition) -{ - QMutexLocker schemaLock(&m_schemaMutex); - - if (m_schemaCache.contains(definition)) { - return m_schemaCache[definition]; - } - - SettingsSchema schema; - // Without this no device setting found its schema and none of them were type checked - QString name = resolveDefinition(definition); - - if (!name.isEmpty()) { - schema = parseSettingsSchema(m_yamlDefinitions[name]); - } - - m_schemaCache.insert(definition, schema); - return schema; -} - -QJsonObject MCPTools::getSpectrumSettings(int deviceSetIndex) -{ - SWGSDRangel::SWGGLSpectrum response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->devicesetSpectrumSettingsGet(deviceSetIndex, response, error), error, "Get spectrum settings"); - return toJson(response); -} - -QJsonObject MCPTools::patchSpectrumSettings(int deviceSetIndex, const QJsonObject& partial, QStringList *unknownKeys) -{ - SWGSDRangel::SWGGLSpectrum current; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->devicesetSpectrumSettingsGet(deviceSetIndex, current, error), error, "Get spectrum settings"); - QJsonObject json = toJson(current); - QStringList unknown; - QJsonObject checked = partial; - SettingsSchema schema = settingsSchema("GLSpectrum"); - - if (schema.m_known) - { - QStringList typeErrors; - checked = checkAgainstSchema(partial, schema, unknown, typeErrors); - - if (!typeErrors.isEmpty()) - { - throw MCPToolError(QString("Wrong value type for spectrum settings: %1. Numbers must be " - "given as JSON numbers, not strings. Nothing was changed.").arg(typeErrors.join("; "))); - } - } - - QStringList merged; - mergeInto(json, checked, merged); - - if (!schema.m_known) { - unknown = merged; - } - - if (unknownKeys) { - *unknownKeys = unknown; - } - - QStringList keys; - extractKeys(checked, keys); - SWGSDRangel::SWGGLSpectrum request; - request.init(); - request.fromJsonObject(json); - error.init(); - check(m_adapter->devicesetSpectrumSettingsPutPatch(deviceSetIndex, false, keys, request, error), error, "Set spectrum settings"); - return toJson(request); -} - -void MCPTools::addRdsHint(QJsonObject& report, const QString& channelType, int deviceSetIndex, int channelIndex) -{ - if (channelType != "BFMDemod") { - return; - } - - if (report.value("BFMDemodReport").toObject().contains("rdsReport")) { - return; - } - - // The report is empty for a channel that is not running as well, where saying anything about - // RDS would only mislead, so the hint is tied to the setting that actually suppresses it - QJsonObject settings = getChannelSettings(deviceSetIndex, channelIndex).value("BFMDemodSettings").toObject(); - - if (settings.value("rdsActive").toInt(0) == 0) - { - report["rdsHint"] = "RDS is not being decoded, which is why this report has no rdsReport. Set rdsActive to 1 with " - "set_channel_settings to get the programme service name (the station name), radio text, programme " - "type and PI code."; - } -} - -QJsonObject MCPTools::patchChannelSettings(int deviceSetIndex, int channelIndex, const QJsonObject& partial) -{ - return applySettingsPatch( - [&](SWGSDRangel::SWGChannelSettings& r, SWGSDRangel::SWGErrorResponse& e) { - return m_adapter->devicesetChannelSettingsGet(deviceSetIndex, channelIndex, r, e); - }, - [&](const QStringList& keys, SWGSDRangel::SWGChannelSettings& r, SWGSDRangel::SWGErrorResponse& e) { - return m_adapter->devicesetChannelSettingsPutPatch(deviceSetIndex, channelIndex, false, keys, r, e); - }, - partial, QString("channel settings of channel %1:%2").arg(deviceSetIndex).arg(channelIndex), - [this](const QString& definition) { return settingsSchema(definition); }); -} - -QJsonObject MCPTools::getFeatureSettings(int featureIndex) -{ - SWGSDRangel::SWGFeatureSettings response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->featuresetFeatureSettingsGet(0, featureIndex, response, error), error, "Get feature settings"); - return toJson(response); -} - -QJsonObject MCPTools::patchFeatureSettings(int featureIndex, const QJsonObject& partial) -{ - return applySettingsPatch( - [&](SWGSDRangel::SWGFeatureSettings& r, SWGSDRangel::SWGErrorResponse& e) { - return m_adapter->featuresetFeatureSettingsGet(0, featureIndex, r, e); - }, - [&](const QStringList& keys, SWGSDRangel::SWGFeatureSettings& r, SWGSDRangel::SWGErrorResponse& e) { - return m_adapter->featuresetFeatureSettingsPutPatch(0, featureIndex, false, keys, r, e); - }, - partial, QString("feature settings of feature %1").arg(featureIndex), - [this](const QString& definition) { return settingsSchema(definition); }); -} - -QJsonObject MCPTools::deviceState(int deviceSetIndex, int subsystemIndex, int run) -{ - SWGSDRangel::SWGDeviceState response; - response.init(); - SWGSDRangel::SWGErrorResponse error; - error.init(); - int rc; - - // The subsystem variants only apply to MIMO devices; single stream devices use the plain calls - bool mimo = deviceSetDirection(deviceSetIndex) == 2; - - auto runGet = [&](SWGSDRangel::SWGDeviceState& s, SWGSDRangel::SWGErrorResponse& e) { - return mimo ? m_adapter->devicesetDeviceSubsystemRunGet(deviceSetIndex, subsystemIndex, s, e) - : m_adapter->devicesetDeviceRunGet(deviceSetIndex, s, e); - }; - - if (run == 1) { - rc = mimo ? m_adapter->devicesetDeviceSubsystemRunPost(deviceSetIndex, subsystemIndex, response, error) - : m_adapter->devicesetDeviceRunPost(deviceSetIndex, response, error); - } else if (run == 0) { - rc = mimo ? m_adapter->devicesetDeviceSubsystemRunDelete(deviceSetIndex, subsystemIndex, response, error) - : m_adapter->devicesetDeviceRunDelete(deviceSetIndex, response, error); - } else { - rc = runGet(response, error); - } - - check(rc, error, run == 1 ? "Start device" : (run == 0 ? "Stop device" : "Get device state")); - - // The state returned by POST/DELETE is the state before the change. Give the device a moment - // and report the state actually reached. - QJsonObject result; - result["deviceSetIndex"] = deviceSetIndex; - - if (run >= 0) - { - QString want = run == 1 ? "running" : "idle"; - QString readError; - - bool reached = waitFor([&]() - { - SWGSDRangel::SWGDeviceState state; - state.init(); - SWGSDRangel::SWGErrorResponse e; - e.init(); - int getRC = runGet(state, e); - - if (getRC / 100 != 2) - { - readError = QString("HTTP %1 %2").arg(getRC).arg(e.getMessage() ? *e.getMessage() : QString()); - return true; // stop polling, reported below - } - - response.init(); - *response.getState() = *state.getState(); - return *state.getState() == want || *state.getState() == "error"; - }, 3000); - - if (!readError.isEmpty()) { - throw MCPToolError(QString("%1 was requested but the device state could not be read back: %2").arg(run == 1 ? "Start" : "Stop").arg(readError)); - } - - if (!reached) { - result["warning"] = QString("The device did not reach the %1 state within 3 seconds. The state reported here is the last one observed").arg(want); - } - } - - result["state"] = *response.getState(); - return result; -} - -QJsonObject MCPTools::featureState(int featureIndex, int run) -{ - // Asking a passive feature to run waits three seconds for a state it never reports, or fails - // outright on the ones that answer 501, so say what it is instead of doing either - if (run >= 0) - { - QString featureType = getFeatureSettings(featureIndex)["featureType"].toString(); - - if (isPassiveFeature(featureType)) - { - QJsonObject passive; - passive["featureIndex"] = featureIndex; - passive["featureType"] = featureType; - passive["state"] = "idle"; - passive["passive"] = true; - passive["note"] = QString("%1 has no run state and does not need starting: it works as soon as it " - "is configured, and reports idle whether or not it is doing anything.").arg(featureType); - return passive; - } - } - - SWGSDRangel::SWGDeviceState response; - response.init(); - SWGSDRangel::SWGErrorResponse error; - error.init(); - int rc; - - if (run == 1) { - rc = m_adapter->featuresetFeatureRunPost(0, featureIndex, response, error); - } else if (run == 0) { - rc = m_adapter->featuresetFeatureRunDelete(0, featureIndex, response, error); - } else { - rc = m_adapter->featuresetFeatureRunGet(0, featureIndex, response, error); - } - - check(rc, error, run == 1 ? "Start feature" : (run == 0 ? "Stop feature" : "Get feature state")); - - QJsonObject result; - result["featureIndex"] = featureIndex; - - if (run >= 0) - { - QString want = run == 1 ? "running" : "idle"; - QString readError; - - bool reached = waitFor([&]() - { - SWGSDRangel::SWGDeviceState state; - state.init(); - SWGSDRangel::SWGErrorResponse e; - e.init(); - int getRC = m_adapter->featuresetFeatureRunGet(0, featureIndex, state, e); - - if (getRC / 100 != 2) - { - readError = QString("HTTP %1 %2").arg(getRC).arg(e.getMessage() ? *e.getMessage() : QString()); - return true; // stop polling, reported below - } - - response.init(); - *response.getState() = *state.getState(); - return *state.getState() == want || *state.getState() == "error"; - }, 3000); - - if (!readError.isEmpty()) { - throw MCPToolError(QString("%1 was requested but the feature state could not be read back: %2").arg(run == 1 ? "Start" : "Stop").arg(readError)); - } - - if (!reached) { - result["warning"] = QString("The feature did not reach the %1 state within 3 seconds. The state reported here is the last one observed").arg(want); - } - } - - result["state"] = *response.getState(); - return result; -} - -// Resolves group name + name (and optionally centre frequency and type) to the full preset identifier -// SDRangel needs. For a save, the identifier of the current device is used when no matching preset exists. -QJsonObject MCPTools::presetIdentifier(const QJsonObject& args, int deviceSetIndex, bool forSave) -{ - QString groupName = argString(args, "groupName"); - QString name = argString(args, "name"); - QString type = argString(args, "type", false); - bool hasFrequency = hasArg(args, "centerFrequency"); - qint64 centerFrequency = argInt64(args, "centerFrequency", false, 0); - - QJsonObject deviceSet; - QString deviceType; - qint64 deviceFrequency = 0; - - if (forSave) - { - deviceSet = getDeviceSet(deviceSetIndex); - QJsonObject sampling = deviceSet["samplingDevice"].toObject(); - deviceFrequency = (qint64) sampling["centerFrequency"].toDouble(); - int direction = sampling["direction"].toInt(0); - deviceType = direction == 0 ? "R" : (direction == 1 ? "T" : "M"); - } - - QJsonArray candidates; - - for (const auto& groupValue : getPresets()["groups"].toArray()) - { - QJsonObject group = groupValue.toObject(); - - if (group["groupName"].toString() != groupName) { - continue; - } - - for (const auto& presetValue : group["presets"].toArray()) - { - QJsonObject preset = presetValue.toObject(); - - if (preset["name"].toString() != name) { - continue; - } - if (!type.isEmpty() && (preset["type"].toString() != type)) { - continue; - } - if (hasFrequency && ((qint64) preset["centerFrequency"].toDouble() != centerFrequency)) { - continue; - } - if (forSave && (preset["type"].toString() != deviceType)) { - continue; - } - - candidates.append(preset); - } - } - - QJsonObject identifier; - identifier["groupName"] = groupName; - identifier["name"] = name; - - if (candidates.count() == 1) - { - QJsonObject preset = candidates.first().toObject(); - identifier["type"] = preset["type"].toString(); - identifier["centerFrequency"] = preset["centerFrequency"].toDouble(); - identifier["exists"] = true; - } - else if (candidates.count() > 1) - { - throw MCPToolError(QString("Several presets match group %1 name %2. Specify centerFrequency and type to choose one of: %3") - .arg(groupName).arg(name).arg(compact(candidates))); - } - else if (forSave) - { - identifier["type"] = deviceType; - identifier["centerFrequency"] = (double) deviceFrequency; - identifier["exists"] = false; - } - else - { - throw MCPToolError(QString("No preset with group %1 and name %2. Call list_presets to see what exists").arg(groupName).arg(name)); - } - - return identifier; -} - -// --------------------------------------------------------------------------- -// Tool registration -// --------------------------------------------------------------------------- - -void MCPTools::registerInstanceTools() -{ - add("get_instance_summary", - "Get an overview of the SDRangel instance: version, all device sets with their sampling device and channels, and all features. " - "Call this first to learn the current state and the indexes to use with other tools.", - schema(QJsonObject()), - [this](const QJsonObject&) { return getInstanceSummary(); }); - - add("list_available_devices", - "List the SDR hardware and software sources/sinks that can be selected in a device set. Each entry gives hwType (used by " - "set_device and describe_settings), serial, sequence and index. Physical devices must be plugged in before SDRangel starts.", - schema({{"direction", directionProp("Only list devices for this direction (rx, tx or mimo). Default: all directions")}}), - [this](const QJsonObject& args) { return getAvailableDevices(argDirection(args, "direction", false, -1)); }); - - add("list_channel_types", - "List the channel plugins (demodulators for rx, modulators for tx) that can be added to a device set. The id is the channelType " - "to pass to add_channel and describe_settings.", - schema({{"direction", directionProp("Only list channels for this direction (rx, tx or mimo). Default: all directions")}}), - [this](const QJsonObject& args) { return getAvailableChannels(argDirection(args, "direction", false, -1)); }); - - add("list_feature_types", - "List the feature plugins that can be added with add_feature. The id is the featureType.", - schema(QJsonObject()), - [this](const QJsonObject&) { return getAvailableFeatures(); }); - - add("describe_settings", - "Get the documentation (OpenAPI YAML) of the settings, report and actions keys of a device, channel or feature type, " - "or of the spectrum display: what each key means, its units, range and enumeration values. Not needed for common keys; " - "call it when a set_* tool reports an unknown key, or before setting a key whose values are codes, such as a style or " - "mode. The output can run to a few thousand tokens.", - schema({ - {"type", strProp("Type identifier: a device hwType such as RTLSDR or TestSource, a channelType such as ADSBDemod or NFMDemod, " - "a featureType such as Map, or spectrum for the spectrum display")}, - {"kind", strProp("Optional: device, channel, feature or spectrum, to disambiguate when the same id exists for several kinds")} - }, {"type"}), - [this](const QJsonObject& args) { return QJsonValue(describeType(argString(args, "type"), argString(args, "kind", false))); }); - - add("get_receiving_guide", - "Read the receiving guide: which demodulator and frequency to use for a given signal or protocol (ADS-B, AIS, APRS, " - "radiosondes, weather satellites, broadcast FM, LoRa, pagers and more), the minimum device sample rate some modes need, " - "and the usual reasons nothing is received. Read this before setting up a receiver for a named signal, rather than " - "guessing frequencies.", - schema(QJsonObject()), - [this](const QJsonObject&) { return QJsonValue(m_docs.guide()); }); - - add("list_docs", - "List the user documentation (readme) available for the device, channel and feature plugins registered in this instance, " - "and for the GUI's own pages such as the spectrum display, with the section headings of each. Use get_docs to read one.", - schema({{"kind", strProp("Optional: only list device, channel, feature or gui docs")}}), - [this](const QJsonObject& args) - { - QString kind = argString(args, "kind", false).trimmed().toLower(); - QJsonObject index = m_docs.index(); - - if (kind.isEmpty()) { - return index; - } - - QJsonArray filtered; - - for (const auto& value : index["docs"].toArray()) - { - if (value.toObject()["kind"].toString() == kind) { - filtered.append(value); - } - } - - QJsonObject result; - result["count"] = filtered.count(); - result["docs"] = filtered; - return result; - }); - - add("get_docs", - "Read the user documentation (readme, as markdown) of a device, channel or feature plugin, or of a GUI page such as the " - "spectrum display: what it does, what each setting means, frequencies and sample rates it needs, and how to use it. Pass " - "section to get just one section (matched against the headings listed by list_docs) as the full documents can be long.", - schema({ - {"type", strProp("Plugin id (e.g. ADSBDemod, RTLSDR, Map), its displayed name (e.g. \"ADS-B Demodulator\"), or a GUI page: " - "spectrum, spectrummarkers, spectrummeasurements, spectrumcalibration, mainspectrum, audio, configurations, deviceuserargs, transverter")}, - {"kind", strProp("Optional: device, channel, feature or gui, to disambiguate")}, - {"section", strProp("Optional: text of a heading; only that section is returned")} - }, {"type"}), - [this](const QJsonObject& args) - { - QString type = argString(args, "type"); - QString kind = argString(args, "kind", false); - const MCPDocs::Doc *doc = m_docs.find(type, kind); - - if (!doc) { - throw MCPToolError(QString("No documentation found for %1. Call list_docs to see what is available").arg(type)); - } - - QString section = argString(args, "section", false); - QString text = m_docs.text(*doc, section); - - if (text.isEmpty()) { - throw MCPToolError(QString("No section matching \"%1\" in the %2 documentation. Sections: %3").arg(section).arg(doc->id).arg(doc->headings.join(" | "))); - } - - return QJsonValue(text); - }); - - add("get_packets", - "Get recently decoded packets from packet-oriented demodulators (AIS, APRS/AX.25 packet, LoRa/ChirpChat, M17, Meshtastic, " - "MeshCore, Inmarsat, radiosonde). Each packet has the raw bytes (hex and printable text) and, where SDRangel can decode it, " - "a decoded object: AIS message type, MMSI, position, course and speed; AX.25 from/to/via and data with APRS position and " - "comment; RS41 radiosonde serial, position and height. Packets are kept in a buffer of the last 1000; use sinceSequence " - "with the lastSequence of a previous call to read only new packets.", - schema({ - {"source", strProp("Only packets from this channel, e.g. \"R0:1\" (device set 0, channel 1)")}, - {"type", strProp("Only packets from channels of this type, e.g. AISDemod, PacketDemod, RadiosondeDemod")}, - {"limit", bounded(intProp("Maximum number of packets to return, most recent first. Default 50"), 1, MCPDataFeed::m_maxPackets)}, - {"sinceSequence", intProp("Only packets with a sequence number greater than this")} - }), - [this](const QJsonObject& args) - { - return m_dataFeed.getPackets(argString(args, "source", false), argString(args, "type", false), - argInt(args, "limit", false, 50), argInt64(args, "sinceSequence", false, 0)); - }); - - add("clear_packets", - "Discard all buffered packets.", - schema(QJsonObject()), - [this](const QJsonObject&) - { - m_dataFeed.clearPackets(); - QJsonObject result; - result["cleared"] = true; - return result; - }); - - add("get_map_items", - "Get the objects currently plotted on the map by the running plugins: aircraft from ADS-B, ships from AIS, APRS stations, " - "radiosondes, satellites, the Sun and Moon from the star tracker, VOR/ILS beacons and so on. Each item has a name, position, " - "altitude, heading, the label and text shown on the map, and for aircraft the full ADS-B state. Only sources that are " - "running produce items; items disappear when their source removes them.", - schema({ - {"source", strProp("Only items from this channel or feature id (e.g. \"R0:0\", \"F:1\") or plugin type (e.g. ADSBDemod, AIS)")}, - {"name", strProp("Only items whose name contains this text, e.g. an ICAO address, MMSI or callsign")}, - {"limit", bounded(intProp("Maximum number of items to return. Default 200"), 1, 5000)}, - {"includeTrack", prop("boolean", "Include the position history of each item. Default false, as tracks can be long")} - }), - [this](const QJsonObject& args) - { - bool includeTrack = argBool(args, "includeTrack", false); - return m_dataFeed.getMapItems(argString(args, "source", false), argString(args, "name", false), - argInt(args, "limit", false, 200), includeTrack); - }); - - add("list_audio_devices", - "List the audio input and output devices available to SDRangel.", - schema(QJsonObject()), - [this](const QJsonObject&) - { - SWGSDRangel::SWGAudioDevices response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->instanceAudioGet(response, error), error, "List audio devices"); - return toJson(response); - }); - - add("get_location", - "Get the station location (latitude and longitude in degrees) used by features such as the Map and satellite tracker.", - schema(QJsonObject()), - [this](const QJsonObject&) - { - SWGSDRangel::SWGLocationInformation response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->instanceLocationGet(response, error), error, "Get location"); - return toJson(response); - }); - - add("set_location", - "Set the station location.", - schema({ - {"latitude", bounded(numProp("Latitude in degrees, positive north"), -90.0, 90.0)}, - {"longitude", bounded(numProp("Longitude in degrees, positive east"), -180.0, 180.0)} - }, {"latitude", "longitude"}), - [this](const QJsonObject& args) - { - SWGSDRangel::SWGLocationInformation response; - response.setLatitude((float) argDouble(args, "latitude")); - response.setLongitude((float) argDouble(args, "longitude")); - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->instanceLocationPut(response, error), error, "Set location"); - return toJson(response); - }); -} - -void MCPTools::registerDeviceSetTools() -{ - add("add_deviceset", - "Create a new device set and optionally select its sampling device in one go. Returns the index of the new device set. " - "Identify the device with hwType and/or serial (from list_available_devices), or deviceIndex (its index in that list). " - "Without a device the new device set uses the first available device of that direction.", - schema({ - {"direction", directionProp("rx for a receiver (default), tx for a transmitter, mimo for a MIMO device")}, - {"hwType", strProp("Hardware type of the device to select, e.g. RTLSDR, HackRF, TestSource")}, - {"serial", strProp("Serial number of the device to select")}, - {"sequence", intProp("Sequence number of the device, to distinguish identical devices")}, - {"displayedName", strProp("Displayed name of the device, as listed by list_available_devices")}, - {"deviceIndex", intProp("Index of the device in the list_available_devices list for this direction")} - }), - [this](const QJsonObject& args) - { - int direction = argDirection(args, "direction", false, 0); - int deviceSetIndex = addDeviceSetAndWait(direction); - - if (hasArg(args, "hwType") || hasArg(args, "serial") || hasArg(args, "displayedName") || hasArg(args, "deviceIndex")) - { - try - { - return selectDevice(deviceSetIndex, args); - } - catch (const MCPToolError& e) - { - throw MCPToolError(QString("Device set %1 was created but the requested device could not be selected: %2. " - "Use set_device on that device set, or remove_last_deviceset. Do not call add_deviceset again.") - .arg(deviceSetIndex).arg(e.message)); - } - } - - QJsonObject result; - result["deviceSetIndex"] = deviceSetIndex; - result["deviceSet"] = getDeviceSet(deviceSetIndex); - return result; - }); - - add("remove_last_deviceset", - "Remove the device set with the highest index. In the GUI the first device set (R0) cannot be removed.", - schema(QJsonObject()), - [this](const QJsonObject&) - { - int before = m_events.m_deviceSetRemoved.loadAcquire(); - SWGSDRangel::SWGSuccessResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->instanceDeviceSetDelete(response, error), error, "Remove device set"); - - if (!waitFor([&]() { return m_events.m_deviceSetRemoved.loadAcquire() > before; })) { - throw MCPToolError("Timed out waiting for the device set to be removed; get_instance_summary shows whether it went"); - } - - QJsonObject result; - result["deviceSetCount"] = deviceSetCount(); - return result; - }); - - add("get_deviceset", - "Get a device set: its sampling device (hwType, serial, centre frequency, state) and the list of its channels with their reports.", - schema({{"deviceSetIndex", deviceSetIndexProp}}, {"deviceSetIndex"}), - [this](const QJsonObject& args) { return getDeviceSet(argInt(args, "deviceSetIndex")); }); - - add("set_device", - "Change the sampling device of an existing device set. Identify the device with hwType and/or serial (from list_available_devices), " - "or deviceIndex. Waits for the change to complete.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"hwType", strProp("Hardware type of the device to select, e.g. RTLSDR")}, - {"serial", strProp("Serial number of the device to select")}, - {"sequence", intProp("Sequence number of the device, to distinguish identical devices")}, - {"displayedName", strProp("Displayed name of the device")}, - {"deviceIndex", intProp("Index of the device in the list_available_devices list for the device set direction")} - }, {"deviceSetIndex"}), - [this](const QJsonObject& args) { return selectDevice(argInt(args, "deviceSetIndex"), args); }); - - add("get_device_settings", - "Get the settings of the sampling device of a device set (centre frequency, sample rate, gain...). The keys depend on the device type.", - schema({{"deviceSetIndex", deviceSetIndexProp}}, {"deviceSetIndex"}), - [this](const QJsonObject& args) { return getDeviceSettings(argInt(args, "deviceSetIndex")); }); - - add("set_device_settings", - "Change some settings of the sampling device of a device set. Give only the keys to change, e.g. {\"centerFrequency\": 1090000000, \"gain\": 400}. " - "Use describe_settings with the device hwType to learn the valid keys, units and value ranges. Returns the keys changed with their applied values.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"settings", objProp("Object with the settings keys to change and their new values")} - }, {"deviceSetIndex", "settings"}), - [this](const QJsonObject& args) { return patchDeviceSettings(argInt(args, "deviceSetIndex"), argObject(args, "settings")); }); - - add("set_center_frequency", - "Tune the sampling device of a device set to a centre frequency in Hz. Channels keep their inputFrequencyOffset relative to it.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"frequency", numProp("Centre frequency in Hz")} - }, {"deviceSetIndex", "frequency"}), - [this](const QJsonObject& args) - { - QJsonObject settings; - settings["centerFrequency"] = (double) argInt64(args, "frequency"); - return patchDeviceSettings(argInt(args, "deviceSetIndex"), settings); - }); - - add("start_device", - "Start the sampling device of a device set so that it streams samples and its channels run. Returns the resulting state.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"subsystemIndex", bounded(intProp("MIMO devices only: 0 for the rx subsystem, 1 for tx. Default 0"), 0, 1)} - }, {"deviceSetIndex"}), - [this](const QJsonObject& args) - { - int deviceSetIndex = argInt(args, "deviceSetIndex"); - QJsonObject state = deviceState(deviceSetIndex, argInt(args, "subsystemIndex", false, 0), 1); - QStringList warnings = basebandWarnings(deviceSetIndex); - - if (!warnings.isEmpty()) { - state["warning"] = warnings.join(" "); - } - - return QJsonValue(state); - }); - - add("stop_device", - "Stop the sampling device of a device set.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"subsystemIndex", bounded(intProp("MIMO devices only: 0 for the rx subsystem, 1 for tx. Default 0"), 0, 1)} - }, {"deviceSetIndex"}), - [this](const QJsonObject& args) { return deviceState(argInt(args, "deviceSetIndex"), argInt(args, "subsystemIndex", false, 0), 0); }); - - add("get_device_report", - "Get the live report of the sampling device of a device set (for example the actual sample rate, gain values, " - "or for file inputs the playback position). Keys depend on the device type.", - schema({{"deviceSetIndex", deviceSetIndexProp}}, {"deviceSetIndex"}), - [this](const QJsonObject& args) - { - SWGSDRangel::SWGDeviceReport response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->devicesetDeviceReportGet(argInt(args, "deviceSetIndex"), response, error), error, "Get device report"); - return toJson(response); - }); - - add("device_action", - "Trigger an action on the sampling device of a device set. Only some device types have actions. Use describe_settings to find " - "the actions keys of the device type; pass them as the actions object, e.g. {\"record\": 1}.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"actions", objProp("Object with the action keys and values for this device type")} - }, {"deviceSetIndex", "actions"}), - [this](const QJsonObject& args) - { - int deviceSetIndex = argInt(args, "deviceSetIndex"); - QJsonObject actions = argObject(args, "actions"); - QJsonObject settings = getDeviceSettings(deviceSetIndex); - QString hwType = settings["deviceHwType"].toString(); - int direction = settings["direction"].toInt(0); - const QMap& map = direction == 0 ? WebAPIUtils::m_sourceDeviceHwIdToActionsKey - : (direction == 1 ? WebAPIUtils::m_sinkDeviceHwIdToActionsKey : WebAPIUtils::m_mimoDeviceHwIdToActionsKey); - - if (!map.contains(hwType)) { - throw MCPToolError(QString("Device type %1 has no actions").arg(hwType)); - } - - QJsonObject json; - json["deviceHwType"] = hwType; - json["direction"] = direction; - json[map[hwType]] = actions.contains(map[hwType]) ? actions[map[hwType]].toObject() : actions; - QStringList keys; - extractKeys(json[map[hwType]].toObject(), keys); - - SWGSDRangel::SWGDeviceActions query; - query.init(); - query.fromJsonObject(json); - SWGSDRangel::SWGSuccessResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->devicesetDeviceActionsPost(deviceSetIndex, keys, query, response, error), error, "Device action"); - return toJson(response); - }); - - add("get_spectrum_settings", - "Get the settings of the main spectrum display of a device set, including FFT and scale, 2D/3D spectrum display, waterfall history, measurements and statistics, math, and saved-memory display settings.", - schema({{"deviceSetIndex", deviceSetIndexProp}}, {"deviceSetIndex"}), - [this](const QJsonObject& args) - { - SWGSDRangel::SWGGLSpectrum response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->devicesetSpectrumSettingsGet(argInt(args, "deviceSetIndex"), response, error), error, "Get spectrum settings"); - return toJson(response); - }); - - add("set_spectrum_settings", - "Change selected settings of the main spectrum display of a device set. Supports FFT and scale, 2D/3D spectrum display, waterfall history, measurements and statistics, math, and saved-memory display settings. Give only the keys to change (see get_spectrum_settings for the keys). " - "Keys whose values are codes are documented by describe_settings with type spectrum: for instance spectrumStyle is 0 line, 1 filled solid colour, 2 filled colour gradient, and colorMap names the gradient. " - "To smooth the trace set both averagingMode (1 moving) and averagingValue (the number of FFTs, e.g. 10): a mode with the value left at 1 averages nothing.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"settings", objProp("Object with the spectrum settings keys to change")} - }, {"deviceSetIndex", "settings"}), - [this](const QJsonObject& args) - { - int deviceSetIndex = argInt(args, "deviceSetIndex"); - QJsonObject partial = argObject(args, "settings"); - QStringList unknownKeys; - - auto read = [&]() - { - SWGSDRangel::SWGGLSpectrum current; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->devicesetSpectrumSettingsGet(deviceSetIndex, current, error), error, "Get spectrum settings"); - return toJson(current); - }; - - const QJsonObject before = read(); - patchSpectrumSettings(deviceSetIndex, partial, &unknownKeys); - - // Read back rather than echo the request: some values are rounded to what the - // display offers, and the caller should see what it got. The patch is applied by - // message, so give it a moment to land: until every key given has either moved or - // was already where it was asked to be - QJsonObject after = read(); - - for (int attempt = 0; attempt < 10; attempt++) - { - bool landed = true; - - for (const QString& key : partial.keys()) - { - if (after.contains(key) && (after[key] == before[key]) && (after[key] != partial[key])) { - landed = false; - } - } - - if (landed) { - break; - } - - QThread::msleep(50); - after = read(); - } - - QJsonObject changed; - QStringList notes; - - for (const QString& key : partial.keys()) - { - if (after.contains(key)) - { - changed[key] = after[key]; - - if (after[key].isDouble() && partial[key].isDouble() && (after[key].toDouble() != partial[key].toDouble())) { - notes.append(QString("%1 was rounded to %2, one of the values the display offers.").arg(key).arg(after[key].toDouble())); - } - } - } - - // A mode with a count of one averages nothing, which is easy to leave that way - if ((after["averagingMode"].toInt() != 0) && (after["averagingValue"].toInt() <= 1)) { - notes.append("averagingMode is set but averagingValue is 1, so no averaging is happening: set averagingValue as well, " - "10 to smooth a trace or 50 to measure a floor. The values available are 1, 2, 5, 10, 20, 50, 100 and so on."); - } - - QJsonObject result; - result["changed"] = changed; - - if (!unknownKeys.isEmpty()) { - result["warning"] = QString("Ignored unknown keys: %1. describe_settings lists the valid ones.").arg(unknownKeys.join(", ")); - } - - if (!notes.isEmpty()) { - result["note"] = notes.join(" "); - } - - return result; - }); - - - add("get_spectrum_report", - "Get the latest spectrum measurement results of a device set: peaks, channel power, adjacent channel power, occupied " - "bandwidth, 3 dB bandwidth, or SNR with THD and SINAD, depending on which measurement is selected with " - "set_spectrum_settings. Only the fields the selected measurement produces are returned, so an absent field was not " - "measured rather than measured as zero. With no measurement selected only measurement 0 comes back. The figures are " - "those of the spectrum as displayed, so they follow the zoom.", - schema({{"deviceSetIndex", deviceSetIndexProp}}, {"deviceSetIndex"}), - [this](const QJsonObject& args) - { - SWGSDRangel::SWGGLSpectrumReport response; - SWGSDRangel::SWGErrorResponse error; - response.init(); - error.init(); - check(m_adapter->devicesetSpectrumReportGet(argInt(args, "deviceSetIndex"), response, error), error, "Get spectrum report"); - return toJson(response); - }); - - - add("get_spectrum_data", - "Get the current power spectrum of a device set, reduced to the number of bins asked for. Use it to see what is on a band " - "without looking at the screen: which parts are occupied, how strong, and where the edges are. Each value covers " - "binBandwidth Hz starting at startFrequency. Reduction is by max, which keeps a narrow carrier that averaging would bury " - "in its neighbours; mean is better for measuring a noise floor. Every value costs tokens, so ask for the coarsest that " - "answers the question and narrow the frequency range instead of asking for more bins.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"bins", bounded(intProp("Number of values to return, most recent spectrum. Default 64"), 1, 512)}, - {"startFrequency", numProp("Only from this frequency in Hz. Default the start of the spectrum")}, - {"stopFrequency", numProp("Only up to this frequency in Hz. Default the end of the spectrum")}, - {"reduce", strProp("max to keep peaks, the default, or mean to average")} - }, {"deviceSetIndex"}), - [this](const QJsonObject& args) - { - SWGSDRangel::SWGGLSpectrumData response; - SWGSDRangel::SWGErrorResponse error; - response.init(); - error.init(); - check(m_adapter->devicesetSpectrumDataGet( - argInt(args, "deviceSetIndex"), - argInt(args, "bins", false, 64), - argInt64(args, "startFrequency", false, 0), - argInt64(args, "stopFrequency", false, 0), - argString(args, "reduce", false, "max"), - response, error), - error, "Get spectrum data"); - QJsonObject json = toJson(response); - - // The generated serialiser drops a list of plain floats, so the values go in by hand - QJsonArray power; - - if (response.getPower()) - { - for (float v : *response.getPower()) { - power.append(std::round((double) v * 10.0) / 10.0); - } - } - - json["power"] = power; - return json; - }); - - add("get_spectrum_history", - "What has been on a band over the last while, from the spectrum history the GUI keeps for scrolling: per bin " - "maximum, mean and occupancy (the fraction of the time the bin was above the noise floor by threshold dB), and a " - "signalList of every run of bins that rose above it, each with its frequency, width, peak, dutyCycle (1 for a " - "continuous carrier, small for bursts) and when it was first and last seen. This is the way to tell a continuous " - "signal from an intermittent one, find where transmissions are without stepping a scanner over them, and measure " - "a floor over time rather than from one snapshot. Only rows taken with the device tuned and sampling as it is now " - "count; after a retune, wait for new history. Scrolling is switched on if it is off, and then there is nothing to " - "report until some has accumulated, so call again after a few seconds. Every bin costs tokens: ask for the coarsest " - "that answers the question.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"seconds", numProp("How far back to look, in seconds. Default 60")}, - {"bins", bounded(intProp("Number of bins to reduce the spectrum to. Default 64"), 1, 512)}, - {"startFrequency", numProp("Only from this frequency in Hz. Default the start of the spectrum")}, - {"stopFrequency", numProp("Only up to this frequency in Hz. Default the end of the spectrum")}, - {"threshold", numProp("dB above the measured floor for a bin to count as occupied. Default 6")} - }, {"deviceSetIndex"}), - [this](const QJsonObject& args) - { - const int deviceSetIndex = argInt(args, "deviceSetIndex"); - const double seconds = argDouble(args, "seconds", false, 60.0); - const QString enabled = ensureSpectrumHistory(deviceSetIndex, seconds); - SWGSDRangel::SWGGLSpectrumHistory response; - SWGSDRangel::SWGErrorResponse error; - response.init(); - error.init(); - const int status = m_adapter->devicesetSpectrumHistoryGet(deviceSetIndex, seconds, - argInt(args, "bins", false, 64), argInt64(args, "startFrequency", false, 0), argInt64(args, "stopFrequency", false, 0), - argDouble(args, "threshold", false, 6.0), response, error); - - if (!enabled.isEmpty() && (status == 404)) - { - QJsonObject result; - result["rows"] = 0; - result["note"] = enabled + " Call again in a few seconds, once some has accumulated."; - return result; - } - - check(status, error, "Get spectrum history"); - QJsonObject json = toJson(response); - QJsonArray maxDb, meanDb, occupancy; - - for (float v : *response.getMaxDb()) { - maxDb.append(std::round((double) v * 10.0) / 10.0); - } - - for (float v : *response.getMeanDb()) { - meanDb.append(std::round((double) v * 10.0) / 10.0); - } - - for (float v : *response.getOccupancy()) { - occupancy.append(std::round((double) v * 100.0) / 100.0); - } - - json["maxDb"] = maxDb; - json["meanDb"] = meanDb; - json["occupancy"] = occupancy; - - if (!enabled.isEmpty()) { - json["note"] = enabled; - } - - return json; - }); - - add("get_waterfall_image", - "A picture of the spectrum history, the waterfall, as a greyscale image: frequency across, time down with the newest " - "row at the bottom, black a little below the noise floor and white at the strongest signal. Use it when the shape of " - "activity matters more than the numbers: a hopping signal, a drifting carrier, a burst pattern, or to see a whole band " - "at once. The reply's text gives the frequency and time extents so the picture can be read. get_spectrum_history " - "gives the same history as numbers. Scrolling is switched on if it is off, and then there is nothing to show until " - "some has accumulated.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"seconds", numProp("How far back to look, in seconds. Default 60")}, - {"width", bounded(intProp("Width in pixels, one per bin. Default 512"), 16, 2048)}, - {"height", bounded(intProp("At most this many rows, the most recent. Default 512"), 16, 2000)}, - {"startFrequency", numProp("Only from this frequency in Hz. Default the start of the spectrum")}, - {"stopFrequency", numProp("Only up to this frequency in Hz. Default the end of the spectrum")} - }, {"deviceSetIndex"}), - [this](const QJsonObject& args) - { - const int deviceSetIndex = argInt(args, "deviceSetIndex"); - const double seconds = argDouble(args, "seconds", false, 60.0); - const QString enabled = ensureSpectrumHistory(deviceSetIndex, seconds); - QByteArray png; - QJsonObject description; - SWGSDRangel::SWGErrorResponse error; - error.init(); - const int status = m_adapter->devicesetSpectrumHistoryImageGet(deviceSetIndex, seconds, - argInt(args, "width", false, 512), argInt64(args, "startFrequency", false, 0), argInt64(args, "stopFrequency", false, 0), - argInt(args, "height", false, 512), png, description, error); - - if (!enabled.isEmpty() && (status == 404)) - { - QJsonObject result; - result["note"] = enabled + " Call again in a few seconds, once some has accumulated."; - return result; - } - - check(status, error, "Get waterfall image"); - QJsonObject image; - image["data"] = QString(png.toBase64()); - image["mimeType"] = "image/png"; - description["_image"] = image; - description["note"] = QString("Frequency runs left to right from %1 to %2 MHz, time top to bottom from %3 to %4 with the newest row at the bottom; black is %5 dB and white %6 dB.%7") - .arg(description["startFrequency"].toDouble() / 1e6, 0, 'f', 4).arg(description["stopFrequency"].toDouble() / 1e6, 0, 'f', 4) - .arg(description["firstTime"].toString()).arg(description["lastTime"].toString()) - .arg(description["blackDb"].toDouble(), 0, 'f', 1).arg(description["whiteDb"].toDouble(), 0, 'f', 1) - .arg(enabled.isEmpty() ? QString() : " " + enabled); - return description; - }); - - add("spectrum_action", - "Act on the main spectrum of a device set. autoscale sets the reference level and range from what is on screen, " - "clearSpectrum discards the histogram and max hold traces, resetMeasurements starts the measurement statistics again, " - "freeze stops spectrum processing and unfreezing resumes it, and gotoMarker retunes to one of the annotations. " - "Everything except freeze acts on the display and so needs the GUI.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"autoscale", prop("boolean", "Set the reference level and range from the spectrum currently displayed")}, - {"clearSpectrum", prop("boolean", "Discard the accumulated histogram and max hold traces")}, - {"resetMeasurements", prop("boolean", "Discard the accumulated measurement statistics")}, - {"freeze", prop("boolean", "True to stop spectrum processing, false to resume it")}, - {"gotoMarker", intProp("Retune to the annotation at this index, counting from 0")} - }, {"deviceSetIndex"}), - [this](const QJsonObject& args) - { - int deviceSetIndex = argInt(args, "deviceSetIndex"); - QJsonObject actions; - - for (const QString& key : {QString("autoscale"), QString("clearSpectrum"), QString("resetMeasurements"), QString("freeze")}) - { - if (hasArg(args, key)) { - actions[key] = argBool(args, key, false) ? 1 : 0; - } - } - - if (hasArg(args, "gotoMarker")) { - actions["gotoMarker"] = argInt(args, "gotoMarker"); - } - - if (actions.isEmpty()) { - throw MCPToolError("Give at least one of autoscale, clearSpectrum, resetMeasurements, freeze or gotoMarker"); - } - - QStringList keys; - extractKeys(actions, keys); - - // fromJsonObject takes its argument by non-const reference and looks every field up - // with operator[], which inserts a null for each one that is absent, so what is echoed - // back is taken before the call rather than after it - QJsonObject applied = actions; - SWGSDRangel::SWGSpectrumActions query; - query.init(); - query.fromJsonObject(actions); - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->devicesetSpectrumActionsPost(deviceSetIndex, keys, query, error), error, "Spectrum action"); - - QJsonObject result; - result["deviceSetIndex"] = deviceSetIndex; - result["applied"] = applied; - return result; - }); - - add("add_annotation", - "Add a labelled annotation to the main spectrum of a device set, for instance the name of the station a channel is tuned to. " - "Appends to the annotations already there instead of replacing them, and turns annotation display on if it is off. " - "Give centerFrequency, which is usually what you want as the bandwidth is then centred on it, or startFrequency.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"text", strProp("Label shown against the annotation, e.g. the RDS programme service name of a broadcast station")}, - {"centerFrequency", numProp("Centre frequency of the annotation in Hz. Give this or startFrequency")}, - {"startFrequency", numProp("Start frequency of the annotation in Hz. Give this or centerFrequency")}, - {"bandwidth", intProp("Width of the annotation in Hz. Default 0, which marks a single frequency")}, - {"color", intProp("Colour packed as blue*65536 + green*256 + red, each component 0 to 255. Default yellow")}, - {"show", bounded(intProp("0 hidden, 1 top marker only, 2 full with text and limits, 3 text only. Default 2"), 0, 3)} - }, {"deviceSetIndex", "text"}), - [this](const QJsonObject& args) - { - int deviceSetIndex = argInt(args, "deviceSetIndex"); - int bandwidth = argInt(args, "bandwidth", false, 0); - - if (bandwidth < 0) { - throw MCPToolError("bandwidth cannot be negative"); - } - - qint64 startFrequency; - - if (hasArg(args, "startFrequency")) { - startFrequency = argInt64(args, "startFrequency"); - } else if (hasArg(args, "centerFrequency")) { - startFrequency = argInt64(args, "centerFrequency") - bandwidth / 2; - } else { - throw MCPToolError("Give either centerFrequency or startFrequency"); - } - - QJsonObject marker; - marker["startFrequency"] = startFrequency; - marker["bandwidth"] = bandwidth; - marker["markerColor"] = argInt(args, "color", false, 65535); // Yellow - marker["show"] = argInt(args, "show", false, 2); - marker["text"] = argString(args, "text"); - - QJsonObject current = getSpectrumSettings(deviceSetIndex); - - // Appended by the settings themselves rather than by reading the list, adding to it and - // writing it back, which would lose an annotation added by anything else in between - QJsonArray markers; - markers.append(marker); - - QJsonObject patch; - patch["annotationMarkers"] = markers; - patch["annotationMarkersMode"] = 1; - // Annotations are drawn only when their bit of markersDisplay is set, so an annotation - // added while it is clear would otherwise be invisible with nothing to say why - patch["markersDisplay"] = current.value("markersDisplay").toInt(0) | 0x2; - - QJsonObject after = patchSpectrumSettings(deviceSetIndex, patch); - QJsonObject result; - result["added"] = marker; - result["annotationMarkers"] = after.value("annotationMarkers").toArray(); - return result; - }); - - add("remove_annotation", - "Remove annotations from the main spectrum of a device set. Give text to remove the annotations carrying that label, " - "frequency to remove those whose span covers it, or all to remove every annotation. Returns what was removed and what is left.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"text", strProp("Remove annotations whose label is exactly this")}, - {"frequency", numProp("Remove annotations whose span covers this frequency in Hz")}, - {"all", prop("boolean", "Remove every annotation. Default false")} - }, {"deviceSetIndex"}), - [this](const QJsonObject& args) - { - int deviceSetIndex = argInt(args, "deviceSetIndex"); - bool all = argBool(args, "all", false); - bool byText = hasArg(args, "text"); - bool byFrequency = hasArg(args, "frequency"); - - // Without a criterion the intent is ambiguous, and either reading of it, removing - // nothing or removing everything, would be wrong often enough to be worth refusing - if (!all && !byText && !byFrequency) { - throw MCPToolError("Give text, frequency or all to say which annotations to remove"); - } - - QString text = argString(args, "text", false); - qint64 frequency = argInt64(args, "frequency", false); - QJsonArray markers = getSpectrumSettings(deviceSetIndex).value("annotationMarkers").toArray(); - QJsonArray kept; - QJsonArray removed; - - for (const QJsonValue& value : markers) - { - QJsonObject marker = value.toObject(); - qint64 start = (qint64) marker.value("startFrequency").toDouble(); - qint64 stop = start + (qint64) marker.value("bandwidth").toDouble(); - bool matches = all - || (byText && (marker.value("text").toString() == text)) - || (byFrequency && (frequency >= start) && (frequency <= stop)); - - if (matches) { - removed.append(marker); - } else { - kept.append(marker); - } - } - - QJsonObject result; - result["removed"] = removed; - - if (removed.isEmpty()) - { - result["annotationMarkers"] = markers; - result["warning"] = "No annotation matched, so nothing was removed"; - return result; - } - - QJsonObject patch; - patch["annotationMarkers"] = kept; - QJsonObject after = patchSpectrumSettings(deviceSetIndex, patch); - result["annotationMarkers"] = after.value("annotationMarkers").toArray(); - return result; - }); -} - -void MCPTools::registerChannelTools() -{ - add("add_channel", - "Add a channel (demodulator or modulator) to a device set and optionally apply initial settings. Returns the index of the new channel. " - "channelType is an id from list_channel_types, e.g. ADSBDemod, NFMDemod, AMDemod, BFMDemod, SSBDemod, AISDemod, PacketDemod, FileSink.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"channelType", strProp("Channel type id from list_channel_types")}, - {"settings", objProp("Optional initial settings for the channel, e.g. {\"inputFrequencyOffset\": 0}. Use describe_settings for the keys")} - }, {"deviceSetIndex", "channelType"}), - [this](const QJsonObject& args) - { - int deviceSetIndex = argInt(args, "deviceSetIndex"); - QString channelType = argString(args, "channelType"); - int channelIndex = addChannelAndWait(deviceSetIndex, channelType); - QJsonObject result; - result["deviceSetIndex"] = deviceSetIndex; - result["channelIndex"] = channelIndex; - QString warning = basebandWarning(deviceSetIndex, channelType); - - if (!warning.isEmpty()) { - result["warning"] = warning; - } - QJsonObject settings = argObject(args, "settings", false); - - if (!settings.isEmpty()) - { - QJsonObject patched; - - try - { - patched = patchChannelSettings(deviceSetIndex, channelIndex, settings); - } - catch (const MCPToolError& e) - { - // The channel exists even though its settings were refused. Say so and give - // its index, otherwise a retry would leave a second one behind. - throw MCPToolError(QString("The %1 channel was created as channel %2 of device set %3, but its initial " - "settings were refused, so it is left with defaults: %4. Use set_channel_settings to correct it, " - "or delete_channel to remove it. Do not call add_channel again.") - .arg(channelType).arg(channelIndex).arg(deviceSetIndex).arg(e.message)); - } - - result["changed"] = patched["changed"]; - - if (patched.contains("warning")) { - result["warning"] = patched["warning"]; - } - } - - return result; - }); - - add("delete_channel", - "Remove a channel from a device set. Channels with a higher index are renumbered down by one.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"channelIndex", channelIndexProp} - }, {"deviceSetIndex", "channelIndex"}), - [this](const QJsonObject& args) - { - int deviceSetIndex = argInt(args, "deviceSetIndex"); - - // Waits for the channel itself to disappear. Waiting for the removed signal would - // sit out the whole timeout for the last channel of a device set, which the device - // set drops from its list before MainCore can look it up to signal it. - deleteChannelAndWait(deviceSetIndex, argInt(args, "channelIndex")); - QJsonObject result; - result["deviceSetIndex"] = deviceSetIndex; - result["channelCount"] = channelCount(deviceSetIndex); - return result; - }); - - add("get_channel_settings", - "Get the settings of a channel. The keys depend on the channel type. inputFrequencyOffset is the channel frequency relative to the device centre frequency in Hz.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"channelIndex", channelIndexProp} - }, {"deviceSetIndex", "channelIndex"}), - [this](const QJsonObject& args) { return getChannelSettings(argInt(args, "deviceSetIndex"), argInt(args, "channelIndex")); }); - - add("set_channel_settings", - "Change some settings of a channel. Give only the keys to change, e.g. {\"inputFrequencyOffset\": 25000, \"squelch\": -40}. " - "Use describe_settings with the channel type to learn the valid keys. Returns the keys changed with their applied values.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"channelIndex", channelIndexProp}, - {"settings", objProp("Object with the settings keys to change and their new values")} - }, {"deviceSetIndex", "channelIndex", "settings"}), - [this](const QJsonObject& args) - { - return patchChannelSettings(argInt(args, "deviceSetIndex"), argInt(args, "channelIndex"), argObject(args, "settings")); - }); - - add("get_channel_report", - "Get the live report of a channel: signal level, squelch state, decoder statistics and so on, depending on the channel type. " - "Omit channelIndex for the reports of every channel of the device set. " - "For DAB, wait briefly after selecting a programme or changing receiver gain and then read the report again. Do not accept " - "sync or audioActive alone as proof of clean reception: if synchronized audio has SNR at or below 0 dB, RTL-SDR overload " - "is likely, so reduce gain through its supported values and keep the setting that gives the best positive SNR.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"channelIndex", intProp("Index of the channel within the device set; omit for all channels")} - }, {"deviceSetIndex"}), - [this](const QJsonObject& args) - { - int deviceSetIndex = argInt(args, "deviceSetIndex"); - SWGSDRangel::SWGErrorResponse error; - error.init(); - - if (hasArg(args, "channelIndex")) - { - int channelIndex = argInt(args, "channelIndex"); - SWGSDRangel::SWGChannelReport response; - check(m_adapter->devicesetChannelReportGet(deviceSetIndex, channelIndex, response, error), error, "Get channel report"); - QJsonObject report = toJson(response); - addRdsHint(report, report.value("channelType").toString(), deviceSetIndex, channelIndex); - return report; - } - - SWGSDRangel::SWGChannelsDetail response; - check(m_adapter->devicesetChannelsReportGet(deviceSetIndex, response, error), error, "Get channels report"); - QJsonObject json = toJson(response); - QJsonArray channels = json.value("channels").toArray(); - - for (int i = 0; i < channels.size(); i++) - { - QJsonObject channel = channels.at(i).toObject(); - QJsonObject report = channel.value("report").toObject(); - // The channel type is on the entry here rather than on the report it carries - addRdsHint(report, channel.value("id").toString(), deviceSetIndex, channel.value("index").toInt()); - channel["report"] = report; - channels[i] = channel; - } - - json["channels"] = channels; - return json; - }); - - add("channel_action", - "Trigger an action on a channel. Only some channel types have actions. Use describe_settings to find the actions keys of the " - "channel type; pass them as the actions object.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"channelIndex", channelIndexProp}, - {"actions", objProp("Object with the action keys and values for this channel type")} - }, {"deviceSetIndex", "channelIndex", "actions"}), - [this](const QJsonObject& args) - { - int deviceSetIndex = argInt(args, "deviceSetIndex"); - int channelIndex = argInt(args, "channelIndex"); - QJsonObject actions = argObject(args, "actions"); - QJsonObject settings = getChannelSettings(deviceSetIndex, channelIndex); - QString channelType = settings["channelType"].toString(); - - if (!WebAPIUtils::m_channelTypeToActionsKey.contains(channelType)) { - throw MCPToolError(QString("Channel type %1 has no actions").arg(channelType)); - } - - QString actionsKey = WebAPIUtils::m_channelTypeToActionsKey[channelType]; - QJsonObject json; - json["channelType"] = channelType; - json["direction"] = settings["direction"].toInt(0); - json[actionsKey] = actions.contains(actionsKey) ? actions[actionsKey].toObject() : actions; - QStringList keys; - extractKeys(json[actionsKey].toObject(), keys); - - SWGSDRangel::SWGChannelActions query; - query.init(); - query.fromJsonObject(json); - SWGSDRangel::SWGSuccessResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->devicesetChannelActionsPost(deviceSetIndex, channelIndex, keys, query, response, error), error, "Channel action"); - return toJson(response); - }); -} - -void MCPTools::registerFeatureTools() -{ - add("add_feature", - "Add a feature (device independent plugin such as Map, AIS, APRS, SatelliteTracker) and optionally apply initial settings. " - "Returns the index of the new feature. featureType is an id from list_feature_types.", - schema({ - {"featureType", strProp("Feature type id from list_feature_types")}, - {"settings", objProp("Optional initial settings for the feature. Use describe_settings for the keys")} - }, {"featureType"}), - [this](const QJsonObject& args) - { - QString featureType = argString(args, "featureType"); - int featureIndex = addFeatureAndWait(featureType); - QJsonObject result; - result["featureIndex"] = featureIndex; - QJsonObject settings = argObject(args, "settings", false); - - if (!settings.isEmpty()) - { - QJsonObject patched; - - try - { - patched = patchFeatureSettings(featureIndex, settings); - } - catch (const MCPToolError& e) - { - throw MCPToolError(QString("The %1 feature was created as feature %2, but its initial settings were " - "refused, so it is left with defaults: %3. Use set_feature_settings to correct it, or " - "delete_feature to remove it. Do not call add_feature again.") - .arg(featureType).arg(featureIndex).arg(e.message)); - } - - result["changed"] = patched["changed"]; - - if (patched.contains("warning")) { - result["warning"] = patched["warning"]; - } - } - - return result; - }); - - add("delete_feature", - "Remove a feature. Features with a higher index are renumbered down by one.", - schema({{"featureIndex", featureIndexProp}}, {"featureIndex"}), - [this](const QJsonObject& args) - { - int featureIndex = argInt(args, "featureIndex"); - QMutexLocker deletionLock(&m_deletionMutex); - requireNotSelf(featureIndex, "deleted"); - const uint64_t target = featureUidAt(featureIndex); - SWGSDRangel::SWGSuccessResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->featuresetFeatureDelete(0, featureIndex, response, error), error, "Delete feature"); - - // FeatureSet drops the feature from its own list before MainCore looks it up, so - // removing the last feature emits no featureRemoved. Watch the feature itself go. - if (!waitFor([&]() { return !featureUids().contains(target); })) { - throw MCPToolError(QString("Timed out waiting for feature %1 to be removed").arg(featureIndex)); - } - - QJsonObject result; - result["featureCount"] = featureCount(); - return result; - }); - - add("get_feature_settings", - "Get the settings of a feature. The keys depend on the feature type.", - schema({{"featureIndex", featureIndexProp}}, {"featureIndex"}), - [this](const QJsonObject& args) { return getFeatureSettings(argInt(args, "featureIndex")); }); - - add("set_feature_settings", - "Change some settings of a feature. Give only the keys to change. Use describe_settings with the feature type to learn the valid keys.", - schema({ - {"featureIndex", featureIndexProp}, - {"settings", objProp("Object with the settings keys to change and their new values")} - }, {"featureIndex", "settings"}), - [this](const QJsonObject& args) { return patchFeatureSettings(argInt(args, "featureIndex"), argObject(args, "settings")); }); - - add("get_feature_report", - "Get the live report of a feature, depending on the feature type.", - schema({{"featureIndex", featureIndexProp}}, {"featureIndex"}), - [this](const QJsonObject& args) - { - SWGSDRangel::SWGFeatureReport response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->featuresetFeatureReportGet(0, argInt(args, "featureIndex"), response, error), error, "Get feature report"); - return toJson(response); - }); - - add("start_feature", - "Start a feature. Most features must be started to do anything, but the passive ones - AIS, AMBE, AntennaTools, " - "APRS, FreqDisplay, LimeRFE, Map, Radiosonde, RemoteControl and SkyMap - have no run state, work as soon as they " - "are configured and always report idle. Starting one of those is answered without doing anything.", - schema({{"featureIndex", featureIndexProp}}, {"featureIndex"}), - [this](const QJsonObject& args) { return featureState(argInt(args, "featureIndex"), 1); }); - - add("stop_feature", - "Stop a feature.", - schema({{"featureIndex", featureIndexProp}}, {"featureIndex"}), - [this](const QJsonObject& args) - { - int featureIndex = argInt(args, "featureIndex"); - requireNotSelf(featureIndex, "stopped"); - return featureState(featureIndex, 0); - }); - - add("feature_action", - "Trigger an action on a feature. Use describe_settings to find the actions keys of the feature type; pass them as the actions object.", - schema({ - {"featureIndex", featureIndexProp}, - {"actions", objProp("Object with the action keys and values for this feature type")} - }, {"featureIndex", "actions"}), - [this](const QJsonObject& args) - { - int featureIndex = argInt(args, "featureIndex"); - QJsonObject actions = argObject(args, "actions"); - QJsonObject settings = getFeatureSettings(featureIndex); - QString featureType = settings["featureType"].toString(); - - if (!WebAPIUtils::m_featureTypeToActionsKey.contains(featureType)) { - throw MCPToolError(QString("Feature type %1 has no actions").arg(featureType)); - } - - QString actionsKey = WebAPIUtils::m_featureTypeToActionsKey[featureType]; - QJsonObject json; - json["featureType"] = featureType; - json[actionsKey] = actions.contains(actionsKey) ? actions[actionsKey].toObject() : actions; - QStringList keys; - extractKeys(json[actionsKey].toObject(), keys); - - SWGSDRangel::SWGFeatureActions query; - query.init(); - query.fromJsonObject(json); - SWGSDRangel::SWGSuccessResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->featuresetFeatureActionsPost(0, featureIndex, keys, query, response, error), error, "Feature action"); - return toJson(response); - }); -} - -void MCPTools::registerPresetTools() -{ - add("list_presets", - "List the saved device set presets. A preset stores a device set's device and channel settings and is identified by group name, " - "name, centre frequency and type (R for rx, T for tx, M for MIMO).", - schema(QJsonObject()), - [this](const QJsonObject&) { return getPresets(); }); - - add("load_preset", - "Load a preset into a device set, replacing its device settings and channels. The preset type must match the device set direction.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"groupName", strProp("Preset group name")}, - {"name", strProp("Preset name")}, - {"centerFrequency", numProp("Preset centre frequency in Hz. Only needed when several presets share the group and name")}, - {"type", strProp("Preset type R, T or M. Only needed when several presets share the group and name")} - }, {"deviceSetIndex", "groupName", "name"}), - [this](const QJsonObject& args) - { - int deviceSetIndex = argInt(args, "deviceSetIndex"); - QJsonObject identifier = presetIdentifier(args, deviceSetIndex, false); - SWGSDRangel::SWGPresetTransfer query; - query.setDeviceSetIndex(deviceSetIndex); - SWGSDRangel::SWGPresetIdentifier *preset = new SWGSDRangel::SWGPresetIdentifier(); - preset->setGroupName(new QString(identifier["groupName"].toString())); - preset->setName(new QString(identifier["name"].toString())); - preset->setType(new QString(identifier["type"].toString())); - preset->setCenterFrequency((qint64) identifier["centerFrequency"].toDouble()); - query.setPreset(preset); - SWGSDRangel::SWGPresetIdentifier response; - response.init(); - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->instancePresetPatch(query, response, error), error, "Load preset"); - pause(500); // Loading replaces the channels; give it a moment before the caller looks - QJsonObject result; - result["loaded"] = toJson(response); - result["deviceSet"] = getDeviceSet(deviceSetIndex); - return result; - }); - - add("save_preset", - "Save the current device settings and channels of a device set as a preset. Updates the preset if one with the same group, name, " - "centre frequency and type exists, otherwise creates it.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"groupName", strProp("Preset group name")}, - {"name", strProp("Preset name")} - }, {"deviceSetIndex", "groupName", "name"}), - [this](const QJsonObject& args) - { - int deviceSetIndex = argInt(args, "deviceSetIndex"); - QJsonObject identifier = presetIdentifier(args, deviceSetIndex, true); - SWGSDRangel::SWGPresetTransfer query; - query.setDeviceSetIndex(deviceSetIndex); - SWGSDRangel::SWGPresetIdentifier *preset = new SWGSDRangel::SWGPresetIdentifier(); - preset->setGroupName(new QString(identifier["groupName"].toString())); - preset->setName(new QString(identifier["name"].toString())); - preset->setType(new QString(identifier["type"].toString())); - preset->setCenterFrequency((qint64) identifier["centerFrequency"].toDouble()); - query.setPreset(preset); - SWGSDRangel::SWGPresetIdentifier response; - response.init(); - SWGSDRangel::SWGErrorResponse error; - error.init(); - bool exists = identifier["exists"].toBool(); - - if (exists) { - check(m_adapter->instancePresetPut(query, response, error), error, "Update preset"); - } else { - check(m_adapter->instancePresetPost(query, response, error), error, "Create preset"); - } - - QJsonObject result; - result["preset"] = toJson(response); - result["created"] = !exists; - return result; - }); - - add("list_configurations", - "List the saved configurations. A configuration stores the whole instance: all device sets, features and workspaces.", - schema(QJsonObject()), - [this](const QJsonObject&) { return getConfigurations(); }); - - add("load_configuration", - "Load a saved configuration, replacing all current device sets and features.", - schema({ - {"groupName", strProp("Configuration group name")}, - {"name", strProp("Configuration name")} - }, {"groupName", "name"}), - [this](const QJsonObject& args) - { - SWGSDRangel::SWGConfigurationIdentifier response; - response.setGroupName(new QString(argString(args, "groupName"))); - response.setName(new QString(argString(args, "name"))); - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->instanceConfigurationPatch(response, error), error, "Load configuration"); - pause(1000); // Loading rebuilds everything - QJsonObject result; - result["configuration"] = toJson(response); - result["instance"] = getInstanceSummary(); - return result; - }); - - add("save_configuration", - "Save the whole current instance as a configuration. Updates the configuration if one with the same group and name exists, otherwise creates it.", - schema({ - {"groupName", strProp("Configuration group name")}, - {"name", strProp("Configuration name")} - }, {"groupName", "name"}), - [this](const QJsonObject& args) - { - QString groupName = argString(args, "groupName"); - QString name = argString(args, "name"); - bool exists = false; - - for (const auto& groupValue : getConfigurations()["groups"].toArray()) - { - QJsonObject group = groupValue.toObject(); - - if (group["groupName"].toString() != groupName) { - continue; - } - - for (const auto& item : group["configurations"].toArray()) - { - if (item.toObject()["name"].toString() == name) { - exists = true; - } - } - } - - SWGSDRangel::SWGConfigurationIdentifier response; - response.setGroupName(new QString(groupName)); - response.setName(new QString(name)); - SWGSDRangel::SWGErrorResponse error; - error.init(); - - if (exists) { - check(m_adapter->instanceConfigurationPut(response, error), error, "Update configuration"); - } else { - check(m_adapter->instanceConfigurationPost(response, error), error, "Create configuration"); - } - - QJsonObject result; - result["configuration"] = toJson(response); - result["created"] = !exists; - return result; - }); -} - -void MCPTools::registerWorkspaceTools() -{ - add("add_workspace", - "GUI only: add a new workspace (a tabbed area holding device, channel and feature windows). Workspaces are numbered from 0.", - schema(QJsonObject()), - [this](const QJsonObject&) - { - SWGSDRangel::SWGSuccessResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->instanceWorkspacePost(response, error), error, "Add workspace"); - return toJson(response); - }); - - add("delete_empty_workspaces", - "GUI only: remove all workspaces that contain no windows.", - schema(QJsonObject()), - [this](const QJsonObject&) - { - SWGSDRangel::SWGSuccessResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->instanceWorkspaceDelete(response, error), error, "Delete empty workspaces"); - return toJson(response); - }); - - add("arrange_workspace", - "GUI only: arrange the windows of a workspace, as its title bar buttons do. cascade, tile, stackVertical and stack " - "rearrange them once and turn auto stacking and tabs off; autostack stacks them now and again whenever a window is " - "added or resized, until another arrangement is asked for; tab shows one window at a time with a tab for each. " - "stack is the usual choice: devices, spectra and channels in columns.", - schema({ - {"workspaceIndex", intProp("Index of the workspace, from 0")}, - {"arrange", enumProp("cascade, tile, stackVertical, stack, autostack or tab", {"cascade", "tile", "stackVertical", "stack", "autostack", "tab"})} - }, {"workspaceIndex", "arrange"}), - [this](const QJsonObject& args) - { - SWGSDRangel::SWGWorkspaceActions query; - query.init(); - query.setArrange(new QString(argString(args, "arrange"))); - SWGSDRangel::SWGSuccessResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->workspaceActionsPost(argInt(args, "workspaceIndex"), query, response, error), error, "Arrange workspace"); - return toJson(response); - }); - - add("list_windows", - "GUI only: every window, with its kind (device, spectrum, channel or feature), indices, title, workspace and whether it " - "is hidden. A hidden window is still running; set_workspace with hidden false shows it again.", - schema({}), - [this](const QJsonObject&) - { - SWGSDRangel::SWGWindowList response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->instanceWindowsGet(response, error), error, "List windows"); - return toJson(response); - }); - - add("set_workspace", - "GUI only: move a window to a workspace, hide it, or show it again. kind is device, spectrum or channel (with " - "deviceSetIndex, plus channelIndex for a channel) or feature (with featureIndex). Give workspaceIndex to move, hidden " - "to hide (true) or show (false), or both. Showing a window raises it and shows the workspace holding it. Hiding a " - "window does not stop it: a hidden demodulator still plays audio. list_windows shows what is hidden.", - schema({ - {"kind", strProp("device, spectrum, channel or feature")}, - {"workspaceIndex", intProp("Workspace to move the window to. Optional")}, - {"hidden", prop("boolean", "true hides the window, false shows it. Optional")}, - {"deviceSetIndex", intProp("For device, spectrum and channel")}, - {"channelIndex", intProp("For channel")}, - {"featureIndex", intProp("For feature")} - }, {"kind"}), - [this](const QJsonObject& args) - { - QString kind = argString(args, "kind").trimmed().toLower(); - - if (!hasArg(args, "workspaceIndex") && !hasArg(args, "hidden")) { - throw MCPToolError("Give workspaceIndex to move the window, hidden to hide or show it, or both"); - } - - // -1 for what was not asked for, as the Web API's own validator passes it - SWGSDRangel::SWGWorkspaceInfo query; - query.setIndex(hasArg(args, "workspaceIndex") ? argInt(args, "workspaceIndex") : -1); - query.setHidden(hasArg(args, "hidden") ? (argBool(args, "hidden", false) ? 1 : 0) : -1); - SWGSDRangel::SWGSuccessResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - - if (kind == "device") { - check(m_adapter->devicesetDeviceWorkspacePut(argInt(args, "deviceSetIndex"), query, response, error), error, "Set device workspace"); - } else if (kind == "spectrum") { - check(m_adapter->devicesetSpectrumWorkspacePut(argInt(args, "deviceSetIndex"), query, response, error), error, "Set spectrum workspace"); - } else if (kind == "channel") { - check(m_adapter->devicesetChannelWorkspacePut(argInt(args, "deviceSetIndex"), argInt(args, "channelIndex"), query, response, error), error, "Set channel workspace"); - } else if (kind == "feature") { - check(m_adapter->featuresetFeatureWorkspacePut(argInt(args, "featureIndex"), query, response, error), error, "Set feature workspace"); - } else { - throw MCPToolError("kind must be device, spectrum, channel or feature"); - } - - return toJson(response); - }); -} - -void MCPTools::registerCaptureTools() -{ - - add("get_server_status", - "This server's own state, in one call: the capture directory and any recordings running; which channels and features " - "feed packets and map items and how much has arrived; and the client event streams (open streams, subscriptions, " - "notifications sent). Open a stream with an HTTP GET on the MCP endpoint with Accept: text/event-stream, then " - "resources/subscribe.", - schema(QJsonObject()), - [this](const QJsonObject&) - { - QJsonObject result; - result["capture"] = m_capture.status(); - result["dataFeed"] = m_dataFeed.getStatus(); - result["streams"] = m_streams ? m_streams->status() : QJsonObject(); - return result; - }); - - add("capture_audio", - QString("Record the demodulated audio of a channel to a WAV file and report where it went, how loud it was and whether it " - "was silent. Works with demodulators that feed the Demod Analyzer, such as NFMDemod, AMDemod, SSBDemod, WFMDemod, " - "BFMDemod, DSDDemod and M17Demod. The device must be running. This call blocks for the duration, so it is limited " - "to %1 seconds. Set inline to true (up to %2 seconds) to also get the audio back as base64 for playing directly: " - "a mono 16 kHz copy, small enough for a tool result, while the file keeps the full rate.") - .arg(MCPCapture::m_maxBlockingSeconds).arg(MCPCapture::m_maxInlineSeconds), - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"channelIndex", channelIndexProp}, - {"seconds", bounded(numProp(QString("How long to record for, up to %1").arg(MCPCapture::m_maxBlockingSeconds)), 0.1, MCPCapture::m_maxBlockingSeconds)}, - {"fileName", strProp("File name relative to the capture directory. The .wav extension is added. Default: audio_")}, - {"inline", prop("boolean", QString("Also return the audio as base64 in audioBase64, as a mono 16 kHz WAV. Only for clips of %1 seconds or less. Default false").arg(MCPCapture::m_maxInlineSeconds))} - }, {"deviceSetIndex", "channelIndex", "seconds"}), - [this](const QJsonObject& args) - { - int deviceSetIndex = argInt(args, "deviceSetIndex"); - int channelIndex = argInt(args, "channelIndex"); - double seconds = argDouble(args, "seconds"); - bool inlineAudio = argBool(args, "inline", false); - - if ((seconds <= 0) || (seconds > MCPCapture::m_maxBlockingSeconds)) { - throw MCPToolError(QString("seconds must be between 0 and %1").arg(MCPCapture::m_maxBlockingSeconds)); - } - - if (inlineAudio && (seconds > MCPCapture::m_maxInlineSeconds)) { - throw MCPToolError(QString("inline audio is only available for %1 seconds or less").arg(MCPCapture::m_maxInlineSeconds)); - } - - QJsonObject state = deviceState(deviceSetIndex, 0, -1); - - if (state["state"].toString() != "running") { - throw MCPToolError("The device is not running, so there is no audio to record. Call start_device first."); - } - - return m_capture.captureAudio(deviceSetIndex, channelIndex, seconds, - argString(args, "fileName", false), inlineAudio); - }); - - add("start_iq_recording", - "Start recording baseband IQ samples to a file. Adds a FileSink channel to the device set unless channelIndex names an " - "existing one, and starts it recording. The device must be running for samples to be written. Recording continues until " - "stop_iq_recording, so use this for long captures and record_iq for short ones. Files are written under the capture " - "directory shown by get_server_status; fileName is relative to it.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"fileName", strProp("File name relative to the capture directory. A timestamp and the .sdriq extension are added. Default: iq_")}, - {"frequencyOffset", intProp("Channel frequency offset from the device centre frequency in Hz. Default 0, which records the full baseband centred on the device frequency")}, - {"log2Decim", bounded(intProp("Decimation as a power of two: 0 records at the device sample rate, 1 halves it, and so on. Default 0"), 0, 6)}, - {"channelIndex", intProp("Use this existing FileSink channel instead of adding one")} - }, {"deviceSetIndex"}), - [this](const QJsonObject& args) - { - int deviceSetIndex = argInt(args, "deviceSetIndex"); - bool created = !hasArg(args, "channelIndex"); - - // A bad file name is refused before a channel is added for it - m_capture.checkFileName(argString(args, "fileName", false), "iq"); - - int channelIndex = created ? addChannelAndWait(deviceSetIndex, "FileSink") : argInt(args, "channelIndex"); - const uint64_t channel = created ? channelUidAt(deviceSetIndex, channelIndex) : 0; - - try - { - QJsonObject result = m_capture.startIQRecording(deviceSetIndex, channelIndex, - argString(args, "fileName", false), argInt(args, "frequencyOffset", false, 0), - argInt(args, "log2Decim", false, 0)); - result["channelCreated"] = created; - QJsonObject state = deviceState(deviceSetIndex, 0, -1); - - if (state["state"].toString() != "running") { - result["warning"] = "The device is not running, so no samples will be recorded. Call start_device."; - } - - return result; - } - catch (const MCPToolError&) - { - // Do not leave a channel behind when the recording could not be set up. By - // identity: a concurrent listen or scan may have renumbered it meanwhile - if (created) { - try { deleteChannelObjectAndWait(channel); } catch (const MCPToolError&) {} - } - - throw; - } - }); - - add("stop_iq_recording", - "Stop an IQ recording started with start_iq_recording and report the files written, with their size and duration.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"channelIndex", intProp("Index of the FileSink channel that is recording")}, - {"deleteChannel", prop("boolean", "Delete the FileSink channel afterwards. Default false")} - }, {"deviceSetIndex", "channelIndex"}), - [this](const QJsonObject& args) - { - int deviceSetIndex = argInt(args, "deviceSetIndex"); - int channelIndex = argInt(args, "channelIndex"); - const uint64_t channel = channelUidAt(deviceSetIndex, channelIndex); - QJsonObject result = m_capture.stopIQRecording(deviceSetIndex, channelIndex); - bool deleteChannel = argBool(args, "deleteChannel", false); - - if (deleteChannel) - { - deleteChannelObjectAndWait(channel); - result["channelDeleted"] = true; - } - - return result; - }); - - add("record_iq", - QString("Record baseband IQ samples for a fixed number of seconds and return the files written. Adds a FileSink channel, " - "records, stops and removes the channel again. This call blocks for the duration, so it is limited to %1 seconds; " - "for longer captures use start_iq_recording and stop_iq_recording. The device must already be running. " - "Note that IQ files are large: roughly 4 bytes per sample per second of the device sample rate.") - .arg(MCPCapture::m_maxBlockingSeconds), - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"seconds", bounded(numProp(QString("How long to record for, up to %1").arg(MCPCapture::m_maxBlockingSeconds)), 0.1, MCPCapture::m_maxBlockingSeconds)}, - {"fileName", strProp("File name relative to the capture directory. A timestamp and the .sdriq extension are added")}, - {"frequencyOffset", intProp("Channel frequency offset from the device centre frequency in Hz. Default 0")}, - {"log2Decim", bounded(intProp("Decimation as a power of two. Default 0"), 0, 6)} - }, {"deviceSetIndex", "seconds"}), - [this](const QJsonObject& args) - { - int deviceSetIndex = argInt(args, "deviceSetIndex"); - double seconds = argDouble(args, "seconds"); - - if ((seconds <= 0) || (seconds > MCPCapture::m_maxBlockingSeconds)) - { - throw MCPToolError(QString("seconds must be between 0 and %1. For a longer capture use start_iq_recording and stop_iq_recording") - .arg(MCPCapture::m_maxBlockingSeconds)); - } - - QJsonObject state = deviceState(deviceSetIndex, 0, -1); - - if (state["state"].toString() != "running") { - throw MCPToolError("The device is not running, so there is nothing to record. Call start_device first."); - } - - // A bad file name is refused before a channel is added for it - m_capture.checkFileName(argString(args, "fileName", false), "iq"); - - int channelIndex = addChannelAndWait(deviceSetIndex, "FileSink"); - - // This call sleeps for up to half a minute and is not serialised against the other - // tools, so another request can delete a channel and renumber this one meanwhile. - // Everything after the sleep therefore works from the channel's UID, not its index. - const uint64_t channel = channelUidAt(deviceSetIndex, channelIndex); - - if (channel == 0) // cannot happen, but do not leave the channel behind if it does - { - try { deleteChannelAndWait(deviceSetIndex, channelIndex); } catch (const MCPToolError&) {} - - throw MCPToolError("The FileSink channel went away as soon as it was added"); - } - - QJsonObject result; - - try - { - QJsonObject started = m_capture.startIQRecording(deviceSetIndex, channelIndex, - argString(args, "fileName", false), argInt(args, "frequencyOffset", false, 0), - argInt(args, "log2Decim", false, 0)); - pause((int) (seconds * 1000.0)); - result = m_capture.stopIQRecording(channel); - result["fileBase"] = started["fileBase"]; - result["requestedSeconds"] = seconds; - } - catch (const MCPToolError&) - { - try { deleteChannelObjectAndWait(channel); } catch (const MCPToolError&) {} - throw; - } - - deleteChannelObjectAndWait(channel); - - if (result["files"].toArray().isEmpty()) { - result["warning"] = "No files were written. Check that the device is running and producing samples."; - } - - return result; - }); -} - -// --------------------------------------------------------------------------- -// Intent level tools: a whole task in one call -// -// Setting up a receiver with the object level tools takes an agent around ten round trips, -// each one a model turn. These do the common tasks in one, using the same helpers, and reply -// with a short summary rather than the objects they created. -// --------------------------------------------------------------------------- - -namespace { - -// What "listen to X in mode Y" needs: the demodulator, its initial settings and the smallest -// baseband that carries it. Values are the ones the receiving guide and readmes give. -struct ListenMode -{ - const char *m_alias; - const char *m_channelType; - int m_rfBandwidth; //!< Hz. Negative selects the lower sideband, as the SSB demodulator does - int m_minBaseband; //!< Hz - const char *m_settings; //!< JSON of further initial settings - int m_scanStep; //!< Hz. The channel spacing scan steps by unless told otherwise; 0 for a mode on fixed frequencies, which is not scanned for - const char *m_feature; //!< A feature the mode's output goes to, added if absent; null for none - int m_pairOffset; //!< Hz. Non-zero for a mode on two channels this far either side of the frequency, one demodulator each -}; - -const char *const bfmSettings = "{\"afBandwidth\":15000,\"audioStereo\":1,\"rdsActive\":1,\"volume\":4,\"squelch\":-60}"; -const char *const amSettings = "{\"afBandwidth\":3000,\"bandpassEnable\":1,\"volume\":4,\"squelch\":-60}"; - -const ListenMode listenModes[] = { - // Broadcast FM asks for twice the baseband its channel needs: a 180 kHz channel in a 256 kS/s - // baseband sits against the edge of the decimation filters, and RDS suffers first; it also - // leaves room to put the channel clear of the device's DC spike - {"bfm", "BFMDemod", 180000, 512000, bfmSettings, 100000, nullptr, 0}, - {"fm", "BFMDemod", 180000, 512000, bfmSettings, 100000, nullptr, 0}, - {"wfm", "WFMDemod", 150000, 512000, "{\"volume\":2,\"squelch\":-60}", 100000, nullptr, 0}, - {"nfm", "NFMDemod", 12500, 48000, "{\"afBandwidth\":3000,\"volume\":2}", 12500, nullptr, 0}, - {"am", "AMDemod", 8000, 48000, amSettings, 25000, nullptr, 0}, - {"airband", "AMDemod", 8000, 48000, amSettings, 25000, nullptr, 0}, - {"ssb", "SSBDemod", 3000, 48000, "{\"volume\":2}", 3000, nullptr, 0}, - {"usb", "SSBDemod", 3000, 48000, "{\"volume\":2}", 3000, nullptr, 0}, - {"lsb", "SSBDemod", -3000, 48000, "{\"volume\":2}", 3000, nullptr, 0}, - {"dab", "DABDemod", 0, 2048000, "{}", 0, nullptr, 0}, - {"adsb", "ADSBDemod", 0, 2400000, "{}", 0, nullptr, 0}, - {"ais", "AISDemod", 0, 128000, "{}", 0, "AIS", 25000}, - {"dsc", "DSCDemod", 450, 48000, "{}", 0, nullptr, 0}, - // Digital voice: the DSD demodulator decides the standard from the baud rate, and its - // discriminator wants the maximum deviation of the standard, the readme's table: DMR 5.4, - // dPMR 2.7, D-Star 3.5, YSF 7.0, NXDN 2.7 kHz. dsd alone is the plugin's defaults, which - // are D-Star's, set explicitly so that a retuned demodulator gets them too. DMR carries - // two time slots, so both are switched on - {"dsd", "DSDDemod", 12500, 48000, "{\"fmDeviation\":3500,\"baudRate\":4800}", 12500, nullptr, 0}, - {"dmr", "DSDDemod", 12500, 48000, "{\"fmDeviation\":5400,\"baudRate\":4800,\"slot1On\":1,\"slot2On\":1}", 12500, nullptr, 0}, - {"dpmr", "DSDDemod", 6250, 48000, "{\"fmDeviation\":2700,\"baudRate\":2400}", 6250, nullptr, 0}, - {"dstar", "DSDDemod", 12500, 48000, "{\"fmDeviation\":3500,\"baudRate\":4800}", 12500, nullptr, 0}, - {"ysf", "DSDDemod", 12500, 48000, "{\"fmDeviation\":7000,\"baudRate\":4800}", 12500, nullptr, 0}, - {"nxdn", "DSDDemod", 12500, 48000, "{\"fmDeviation\":2700,\"baudRate\":4800}", 12500, nullptr, 0}, - {"nxdn24", "DSDDemod", 6250, 48000, "{\"fmDeviation\":2700,\"baudRate\":2400}", 6250, nullptr, 0}, - {"pager", "PagerDemod", 20000, 48000, "{}", 12500, nullptr, 0}, - {"pocsag", "PagerDemod", 20000, 48000, "{}", 12500, nullptr, 0}, - {"sonde", "RadiosondeDemod", 9600, 48000, "{}", 10000, "Radiosonde", 0}, - {"radiosonde", "RadiosondeDemod", 9600, 48000, "{}", 10000, "Radiosonde", 0}, - // AX.25 packet at 1200 baud AFSK. APRS is the same signal on a fixed regional frequency, - // with the APRS feature to plot the stations - {"packet", "PacketDemod", 12500, 48000, "{}", 0, nullptr, 0}, - {"aprs", "PacketDemod", 12500, 48000, "{}", 0, "APRS", 0}, -}; - -const char *const listenModeList = "bfm, wfm, nfm, am, ssb, usb, lsb, dab, adsb, ais, dsc, dsd, dmr, dpmr, dstar, ysf, nxdn, pager, sonde, packet, aprs"; - -// The feature a demodulator of this type feeds, by the modes that add one; null for none -const char *featureForChannelType(const QString& channelType) -{ - for (const ListenMode& mode : listenModes) - { - if (mode.m_feature && (channelType == QLatin1String(mode.m_channelType))) { - return mode.m_feature; - } - } - - return nullptr; -} - -// What listen and scan say about the features a reclaim took away -QStringList featureNotes(const QStringList& reclaimedFeatures) -{ - if (reclaimedFeatures.isEmpty()) { - return QStringList(); - } - - return QStringList(QString("Removed the %1 feature%2 an earlier listen added, as nothing feeds %3 now.") - .arg(reclaimedFeatures.join(" and ")).arg(reclaimedFeatures.size() == 1 ? "" : "s") - .arg(reclaimedFeatures.size() == 1 ? "it" : "them")); -} - -const ListenMode *findListenMode(const QString& alias) -{ - for (const ListenMode& mode : listenModes) - { - if (alias.compare(QLatin1String(mode.m_alias), Qt::CaseInsensitive) == 0) { - return &mode; - } - } - - return nullptr; -} - -// The device rate and decimation that give at least the wanted baseband. These are the rates -// an RTL-SDR runs reliably; DAB needs exactly 2.048 MS/s. -void rateFor(int minBaseband, int& devSampleRate, int& log2Decim) -{ - if (minBaseband <= 256000) { devSampleRate = 1024000; log2Decim = 2; } - else if (minBaseband <= 512000) { devSampleRate = 1024000; log2Decim = 1; } - else if (minBaseband <= 1024000) { devSampleRate = 1024000; log2Decim = 0; } - else if (minBaseband <= 2048000) { devSampleRate = 2048000; log2Decim = 0; } - else { devSampleRate = 2400000; log2Decim = 0; } -} - -// The baseband a channel type needs, from the table listen uses, so that there is one set of -// numbers rather than two that can disagree. 0 when the type is not in it. -int minimumBasebandFor(const QString& channelType) -{ - for (const ListenMode& mode : listenModes) - { - if (channelType.compare(QLatin1String(mode.m_channelType), Qt::CaseInsensitive) == 0) { - return mode.m_minBaseband; - } - } - - return 0; -} - -// Devices that are not radios attached to this machine, skipped when choosing one automatically -const QStringList virtualDeviceTypes = { - "TestSource", "FileInput", "SigMFFileInput", "LocalInput", "RemoteInput", "RemoteTCPInput", - "KiwiSDR", "AudioInput", "AaroniaRTSA", "AndroidSdrDriverInput" -}; - -// The type specific sub-object of a settings reply, e.g. the rtlSdrSettings of a device -QJsonObject settingsOf(const QJsonObject& reply) -{ - return reply[findSettingsKey(reply)].toObject(); -} - -// A signal level from a channel report, whatever the plugin calls it -bool signalLevel(const QJsonObject& report, double& db) -{ - for (const QString& key : report.keys()) - { - if (!key.endsWith("Report") || !report[key].isObject()) { - continue; - } - - QJsonObject sub = report[key].toObject(); - - for (const QString& k : sub.keys()) - { - if ((k.contains("PowerDB", Qt::CaseInsensitive) || (k == "rssi")) && sub[k].isDouble()) - { - db = sub[k].toDouble(); - return true; - } - } - } - - return false; -} - -} // namespace - -// A channel whose baseband is too narrow produces nothing, or silence, with no error anywhere: -// the demodulator simply never sees the signal. The rule is in this server's instructions, but -// it is read once at the start of a conversation and needed much later, so it is repeated here, -// where the numbers are known and the fix can be named. -QString MCPTools::basebandWarning(int deviceSetIndex, const QString& channelType) -{ - int needed = minimumBasebandFor(channelType); - - if (needed <= 0) { - return QString(); // nothing known about what this type needs - } - - QJsonObject settings; - - try - { - settings = settingsOf(getDeviceSettings(deviceSetIndex)); - } - catch (const MCPToolError&) - { - return QString(); // no device, or it cannot be read: not this call's problem to report - } - - // Only devices that express their rate this way can be checked. Saying nothing is better - // than guessing at a device whose keys are not these - if (!settings.contains("devSampleRate") || !settings.contains("log2Decim")) { - return QString(); - } - - int baseband = settings["devSampleRate"].toInt() >> settings["log2Decim"].toInt(); - - if (baseband >= needed) { - return QString(); - } - - int wantedRate = 0; - int wantedDecim = 0; - rateFor(needed, wantedRate, wantedDecim); - - return QString("%1 needs a baseband of at least %2 Hz, but device set %3 provides %4 Hz, so the channel " - "cannot work as it stands. Call set_device_settings with devSampleRate %5 and log2Decim %6.") - .arg(channelType).arg(needed).arg(deviceSetIndex).arg(baseband).arg(wantedRate).arg(wantedDecim); -} - -QStringList MCPTools::basebandWarnings(int deviceSetIndex) -{ - QStringList warnings; - QJsonObject deviceSet; - - try - { - deviceSet = getDeviceSet(deviceSetIndex); - } - catch (const MCPToolError&) - { - return warnings; - } - - QSet seen; - - for (const QJsonValue& value : deviceSet["channels"].toArray()) - { - QString channelType = value.toObject()["id"].toString(); - - if (channelType.isEmpty() || seen.contains(channelType)) { - continue; // several of a type would repeat the same sentence - } - - seen.insert(channelType); - QString warning = basebandWarning(deviceSetIndex, channelType); - - if (!warning.isEmpty()) { - warnings.append(warning); - } - } - - return warnings; -} - -QStringList MCPTools::channelTypeIds(int direction) -{ - SWGSDRangel::SWGInstanceChannelsResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->instanceChannels(direction, response, error), error, "List channel types"); - QStringList ids; - - for (const QJsonValue& v : toJson(response)["channels"].toArray()) { - ids.append(v.toObject()["id"].toString()); - } - - return ids; -} - -void MCPTools::relocateChannel(uint64_t channelUid, int& deviceSetIndex, int& channelIndex, const QString& what) -{ - if (!MCPCapture::locateChannel(channelUid, deviceSetIndex, channelIndex)) { - throw MCPToolError(QString("The %1 channel no longer exists: another request removed it, or its device set, " - "while this call was running").arg(what)); - } -} - -void MCPTools::trackIntentChannel(uint64_t channelUid) -{ - if (channelUid == 0) { - return; - } - - QMutexLocker locker(&m_intentMutex); - m_intentChannels.insert(channelUid); -} - -void MCPTools::untrackIntentChannel(uint64_t channelUid) -{ - QMutexLocker locker(&m_intentMutex); - m_intentChannels.remove(channelUid); -} - -QSet MCPTools::intentChannels() -{ - QMutexLocker locker(&m_intentMutex); - return m_intentChannels; -} - -// What a device set carries besides one channel, and which of it listen or scan put there. -// Read from the live device set rather than any earlier snapshot, as a reclaim in between -// changes both the indices and the answer -QList MCPTools::channelNotes(int deviceSetIndex, const QSet& except) -{ - const QSet intent = intentChannels(); - QList notes; - - for (const QJsonValue& v : getDeviceSet(deviceSetIndex)["channels"].toArray()) - { - QJsonObject channel = v.toObject(); - int index = channel["index"].toInt(); - const uint64_t uid = channelUidAt(deviceSetIndex, index); - - if ((uid != 0) && !except.contains(uid)) { - notes.append({uid, index, channel["id"].toString(), intent.contains(uid)}); - } - } - - return notes; -} - -QStringList MCPTools::reclaimIntentChannels(int deviceSetIndex, const QSet& keep) -{ - QStringList removed; - - // Each is deleted by identity, wherever it has been renumbered to by then, and highest - // index first so that the ids come out in the order the device set listed them - QList notes = channelNotes(deviceSetIndex); - - for (int i = notes.size() - 1; i >= 0; i--) - { - if (!notes[i].m_intent || keep.contains(notes[i].m_uid)) { - continue; - } - - try - { - deleteChannelObjectAndWait(notes[i].m_uid); - removed.prepend(notes[i].m_id); - } - catch (const MCPToolError&) {} - - // Tracked no longer either way: if it could not be deleted now it will not be later - untrackIntentChannel(notes[i].m_uid); - } - - return removed; -} - -// Retuning the demodulator a previous listen added is what a person would do, and spares the -// audio device and the GUI a close and reopen. Only when the intent channels of that type are -// exactly the count the mode uses (one, or two for a paired mode such as AIS), and no scan's -// FreqScanner is there to be driving them. The first is returned; a paired mode finds the -// other among the intent channels of the type -uint64_t MCPTools::reusableIntentChannel(int deviceSetIndex, const QString& channelType, int& channelIndex, int wanted) -{ - uint64_t candidate = 0; - int candidates = 0; - - for (const ChannelNote& note : channelNotes(deviceSetIndex)) - { - if (!note.m_intent) { - continue; - } - - if (note.m_id == "FreqScanner") { - return 0; - } - - if (note.m_id == channelType) - { - if (candidate == 0) - { - candidate = note.m_uid; - channelIndex = note.m_index; - } - - candidates++; - } - } - - return (candidates == wanted) ? candidate : 0; -} - -// A retune moves every channel on the device set, since each is an offset from the centre. A -// channel the user added is kept on the frequency it had when the new baseband holds it; an -// audio demodulator it cannot hold is removed, as all it could do is play noise; anything else -// is left, with a note, since a file sink or an analyser may be wanted regardless -MCPTools::RetuneOutcome MCPTools::retuneOtherChannels(int deviceSetIndex, double previousCentre, double centre, int baseband) -{ - RetuneOutcome outcome; - - if ((qint64) previousCentre == (qint64) centre) { - return outcome; - } - - static const QStringList audioDemods = { - "AMDemod", "BFMDemod", "DABDemod", "DATVDemod", "DSDDemod", "FreeDVDemod", "ILSDemod", "M17Demod", - "NFMDemod", "SSBDemod", "VORDemod", "VORDemodMC", "WFMDemod", "WDSPRx" - }; - - const QSet intent = intentChannels(); - QJsonObject set = getDeviceSet(deviceSetIndex); - - if (baseband <= 0) { - baseband = set["samplingDevice"].toObject()["bandwidth"].toInt(); - } - - struct Item { int m_index; QString m_id; uint64_t m_uid; qint64 m_offset; }; - QList items; - - for (const QJsonValue& v : set["channels"].toArray()) - { - QJsonObject channel = v.toObject(); - const int index = channel["index"].toInt(); - const uint64_t uid = channelUidAt(deviceSetIndex, index); - - if ((uid != 0) && !intent.contains(uid)) { - items.append({index, channel["id"].toString(), uid, (qint64) channel["deltaFrequency"].toDouble()}); - } - } - - // Highest index first, so that a removal does not renumber one still to be visited - for (int i = items.size() - 1; i >= 0; i--) - { - const Item& item = items[i]; - const qint64 wanted = (qint64) previousCentre + item.m_offset; // where it was listening - const qint64 offset = wanted - (qint64) centre; - const QString where = QString("%1 at %2 MHz").arg(item.m_id).arg(wanted / 1e6, 0, 'f', 3); - - // The offset key differs by type: most have inputFrequencyOffset, the Channel Analyzer - // frequency, ATV intFrequencyOffset, DATV centerFrequency; a sink or a scanner has none - // and is left alone. Read the live settings to find which, rather than guess - QString offsetKey; - - if ((baseband > 0) && (qAbs(offset) <= baseband * 0.45)) // a tenth kept clear at each edge - { - try - { - QJsonObject current = settingsOf(getChannelSettings(deviceSetIndex, item.m_index)); - - for (const char *key : {"inputFrequencyOffset", "frequency", "intFrequencyOffset", "centerFrequency"}) - { - if (current.contains(key)) - { - offsetKey = key; - break; - } - } - } - catch (const MCPToolError&) {} - } - - if (!offsetKey.isEmpty()) - { - try - { - QJsonObject partial; - partial[offsetKey] = (double) offset; - patchChannelSettings(deviceSetIndex, item.m_index, partial); - outcome.m_kept.append(where); - } - catch (const MCPToolError&) - { - outcome.m_stranded.append(where); - } - } - else if ((baseband > 0) && audioDemods.contains(item.m_id)) - { - try - { - deleteChannelObjectAndWait(item.m_uid); - outcome.m_removed.append(where); - } - catch (const MCPToolError&) - { - outcome.m_stranded.append(where); - } - } - else - { - outcome.m_stranded.append(where); - } - } - - return outcome; -} - -QStringList MCPTools::intentNotes(int deviceSetIndex, const QSet& added, const QStringList& reclaimed, - bool reused, double previousCentre, double centre, const RetuneOutcome& outcome) -{ - QStringList notes; - - if (!reclaimed.isEmpty()) - { - notes.append(QString("Removed %1 channel%2 (%3) that earlier listen or scan calls added to device set %4; pass replace false to keep them.") - .arg(reclaimed.size()).arg(reclaimed.size() == 1 ? "" : "s").arg(reclaimed.join(", ")).arg(deviceSetIndex)); - } - - // Read from the live device set rather than the snapshot pickReceiver made, which still - // lists whatever the reclaim has since removed - QStringList leftovers; - QStringList others; - - for (const ChannelNote& note : channelNotes(deviceSetIndex, added)) { - (note.m_intent ? leftovers : others).append(note.m_id); - } - - // Only possible with replace false, and then it is the caller's own trail - if (!leftovers.isEmpty()) - { - notes.append(QString("Device set %1 still has %2 channel%3 (%4) from earlier listen or scan calls, any audio ones still playing; cleanup removes them.") - .arg(deviceSetIndex).arg(leftovers.size()).arg(leftovers.size() == 1 ? "" : "s").arg(leftovers.join(", "))); - } - - // What the retune did to the channels the user added, and how to put back what it took - if (reused && ((qint64) previousCentre != (qint64) centre) - && !(outcome.m_kept.isEmpty() && outcome.m_removed.isEmpty() && outcome.m_stranded.isEmpty())) - { - QString note = QString("Retuned device set %1 from %2 to %3 MHz.").arg(deviceSetIndex) - .arg(previousCentre / 1e6, 0, 'f', 3).arg(centre / 1e6, 0, 'f', 3); - - if (!outcome.m_kept.isEmpty()) { - note += QString(" Kept %1 other channel%2 on frequency by moving the offset: %3.") - .arg(outcome.m_kept.size()).arg(outcome.m_kept.size() == 1 ? "" : "s").arg(outcome.m_kept.join(", ")); - } - - if (!outcome.m_removed.isEmpty()) { - note += QString(" Removed %1 audio demodulator%2 the new baseband could not hold, which would only have played noise: %3. " - "They were not added by listen or scan; add_channel puts one back.") - .arg(outcome.m_removed.size()).arg(outcome.m_removed.size() == 1 ? "" : "s").arg(outcome.m_removed.join(", ")); - } - - if (!outcome.m_stranded.isEmpty()) { - note += QString(" Left %1 other channel%2 that the new baseband does not hold, not being audio: %3. " - "set_channel_settings inputFrequencyOffset retunes one, delete_channel removes it.") - .arg(outcome.m_stranded.size()).arg(outcome.m_stranded.size() == 1 ? "" : "s").arg(outcome.m_stranded.join(", ")); - } - - notes.append(note); - } - - (void) others; - return notes; -} - -QJsonObject MCPTools::channelReport(int deviceSetIndex, int channelIndex) -{ - SWGSDRangel::SWGChannelReport response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->devicesetChannelReportGet(deviceSetIndex, channelIndex, response, error), error, "Get channel report"); - return toJson(response); -} - -void MCPTools::postChannelAction(int deviceSetIndex, int channelIndex, const QJsonObject& actions) -{ - QJsonObject settings = getChannelSettings(deviceSetIndex, channelIndex); - QString channelType = settings["channelType"].toString(); - - if (!WebAPIUtils::m_channelTypeToActionsKey.contains(channelType)) { - throw MCPToolError(QString("Channel type %1 has no actions").arg(channelType)); - } - - QJsonObject json; - json["channelType"] = channelType; - json["direction"] = settings["direction"].toInt(0); - json[WebAPIUtils::m_channelTypeToActionsKey[channelType]] = actions; - QStringList keys; - extractKeys(actions, keys); - - SWGSDRangel::SWGChannelActions query; - query.init(); - query.fromJsonObject(json); - SWGSDRangel::SWGSuccessResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->devicesetChannelActionsPost(deviceSetIndex, channelIndex, keys, query, response, error), error, "Channel action"); -} - -// Finds or creates a receive device set holding a suitable device and sets its sample rate. -// An existing set holding the same device is reused rather than fought for the hardware; the -// caller tunes the centre frequency and is told what else that set carries. -// Takes away the device set listen or scan created when the call fails before it is done -// with it, so a retry does not build another beside a half made one. Cleared on success -class NewDeviceSetGuard -{ -public: - NewDeviceSetGuard(MCPTools *tools, int deviceSetIndex) : - m_tools(tools), - m_deviceSetIndex(deviceSetIndex), - m_identity(deviceSetIndex >= 0 ? tools->deviceSetIdentity(deviceSetIndex) : 0) - {} - ~NewDeviceSetGuard() - { - if (m_deviceSetIndex >= 0) { - m_tools->discardNewDeviceSet(m_deviceSetIndex, m_identity); - } - } - void keep() { m_deviceSetIndex = -1; } - -private: - MCPTools *m_tools; - int m_deviceSetIndex; - uint64_t m_identity; //!< Of the set as it was when this call made it -}; - -QJsonObject MCPTools::pickReceiver(const QJsonObject& args, int minBaseband, const QSet& doomed, bool profileGain) -{ - SWGSDRangel::SWGInstanceDevicesResponse devicesResponse; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->instanceDevices(0, devicesResponse, error), error, "List devices"); - QJsonArray devices = toJson(devicesResponse)["devices"].toArray(); - - // Which device: the one the caller named; else the first real radio that was actually - // enumerated, which is the one with a serial number - some plugins list a placeholder - // entry for hardware that is not attached, and it has none; else anything - QJsonObject chosen; - QJsonObject fallback; - QString wanted = argString(args, "device", false).trimmed(); - - for (const QJsonValue& v : devices) - { - QJsonObject d = v.toObject(); - - if (!wanted.isEmpty()) - { - if ((d["serial"].toString().compare(wanted, Qt::CaseInsensitive) == 0) - || (d["displayedName"].toString().compare(wanted, Qt::CaseInsensitive) == 0) - || (d["hwType"].toString().compare(wanted, Qt::CaseInsensitive) == 0)) - { - chosen = d; - break; - } - } - else if (!virtualDeviceTypes.contains(d["hwType"].toString())) - { - if (!d["serial"].toString().isEmpty()) { chosen = d; break; } - if (fallback.isEmpty()) { fallback = d; } - } - } - - if (chosen.isEmpty() && wanted.isEmpty()) { - chosen = fallback.isEmpty() && !devices.isEmpty() ? devices.first().toObject() : fallback; - } - - if (chosen.isEmpty()) { - throw MCPToolError(QString("No receive device matches %1. list_available_devices shows what there is.").arg(wanted.isEmpty() ? "anything" : wanted)); - } - - QString hwType = chosen["hwType"].toString(); - QString serial = chosen["serial"].toString(); - - // Reuse a device set that already holds this device - int deviceSetIndex = -1; - QJsonArray otherChannels; - QJsonArray deviceSets = getInstanceSummary()["devicesetlist"].toObject()["deviceSets"].toArray(); - - for (const QJsonValue& v : deviceSets) - { - QJsonObject ds = v.toObject(); - QJsonObject sd = ds["samplingDevice"].toObject(); - - if (sd["direction"].toInt() != 0) { - continue; - } - - bool same = serial.isEmpty() ? (sd["hwType"].toString() == hwType) : (sd["serial"].toString() == serial); - - if (same) - { - deviceSetIndex = sd["index"].toInt(); - - // Channels the caller is about to remove are not ones the set has to go on - // serving, so they neither hold the baseband width up nor count as carried - for (const QJsonValue& c : ds["channels"].toArray()) - { - QJsonObject channel = c.toObject(); - - if (!doomed.contains(channelUidAt(deviceSetIndex, channel["index"].toInt()))) { - otherChannels.append(channel["id"].toString()); - } - } - - break; - } - } - - bool reused = deviceSetIndex >= 0; - - if (!reused) { - deviceSetIndex = addDeviceSetAndWait(0); - } - - // Until the caller has it, a set made here that cannot be finished is this function's to - // take away again - NewDeviceSetGuard newDeviceSet(this, reused ? -1 : deviceSetIndex); - - if (!reused) - { - QJsonObject select; - select["hwType"] = hwType; - - if (!serial.isEmpty()) { - select["serial"] = serial; - } - - selectDevice(deviceSetIndex, select); - } - - QJsonObject before = settingsOf(getDeviceSettings(deviceSetIndex)); - - // Only the devices whose rate keys and supported rates are known are set; others keep - // their configured rate and the caller is told to check it - QString rateKey; - - if (hwType == "RTLSDR") { - rateKey = "devSampleRate"; - } else if (hwType == "TestSource") { - rateKey = "sampleRate"; - } - - // A reused device set is already feeding its other channels the width it has. Widening it for - // the new channel leaves them working, narrowing it to what only the new one needs takes their - // signal away, so the width already configured is a floor rather than something to overwrite - int existingBaseband = 0; - - if (reused && !otherChannels.isEmpty() && !rateKey.isEmpty()) - { - int rate = before[rateKey].toInt(); - - if (rate > 0) { - existingBaseband = rate >> before["log2Decim"].toInt(); - } - } - - int devSampleRate = 0; - int log2Decim = 0; - rateFor(qMax(minBaseband, existingBaseband), devSampleRate, log2Decim); - QJsonObject partial; - QString rateNote; - int baseband = 0; - - if (!rateKey.isEmpty()) - { - baseband = devSampleRate >> log2Decim; - - if (baseband < existingBaseband) - { - // Wider than rateFor is able to ask for, so leave the rate alone altogether - baseband = existingBaseband; - rateNote = QString("Device set %1 was left at %2 S/s of baseband, which its other channels need.") - .arg(deviceSetIndex).arg(existingBaseband); - } - else - { - partial[rateKey] = devSampleRate; - partial["log2Decim"] = log2Decim; - - if (existingBaseband > minBaseband) { - rateNote = QString("Device set %1 was kept at %2 S/s of baseband rather than the %3 this channel needs, for its other channels.") - .arg(deviceSetIndex).arg(baseband).arg(minBaseband); - } - } - } - - // Only a device set this call created gets the receiver profile: one that was found is the - // user's, and its gain stays whatever they set - if (!reused && (hwType == "RTLSDR")) - { - partial["dcBlock"] = 1; - partial["iqImbalance"] = 1; - - // A fixed 40 dB when the caller is not about to measure one: the tuner's own AGC is - // unreliable on weak signals, and the default gain left the airband 35 dB down on what - // a hand-set receiver saw - if (profileGain) - { - partial["agc"] = 0; - partial["gain"] = 402; - rateNote = (rateNote.isEmpty() ? QString() : rateNote + " ") - + QString("Device set %1 is new, so its RTL-SDR was set to 40 dB gain with AGC off; set_device_settings changes it.") - .arg(deviceSetIndex); - } - } - - if (!partial.isEmpty()) { - patchDeviceSettings(deviceSetIndex, partial); - } - - QJsonObject result; - result["deviceSetIndex"] = deviceSetIndex; - result["hwType"] = hwType; - result["device"] = chosen["displayedName"].toString(); - result["reused"] = reused; - result["previousCentre"] = before["centerFrequency"].toDouble(); - result["otherChannels"] = otherChannels; - result["baseband"] = baseband; - result["rateNote"] = rateNote; - newDeviceSet.keep(); - return result; -} - -// The tune_gain tool, also run by listen and scan when they set up a receiver on a new -// device set or move one to another band -QJsonObject MCPTools::tuneGain(const QJsonObject& args) -{ - int deviceSetIndex = argInt(args, "deviceSetIndex"); - QJsonObject reply = getDeviceSettings(deviceSetIndex); - const QString hwType = reply["deviceHwType"].toString(); - QJsonObject settings = settingsOf(reply); - - if (deviceState(deviceSetIndex, 0, -1)["state"].toString() != "running") { - throw MCPToolError("The device is not running, so there is nothing to measure. start_device first."); - } - - // What this knows about each device's gain: the key, its manual AGC setting, and the - // values to try. Where a device has several gain stages the one before the mixer is - // tuned, as that is where overload happens; the rest keep their settings - struct Knob { QString key; QString agcKey; int agcOff; QList values; QString unit; QString note; }; - Knob knob; - const bool custom = hasArg(args, "gainKey"); - - if (custom) - { - knob.key = argString(args, "gainKey"); - knob.agcKey = argString(args, "agcKey", false); - knob.agcOff = 0; - knob.unit = "the key's own units"; - - for (const QJsonValue& v : args["values"].toArray()) { - knob.values.append(v.toDouble()); - } - - if (knob.values.size() < 2) { - throw MCPToolError("Give at least two values to try with gainKey"); - } - } - else if (hwType == "RTLSDR") - { - // The tuner takes only the values it lists, in tenths of a decibel - knob = {"gain", "agc", 0, {}, "tenths of a dB", "The tuner's AGC is off, as it must be for the gain to hold"}; - SWGSDRangel::SWGDeviceReport report; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->devicesetDeviceReportGet(deviceSetIndex, report, error), error, "Get device report"); - QJsonObject json = toJson(report); - - for (const QString& key : json.keys()) - { - for (const QJsonValue& g : json[key].toObject()["gains"].toArray()) { - knob.values.append(g.toObject()["gainCB"].toDouble()); - } - } - - if (knob.values.isEmpty()) { - throw MCPToolError("The RTL-SDR reported no supported gain values; is the device open?"); - } - } - else if (hwType == "HackRF") { - knob = {"lnaGain", "", 0, {0, 8, 16, 24, 32, 40}, "dB", "Only the LNA is stepped; vgaGain is left as it is"}; - } - else if (hwType == "Airspy") { - knob = {"lnaGain", "lnaAGC", 0, {0, 2, 4, 6, 8, 10, 12, 14}, "steps", "Only the LNA is stepped; mixerGain and vgaGain are left as they are, with the LNA AGC off"}; - } - else if (hwType == "LimeSDR") { - knob = {"gain", "gainMode", 1, {0, 10, 20, 30, 40, 50, 60, 70}, "dB", "gainMode set to manual"}; - } - else if (hwType == "PlutoSDR") { - knob = {"gain", "gainMode", 0, {0, 10, 20, 30, 40, 50, 60, 70}, "dB", "gainMode set to manual"}; - } - else if (hwType == "USRP") { - knob = {"gain", "gainMode", 1, {0, 10, 20, 30, 40, 50, 60, 70}, "dB", "gainMode set to manual"}; - } - else - { - throw MCPToolError(QString("tune_gain does not know the gain settings of a %1. Read them with describe_settings and " - "give gainKey, values and, if it has one, agcKey.").arg(hwType)); - } - - std::sort(knob.values.begin(), knob.values.end()); - knob.values.erase(std::unique(knob.values.begin(), knob.values.end()), knob.values.end()); - - // Spread the steps over the range rather than trying every value a tuner offers - const int steps = qBound(3, argInt(args, "steps", false, 8), 16); - QList candidates; - - if (knob.values.size() <= steps) { - candidates = knob.values; - } - else - { - for (int i = 0; i < steps; i++) { - candidates.append(knob.values[(int) std::round(i * (knob.values.size() - 1) / (double) (steps - 1))]); - } - } - - const bool apply = argBool(args, "apply", true); - - // A key the device does not have would be patched away as unknown at every step, and the - // sweep would then measure the same gain six times and report a choice it never made - if (!settings.contains(knob.key)) { - throw MCPToolError(QString("%1 has no %2 setting; describe_settings shows its keys").arg(hwType).arg(knob.key)); - } - - if (!knob.agcKey.isEmpty() && !settings.contains(knob.agcKey)) { - throw MCPToolError(QString("%1 has no %2 setting; describe_settings shows its keys").arg(hwType).arg(knob.agcKey)); - } - - const double previous = settings[knob.key].toDouble(); - const double previousAgc = knob.agcKey.isEmpty() ? 0 : settings[knob.agcKey].toDouble(); - const qint64 frequency = (qint64) argDouble(args, "frequency", false, 0); - const qint64 bandwidth = (qint64) argDouble(args, "bandwidth", false, 200000); - - // One reading: the floor is the median over the baseband, the signal the strongest bin, - // in the window asked for or anywhere. Max reduction keeps a narrow carrier - auto measure = [&](double& floorDb, double& peakDb) - { - SWGSDRangel::SWGGLSpectrumData response; - SWGSDRangel::SWGErrorResponse error; - response.init(); - error.init(); - check(m_adapter->devicesetSpectrumDataGet(deviceSetIndex, 256, 0, 0, "max", response, error), error, "Get spectrum data"); - // Read from the object: the generated JSON serialiser drops a list of plain floats - const bool linear = response.getLinear() != 0; - QList powers; - - if (response.getPower()) - { - for (float v : *response.getPower()) { - powers.append(linear ? 10.0 * std::log10(std::max((double) v, 1e-20)) : (double) v); - } - } - - if (powers.isEmpty()) { - throw MCPToolError("The spectrum returned no data"); - } - - QList sorted = powers; - std::sort(sorted.begin(), sorted.end()); - floorDb = sorted[sorted.size() / 2]; - - if (frequency > 0) - { - // The data call clamps to the baseband, which would silently measure noise at - // its edge for a frequency outside it - const qint64 low = response.getCenterFrequency() - response.getBandwidth() / 2; - const qint64 high = response.getCenterFrequency() + response.getBandwidth() / 2; - - if ((frequency < low) || (frequency > high)) - { - throw MCPToolError(QString("%1 MHz is outside the baseband, which covers %2 to %3 MHz; tune the device so that it is inside, or leave frequency out") - .arg(frequency / 1e6, 0, 'f', 3).arg(low / 1e6, 0, 'f', 3).arg(high / 1e6, 0, 'f', 3)); - } - - SWGSDRangel::SWGGLSpectrumData window; - SWGSDRangel::SWGErrorResponse windowError; - window.init(); - windowError.init(); - check(m_adapter->devicesetSpectrumDataGet(deviceSetIndex, 32, frequency - bandwidth / 2, frequency + bandwidth / 2, "max", window, windowError), - windowError, "Get spectrum data"); - peakDb = -1e9; - - if (window.getPower()) - { - for (float v : *window.getPower()) { - peakDb = std::max(peakDb, linear ? 10.0 * std::log10(std::max((double) v, 1e-20)) : (double) v); - } - } - - if (peakDb < -1e8) { - throw MCPToolError("The spectrum has no bins at that frequency; it must be inside the baseband"); - } - } - else - { - peakDb = sorted.last(); - } - }; - - struct Row { double gain; double floorDb; double peakDb; double snrDb; }; - QList rows; - - auto setGain = [&](double gain, bool agcOff) - { - QJsonObject partial; - partial[knob.key] = gain; - - if (!knob.agcKey.isEmpty()) { - partial[knob.agcKey] = agcOff ? knob.agcOff : previousAgc; - } - - patchDeviceSettings(deviceSetIndex, partial); - }; - - try - { - for (double gain : candidates) - { - setGain(gain, true); - pause(700); // the tuner, the spectrum averaging and a stale FFT - double floorSum = 0.0; - double peakSum = 0.0; - const int samples = 3; - - for (int i = 0; i < samples; i++) - { - if (i > 0) { - pause(250); - } - - double floorDb, peakDb; - measure(floorDb, peakDb); - floorSum += floorDb; - peakSum += peakDb; - } - - rows.append({gain, floorSum / samples, peakSum / samples, (peakSum - floorSum) / samples}); - } - } - catch (const MCPToolError&) - { - setGain(previous, false); // as it was, AGC included - throw; - } - - auto toDb = [&](double gain) { return (knob.unit == "tenths of a dB") ? gain / 10.0 : gain; }; - - // Overload shows as the floor climbing faster than the gain did. The first step - // where it does bounds the usable range from above - QStringList notes; - int compressed = 0; - int overloadFrom = rows.size(); // index of the first row that is overloaded - - for (int i = 1; i < rows.size(); i++) - { - const double gainStep = toDb(rows[i].gain) - toDb(rows[i - 1].gain); - - if ((gainStep > 0) && (rows[i].floorDb - rows[i - 1].floorDb > gainStep + 3.0)) - { - compressed++; - overloadFrom = std::min(overloadFrom, i); - } - } - - if (compressed > 0) { - notes.append(QString("The noise floor rose faster than the gain over %1 step%2, which is the front end overloading; the higher gains are not usable here.") - .arg(compressed).arg(compressed == 1 ? "" : "s")); - } - - // Best SNR, then the lowest gain within a decibel of it - double best = -1e9; - for (const Row& r : rows) { best = std::max(best, r.snrDb); } - const Row *chosen = nullptr; - QString judgedBy = frequency > 0 ? QString("the signal at %1 MHz").arg(frequency / 1e6, 0, 'f', 3) : QString("the strongest signal in the baseband"); - - if (best >= 6.0) - { - for (const Row& r : rows) { if ((r.snrDb >= best - 1.0) && !chosen) { chosen = &r; } } - } - else - { - // Nothing stood clear of the floor, so the floor itself has to decide: at low gain - // it is the converter's own noise and does not move; as gain rises the antenna's - // noise comes through and lifts it, which is when weak signals become receivable; - // and past overload it lifts faster than the gain. Take the lowest gain that puts - // the floor 8 dB above the converter's, which is the antenna's noise dominating - // by the usual 10 dB rule with a little allowance for the steps being coarse, or - // the last gain before overload if none does - double adcFloor = 1e9; - for (const Row& r : rows) { adcFloor = std::min(adcFloor, r.floorDb); } - const int lastUsable = std::max(0, overloadFrom - 1); - static const double antennaDominates = 8.0; - - for (int i = 0; (i <= lastUsable) && !chosen; i++) - { - if (rows[i].floorDb >= adcFloor + antennaDominates) { - chosen = &rows[i]; - } - } - - if (!chosen) { - chosen = &rows[lastUsable]; - } - - judgedBy = "the noise floor alone, as no signal stood clear of it"; - notes.append(QString("No signal stood more than 6 dB above the floor, so the gain is set from the floor instead: %1.") - .arg((rows[lastUsable].floorDb < adcFloor + antennaDominates) - ? "the floor never rose 8 dB above the converter's own noise before overload, so the last gain before overload is taken; check the antenna if that seems low" - : "the lowest gain at which the antenna's noise, not the converter's, sets the floor")); - } - - if (chosen == &rows.last()) { - notes.append("The best was the highest gain tried: the signal is weak or the site quiet, and more gain would not overload yet."); - } else if (chosen == &rows.first()) { - notes.append("The best was the lowest gain tried: a strong-signal site. Consider an attenuator if the floor still rises with the lowest gain."); - } - - bool autoscaled = false; - - if (apply) - { - setGain(chosen->gain, true); - - // The spectrum was scaled for the gain it had, and a change of tens of decibels - // leaves the trace off the top or along the bottom of the display. Once the new gain - // has reached the trace, the range is set from it, as the GUI's autoscale button does - if (argBool(args, "autoscale", true)) - { - try - { - pause(700); - autoscaleSpectrum(deviceSetIndex); - autoscaled = true; - } - catch (const MCPToolError& e) - { - notes.append(QString("The spectrum could not be autoscaled: %1").arg(e.message)); - } - } - } - else - { - setGain(previous, false); - notes.append("Not applied: the gain is back as it was."); - } - - if (!knob.note.isEmpty()) { - notes.append(knob.note + "."); - } - - QJsonObject result; - result["deviceSetIndex"] = deviceSetIndex; - result["hwType"] = hwType; - result["autoscaled"] = autoscaled; - result["gainKey"] = knob.key; - result["unit"] = knob.unit; - result["previous"] = previous; - result["chosen"] = chosen->gain; - result["applied"] = apply; - result["bestSnrDb"] = chosen->snrDb; - result["judgedBy"] = judgedBy; - QJsonArray table; - - for (const Row& r : rows) - { - QJsonObject o; - o["gain"] = r.gain; - o["floorDb"] = std::round(r.floorDb * 10) / 10; - o["signalDb"] = std::round(r.peakDb * 10) / 10; - o["snrDb"] = std::round(r.snrDb * 10) / 10; - table.append(o); - } - - result["table"] = table; - - if (!notes.isEmpty()) { - result["note"] = notes.join(" "); - } - - return result; -} - -// A mode whose output is only useful through a feature, such as AIS to the AIS feature's ship -// list and the map, gets that feature added with the demodulator. One that is there already is -// left alone, whatever it is set to -int MCPTools::ensureFeature(const QString& featureType, int& featureIndex) -{ - for (const QJsonValue& v : getInstanceSummary()["featureset"].toObject()["features"].toArray()) - { - QJsonObject f = v.toObject(); - - if (f["id"].toString() == featureType) - { - featureIndex = f["index"].toInt(); - return 0; - } - } - - featureIndex = addFeatureAndWait(featureType); - trackIntentFeature(featureUidAt(featureIndex)); - return 1; -} - -void MCPTools::trackIntentFeature(uint64_t featureUid) -{ - if (featureUid == 0) { - return; - } - - QMutexLocker locker(&m_intentMutex); - m_intentFeatures.insert(featureUid); -} - -// A feature listen added goes with the demodulators that fed it: once the last of those is -// reclaimed, on whichever device set, it would only show stale data. One the next mode -// needs, or that a demodulator anywhere still feeds, stays: the user may have added their own -// decoder since and be reading the feature through it -QStringList MCPTools::reclaimIntentFeatures(const QString& keepType) -{ - QSet tracked; - { - QMutexLocker locker(&m_intentMutex); - tracked = m_intentFeatures; - } - - if (tracked.isEmpty()) { - return QStringList(); - } - - // The feature types the remaining channels feed, whoever added them - QSet needed; - - if (!keepType.isEmpty()) { - needed.insert(keepType); - } - - for (int deviceSetIndex = 0; deviceSetIndex < deviceSetCount(); deviceSetIndex++) - { - for (const ChannelNote& note : channelNotes(deviceSetIndex)) - { - const char *feature = featureForChannelType(note.m_id); - - if (feature) { - needed.insert(QString(feature)); - } - } - } - - QStringList removed; - const std::vector& featureSets = MainCore::instance()->getFeatureeSets(); - - if (featureSets.empty()) { - return removed; - } - - // Collected first: deleting renumbers the rest, and by UID, as each deletion waits - QList> doomed; - - for (int i = 0; i < featureSets[0]->getNumberOfFeatures(); i++) - { - const Feature *feature = featureSets[0]->getFeatureAt(i); - - if (feature && tracked.contains(feature->getUID()) && !needed.contains(feature->getIdentifier())) { - doomed.append(qMakePair(feature->getUID(), feature->getIdentifier())); - } - } - - for (const auto& feature : doomed) - { - try - { - deleteFeatureObjectAndWait(feature.first); - removed.append(feature.second); - } - catch (const MCPToolError&) {} - } - - // Tracked no longer: those removed, and any the user had already deleted - QMutexLocker locker(&m_intentMutex); - - for (uint64_t uid : tracked) - { - bool present = false; - - for (int i = 0; i < featureSets[0]->getNumberOfFeatures(); i++) - { - const Feature *feature = featureSets[0]->getFeatureAt(i); - - if (feature && (feature->getUID() == uid)) - { - present = true; - break; - } - } - - if (!present) { - m_intentFeatures.remove(uid); - } - } - - return removed; -} - -void MCPTools::deleteFeatureObjectAndWait(uint64_t featureUid) -{ - QMutexLocker deletionLock(&m_deletionMutex); - int featureIndex = -1; - const std::vector& featureSets = MainCore::instance()->getFeatureeSets(); - - if (!featureSets.empty() && (featureUid != 0)) - { - for (int i = 0; i < featureSets[0]->getNumberOfFeatures(); i++) - { - const Feature *feature = featureSets[0]->getFeatureAt(i); - - if (feature && (feature->getUID() == featureUid)) - { - featureIndex = i; - break; - } - } - } - - if (featureIndex < 0) { - return; // Already gone - } - - requireNotSelf(featureIndex, "deleted"); - SWGSDRangel::SWGSuccessResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->featuresetFeatureDelete(0, featureIndex, response, error), error, "Delete feature"); - - if (!waitFor([&]() { return !featureUids().contains(featureUid); })) { - throw MCPToolError(QString("Timed out waiting for feature %1 to be removed").arg(featureIndex)); - } -} - -void MCPTools::autoscaleSpectrum(int deviceSetIndex) -{ - QJsonObject actions; - actions["autoscale"] = 1; - QStringList keys; - extractKeys(actions, keys); - SWGSDRangel::SWGSpectrumActions query; - query.init(); - query.fromJsonObject(actions); - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->devicesetSpectrumActionsPost(deviceSetIndex, keys, query, error), error, "Autoscale spectrum"); -} - -// The history the spectrum tools read is the display's scroll buffer, which fills only while -// scrolling is on. Switched on here with a length that covers what was asked for at a -// typical refresh rate, and at least a couple of minutes; a longer length the user has set -// is left alone -QString MCPTools::ensureSpectrumHistory(int deviceSetIndex, double seconds) -{ - QJsonObject settings = getSpectrumSettings(deviceSetIndex); - const bool scrolling = settings["scrollBar"].toInt() != 0; - const int length = settings["scrollLength"].toInt(); - const int wanted = qBound(1200, (int) (seconds * 20.0), 4000); - - if (scrolling && (length >= wanted)) { - return QString(); - } - - QJsonObject partial; - partial["scrollBar"] = 1; - partial["scrollLength"] = qMax(length, wanted); - patchSpectrumSettings(deviceSetIndex, partial); - return scrolling - ? QString("The spectrum history was lengthened to %1 rows to cover %2 seconds.").arg(qMax(length, wanted)).arg(seconds) - : QString("Spectrum scrolling was switched on, as the history the spectrum keeps for it is what this reads; it starts now."); -} - -// The gain suits a band and an antenna, not a mode: a device set that was just created has -// whatever gain it came with, and one moved to another band has the gain of the last one. A -// move within a band, or a change of mode on the same frequency, needs no new measurement -bool MCPTools::gainWorthTuning(bool reused, double previousCentre, double centre) -{ - if (!reused) { - return true; - } - - return std::abs(centre - previousCentre) > 0.1 * std::max(centre, previousCentre); -} - -void MCPTools::registerIntentTools() -{ - static const QString deviceHint = "Optional: which device, by serial, displayed name or type (e.g. RTLSDR) as shown by " - "list_available_devices. Default: the first radio attached to this machine"; - - add("listen", - "Receive a frequency in one call: picks a device, creates or reuses its device set, sets the sample rate, adds the " - "demodulator with sensible settings, starts the device and reports the signal level. Audio plays on the default output. " - "Use the individual tools afterwards to adjust, e.g. set_channel_settings for squelch or volume. Modes whose output " - "goes to a feature add it too: ais adds the AIS feature, sonde the Radiosonde feature and aprs the APRS feature, whose " - "reports and map items carry what was decoded; a later listen or scan removes the feature again once nothing it added " - "feeds it. ais is received on two channels, so give 162000000 and it puts a demodulator on each of 161.975 and " - "162.025 MHz.", - schema({ - {"frequency", numProp("Frequency to receive in Hz, e.g. 97300000 for 97.3 MHz")}, - {"mode", strProp("bfm (broadcast FM with stereo and RDS), wfm, nfm, am or airband, ssb/usb, lsb, dab, adsb, ais, dsc, dsd/dmr, " - "dmr, dpmr, dstar, ysf, nxdn or nxdn24 (digital voice through the DSD demodulator with the deviation and baud rate of that standard), " - "pager (POCSAG), sonde (RS41 radiosondes), packet (AX.25), aprs (APRS with its feature), or any channel type id from list_channel_types. Default nfm")}, - {"device", strProp(deviceHint)}, - {"replace", prop("boolean", "Retune the demodulator a previous listen added to this device set when it is of the same type, and remove every other channel earlier listen and scan calls added there, so that exploring a band does not leave a trail of demodulators all playing audio and mis-tuned for the current centre frequency. Channels added any other way are kept on their frequency where the baseband still holds them; audio demodulators it cannot hold are removed, anything else is left and named. Default true")}, - {"tuneGain", prop("boolean", "Measure and set the receiver gain, as tune_gain does, when the device set is new or the retune is to another band (more than a tenth of the frequency away). Adds several seconds in those cases and none otherwise. false leaves the gain as it is. Default true")} - }, {"frequency"}), - [this](const QJsonObject& args) - { - qint64 frequency = (qint64) argDouble(args, "frequency"); - QString modeName = argString(args, "mode", false, "nfm").trimmed(); - const ListenMode *mode = findListenMode(modeName); - QString channelType; - int rfBandwidth = 0; - int minBaseband = 256000; - QJsonObject initial; - QString companionFeature; - int pairOffset = 0; - - if (mode) - { - channelType = mode->m_channelType; - rfBandwidth = mode->m_rfBandwidth; - minBaseband = mode->m_minBaseband; - initial = QJsonDocument::fromJson(mode->m_settings).object(); - companionFeature = mode->m_feature ? QString(mode->m_feature) : QString(); - pairOffset = mode->m_pairOffset; - } - else - { - for (const QString& id : channelTypeIds(0)) - { - if (id.compare(modeName, Qt::CaseInsensitive) == 0) { - channelType = id; - } - } - - if (channelType.isEmpty()) { - throw MCPToolError(QString("Unknown mode %1. Use one of %2, or a channel type from list_channel_types").arg(modeName).arg(listenModeList)); - } - } - - const bool replace = argBool(args, "replace", true); - const bool wantTuneGain = argBool(args, "tuneGain", true); - QJsonObject receiver = pickReceiver(args, minBaseband, replace ? intentChannels() : QSet(), !wantTuneGain); - int deviceSetIndex = receiver["deviceSetIndex"].toInt(); - - // A device set this call created and cannot finish is taken away again, or a retry - // would build another beside it - NewDeviceSetGuard newDeviceSet(this, receiver["reused"].toBool() ? -1 : deviceSetIndex); - int baseband = receiver["baseband"].toInt(); - - // Keep the channel off the device's DC spike when the baseband has room for it: far - // enough that the spike falls outside the channel, or not at all. A spike inside a - // wide FM channel is an interferer 25 kHz from the carrier, which is worse than one - // on the carrier itself - int offset = 0; - - if ((pairOffset == 0) && (rfBandwidth != 0) && (baseband > 0)) - { - const int clear = qAbs(rfBandwidth) / 2 + 25000; // spike 25 kHz beyond the channel edge - - if (baseband / 2 >= clear + qAbs(rfBandwidth) / 2) { - offset = -clear; - } - } - - // A paired mode, such as AIS on 161.975 and 162.025 MHz, centres the device on the - // frequency asked for and puts a demodulator either side of it - const qint64 centre = (pairOffset != 0) ? frequency : frequency - offset; - - if (pairOffset != 0) { - offset = -pairOffset; - } - - // A demodulator of the right type that a previous listen added is retuned rather - // than replaced; anything else the intent tools added goes as before - int channelIndex = -1; - uint64_t channel = replace ? reusableIntentChannel(deviceSetIndex, channelType, channelIndex, pairOffset != 0 ? 2 : 1) : 0; - const bool retuned = channel != 0; - - // A paired mode keeps its other demodulator through the reclaim as well - QSet kept; - - if (retuned) - { - kept.insert(channel); - - if (pairOffset != 0) - { - for (const ChannelNote& note : channelNotes(deviceSetIndex, {channel})) - { - if (note.m_intent && (note.m_id == channelType)) - { - kept.insert(note.m_uid); - break; - } - } - } - } - - const QStringList reclaimed = replace ? reclaimIntentChannels(deviceSetIndex, kept) : QStringList(); - const QStringList reclaimedFeatures = replace ? reclaimIntentFeatures(companionFeature) : QStringList(); - - // The device is retuned only once the reclaim is done: a scanner an earlier scan - // left running would otherwise step the device on again between the two, and the - // demodulator would be added against a centre the scanner chose - QJsonObject tune; - tune["centerFrequency"] = (double) centre; - patchDeviceSettings(deviceSetIndex, tune); - const RetuneOutcome outcome = receiver["reused"].toBool() - ? retuneOtherChannels(deviceSetIndex, receiver["previousCentre"].toDouble(), (double) centre, baseband) - : RetuneOutcome(); - - if (retuned) - { - // The reclaim may have renumbered it - relocateChannel(channel, deviceSetIndex, channelIndex, "demodulator"); - } - else - { - channelIndex = addChannelAndWait(deviceSetIndex, channelType); - channel = channelUidAt(deviceSetIndex, channelIndex); - trackIntentChannel(channel); - } - - initial["inputFrequencyOffset"] = offset; - - if (rfBandwidth != 0) { - initial["rfBandwidth"] = rfBandwidth; - } - - QJsonObject patched; - QString state; - - // Do not leave a half configured channel behind if setting it up fails. One that was - // there already stays, as the previous listen left it - try - { - patched = patchChannelSettings(deviceSetIndex, channelIndex, initial); - state = deviceState(deviceSetIndex, 0, 1)["state"].toString(); - } - catch (const MCPToolError&) - { - if (!retuned) - { - try { deleteChannelObjectAndWait(channel); } catch (const MCPToolError&) {} - untrackIntentChannel(channel); - } - - throw; - } - - QJsonObject result; - result["deviceSetIndex"] = deviceSetIndex; - result["channelIndex"] = channelIndex; - result["device"] = receiver["device"]; - result["frequency"] = (double) frequency; - result["mode"] = modeName; - result["channelType"] = channelType; - result["state"] = state; - QStringList notes; - - if (retuned) - { - result["retuned"] = true; - notes.append(QString("Retuned the %1 a previous listen added to device set %2 rather than adding another; its other settings are as they were.") - .arg(channelType).arg(deviceSetIndex)); - } - - // The second demodulator of a paired mode, on the other channel. A retuned first - // one may already have its partner from the previous listen; a fresh one needs it - uint64_t partner = 0; - - if (pairOffset != 0) - { - int partnerIndex = -1; - - for (const ChannelNote& note : channelNotes(deviceSetIndex, {channel})) - { - if (note.m_intent && (note.m_id == channelType)) - { - partnerIndex = note.m_index; - partner = note.m_uid; - break; - } - } - - if (partner == 0) - { - partnerIndex = addChannelAndWait(deviceSetIndex, channelType); - partner = channelUidAt(deviceSetIndex, partnerIndex); - trackIntentChannel(partner); - } - - QJsonObject partnerSettings = initial; - partnerSettings["inputFrequencyOffset"] = pairOffset; - - try - { - patchChannelSettings(deviceSetIndex, partnerIndex, partnerSettings); - } - catch (const MCPToolError& e) - { - notes.append(QString("The second %1 could not be configured: %2").arg(channelType).arg(e.message)); - } - - relocateChannel(partner, deviceSetIndex, partnerIndex, "second demodulator"); - relocateChannel(channel, deviceSetIndex, channelIndex, "demodulator"); - result["channelIndex"] = channelIndex; - result["secondChannelIndex"] = partnerIndex; - QJsonArray frequencies; - frequencies.append((double) (frequency - pairOffset)); - frequencies.append((double) (frequency + pairOffset)); - result["frequencies"] = frequencies; - notes.append(QString("%1 is received on two channels, so there are two %2: channel %3 on %4 MHz and channel %5 on %6 MHz, with the device centred between them.") - .arg(modeName.toUpper()).arg(channelType).arg(channelIndex).arg((frequency - pairOffset) / 1e6, 0, 'f', 3) - .arg(partnerIndex).arg((frequency + pairOffset) / 1e6, 0, 'f', 3)); - } - - // The feature the mode's output goes to, so that the decoded data has somewhere to be - // read from and shown - if (!companionFeature.isEmpty()) - { - try - { - int featureIndex = -1; - const int added = ensureFeature(companionFeature, featureIndex); - result["featureIndex"] = featureIndex; - result["featureType"] = companionFeature; - notes.append(added - ? QString("Added the %1 feature (F%2), which collects what the demodulator decodes; get_feature_report reads it, and it feeds the map.").arg(companionFeature).arg(featureIndex) - : QString("The %1 feature (F%2) is already there and collects what the demodulator decodes.").arg(companionFeature).arg(featureIndex)); - } - catch (const MCPToolError& e) - { - notes.append(QString("The %1 feature could not be added: %2").arg(companionFeature).arg(e.message)); - } - } - - if (state == "running") - { - // A new device set, or one moved to another band, has no gain to speak of yet - if (wantTuneGain && gainWorthTuning(receiver["reused"].toBool(), receiver["previousCentre"].toDouble(), (double) centre)) - { - QJsonObject gainArgs; - gainArgs["deviceSetIndex"] = deviceSetIndex; - gainArgs["frequency"] = (double) frequency; - gainArgs["bandwidth"] = (double) (rfBandwidth != 0 ? qAbs(rfBandwidth) : 2000000); - gainArgs["steps"] = 6; - - try - { - QJsonObject tuned = tuneGain(gainArgs); - QJsonObject gain; - gain["key"] = tuned["gainKey"]; - gain["value"] = tuned["chosen"]; - gain["unit"] = tuned["unit"]; - gain["snrDb"] = tuned["bestSnrDb"]; - result["gain"] = gain; - notes.append(QString("Gain measured and set to %1 (%2), judged by %3, as %4%5; tune_gain shows the table, and tuneGain false leaves the gain alone.") - .arg(tuned["chosen"].toDouble()).arg(tuned["unit"].toString()).arg(tuned["judgedBy"].toString()) - .arg(receiver["reused"].toBool() ? "the retune was to another band" : "the device set is new") - .arg(tuned["autoscaled"].toBool() ? ", and the spectrum autoscaled to suit it" : "")); - } - catch (const MCPToolError& e) - { - notes.append(QString("The gain was not measured: %1").arg(e.message)); - } - } - - pause(1500); - // The channel may have been renumbered while we waited - relocateChannel(channel, deviceSetIndex, channelIndex, "demodulator"); - result["deviceSetIndex"] = deviceSetIndex; - result["channelIndex"] = channelIndex; - - // The power measurement sits at the channel's floor until the demodulator has run - // for a moment, and a floor reading looks exactly like an empty band. Wait for a - // real one: reporting the floor has sent callers away from a signal that was - // decoding perfectly well. CalcDb::dbPower returns 10*log10(floor) while there is - // nothing to measure, which is -100 dB or below for every floor in use here - double db = 0.0; - bool measured = false; - bool noReport = false; - QElapsedTimer settling; - settling.start(); - - while (true) - { - QJsonObject report; - - // A demodulator with no report at all (APT, ATV) is not a failure of the - // receiver that was just built - try - { - report = channelReport(deviceSetIndex, channelIndex); - } - catch (const MCPToolError&) - { - noReport = true; - break; - } - - if (signalLevel(report, db)) - { - measured = true; - - if (db > -100.0) { - break; - } - } - - if (settling.elapsed() > 4000) { - break; - } - - pause(250); - } - - if (noReport) - { - notes.append(QString("%1 has no channel report, so there is no signal level to give; %2.") - .arg(channelType) - .arg(companionFeature.isEmpty() ? QString("get_spectrum_data shows whether there is a signal") - : QString("what it decodes appears in the %1 feature's report and in get_packets").arg(companionFeature))); - } - else if (measured) - { - result["signalDb"] = db; - - if (db <= -100.0) { - notes.append("signalDb is still at the measurement floor, which usually means the channel " - "has not settled rather than that the band is empty. Read get_channel_report again in " - "a few seconds before concluding nothing is there."); - } - } - } - else - { - notes.append("The device did not start. If another device set holds the same hardware, stop it first, or pass a different device."); - } - - if (baseband > 0) { - result["basebandSampleRate"] = baseband; - } else { - notes.append(QString("The sample rate of a %1 was left as configured; check it exceeds %2 S/s with get_device_settings.").arg(receiver["hwType"].toString()).arg(minBaseband)); - } - - if (!receiver["rateNote"].toString().isEmpty()) { - notes.append(receiver["rateNote"].toString()); - } - - notes.append(intentNotes(deviceSetIndex, partner ? QSet({channel, partner}) : QSet({channel}), - reclaimed, receiver["reused"].toBool(), - receiver["previousCentre"].toDouble(), (double) centre, outcome)); - notes.append(featureNotes(reclaimedFeatures)); - - if (patched.contains("warning")) { - notes.append(patched["warning"].toString()); - } - - if (!notes.isEmpty()) { - result["note"] = notes.join(" "); - } - - newDeviceSet.keep(); - return result; - }); - - QJsonObject frequencyList = prop("array", "Frequencies to scan in Hz. Alternatively give startFrequency, stopFrequency and stepFrequency"); - QJsonObject items; - items["type"] = "number"; - frequencyList["items"] = items; - - add("scan", - "Scan a set of frequencies for activity and listen to whichever is active, in one call: sets up a receiver, a demodulator " - "and a Frequency Scanner, starts scanning, watches for a while and reports what it found. active lists every frequency " - "above the threshold with its level, strongest first; that is the list to use for stations and other continuous " - "signals. heard lists where the scanner parked and for how long, which only tells intermittent signals apart, since " - "on a continuous carrier it parks on the first and stays. " - "The scanner keeps running afterwards; get_channel_report on the scanner channel shows its state (2 scanning, 3 receiving, " - "4 holding), channel_action {\"run\": 0} stops it. The demodulator and scanner it added stay on the device set until the " - "next listen or scan there replaces them, or cleanup removes them; they are not removed when this call returns. " - "Blocks for the watch period, so it is capped at 30 seconds.", - schema({ - {"frequencies", frequencyList}, - {"startFrequency", numProp("Start of a range in Hz, with stopFrequency and stepFrequency")}, - {"stopFrequency", numProp("End of the range in Hz, inclusive")}, - {"stepFrequency", numProp("Channel spacing in Hz. Optional: without it the spacing usual for the mode is used (bfm 100 kHz, am 25 kHz, " - "nfm/dsd/pager 12.5 kHz, sonde 10 kHz, ssb 3 kHz), which is the right choice unless the band is known to differ, " - "e.g. 8333 for airband 8.33 kHz channels in Europe. Broadcast FM stations sit on a 100 kHz raster everywhere; only " - "the Americas confine them to the odd tenths, so bfm/wfm ranges are scanned at 100 kHz whatever step is given")}, - {"mode", strProp("Demodulator, as for listen: bfm, wfm, nfm, am, ssb/usb/lsb, dsd, pager, sonde. Modes on fixed frequencies (adsb, ais, " - "dab, dsc) cannot be scanned for; listen to those directly. Default am")}, - {"threshold", numProp("Power in dB above which a frequency counts as active. Leave it out unless you have a reason: the scale " - "depends on the device and its gain, so by default the noise floor is measured first and the threshold set " - "12 dB above it. Both are reported, so a second scan can adjust")}, - {"seconds", bounded(numProp("How long to watch before replying, 3 to 30. Default 10"), 3, 30)}, - {"device", strProp(deviceHint)}, - {"replace", prop("boolean", "Remove every channel earlier listen and scan calls added to this device set first, as listen does. Channels added any other way are kept on their frequency where the baseband still holds them; audio demodulators it cannot hold are removed, anything else is left and named. Default true")}, - {"tuneGain", prop("boolean", "Measure and set the receiver gain first, as tune_gain does, when the device set is new or the retune is to another band. Adds several seconds in those cases and none otherwise. false leaves the gain as it is. Default true")} - }), - [this](const QJsonObject& args) - { - QList frequencies; - const bool fromRange = !hasArg(args, "frequencies"); - qint64 rangeStart = 0; - qint64 rangeStop = 0; - qint64 rangeStep = 0; // as given; zero to step by the mode's usual channel spacing - - if (fromRange) - { - rangeStart = (qint64) argDouble(args, "startFrequency"); - rangeStop = (qint64) argDouble(args, "stopFrequency"); - rangeStep = hasArg(args, "stepFrequency") ? (qint64) argDouble(args, "stepFrequency") : 0; - - if ((rangeStep < 0) || (rangeStop < rangeStart)) { - throw MCPToolError("stepFrequency must be positive and stopFrequency at least startFrequency"); - } - } - else - { - for (const QJsonValue& v : args["frequencies"].toArray()) { - frequencies.append((qint64) v.toDouble()); - } - - if (frequencies.isEmpty()) { - throw MCPToolError("Give frequencies, or startFrequency and stopFrequency"); - } - } - - QString modeName = argString(args, "mode", false, "am").trimmed(); - const ListenMode *mode = findListenMode(modeName); - - if (!mode) { - throw MCPToolError(QString("Unknown mode %1. Use one of %2").arg(modeName).arg(listenModeList)); - } - - // A mode on fixed frequencies has nothing to be found by stepping - if (mode->m_scanStep == 0) - { - throw MCPToolError(QString("%1 is received on fixed frequencies, so there is nothing to scan for: listen to them directly. " - "get_receiving_guide lists them (ADS-B 1090 MHz; AIS 161.975 and 162.025 MHz; DSC 2187.5 kHz, 8414.5 kHz, " - "16804.5 kHz and 156.525 MHz; DAB on the Band III blocks, one dab channel per block).").arg(mode->m_channelType)); - } - - // Without a threshold, measure the noise floor first and sit 12 dB above it: the - // level scale depends on the device and its gain, so no fixed number suits all - bool autoThreshold = !hasArg(args, "threshold"); - double threshold = autoThreshold ? -100.0 : argDouble(args, "threshold"); - int seconds = qBound(3, (int) argDouble(args, "seconds", false, 10.0), 30); - int channelBandwidth = qAbs(mode->m_rfBandwidth) > 0 ? qAbs(mode->m_rfBandwidth) : 8000; - - // Broadcast FM stations sit on a 100 kHz raster everywhere but the Americas, where - // they keep to the odd tenths. A 200 kHz step from 87.5 MHz, the usual assumption, - // lands beside every even-tenth station: with a channel this wide the station still - // shows up, 100 kHz off and weaker, and then nothing decodes. So a coarser step on - // a broadcast range is scanned at 100 kHz, which loses nothing where the odd tenths - // are the rule - const bool broadcast = (mode->m_channelType == "BFMDemod") || (mode->m_channelType == "WFMDemod"); - QString rasterNote; - - if (fromRange) - { - qint64 step = (rangeStep > 0) ? rangeStep : mode->m_scanStep; - - if (broadcast && (step > 100000)) - { - step = 100000; - rasterNote = QString("Scanned at 100 kHz rather than the %1 kHz step given: broadcast FM stations are on a 100 kHz raster " - "outside the Americas, and a coarser step lands beside them rather than on them.").arg(rangeStep / 1000.0, 0, 'g', 4); - } - else if (rangeStep > mode->m_scanStep) - { - rasterNote = QString("The %1 kHz step given is coarser than the %2 kHz channel spacing usual for %3, so channels between the steps were not seen.") - .arg(rangeStep / 1000.0, 0, 'g', 4).arg(mode->m_scanStep / 1000.0, 0, 'g', 4).arg(modeName); - } - else if (rangeStep == 0) - { - rasterNote = QString("Stepped by %1 kHz, the channel spacing usual for %2; give stepFrequency for another.") - .arg(step / 1000.0, 0, 'g', 4).arg(modeName); - } - - // Counted before it is built: a step given in kHz by mistake, 12 Hz for 12.5, - // would otherwise fill millions of entries before the limit was looked at - const qint64 count = (rangeStop - rangeStart) / step + 1; - - if (count > 2000) { - throw MCPToolError(QString("%1 frequencies is too many; use a coarser step or a narrower range (2000 at most)").arg(count)); - } - - for (qint64 f = rangeStart; f <= rangeStop; f += step) { - frequencies.append(f); - } - } - - if (frequencies.size() > 2000) { - throw MCPToolError(QString("%1 frequencies is too many; use a coarser step or a narrower range (2000 at most)").arg(frequencies.size())); - } - - std::sort(frequencies.begin(), frequencies.end()); - - // A wide baseband means fewer retunes per sweep - const bool replace = argBool(args, "replace", true); - const bool wantTuneGain = argBool(args, "tuneGain", true); - QJsonObject receiver = pickReceiver(args, 2400000, replace ? intentChannels() : QSet(), !wantTuneGain); - int deviceSetIndex = receiver["deviceSetIndex"].toInt(); - NewDeviceSetGuard newDeviceSet(this, receiver["reused"].toBool() ? -1 : deviceSetIndex); - - // The reclaim comes before the retune: a scanner an earlier scan left running would - // otherwise move the device again between the two - const QStringList reclaimed = replace ? reclaimIntentChannels(deviceSetIndex) : QStringList(); - const QStringList reclaimedFeatures = replace ? reclaimIntentFeatures() : QStringList(); - QJsonObject tune; - tune["centerFrequency"] = (double) ((frequencies.first() + frequencies.last()) / 2); - patchDeviceSettings(deviceSetIndex, tune); - const RetuneOutcome outcome = receiver["reused"].toBool() - ? retuneOtherChannels(deviceSetIndex, receiver["previousCentre"].toDouble(), tune["centerFrequency"].toDouble(), receiver["baseband"].toInt()) - : RetuneOutcome(); - - int demod = addChannelAndWait(deviceSetIndex, mode->m_channelType); - const uint64_t demodChannel = channelUidAt(deviceSetIndex, demod); - trackIntentChannel(demodChannel); - int scanner = -1; - uint64_t scannerChannel = 0; - - // Anything that fails from here on removes both channels rather than leaving a - // half built scanner running on the user's radio - auto discard = [&]() - { - if (scannerChannel != 0) - { - try { deleteChannelObjectAndWait(scannerChannel); } catch (const MCPToolError&) {} - untrackIntentChannel(scannerChannel); - } - - try { deleteChannelObjectAndWait(demodChannel); } catch (const MCPToolError&) {} - untrackIntentChannel(demodChannel); - }; - - try - { - QJsonObject initial = QJsonDocument::fromJson(mode->m_settings).object(); - initial["inputFrequencyOffset"] = 0; - - if (mode->m_rfBandwidth != 0) { - initial["rfBandwidth"] = mode->m_rfBandwidth; - } - - patchChannelSettings(deviceSetIndex, demod, initial); - scanner = addChannelAndWait(deviceSetIndex, "FreqScanner"); - scannerChannel = channelUidAt(deviceSetIndex, scanner); - trackIntentChannel(scannerChannel); - } - catch (const MCPToolError&) - { - discard(); - throw; - } - - // Everything up to the scanner running with its threshold is set up, and a failure - // anywhere in it, the device not starting, the scanner refusing its settings or - // its run action, or measuring nothing, removes both channels the same way - QString gainNote; - double measuredFloor = 0.0; - bool haveFloor = false; - - try - { - QString state = deviceState(deviceSetIndex, 0, 1)["state"].toString(); - - if (state != "running") { - throw MCPToolError(QString("The device did not start (state %1), so the demodulator and scanner were removed again.").arg(state)); - } - - // Before the scanner measures anything: the gain sets the floor it measures against - if (wantTuneGain && gainWorthTuning(receiver["reused"].toBool(), receiver["previousCentre"].toDouble(), tune["centerFrequency"].toDouble())) - { - QJsonObject gainArgs; - gainArgs["deviceSetIndex"] = deviceSetIndex; - gainArgs["steps"] = 6; - - try - { - QJsonObject tuned = tuneGain(gainArgs); - gainNote = QString("Gain measured and set to %1 (%2) first, as %3%4; tuneGain false leaves it alone.") - .arg(tuned["chosen"].toDouble()).arg(tuned["unit"].toString()) - .arg(receiver["reused"].toBool() ? "the retune was to another band" : "the device set is new") - .arg(tuned["autoscaled"].toBool() ? ", and the spectrum autoscaled to suit it" : ""); - } - catch (const MCPToolError& e) - { - gainNote = QString("The gain was not measured: %1").arg(e.message); - } - } - - // The scanner's baseband only takes settings while it is running, so configure it - // after the device has started - pause(1500); - relocateChannel(demodChannel, deviceSetIndex, demod, "demodulator"); - relocateChannel(scannerChannel, deviceSetIndex, scanner, "scanner"); - QJsonArray list; - - for (qint64 f : frequencies) - { - QJsonObject entry; - entry["frequency"] = (double) f; - entry["enabled"] = 1; - list.append(entry); - } - - QJsonObject scannerSettings; - scannerSettings["channel"] = QString("R%1:%2").arg(deviceSetIndex).arg(demod); - scannerSettings["channelBandwidth"] = channelBandwidth; - scannerSettings["channelFrequencyOffset"] = 25000; - scannerSettings["threshold"] = threshold; - scannerSettings["scanTime"] = 0.1; - scannerSettings["tuneTime"] = 250; - scannerSettings["retransmitTime"] = 2.5; - scannerSettings["priority"] = 0; - scannerSettings["measurement"] = 0; - scannerSettings["mode"] = autoThreshold ? 2 : 1; // scan only while measuring, else continuous - scannerSettings["frequencies"] = list; - patchChannelSettings(deviceSetIndex, scanner, scannerSettings); - QJsonObject run; - run["run"] = 1; - postChannelAction(deviceSetIndex, scanner, run); - - if (autoThreshold) - { - // The power scale depends on the device and its gain, so the only threshold that - // is right everywhere is one measured here: the median over the frequencies is - // the floor, as most of any band is empty. Wait for the first sweep to have - // measured every frequency rather than guess after a fixed time; a long list - // at a low sample rate takes a while - QList powers; - - for (int attempt = 0; (attempt < 30) && (powers.size() < frequencies.size()); attempt++) - { - pause(500); - relocateChannel(scannerChannel, deviceSetIndex, scanner, "scanner"); - powers.clear(); - - for (const QJsonValue& v : channelReport(deviceSetIndex, scanner)["FreqScannerReport"].toObject()["channelState"].toArray()) - { - QJsonObject s = v.toObject(); - - if (s.contains("power")) { - powers.append(s["power"].toDouble()); - } - } - } - - if (powers.isEmpty()) { - throw MCPToolError("The scanner measured nothing in 15 seconds, so no threshold could be set. " - "Check the device is running and producing samples, or give threshold explicitly."); - } - - std::sort(powers.begin(), powers.end()); - measuredFloor = powers[powers.size() / 2]; - haveFloor = true; - threshold = measuredFloor + 12.0; - - // Changing the mode restarts the scan with the new threshold - QJsonObject arm; - arm["threshold"] = threshold; - arm["mode"] = 1; - patchChannelSettings(deviceSetIndex, scanner, arm); - } - } - catch (const MCPToolError&) - { - discard(); - throw; - } - - // Watch: where it parks, and how strong each channel got - QMap heard; - QMap strongest; - - for (int i = 0; i < seconds; i++) - { - pause(1000); - relocateChannel(scannerChannel, deviceSetIndex, scanner, "scanner"); - relocateChannel(demodChannel, deviceSetIndex, demod, "demodulator"); - QJsonObject report = channelReport(deviceSetIndex, scanner)["FreqScannerReport"].toObject(); - int scanState = report["scanState"].toInt(); - - for (const QJsonValue& v : report["channelState"].toArray()) - { - QJsonObject s = v.toObject(); - qint64 f = (qint64) s["frequency"].toDouble(); - strongest[f] = qMax(strongest.value(f, -999.0), s["power"].toDouble()); - } - - if ((scanState == 3) || (scanState == 4)) - { - // One snapshot for both halves of the sum: read separately, a retune - // between them would pair a new centre with an old offset - QJsonObject set = getDeviceSet(deviceSetIndex); - qint64 centre = (qint64) set["samplingDevice"].toObject()["centerFrequency"].toDouble(); - - for (const QJsonValue& v : set["channels"].toArray()) - { - QJsonObject ch = v.toObject(); - - if (ch["index"].toInt() == demod) { - heard[centre + (qint64) ch["deltaFrequency"].toDouble()] += 1; - } - } - } - } - - QJsonObject result; - result["deviceSetIndex"] = deviceSetIndex; - result["demodChannelIndex"] = demod; - result["scannerChannelIndex"] = scanner; - result["device"] = receiver["device"]; - result["frequencies"] = frequencies.size(); - result["threshold"] = threshold; - result["secondsWatched"] = seconds; - - // A channel this wide takes in a station on the neighbouring raster steps as well, - // weaker and off frequency, so of the neighbours within a channel of each other - // only the strongest is a station; the rest are its skirts - auto isLocalPeak = [&](qint64 f) - { - const double power = strongest.value(f, -999.0); - - for (auto it = strongest.lowerBound(f - channelBandwidth); (it != strongest.end()) && (it.key() <= f + channelBandwidth); ++it) - { - if ((it.key() != f) && ((it.value() > power) || ((it.value() == power) && (it.key() < f)))) { - return false; - } - } - - return true; - }; - - QList> byTime; - for (auto it = heard.begin(); it != heard.end(); ++it) { if (isLocalPeak(it.key())) { byTime.append(qMakePair(it.value(), it.key())); } } - std::sort(byTime.begin(), byTime.end(), [](const QPair& a, const QPair& b) { return a.first > b.first; }); - QJsonArray heardArray; - - for (const auto& p : byTime) - { - QJsonObject h; - h["frequency"] = (double) p.second; - h["seconds"] = p.first; - heardArray.append(h); - } - - result["heard"] = heardArray; - - QList> byPower; - QList allPowers; // every frequency, for the floor estimate - for (auto it = strongest.begin(); it != strongest.end(); ++it) { allPowers.append(it.value()); if (isLocalPeak(it.key())) { byPower.append(qMakePair(it.value(), it.key())); } } - std::sort(byPower.begin(), byPower.end(), [](const QPair& a, const QPair& b) { return a.first > b.first; }); - std::sort(allPowers.begin(), allPowers.end()); - // Everything above the threshold, strongest first: for a band of continuous carriers - // this is the answer, as the scanner parks on the first one it finds and never gets - // to the rest. Capped well above any real band's station count, so that a threshold - // set too low on a long list cannot flood the reply - QJsonArray activeArray; - QJsonArray strongestArray; - static const int activeCap = 100; - - for (int i = 0; i < byPower.size(); i++) - { - QJsonObject s; - s["frequency"] = (double) byPower[i].second; - s["dB"] = byPower[i].first; - - if (i < 5) { - strongestArray.append(s); - } - - if ((byPower[i].first >= threshold) && (activeArray.size() < activeCap)) { - activeArray.append(s); - } - } - - result["active"] = activeArray; - result["activeCount"] = activeArray.size(); - result["strongest"] = strongestArray; - - if (haveFloor) { - result["noiseFloorDb"] = measuredFloor; - } else if (!allPowers.isEmpty()) { - result["noiseFloorDb"] = allPowers[allPowers.size() / 2]; - } - - if (autoThreshold) { - result["thresholdAuto"] = true; - } - - QStringList notes; - - if (!rasterNote.isEmpty()) { - notes.append(rasterNote); - } - - if (!gainNote.isEmpty()) { - notes.append(gainNote); - } - - if (!receiver["rateNote"].toString().isEmpty()) { - notes.append(receiver["rateNote"].toString()); - } - - if (activeArray.isEmpty()) { - notes.append("Nothing exceeded the threshold. Compare threshold with noiseFloorDb and the strongest channels; a second scan with threshold given lowers it."); - } else if (heardArray.isEmpty()) { - notes.append("The scanner did not park on any of the active frequencies while watching; active is still the list of what was found."); - } - - notes.append(intentNotes(deviceSetIndex, {demodChannel, scannerChannel}, reclaimed, receiver["reused"].toBool(), - receiver["previousCentre"].toDouble(), tune["centerFrequency"].toDouble(), outcome)); - notes.append(featureNotes(reclaimedFeatures)); - - if (!notes.isEmpty()) { - result["note"] = notes.join(" "); - } - - newDeviceSet.keep(); - return result; - }); - - add("cleanup", - "Remove the channels that listen and scan added, on one device set or all of them, and the features listen added " - "for them (AIS, Radiosonde, APRS) once nothing feeds them. Each is otherwise left running, every demodulator playing " - "audio, until the next listen or scan on the same device set replaces it. Channels and features added any other way " - "are left alone; delete_channel and delete_feature remove those.", - schema({ - {"deviceSetIndex", intProp("Only this device set. Default: every device set")} - }), - [this](const QJsonObject& args) - { - QList deviceSetIndices; - - if (hasArg(args, "deviceSetIndex")) - { - deviceSetIndices.append(argInt(args, "deviceSetIndex")); - } - else - { - for (const QJsonValue& v : getInstanceSummary()["devicesetlist"].toObject()["deviceSets"].toArray()) { - deviceSetIndices.append(v.toObject()["samplingDevice"].toObject()["index"].toInt()); - } - } - - QJsonArray removed; - int count = 0; - - for (int deviceSetIndex : deviceSetIndices) - { - for (const QString& id : reclaimIntentChannels(deviceSetIndex)) - { - removed.append(QString("R%1:%2").arg(deviceSetIndex).arg(id)); - count++; - } - } - - QJsonArray features; - - for (const QString& id : reclaimIntentFeatures()) - { - features.append(id); - count++; - } - - QJsonObject result; - result["removed"] = count; - result["channels"] = removed; - result["features"] = features; - - if (count == 0) { - result["note"] = "Nothing to remove: no channel or feature added by listen or scan is still there."; - } - - return result; - }); - - add("tune_gain", - "Find the receiver gain that gives the best signal to noise ratio and apply it: steps the device through its gain range " - "and at each step measures the noise floor and the strongest signal on the main spectrum. Too little gain leaves weak " - "signals under the converter's own noise; too much overloads the front end, which raises the floor faster than the " - "signal and adds spurious products, so the best gain is where the difference between them peaks, and of gains within a " - "decibel of that the lowest is taken, for headroom. On a quiet band, where no signal stands clear of the floor, the " - "floor alone decides: the lowest gain at which the antenna's noise rather than the converter's sets it, short of " - "overload. Turns the device's AGC off, as it has to for a manual gain to mean " - "anything. The device must be running. Blocks for a few seconds per step; the reply carries the whole table so the " - "choice can be judged. Give frequency to judge by a particular signal rather than the strongest one. Once the gain " - "is applied the main spectrum is autoscaled to suit it, unless autoscale is false.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"frequency", numProp("Judge by the signal at this frequency in Hz rather than the strongest in the baseband. It must be inside the baseband")}, - {"bandwidth", numProp("Width in Hz around frequency to look for the signal in. Default 200000")}, - {"steps", bounded(intProp("How many gain values to try, spread over the range. Default 8"), 3, 16)}, - {"apply", prop("boolean", "Apply the chosen gain. false measures and reports but puts the gain back as it was. Default true")}, - {"autoscale", prop("boolean", "Once the chosen gain is applied, set the main spectrum's reference level and range from what it then shows, as spectrum_action autoscale does, so the display suits the new gain. Default true")}, - {"gainKey", strProp("For a device type this does not know: the settings key of its gain, from describe_settings. Then give values too")}, - {"values", prop("array", "For a device type this does not know: the gain values to try, in the key's own units, lowest first")}, - {"agcKey", strProp("For a device type this does not know: the settings key that turns its AGC off when set to 0")} - }, {"deviceSetIndex"}), - [this](const QJsonObject& args) { return tuneGain(args); }); - - add("get_status", - "One line per device set and feature: device, frequency, run state and channels. The cheapest way to see what is going on.", - schema(QJsonObject()), - [this](const QJsonObject&) - { - QJsonObject summary = getInstanceSummary(); - QStringList lines; - - for (const QJsonValue& v : summary["devicesetlist"].toObject()["deviceSets"].toArray()) - { - QJsonObject ds = v.toObject(); - QJsonObject sd = ds["samplingDevice"].toObject(); - QStringList channels; - - for (const QJsonValue& c : ds["channels"].toArray()) - { - QJsonObject ch = c.toObject(); - channels.append(QString("%1 %2%3k").arg(ch["id"].toString()) - .arg(ch["deltaFrequency"].toDouble() >= 0 ? "+" : "").arg(ch["deltaFrequency"].toDouble() / 1000.0, 0, 'f', 1)); - } - - static const char *const prefixes[] = {"R", "T", "M"}; - lines.append(QString("%1%2 %3 %4 %5 MHz %6%7") - .arg(prefixes[qBound(0, sd["direction"].toInt(), 2)]).arg(sd["index"].toInt()) - .arg(sd["hwType"].toString()).arg(sd["serial"].toString()) - .arg(sd["centerFrequency"].toDouble() / 1e6, 0, 'f', 3).arg(sd["state"].toString()) - .arg(channels.isEmpty() ? QString() : ": " + channels.join(", "))); - } - - for (const QJsonValue& v : summary["featureset"].toObject()["features"].toArray()) - { - QJsonObject f = v.toObject(); - int index = f["index"].toInt(); - lines.append(QString("F%1 %2 %3").arg(index).arg(f["id"].toString()).arg(featureState(index, -1)["state"].toString())); - } - - return QJsonValue(lines.isEmpty() ? QString("Nothing configured") : lines.join("\n")); - }); -} +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// (at your option) any later version. // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "SWGErrorResponse.h" +#include "SWGSuccessResponse.h" +#include "SWGInstanceSummaryResponse.h" +#include "SWGInstanceDevicesResponse.h" +#include "SWGInstanceChannelsResponse.h" +#include "SWGInstanceFeaturesResponse.h" +#include "SWGDeviceSetList.h" +#include "SWGDeviceSet.h" +#include "SWGDeviceListItem.h" +#include "SWGDeviceSettings.h" +#include "SWGDeviceState.h" +#include "SWGDeviceReport.h" +#include "SWGDeviceActions.h" +#include "SWGChannelSettings.h" +#include "SWGChannelReport.h" +#include "SWGChannelActions.h" +#include "SWGChannelsDetail.h" +#include "SWGFeatureSet.h" +#include "SWGFeatureSettings.h" +#include "SWGFeatureReport.h" +#include "SWGFeatureActions.h" +#include "SWGPresets.h" +#include "SWGPresetGroup.h" +#include "SWGPresetItem.h" +#include "SWGPresetTransfer.h" +#include "SWGPresetIdentifier.h" +#include "SWGConfigurations.h" +#include "SWGConfigurationIdentifier.h" +#include "SWGWorkspaceInfo.h" +#include "SWGWorkspaceActions.h" +#include "SWGWindowList.h" +#include "SWGGLSpectrum.h" +#include "SWGGLSpectrumReport.h" +#include "SWGSpectrumActions.h" +#include "SWGGLSpectrumData.h" +#include "SWGGLSpectrumHistory.h" +#include "SWGSpectrumHistorySignal.h" +#include "SWGAudioDevices.h" +#include "SWGLocationInformation.h" + +#include "maincore.h" +#include "device/deviceset.h" +#include "channel/channelapi.h" +#include "device/deviceapi.h" +#include "feature/feature.h" +#include "feature/featureset.h" +#include "webapi/webapiadapterinterface.h" +#include "webapi/webapiutils.h" + +#include "mcpstreams.h" +#include "mcptools.h" + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +namespace { + +QJsonObject toJson(SWGSDRangel::SWGObject& object) +{ + QJsonObject *obj = object.asJsonObject(); + QJsonObject result = *obj; + delete obj; + return result; +} + +QString compact(const QJsonValue& value) +{ + if (value.isObject()) { + return QString(QJsonDocument(value.toObject()).toJson(QJsonDocument::Compact)); + } else if (value.isArray()) { + return QString(QJsonDocument(value.toArray()).toJson(QJsonDocument::Compact)); + } else if (value.isString()) { + return value.toString(); + } else { + return QString(QJsonDocument(QJsonArray({value})).toJson(QJsonDocument::Compact)); + } +} + +// Throws if the Web API call failed +void check(int httpRC, SWGSDRangel::SWGErrorResponse& error, const QString& what) +{ + if (httpRC / 100 != 2) + { + QString message = error.getMessage() ? *error.getMessage() : QString(); + throw MCPToolError(QString("%1 failed (HTTP %2)%3").arg(what).arg(httpRC).arg(message.isEmpty() ? "" : ": " + message)); + } +} + +// Argument access. Accepts numbers given as strings, as models sometimes do. +bool hasArg(const QJsonObject& args, const QString& key) +{ + return args.contains(key) && !args[key].isNull() && !args[key].isUndefined(); +} + +// Models write booleans as JSON booleans mostly, but also as "true"/"false" strings and as 0/1, +// and QJsonValue::toBool answers its default for anything but a JSON boolean, which turned +// replace "false" into true. Absent, null and anything unreadable give the default +bool argBool(const QJsonObject& args, const QString& key, bool defaultValue) +{ + if (!hasArg(args, key)) { + return defaultValue; + } + + const QJsonValue value = args.value(key); + + if (value.isBool()) { + return value.toBool(); + } + + if (value.isDouble()) { + return value.toDouble() != 0.0; + } + + if (value.isString()) + { + const QString text = value.toString().trimmed().toLower(); + + if ((text == "true") || (text == "1") || (text == "yes") || (text == "on")) { + return true; + } + + if ((text == "false") || (text == "0") || (text == "no") || (text == "off") || text.isEmpty()) { + return false; + } + } + + return defaultValue; +} + +int argInt(const QJsonObject& args, const QString& key, bool required = true, int defaultValue = 0) +{ + if (!hasArg(args, key)) + { + if (required) { + throw MCPToolError(QString("Missing required argument: %1").arg(key)); + } + + return defaultValue; + } + + QJsonValue value = args[key]; + + if (value.isDouble()) { + return (int) value.toDouble(); + } + + bool ok; + int result = value.toString().trimmed().toInt(&ok); + + if (!ok) + { + double d = value.toString().trimmed().toDouble(&ok); + + if (ok) { + return (int) d; + } + + throw MCPToolError(QString("Argument %1 must be an integer").arg(key)); + } + + return result; +} + +qint64 argInt64(const QJsonObject& args, const QString& key, bool required = true, qint64 defaultValue = 0) +{ + if (!hasArg(args, key)) + { + if (required) { + throw MCPToolError(QString("Missing required argument: %1").arg(key)); + } + + return defaultValue; + } + + QJsonValue value = args[key]; + + if (value.isDouble()) { + return (qint64) value.toDouble(); + } + + bool ok; + double d = value.toString().trimmed().toDouble(&ok); + + if (!ok) { + throw MCPToolError(QString("Argument %1 must be a number").arg(key)); + } + + return (qint64) d; +} + +double argDouble(const QJsonObject& args, const QString& key, bool required = true, double defaultValue = 0.0) +{ + if (!hasArg(args, key)) + { + if (required) { + throw MCPToolError(QString("Missing required argument: %1").arg(key)); + } + + return defaultValue; + } + + QJsonValue value = args[key]; + + if (value.isDouble()) { + return value.toDouble(); + } + + bool ok; + double d = value.toString().trimmed().toDouble(&ok); + + if (!ok) { + throw MCPToolError(QString("Argument %1 must be a number").arg(key)); + } + + return d; +} + +QString argString(const QJsonObject& args, const QString& key, bool required = true, const QString& defaultValue = QString()) +{ + if (!hasArg(args, key)) + { + if (required) { + throw MCPToolError(QString("Missing required argument: %1").arg(key)); + } + + return defaultValue; + } + + QJsonValue value = args[key]; + + if (value.isString()) { + return value.toString(); + } else if (value.isDouble()) { + return QString::number(value.toDouble(), 'g', 15); + } else { + return compact(value); + } +} + +QJsonObject argObject(const QJsonObject& args, const QString& key, bool required = true) +{ + if (!hasArg(args, key)) + { + if (required) { + throw MCPToolError(QString("Missing required argument: %1").arg(key)); + } + + return QJsonObject(); + } + + QJsonValue value = args[key]; + + if (value.isObject()) { + return value.toObject(); + } + + // Tolerate an object passed as a JSON string + if (value.isString()) + { + QJsonDocument doc = QJsonDocument::fromJson(value.toString().toUtf8()); + + if (doc.isObject()) { + return doc.object(); + } + } + + throw MCPToolError(QString("Argument %1 must be a JSON object").arg(key)); +} + +// direction: "rx" / "tx" / "mimo" or 0 / 1 / 2 +int argDirection(const QJsonObject& args, const QString& key = "direction", bool required = false, int defaultValue = 0) +{ + if (!hasArg(args, key)) + { + if (required) { + throw MCPToolError(QString("Missing required argument: %1").arg(key)); + } + + return defaultValue; + } + + QJsonValue value = args[key]; + + if (value.isDouble()) { + return (int) value.toDouble(); + } + + QString s = value.toString().trimmed().toLower(); + + if ((s == "rx") || (s == "0") || (s == "receive") || (s == "source")) { + return 0; + } else if ((s == "tx") || (s == "1") || (s == "transmit") || (s == "sink")) { + return 1; + } else if ((s == "mimo") || (s == "2")) { + return 2; + } + + throw MCPToolError(QString("Argument %1 must be \"rx\", \"tx\" or \"mimo\"").arg(key)); +} + +QString directionName(int direction) +{ + switch (direction) + { + case 0: return "rx"; + case 1: return "tx"; + case 2: return "mimo"; + default: return QString::number(direction); + } +} + +// JSON schema builders +QJsonObject prop(const QString& type, const QString& description) +{ + QJsonObject p; + p["type"] = type; + p["description"] = description; + return p; +} + +QJsonObject intProp(const QString& description) { return prop("integer", description); } +QJsonObject numProp(const QString& description) { return prop("number", description); } +QJsonObject strProp(const QString& description) { return prop("string", description); } +QJsonObject objProp(const QString& description) { return prop("object", description); } + +QJsonObject enumProp(const QString& description, const QStringList& values) +{ + QJsonObject p = strProp(description); + p["enum"] = QJsonArray::fromStringList(values); + return p; +} + +QJsonObject directionProp(const QString& description) +{ + return enumProp(description, {"rx", "tx", "mimo"}); +} + +// Adds the bounds a handler enforces at runtime to the schema, so a client can see them +QJsonObject bounded(QJsonObject property, double minimum, double maximum) +{ + property["minimum"] = minimum; + property["maximum"] = maximum; + return property; +} + +QJsonObject schema(const QJsonObject& properties, const QStringList& required = QStringList()) +{ + QJsonObject s; + s["type"] = "object"; + s["properties"] = properties; + s["required"] = QJsonArray::fromStringList(required); + s["additionalProperties"] = false; + return s; +} + +const QJsonObject deviceSetIndexProp = intProp("Index of the device set (0 for R0, the first device set)"); +const QJsonObject channelIndexProp = intProp("Index of the channel within the device set"); +const QJsonObject featureIndexProp = intProp("Index of the feature within the feature set"); + +// Settings keys in the form used by the Web API PATCH: nested keys are dotted, array elements indexed +void extractKeys(const QJsonObject& json, QStringList& keys, const QString& prefix = QString()) +{ + for (const QString& key : json.keys()) + { + QString full = prefix.isEmpty() ? key : prefix + "." + key; + keys.append(full); + + if (json[key].isObject()) + { + extractKeys(json[key].toObject(), keys, full); + } + else if (json[key].isArray()) + { + QJsonArray array = json[key].toArray(); + + for (int i = 0; i < array.count(); i++) + { + QString element = QString("%1[%2]").arg(full).arg(i); + keys.append(element); + + if (array.at(i).isObject()) { + extractKeys(array.at(i).toObject(), keys, element); + } + } + } + } +} + +// Applies patch on top of target. Objects are merged recursively, everything else replaced. +// Keys absent from target are reported (they may still be valid: empty strings are not serialized). +void mergeInto(QJsonObject& target, const QJsonObject& patch, QStringList& unknownKeys, const QString& prefix = QString()) +{ + for (const QString& key : patch.keys()) + { + QString full = prefix.isEmpty() ? key : prefix + "." + key; + + if (!target.contains(key)) { + unknownKeys.append(full); + } + + if (patch[key].isObject() && target[key].isObject()) + { + QJsonObject sub = target[key].toObject(); + mergeInto(sub, patch[key].toObject(), unknownKeys, full); + target[key] = sub; + } + else + { + target[key] = patch[key]; + } + } +} + +int leadingSpaces(const QString& line) +{ + int count = 0; + + while ((count < line.length()) && (line.at(count) == ' ')) { + count++; + } + + return count; +} + +// Reads the property names and types out of one swagger definition. Only the properties of the +// definition itself are taken: the attributes of a property sit two spaces further in, so an +// items: block of an array cannot be mistaken for the array's own type. +SettingsSchema parseSettingsSchema(const QString& yaml) +{ + SettingsSchema schema; + int propertiesIndent = -1; + int nameIndent = -1; + QString property; + + for (const QString& line : yaml.split('\n')) + { + QString text = line.trimmed(); + + if (text.isEmpty() || text.startsWith('#')) { + continue; + } + + int indent = leadingSpaces(line); + + if (propertiesIndent < 0) + { + if (text == "properties:") { + propertiesIndent = indent; + } + + continue; + } + + if (indent <= propertiesIndent) { + break; // out of the properties block and into the next section of the definition + } + + if (nameIndent < 0) { + nameIndent = indent; + } + + if (indent == nameIndent) + { + if (text.endsWith(':')) + { + property = text.left(text.length() - 1); + schema.m_types.insert(property, QString()); + } + else + { + property.clear(); + } + } + else if ((indent == nameIndent + 2) && !property.isEmpty()) + { + if (text.startsWith("type:")) { + schema.m_types[property] = text.mid(5).trimmed(); + } else if (text.startsWith("$ref:") && schema.m_types.value(property).isEmpty()) { + schema.m_types[property] = "object"; + } + } + } + + schema.m_known = !schema.m_types.isEmpty(); + return schema; +} + +// Checks a patch against the schema and returns it with the one conversion worth making. Values +// are checked here rather than left to the SWG object, whose setValue() turns a string into zero +// without complaint: "rfBandwidth": "wide" would otherwise stop the channel demodulating and be +// reported as a successful change. +QJsonObject checkAgainstSchema(const QJsonObject& patch, const SettingsSchema& schema, + QStringList& unknownKeys, QStringList& typeErrors) +{ + QJsonObject checked; + + for (const QString& key : patch.keys()) + { + QJsonValue value = patch[key]; + + if (!schema.m_types.contains(key)) + { + unknownKeys.append(key); + checked[key] = value; + continue; + } + + QString type = schema.m_types[key]; + bool numeric = (type == "integer") || (type == "number"); + + if (numeric && value.isBool()) + { + // Unambiguous and lossless, and the natural way to write a 0/1 flag + checked[key] = value.toBool() ? 1 : 0; + continue; + } + + bool ok = true; + + if (numeric) { + ok = value.isDouble(); + } else if (type == "string") { + ok = value.isString(); + } else if (type == "array") { + ok = value.isArray(); + } else if (type == "object") { + ok = value.isObject(); + } + + if (!ok) + { + QString got = value.isString() ? "string" : + value.isDouble() ? "number" : + value.isBool() ? "boolean" : + value.isArray() ? "array" : + value.isObject() ? "object" : "null"; + typeErrors.append(QString("%1 expects %2 but was given a %3 (%4)") + .arg(key).arg(type).arg(got).arg(compact(QJsonObject{{key, value}}))); + } + + checked[key] = value; + } + + return checked; +} + +// The key holding the type specific settings, e.g. "rtlSdrSettings" or "ADSBDemodSettings" +QString findSettingsKey(const QJsonObject& json) +{ + for (const QString& key : json.keys()) + { + if (key.endsWith("Settings") && json[key].isObject()) { + return key; + } + } + + return QString(); +} + +// Generic settings patch: read current settings, merge the partial object given by the model +// into the type specific sub-object, then PATCH with the list of changed keys. +template +QJsonObject applySettingsPatch( + const std::function& get, + const std::function& put, + const QJsonObject& partial, + const QString& what, + const std::function& schemaFor) +{ + SWGSDRangel::SWGErrorResponse error; + error.init(); + SWG current; + check(get(current, error), error, "Get " + what); + QJsonObject json = toJson(current); + QString settingsKey = findSettingsKey(json); + + if (settingsKey.isEmpty()) { + throw MCPToolError(QString("Cannot find settings object in current %1: %2").arg(what).arg(compact(json))); + } + + QJsonObject subPartial; + + if (partial.contains(settingsKey)) + { + subPartial = partial[settingsKey].toObject(); + } + else + { + for (const QString& key : partial.keys()) + { + if (key.endsWith("Settings") && partial[key].isObject()) { + throw MCPToolError(QString("Settings object key %1 does not match the current type. Expected %2 or the bare settings object").arg(key).arg(settingsKey)); + } + } + + subPartial = partial; + } + + if (subPartial.isEmpty()) { + throw MCPToolError("No settings given"); + } + + QStringList unknownKeys; + SettingsSchema schema = schemaFor(settingsKey); + + if (schema.m_known) + { + QStringList typeErrors; + subPartial = checkAgainstSchema(subPartial, schema, unknownKeys, typeErrors); + + if (!typeErrors.isEmpty()) + { + throw MCPToolError(QString("Wrong value type for %1: %2. Numbers must be given as JSON " + "numbers, not strings. Nothing was changed.").arg(settingsKey).arg(typeErrors.join("; "))); + } + } + + QJsonObject sub = json[settingsKey].toObject(); + QStringList merged; + mergeInto(sub, subPartial, merged); + json[settingsKey] = sub; + + if (!schema.m_known) + { + // Without a schema the only test left is whether the key is in the current settings, which + // misses any string setting that is currently empty. Better than nothing, but not by much + unknownKeys = merged; + } + + QStringList keys; + extractKeys(subPartial, keys); + + SWG request; + request.fromJsonObject(json); + error.init(); + check(put(keys, request, error), error, "Set " + what); + + // Reply with only what was asked for, read back from the object that was sent. Echoing + // the whole settings block cost a client about 500 tokens per call, carried for the rest + // of the conversation, to confirm a one key change. + QJsonObject after = toJson(request)[settingsKey].toObject(); + QJsonObject changed; + + for (const QString& key : subPartial.keys()) + { + if (after.contains(key)) { + changed[key] = after[key]; + } + } + + QJsonObject result; + result["changed"] = changed; + + if (!unknownKeys.isEmpty()) { + result["warning"] = QString("Ignored unknown keys: %1. describe_settings lists the valid ones.").arg(unknownKeys.join(", ")); + } + + return result; +} + +QString capitalize(const QString& s) +{ + return s.isEmpty() ? s : s.at(0).toUpper() + s.mid(1); +} + +// The plugin lists carry a URI, a version and an index per entry that no caller needs. Each +// becomes one string: the id the other tools take, with the display name in brackets when it +// says something the id does not. +// Features with no run state: they work from the moment they are configured. Some answer the run +// request with 501 and the rest accept it and stay idle, so neither the request nor the state that +// follows it tells them apart from a feature that is slow to start +const QStringList passiveFeatureTypes = { + "AIS", "AMBE", "AntennaTools", "APRS", "FreqDisplay", "LimeRFE", "Map", "Radiosonde", + "RemoteControl", "SkyMap" +}; + +bool isPassiveFeature(const QString& featureType) +{ + return passiveFeatureTypes.contains(featureType); +} + +QJsonArray idsAndNames(const QJsonArray& plugins) +{ + QJsonArray out; + + for (const QJsonValue& v : plugins) + { + QJsonObject p = v.toObject(); + QString id = p["id"].toString(); + QString name = p["name"].toString(); + + if (!name.isEmpty() && (name.compare(id, Qt::CaseInsensitive) != 0)) { + out.append(QString("%1 (%2)").arg(id).arg(name)); + } else { + out.append(id); + } + } + + return out; +} + +} // namespace + +// --------------------------------------------------------------------------- +// Event counter +// --------------------------------------------------------------------------- + +MCPEventCounter::MCPEventCounter() : + m_deviceSetAdded(0), + m_deviceSetRemoved(0), + m_deviceChanged(0), + m_channelAdded(0), + m_channelRemoved(0), + m_featureAdded(0), + m_featureRemoved(0) +{ + MainCore *mainCore = MainCore::instance(); + connect(mainCore, &MainCore::deviceSetAdded, this, &MCPEventCounter::onDeviceSetAdded); + connect(mainCore, &MainCore::deviceSetRemoved, this, &MCPEventCounter::onDeviceSetRemoved); + connect(mainCore, &MainCore::deviceChanged, this, &MCPEventCounter::onDeviceChanged); + connect(mainCore, &MainCore::channelAdded, this, &MCPEventCounter::onChannelAdded); + connect(mainCore, &MainCore::channelRemoved, this, &MCPEventCounter::onChannelRemoved); + connect(mainCore, &MainCore::featureAdded, this, &MCPEventCounter::onFeatureAdded); + connect(mainCore, &MainCore::featureRemoved, this, &MCPEventCounter::onFeatureRemoved); +} + +void MCPEventCounter::onDeviceSetAdded(int index, DeviceAPI *device) +{ + (void) index; + (void) device; + m_deviceSetAdded.fetchAndAddRelease(1); +} + +void MCPEventCounter::onDeviceSetRemoved(int index) +{ + (void) index; + m_deviceSetRemoved.fetchAndAddRelease(1); +} + +void MCPEventCounter::onDeviceChanged(int index) +{ + (void) index; + m_deviceChanged.fetchAndAddRelease(1); +} + +void MCPEventCounter::onChannelAdded(int deviceSetIndex, ChannelAPI *channel) +{ + (void) deviceSetIndex; + (void) channel; + m_channelAdded.fetchAndAddRelease(1); +} + +void MCPEventCounter::onChannelRemoved(int deviceSetIndex, ChannelAPI *channel) +{ + (void) deviceSetIndex; + (void) channel; + m_channelRemoved.fetchAndAddRelease(1); +} + +void MCPEventCounter::onFeatureAdded(int featureSetIndex, Feature *feature) +{ + (void) featureSetIndex; + (void) feature; + m_featureAdded.fetchAndAddRelease(1); +} + +void MCPEventCounter::onFeatureRemoved(int featureSetIndex, Feature *feature) +{ + (void) featureSetIndex; + (void) feature; + m_featureRemoved.fetchAndAddRelease(1); +} + +// --------------------------------------------------------------------------- +// Registry +// --------------------------------------------------------------------------- + +MCPTools::MCPTools(WebAPIAdapterInterface *webAPIAdapterInterface) : + m_adapter(webAPIAdapterInterface), + m_capture(webAPIAdapterInterface), + m_streams(nullptr), + m_ownerFeature(nullptr), + m_stopping(0), + m_yamlLoaded(false) +{ + registerInstanceTools(); + registerDeviceSetTools(); + registerChannelTools(); + registerFeatureTools(); + registerPresetTools(); + registerWorkspaceTools(); + registerCaptureTools(); + registerIntentTools(); +} + +void MCPTools::setStopping(bool stopping) +{ + m_stopping.storeRelease(stopping ? 1 : 0); + m_capture.setStopping(stopping); +} + +// The tools run on HTTP threads and wait for work that completes on the main thread. When the +// server stops, the main thread waits for the HTTP threads instead, so a wait that carried on +// would hold it for its whole timeout, or for ever where the main thread itself is what is +// waited for. Every wait therefore gives up at once when a stop is under way +bool MCPTools::waitFor(const std::function& condition, int timeoutMs) const +{ + QElapsedTimer timer; + timer.start(); + + while (!condition()) + { + if (m_stopping.loadAcquire()) { + throw MCPToolError("The MCP server is stopping, so this call was abandoned"); + } + + if (timer.elapsed() > timeoutMs) { + return false; + } + + QThread::msleep(20); + } + + return true; +} + +void MCPTools::pause(int ms) const +{ + QElapsedTimer timer; + timer.start(); + + for (;;) + { + if (m_stopping.loadAcquire()) { + throw MCPToolError("The MCP server is stopping, so this call was abandoned"); + } + + // Read once: read again for the sleep, the limit could pass in between and a negative + // remainder become an unsigned sleep of weeks + const qint64 remaining = ms - timer.elapsed(); + + if (remaining <= 0) { + return; + } + + QThread::msleep((unsigned long) std::min(50, remaining)); + } +} + +// Per tool behaviour. The MCP hints are narrower than they look: destructiveHint false means +// the tool is additive only, so anything that overwrites existing state is destructive, and +// openWorldHint true means the tool can reach beyond this application, which covers commanding +// the radio, features that talk to network services, and data arriving from unknown transmitters. +struct ToolBehaviour +{ + bool m_readOnly; + bool m_destructive; + bool m_idempotent; + bool m_openWorld; +}; + +static ToolBehaviour behaviourFor(const QString& name) +{ + // Reads of this instance's own configuration and of documentation compiled into the plugin + static const QStringList localReads = { + "get_instance_summary", "list_available_devices", "list_channel_types", "list_feature_types", + "describe_settings", "get_receiving_guide", "list_docs", "get_docs", "list_audio_devices", + "get_location", "get_deviceset", "get_device_settings", + "get_spectrum_settings", "get_spectrum_report", "get_spectrum_data", "get_channel_settings", "get_feature_settings", + "list_presets", "list_configurations", "get_server_status", "get_status" + }; + + // Reads that return data received off the air, from transmitters this instance does not + // control, or from the network services some features talk to. Reports carry it as well as + // the dedicated data feeds do: an ADS-B report, for instance, lists the aircraft heard. + static const QStringList offAirReads = { + "get_packets", "get_map_items", "get_channel_report", + "get_device_report", "get_feature_report" + }; + + // Purely additive: they create something new and overwrite nothing + static const QStringList additive = { + "add_deviceset", "add_channel", "add_feature", "add_workspace", "add_annotation" + }; + + if (localReads.contains(name)) { + return {true, false, true, false}; + } + + if (offAirReads.contains(name)) { + return {true, false, true, true}; + } + + if (additive.contains(name)) { + return {false, false, false, true}; + } + + // Everything else changes or removes state. Only the workspace moves and the settings writes + // land in the same place when repeated; captures, actions and creation do not. + bool idempotent = name.startsWith("set_") || name.startsWith("stop_") || (name == "clear_packets"); + return {false, true, idempotent, true}; +} + +void MCPTools::add(const QString& name, const QString& description, const QJsonObject& inputSchema, + std::function handler) +{ + Tool tool; + tool.name = name; + tool.description = description; + tool.inputSchema = inputSchema; + tool.handler = handler; + m_tools.append(tool); +} + +QJsonArray MCPTools::listTools() const +{ + QJsonArray tools; + + for (const Tool& tool : m_tools) + { + QJsonObject t; + t["name"] = tool.name; + t["description"] = tool.description; + t["inputSchema"] = tool.inputSchema; + ToolBehaviour behaviour = behaviourFor(tool.name); + // Clients carry the whole tool list on every turn, so only say what differs from the + // defaults the MCP schema gives an absent hint (read-write, destructive, not + // idempotent, open world), and no title, which would repeat the description + QJsonObject annotations; + if (behaviour.m_readOnly) { annotations["readOnlyHint"] = true; } + if (!behaviour.m_destructive) { annotations["destructiveHint"] = false; } + if (behaviour.m_idempotent) { annotations["idempotentHint"] = true; } + if (!behaviour.m_openWorld) { annotations["openWorldHint"] = false; } + if (!annotations.isEmpty()) { t["annotations"] = annotations; } + tools.append(t); + } + + return tools; +} + +QJsonObject MCPTools::callTool(const QString& name, const QJsonObject& arguments) +{ + const Tool *tool = nullptr; + + for (const Tool& t : m_tools) + { + if (t.name == name) + { + tool = &t; + break; + } + } + + if (!tool) { + throw MCPError(-32602, QString("Unknown tool: %1").arg(name)); + } + + QJsonObject result; + QJsonArray content; + + try + { + // Every input schema says additionalProperties: false, so an argument a tool does not + // define is a mistake worth reporting. Dropping it silently turns a wrong call into a + // plausible wrong answer: get_packets, which filters on source and type, looks as though + // it is ignoring a deviceSetIndex and channelIndex filter it never had + QJsonObject properties = tool->inputSchema.value("properties").toObject(); + QStringList unknown; + + for (const QString& key : arguments.keys()) + { + if (!properties.contains(key)) { + unknown.append(key); + } + } + + if (!unknown.isEmpty()) + { + QStringList accepted = properties.keys(); + throw MCPToolError(QString("%1 does not take %2. It accepts: %3") + .arg(name) + .arg(unknown.join(", ")) + .arg(accepted.isEmpty() ? QString("no arguments") : accepted.join(", "))); + } + + QJsonValue value = tool->handler(arguments); + + // A handler that has a picture to show puts it under _image, which becomes an image + // content item beside the text rather than a base64 blob in it + QJsonObject image; + + if (value.isObject() && value.toObject().contains("_image")) + { + QJsonObject object = value.toObject(); + image = object.take("_image").toObject(); + value = object; + } + + QJsonObject text; + text["type"] = "text"; + text["text"] = compact(value); + content.append(text); + + if (!image.isEmpty()) + { + QJsonObject item; + item["type"] = "image"; + item["data"] = image["data"]; + item["mimeType"] = image["mimeType"]; + content.append(item); + } + + if (value.isObject()) { + result["structuredContent"] = value; + } + + result["isError"] = false; + } + catch (const MCPToolError& e) + { + qDebug() << "MCPTools::callTool:" << name << "error:" << e.message; + QJsonObject text; + text["type"] = "text"; + text["text"] = "Error: " + e.message; + content.append(text); + result["isError"] = true; + } + + result["content"] = content; + return result; +} + +// --------------------------------------------------------------------------- +// Instance level data +// --------------------------------------------------------------------------- + +QJsonObject MCPTools::getInstanceSummary() +{ + SWGSDRangel::SWGInstanceSummaryResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->instanceSummary(response, error), error, "Get instance summary"); + return toJson(response); +} + +QJsonObject MCPTools::getAvailableDevices(int direction) +{ + QJsonObject result; + + for (int dir = 0; dir < 3; dir++) + { + if ((direction >= 0) && (direction != dir)) { + continue; + } + + SWGSDRangel::SWGInstanceDevicesResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->instanceDevices(dir, response, error), error, "List devices"); + result[directionName(dir)] = toJson(response)["devices"].toArray(); + } + + return result; +} + +QJsonObject MCPTools::getAvailableChannels(int direction) +{ + QJsonObject result; + + for (int dir = 0; dir < 3; dir++) + { + if ((direction >= 0) && (direction != dir)) { + continue; + } + + SWGSDRangel::SWGInstanceChannelsResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->instanceChannels(dir, response, error), error, "List channel types"); + result[directionName(dir)] = idsAndNames(toJson(response)["channels"].toArray()); + } + + return result; +} + +QJsonObject MCPTools::getAvailableFeatures() +{ + SWGSDRangel::SWGInstanceFeaturesResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->instanceFeatures(response, error), error, "List feature types"); + QJsonObject result; + QJsonArray features; + + for (const QJsonValue& v : toJson(response)["features"].toArray()) + { + QString entry = v.toObject()["id"].toString(); + features.append(isPassiveFeature(entry) + ? QString("%1 [passive: no run state, do not start it]").arg(idsAndNames(QJsonArray{v}).first().toString()) + : idsAndNames(QJsonArray{v}).first().toString()); + } + + result["features"] = features; + return result; +} + +QJsonObject MCPTools::getPresets() +{ + SWGSDRangel::SWGPresets response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->instancePresetsGet(response, error), error, "List presets"); + return toJson(response); +} + +QJsonObject MCPTools::getConfigurations() +{ + SWGSDRangel::SWGConfigurations response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->instanceConfigurationsGet(response, error), error, "List configurations"); + return toJson(response); +} + +QJsonObject MCPTools::getDeviceSet(int deviceSetIndex) +{ + SWGSDRangel::SWGDeviceSet response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->devicesetGet(deviceSetIndex, response, error), error, QString("Get device set %1").arg(deviceSetIndex)); + return toJson(response); +} + +void MCPTools::loadYamlDefinitions() +{ + if (m_yamlLoaded) { + return; + } + + m_yamlLoaded = true; + QDir dir(":/webapi/doc/swagger/include"); + QRegularExpression definitionStart("^([A-Za-z0-9_]+):\\s*$"); + + for (const QString& fileName : dir.entryList(QStringList("*.yaml"), QDir::Files)) + { + QFile file(dir.filePath(fileName)); + + if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { + continue; + } + + QString name; + QStringList block; + + for (const QString& line : QString::fromUtf8(file.readAll()).split('\n')) + { + QRegularExpressionMatch match = definitionStart.match(line); + + if (match.hasMatch()) + { + if (!name.isEmpty()) { + m_yamlDefinitions[name] = block.join('\n').trimmed(); + } + + name = match.captured(1); + block.clear(); + } + + block.append(line); + } + + if (!name.isEmpty()) { + m_yamlDefinitions[name] = block.join('\n').trimmed(); + } + } + + for (auto name = m_yamlDefinitions.keyBegin(); name != m_yamlDefinitions.keyEnd(); ++name) { + m_yamlDefinitionsByLower.insert(name->toLower(), *name); + } + + qDebug("MCPTools::loadYamlDefinitions: %d definitions", (int) m_yamlDefinitions.size()); +} + +// The JSON settings key does not always capitalise the way its swagger definition does: +// testSourceSettings comes from TestSourceSettings, and sdrPlayV3Settings from SDRPlayV3Settings. +// Only the case ever differs, so a name that does not match exactly is looked up without it. +// Returns an empty string when there is no such definition +QString MCPTools::resolveDefinition(const QString& name) +{ + loadYamlDefinitions(); + + if (m_yamlDefinitions.contains(name)) { + return name; + } + + return m_yamlDefinitionsByLower.value(name.toLower()); +} + +QString MCPTools::describeType(const QString& typeIn, const QString& kindIn) +{ + QMutexLocker schemaLock(&m_schemaMutex); + loadYamlDefinitions(); + QString type = typeIn.trimmed(); + QString kind = kindIn.trimmed().toLower(); + // (settings JSON key, description of what matched) + QList> matches; + + // The spectrum display is not a type: its definitions are named after it directly + const QString lower = type.toLower(); + + if ((kind == "spectrum") || (lower == "spectrum") || (lower == "glspectrum")) + { + QStringList out; + out.append("# main spectrum display of a device set\n# get_spectrum_settings / set_spectrum_settings, get_spectrum_report, spectrum_action\n" + "# get_docs spectrum explains the display and its controls\n"); + + for (const QString& definition : {"GLSpectrum", "GLSpectrumReport", "SpectrumActions"}) + { + if (m_yamlDefinitions.contains(definition)) + { + out.append(m_yamlDefinitions[definition]); + out.append(""); + } + } + + return out.join('\n'); + } + + if (kind.isEmpty() || (kind == "channel")) + { + if (WebAPIUtils::m_channelTypeToSettingsKey.contains(type)) { + matches.append({WebAPIUtils::m_channelTypeToSettingsKey[type], "channel type " + type}); + } + } + + if (kind.isEmpty() || (kind == "device")) + { + if (WebAPIUtils::m_sourceDeviceHwIdToSettingsKey.contains(type)) { + matches.append({WebAPIUtils::m_sourceDeviceHwIdToSettingsKey[type], "rx device " + type}); + } + if (WebAPIUtils::m_sinkDeviceHwIdToSettingsKey.contains(type)) { + matches.append({WebAPIUtils::m_sinkDeviceHwIdToSettingsKey[type], "tx device " + type}); + } + if (WebAPIUtils::m_mimoDeviceHwIdToSettingsKey.contains(type)) { + matches.append({WebAPIUtils::m_mimoDeviceHwIdToSettingsKey[type], "mimo device " + type}); + } + } + + if (kind.isEmpty() || (kind == "feature")) + { + if (WebAPIUtils::m_featureTypeToSettingsKey.contains(type)) { + matches.append({WebAPIUtils::m_featureTypeToSettingsKey[type], "feature type " + type}); + } + } + + // Also accept a definition name given directly, e.g. "RtlSdrSettings" or "RtlSdr" + if (matches.isEmpty()) + { + if (!resolveDefinition(type + "Settings").isEmpty()) { + matches.append({type + "Settings", type}); + } else if (!resolveDefinition(type).isEmpty()) { + matches.append({type, type}); + } + } + + if (matches.isEmpty()) + { + throw MCPToolError(QString("Unknown type %1. Use the id values returned by list_channel_types, list_feature_types " + "or the hwType values returned by list_available_devices").arg(type)); + } + + QStringList out; + + for (const auto& match : matches) + { + QString settingsKey = match.first; + QString base = capitalize(settingsKey); + + if (base.endsWith("Settings")) { + base.chop(QString("Settings").size()); + } + + out.append(QString("# %1\n# Settings JSON key: %2\n").arg(match.second).arg(settingsKey)); + bool found = false; + + // A definition given by its own name that is not a Settings one, such as a Report or a + // marker, is what was asked for and is not reached by the suffixes below + if (!settingsKey.endsWith("Settings") && m_yamlDefinitions.contains(resolveDefinition(settingsKey))) + { + out.append(m_yamlDefinitions[resolveDefinition(settingsKey)]); + out.append(""); + found = true; + } + + for (const QString suffix : {"Settings", "Report", "Actions"}) + { + QString definition = resolveDefinition(base + suffix); + + if (!definition.isEmpty()) + { + out.append(m_yamlDefinitions[definition]); + out.append(""); + found = true; + } + } + + if (!found) { + out.append(QString("No documentation found for %1").arg(base)); + } + } + + return out.join('\n'); +} + +// --------------------------------------------------------------------------- +// Device set helpers +// --------------------------------------------------------------------------- + +int MCPTools::deviceSetCount() const +{ + return (int) MainCore::instance()->getDeviceSets().size(); +} + +int MCPTools::channelCount(int deviceSetIndex) const +{ + const std::vector& deviceSets = MainCore::instance()->getDeviceSets(); + + if ((deviceSetIndex < 0) || (deviceSetIndex >= (int) deviceSets.size())) { + return -1; + } + + return deviceSets[deviceSetIndex]->getNumberOfChannels(); +} + +int MCPTools::featureCount() const +{ + const std::vector& featureSets = MainCore::instance()->getFeatureeSets(); + + if (featureSets.empty()) { + return -1; + } + + return featureSets[0]->getNumberOfFeatures(); +} + +int MCPTools::deviceSetDirection(int deviceSetIndex) +{ + QJsonObject deviceSet = getDeviceSet(deviceSetIndex); + return deviceSet["samplingDevice"].toObject()["direction"].toInt(0); +} + +// Selects the sampling device of a device set from hwType / serial / sequence / displayedName / deviceIndex +// and waits for SDRangel to switch to it. +QJsonObject MCPTools::selectDevice(int deviceSetIndex, const QJsonObject& args) +{ + int direction = deviceSetDirection(deviceSetIndex); + QString hwType = argString(args, "hwType", false); + QString serial = argString(args, "serial", false); + QString displayedName = argString(args, "displayedName", false); + int sequence = argInt(args, "sequence", false, -1); + int streamIndex = argInt(args, "deviceStreamIndex", false, -1); + + if (hasArg(args, "deviceIndex")) + { + // Resolve the index in the available devices list to concrete identifiers + int deviceIndex = argInt(args, "deviceIndex"); + QJsonArray devices = getAvailableDevices(direction)[directionName(direction)].toArray(); + bool found = false; + + for (const auto& value : devices) + { + QJsonObject device = value.toObject(); + + if (device["index"].toInt(-1) == deviceIndex) + { + hwType = device["hwType"].toString(); + serial = device["serial"].toString(); + sequence = device["sequence"].toInt(-1); + streamIndex = device["deviceStreamIndex"].toInt(-1); + displayedName = device["displayedName"].toString(); + found = true; + break; + } + } + + if (!found) { + throw MCPToolError(QString("No %1 device with index %2 in the available devices list").arg(directionName(direction)).arg(deviceIndex)); + } + } + + if (hwType.isEmpty() && serial.isEmpty() && displayedName.isEmpty()) { + throw MCPToolError("Specify at least one of hwType, serial, displayedName or deviceIndex to select a device"); + } + + SWGSDRangel::SWGDeviceListItem query; + query.setDirection(direction); + query.setIndex(-1); + query.setSequence(sequence); + query.setDeviceStreamIndex(streamIndex); + + if (!hwType.isEmpty()) { + query.setHwType(new QString(hwType)); + } + if (!serial.isEmpty()) { + query.setSerial(new QString(serial)); + } + if (!displayedName.isEmpty()) { + query.setDisplayedName(new QString(displayedName)); + } + + SWGSDRangel::SWGDeviceListItem response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + int changedBefore = m_events.m_deviceChanged.loadAcquire(); + check(m_adapter->devicesetDevicePut(deviceSetIndex, query, response, error), error, "Select device"); + + QJsonObject selected = toJson(response); + QString wantHwType = selected["hwType"].toString(); + QString wantSerial = selected["serial"].toString(); + int wantSequence = selected["sequence"].toInt(-1); + + // The change completes on the main thread and is signalled by MainCore::deviceChanged + QJsonObject deviceSet; + bool done = waitFor([&]() + { + if (m_events.m_deviceChanged.loadAcquire() == changedBefore) { + return false; + } + + deviceSet = getDeviceSet(deviceSetIndex); + QJsonObject sampling = deviceSet["samplingDevice"].toObject(); + return (sampling["hwType"].toString() == wantHwType) + && (wantSerial.isEmpty() || (sampling["serial"].toString() == wantSerial)) + && ((wantSequence < 0) || (sampling["sequence"].toInt(-1) == wantSequence)); + }); + + QJsonObject result; + result["deviceSetIndex"] = deviceSetIndex; + result["selectedDevice"] = selected; + result["deviceSet"] = deviceSet; + + if (!done) { + result["warning"] = "Timed out waiting for the device change to complete. Call get_deviceset to check."; + } + + return result; +} + +QJsonObject MCPTools::getDeviceSettings(int deviceSetIndex) +{ + SWGSDRangel::SWGDeviceSettings response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->devicesetDeviceSettingsGet(deviceSetIndex, response, error), error, "Get device settings"); + return toJson(response); +} + +QJsonObject MCPTools::patchDeviceSettings(int deviceSetIndex, const QJsonObject& partial) +{ + return applySettingsPatch( + [&](SWGSDRangel::SWGDeviceSettings& r, SWGSDRangel::SWGErrorResponse& e) { + return m_adapter->devicesetDeviceSettingsGet(deviceSetIndex, r, e); + }, + [&](const QStringList& keys, SWGSDRangel::SWGDeviceSettings& r, SWGSDRangel::SWGErrorResponse& e) { + return m_adapter->devicesetDeviceSettingsPutPatch(deviceSetIndex, false, keys, r, e); + }, + partial, QString("device settings of device set %1").arg(deviceSetIndex), + [this](const QString& definition) { return settingsSchema(definition); }); +} + +QSet MCPTools::channelUids(int deviceSetIndex) const +{ + QSet result; + const std::vector& deviceSets = MainCore::instance()->getDeviceSets(); + + if ((deviceSetIndex < 0) || (deviceSetIndex >= (int) deviceSets.size())) { + return result; + } + + DeviceSet *deviceSet = deviceSets[deviceSetIndex]; + + for (int i = 0; i < deviceSet->getNumberOfChannels(); i++) + { + const ChannelAPI *channel = deviceSet->getChannelAt(i); + + if (channel) { + result.insert(channel->getUID()); + } + } + + return result; +} + +QSet MCPTools::featureUids() const +{ + QSet result; + const std::vector& featureSets = MainCore::instance()->getFeatureeSets(); + + if (featureSets.empty()) { + return result; + } + + for (int i = 0; i < featureSets[0]->getNumberOfFeatures(); i++) + { + const Feature *feature = featureSets[0]->getFeatureAt(i); + + if (feature) { + result.insert(feature->getUID()); + } + } + + return result; +} + +QSet MCPTools::deviceSetPointers() const +{ + QSet result; + + for (DeviceSet *deviceSet : MainCore::instance()->getDeviceSets()) { + result.insert(deviceSet); + } + + return result; +} + +// Adds a channel and waits for SDRangel to create it (which happens on the main thread), +// returning its index. The channel is ready to accept settings when this returns. +// +// The new channel is found by identity rather than by taking the last index: the GUI or +// another request can create a channel at the same time, and picking the highest index would +// then configure or delete somebody else's channel. +int MCPTools::addChannelAndWait(int deviceSetIndex, const QString& channelType) +{ + QMutexLocker creationLock(&m_creationMutex); + int direction = deviceSetDirection(deviceSetIndex); + int before = channelCount(deviceSetIndex); + + // A MIMO device set takes receive and transmit channels as well as MIMO ones, and the + // adapter looks the type up in the list the direction names, so the direction has to be + // the channel's rather than the device set's + if (direction == 2) + { + if (channelTypeIds(0).contains(channelType)) { + direction = 0; + } else if (channelTypeIds(1).contains(channelType)) { + direction = 1; + } + } + + if (before < 0) { + throw MCPToolError(QString("No device set with index %1").arg(deviceSetIndex)); + } + + QSet existing = channelUids(deviceSetIndex); + SWGSDRangel::SWGChannelSettings query; + query.setDirection(direction); + query.setChannelType(new QString(channelType)); + SWGSDRangel::SWGSuccessResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + int addedBefore = m_events.m_channelAdded.loadAcquire(); + check(m_adapter->devicesetChannelPost(deviceSetIndex, query, response, error), error, QString("Add channel %1").arg(channelType)); + + int channelIndex = -1; + bool created = waitFor([&]() + { + if (m_events.m_channelAdded.loadAcquire() <= addedBefore) { + return false; + } + + const std::vector& deviceSets = MainCore::instance()->getDeviceSets(); + + if ((deviceSetIndex < 0) || (deviceSetIndex >= (int) deviceSets.size())) { + return false; + } + + DeviceSet *deviceSet = deviceSets[deviceSetIndex]; + + for (int i = 0; i < deviceSet->getNumberOfChannels(); i++) + { + ChannelAPI *channel = deviceSet->getChannelAt(i); + + if (!channel || existing.contains(channel->getUID())) { + continue; + } + + QString id; + channel->getIdentifier(id); + + if (id == channelType) + { + channelIndex = i; + return true; + } + } + + return false; + }); + + if (!created || (channelIndex < 0)) { + throw MCPToolError(QString("Timed out waiting for the %1 channel to be created").arg(channelType)); + } + + // The channel needs a moment before it can accept settings + waitFor([&]() + { + SWGSDRangel::SWGChannelSettings s; + SWGSDRangel::SWGErrorResponse e; + e.init(); + return m_adapter->devicesetChannelSettingsGet(deviceSetIndex, channelIndex, s, e) / 100 == 2; + }, 2000); + + return channelIndex; +} + +// As for channels, the new feature is found by identity so that a feature created at the same +// time by the GUI or another request is never mistaken for this one. +int MCPTools::addFeatureAndWait(const QString& featureType) +{ + QMutexLocker creationLock(&m_creationMutex); + if (featureCount() < 0) { + throw MCPToolError("No feature set available"); + } + + QSet existing = featureUids(); + SWGSDRangel::SWGFeatureSettings query; + query.setFeatureType(new QString(featureType)); + SWGSDRangel::SWGSuccessResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + int addedBefore = m_events.m_featureAdded.loadAcquire(); + check(m_adapter->featuresetFeaturePost(0, query, response, error), error, QString("Add feature %1").arg(featureType)); + + int featureIndex = -1; + auto findNew = [&]() + { + const std::vector& featureSets = MainCore::instance()->getFeatureeSets(); + + if (featureSets.empty()) { + return -1; + } + + for (int i = 0; i < featureSets[0]->getNumberOfFeatures(); i++) + { + Feature *feature = featureSets[0]->getFeatureAt(i); + + if (!feature || existing.contains(feature->getUID())) { + continue; + } + + if (feature->getIdentifier() == featureType) { + return i; + } + } + + return -1; + }; + + // The wait ends as soon as the feature appears, so a longer limit only costs time when one + // genuinely fails to be created. The Map takes a while: it brings up a web engine + waitFor([&]() + { + if (m_events.m_featureAdded.loadAcquire() <= addedBefore) { + return false; + } + + featureIndex = findNew(); + return featureIndex >= 0; + }, 15000); + + if (featureIndex < 0) + { + // Look once more before reporting a failure. A caller told that creation failed when it + // did not will retry, and every retry builds another one + featureIndex = findNew(); + } + + if (featureIndex < 0) { + throw MCPToolError(QString("Timed out waiting for the %1 feature to be created").arg(featureType)); + } + + // The feature needs a moment before it can accept settings + waitFor([&]() + { + SWGSDRangel::SWGFeatureSettings s; + SWGSDRangel::SWGErrorResponse e; + e.init(); + return m_adapter->featuresetFeatureSettingsGet(0, featureIndex, s, e) / 100 == 2; + }, 2000); + + return featureIndex; +} + +// Device set creation runs as a state machine on the main thread; MainCore::deviceSetAdded +// marks the end. The new set is identified by pointer for the same reason as above. +int MCPTools::addDeviceSetAndWait(int direction) +{ + QMutexLocker creationLock(&m_creationMutex); + QSet existing = deviceSetPointers(); + int before = m_events.m_deviceSetAdded.loadAcquire(); + SWGSDRangel::SWGSuccessResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->instanceDeviceSetPost(direction, response, error), error, "Add device set"); + + int deviceSetIndex = -1; + bool created = waitFor([&]() + { + if (m_events.m_deviceSetAdded.loadAcquire() <= before) { + return false; + } + + const std::vector& deviceSets = MainCore::instance()->getDeviceSets(); + + for (int i = 0; i < (int) deviceSets.size(); i++) + { + if (!existing.contains(deviceSets[i])) + { + deviceSetIndex = i; + return true; + } + } + + return false; + }); + + if (!created || (deviceSetIndex < 0)) { + throw MCPToolError("Timed out waiting for the device set to be created"); + } + + return deviceSetIndex; +} + +// Deletes a channel and waits for SDRangel to remove it +// Watches the channel itself disappear rather than the removed signal, which is not emitted +// for the last channel of a device set +void MCPTools::deleteChannelAndWait(int deviceSetIndex, int channelIndex) +{ + QMutexLocker deletionLock(&m_deletionMutex); + deleteChannelLocked(deviceSetIndex, channelIndex); +} + +void MCPTools::deleteChannelLocked(int deviceSetIndex, int channelIndex) +{ + const uint64_t target = channelUidAt(deviceSetIndex, channelIndex); + SWGSDRangel::SWGSuccessResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->devicesetChannelDelete(deviceSetIndex, channelIndex, response, error), error, "Delete channel"); + + if (!waitFor([&]() { return !channelUids(deviceSetIndex).contains(target); })) { + throw MCPToolError(QString("Timed out waiting for channel %1:%2 to be removed").arg(deviceSetIndex).arg(channelIndex)); + } + + m_capture.forgetRecording(target); +} + +// Deletes a channel identified by its UID. A caller that waited, for instance for a +// recording to finish, cannot rely on the index it started with: deleting a lower numbered +// channel meanwhile renumbers everything above it. +void MCPTools::deleteChannelObjectAndWait(uint64_t channelUid) +{ + // The lookup and the delete under one lock, or another call's delete in between renumbers + // the index just found + QMutexLocker deletionLock(&m_deletionMutex); + int deviceSetIndex = -1; + int channelIndex = -1; + + if (!MCPCapture::locateChannel(channelUid, deviceSetIndex, channelIndex)) + { + m_capture.forgetRecording(channelUid); + return; // already gone, which is what was asked for + } + + deleteChannelLocked(deviceSetIndex, channelIndex); +} + +uint64_t MCPTools::deviceSetIdentity(int deviceSetIndex) const +{ + const std::vector& deviceSets = MainCore::instance()->getDeviceSets(); + + if ((deviceSetIndex < 0) || (deviceSetIndex >= (int) deviceSets.size()) || !deviceSets[deviceSetIndex]) { + return 0; + } + + const DeviceSet *deviceSet = deviceSets[deviceSetIndex]; + const uint64_t engine = deviceSet->m_deviceAPI ? deviceSet->m_deviceAPI->getDeviceUID() : 0; + return (engine << 32) ^ reinterpret_cast(deviceSet); +} + +void MCPTools::discardNewDeviceSet(int deviceSetIndex, uint64_t identity) +{ + try + { + QMutexLocker deletionLock(&m_deletionMutex); + + // Only the last device set can be removed, and only when it is still the one made + // here: another call may have added one since, or removed this one and put another + // at the same index while this call slept, and then what is there is left for the user + if ((deviceSetIndex < 0) || (deviceSetIndex != deviceSetCount() - 1) + || (identity == 0) || (deviceSetIdentity(deviceSetIndex) != identity)) { + return; + } + + int before = m_events.m_deviceSetRemoved.loadAcquire(); + SWGSDRangel::SWGSuccessResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->instanceDeviceSetDelete(response, error), error, "Remove device set"); + waitFor([&]() { return m_events.m_deviceSetRemoved.loadAcquire() > before; }); + } + catch (const MCPToolError&) {} +} + +const void *MCPTools::featureAt(int featureIndex) const +{ + const std::vector& featureSets = MainCore::instance()->getFeatureeSets(); + + if (featureSets.empty() || (featureIndex < 0) || (featureIndex >= featureSets[0]->getNumberOfFeatures())) { + return nullptr; + } + + return featureSets[0]->getFeatureAt(featureIndex); +} + +uint64_t MCPTools::featureUidAt(int featureIndex) const +{ + const Feature *feature = static_cast(featureAt(featureIndex)); + return feature ? feature->getUID() : 0; +} + +uint64_t MCPTools::channelUidAt(int deviceSetIndex, int channelIndex) const +{ + return MCPCapture::channelUidAt(deviceSetIndex, channelIndex); +} + +// Deleting or stopping the feature that is serving this request would tear down the HTTP +// listener from inside its own handler, so it is refused rather than attempted. +void MCPTools::requireNotSelf(int featureIndex, const QString& action) const +{ + if (m_ownerFeature && (featureAt(featureIndex) == m_ownerFeature)) + { + throw MCPToolError(QString("Feature %1 is the MCP Server serving this request and cannot be %2 through it. " + "Use the SDRangel GUI or the REST API instead.").arg(featureIndex).arg(action)); + } +} + +QJsonObject MCPTools::getChannelSettings(int deviceSetIndex, int channelIndex) +{ + SWGSDRangel::SWGChannelSettings response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->devicesetChannelSettingsGet(deviceSetIndex, channelIndex, response, error), error, "Get channel settings"); + return toJson(response); +} + +SettingsSchema MCPTools::settingsSchema(const QString& definition) +{ + QMutexLocker schemaLock(&m_schemaMutex); + + if (m_schemaCache.contains(definition)) { + return m_schemaCache[definition]; + } + + SettingsSchema schema; + // Without this no device setting found its schema and none of them were type checked + QString name = resolveDefinition(definition); + + if (!name.isEmpty()) { + schema = parseSettingsSchema(m_yamlDefinitions[name]); + } + + m_schemaCache.insert(definition, schema); + return schema; +} + +QJsonObject MCPTools::getSpectrumSettings(int deviceSetIndex) +{ + SWGSDRangel::SWGGLSpectrum response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->devicesetSpectrumSettingsGet(deviceSetIndex, response, error), error, "Get spectrum settings"); + return toJson(response); +} + +QJsonObject MCPTools::patchSpectrumSettings(int deviceSetIndex, const QJsonObject& partial, QStringList *unknownKeys) +{ + SWGSDRangel::SWGGLSpectrum current; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->devicesetSpectrumSettingsGet(deviceSetIndex, current, error), error, "Get spectrum settings"); + QJsonObject json = toJson(current); + QStringList unknown; + QJsonObject checked = partial; + SettingsSchema schema = settingsSchema("GLSpectrum"); + + if (schema.m_known) + { + QStringList typeErrors; + checked = checkAgainstSchema(partial, schema, unknown, typeErrors); + + if (!typeErrors.isEmpty()) + { + throw MCPToolError(QString("Wrong value type for spectrum settings: %1. Numbers must be " + "given as JSON numbers, not strings. Nothing was changed.").arg(typeErrors.join("; "))); + } + } + + QStringList merged; + mergeInto(json, checked, merged); + + if (!schema.m_known) { + unknown = merged; + } + + if (unknownKeys) { + *unknownKeys = unknown; + } + + QStringList keys; + extractKeys(checked, keys); + SWGSDRangel::SWGGLSpectrum request; + request.init(); + request.fromJsonObject(json); + error.init(); + check(m_adapter->devicesetSpectrumSettingsPutPatch(deviceSetIndex, false, keys, request, error), error, "Set spectrum settings"); + return toJson(request); +} + +void MCPTools::addRdsHint(QJsonObject& report, const QString& channelType, int deviceSetIndex, int channelIndex) +{ + if (channelType != "BFMDemod") { + return; + } + + if (report.value("BFMDemodReport").toObject().contains("rdsReport")) { + return; + } + + // The report is empty for a channel that is not running as well, where saying anything about + // RDS would only mislead, so the hint is tied to the setting that actually suppresses it + QJsonObject settings = getChannelSettings(deviceSetIndex, channelIndex).value("BFMDemodSettings").toObject(); + + if (settings.value("rdsActive").toInt(0) == 0) + { + report["rdsHint"] = "RDS is not being decoded, which is why this report has no rdsReport. Set rdsActive to 1 with " + "set_channel_settings to get the programme service name (the station name), radio text, programme " + "type and PI code."; + } +} + +QJsonObject MCPTools::patchChannelSettings(int deviceSetIndex, int channelIndex, const QJsonObject& partial) +{ + return applySettingsPatch( + [&](SWGSDRangel::SWGChannelSettings& r, SWGSDRangel::SWGErrorResponse& e) { + return m_adapter->devicesetChannelSettingsGet(deviceSetIndex, channelIndex, r, e); + }, + [&](const QStringList& keys, SWGSDRangel::SWGChannelSettings& r, SWGSDRangel::SWGErrorResponse& e) { + return m_adapter->devicesetChannelSettingsPutPatch(deviceSetIndex, channelIndex, false, keys, r, e); + }, + partial, QString("channel settings of channel %1:%2").arg(deviceSetIndex).arg(channelIndex), + [this](const QString& definition) { return settingsSchema(definition); }); +} + +QJsonObject MCPTools::getFeatureSettings(int featureIndex) +{ + SWGSDRangel::SWGFeatureSettings response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->featuresetFeatureSettingsGet(0, featureIndex, response, error), error, "Get feature settings"); + return toJson(response); +} + +QJsonObject MCPTools::patchFeatureSettings(int featureIndex, const QJsonObject& partial) +{ + return applySettingsPatch( + [&](SWGSDRangel::SWGFeatureSettings& r, SWGSDRangel::SWGErrorResponse& e) { + return m_adapter->featuresetFeatureSettingsGet(0, featureIndex, r, e); + }, + [&](const QStringList& keys, SWGSDRangel::SWGFeatureSettings& r, SWGSDRangel::SWGErrorResponse& e) { + return m_adapter->featuresetFeatureSettingsPutPatch(0, featureIndex, false, keys, r, e); + }, + partial, QString("feature settings of feature %1").arg(featureIndex), + [this](const QString& definition) { return settingsSchema(definition); }); +} + +QJsonObject MCPTools::deviceState(int deviceSetIndex, int subsystemIndex, int run) +{ + SWGSDRangel::SWGDeviceState response; + response.init(); + SWGSDRangel::SWGErrorResponse error; + error.init(); + int rc; + + // The subsystem variants only apply to MIMO devices; single stream devices use the plain calls + bool mimo = deviceSetDirection(deviceSetIndex) == 2; + + auto runGet = [&](SWGSDRangel::SWGDeviceState& s, SWGSDRangel::SWGErrorResponse& e) { + return mimo ? m_adapter->devicesetDeviceSubsystemRunGet(deviceSetIndex, subsystemIndex, s, e) + : m_adapter->devicesetDeviceRunGet(deviceSetIndex, s, e); + }; + + if (run == 1) { + rc = mimo ? m_adapter->devicesetDeviceSubsystemRunPost(deviceSetIndex, subsystemIndex, response, error) + : m_adapter->devicesetDeviceRunPost(deviceSetIndex, response, error); + } else if (run == 0) { + rc = mimo ? m_adapter->devicesetDeviceSubsystemRunDelete(deviceSetIndex, subsystemIndex, response, error) + : m_adapter->devicesetDeviceRunDelete(deviceSetIndex, response, error); + } else { + rc = runGet(response, error); + } + + check(rc, error, run == 1 ? "Start device" : (run == 0 ? "Stop device" : "Get device state")); + + // The state returned by POST/DELETE is the state before the change. Give the device a moment + // and report the state actually reached. + QJsonObject result; + result["deviceSetIndex"] = deviceSetIndex; + + if (run >= 0) + { + QString want = run == 1 ? "running" : "idle"; + QString readError; + + bool reached = waitFor([&]() + { + SWGSDRangel::SWGDeviceState state; + state.init(); + SWGSDRangel::SWGErrorResponse e; + e.init(); + int getRC = runGet(state, e); + + if (getRC / 100 != 2) + { + readError = QString("HTTP %1 %2").arg(getRC).arg(e.getMessage() ? *e.getMessage() : QString()); + return true; // stop polling, reported below + } + + response.init(); + *response.getState() = *state.getState(); + return *state.getState() == want || *state.getState() == "error"; + }, 3000); + + if (!readError.isEmpty()) { + throw MCPToolError(QString("%1 was requested but the device state could not be read back: %2").arg(run == 1 ? "Start" : "Stop").arg(readError)); + } + + if (!reached) { + result["warning"] = QString("The device did not reach the %1 state within 3 seconds. The state reported here is the last one observed").arg(want); + } + } + + result["state"] = *response.getState(); + return result; +} + +QJsonObject MCPTools::featureState(int featureIndex, int run) +{ + // Asking a passive feature to run waits three seconds for a state it never reports, or fails + // outright on the ones that answer 501, so say what it is instead of doing either + if (run >= 0) + { + QString featureType = getFeatureSettings(featureIndex)["featureType"].toString(); + + if (isPassiveFeature(featureType)) + { + QJsonObject passive; + passive["featureIndex"] = featureIndex; + passive["featureType"] = featureType; + passive["state"] = "idle"; + passive["passive"] = true; + passive["note"] = QString("%1 has no run state and does not need starting: it works as soon as it " + "is configured, and reports idle whether or not it is doing anything.").arg(featureType); + return passive; + } + } + + SWGSDRangel::SWGDeviceState response; + response.init(); + SWGSDRangel::SWGErrorResponse error; + error.init(); + int rc; + + if (run == 1) { + rc = m_adapter->featuresetFeatureRunPost(0, featureIndex, response, error); + } else if (run == 0) { + rc = m_adapter->featuresetFeatureRunDelete(0, featureIndex, response, error); + } else { + rc = m_adapter->featuresetFeatureRunGet(0, featureIndex, response, error); + } + + check(rc, error, run == 1 ? "Start feature" : (run == 0 ? "Stop feature" : "Get feature state")); + + QJsonObject result; + result["featureIndex"] = featureIndex; + + if (run >= 0) + { + QString want = run == 1 ? "running" : "idle"; + QString readError; + + bool reached = waitFor([&]() + { + SWGSDRangel::SWGDeviceState state; + state.init(); + SWGSDRangel::SWGErrorResponse e; + e.init(); + int getRC = m_adapter->featuresetFeatureRunGet(0, featureIndex, state, e); + + if (getRC / 100 != 2) + { + readError = QString("HTTP %1 %2").arg(getRC).arg(e.getMessage() ? *e.getMessage() : QString()); + return true; // stop polling, reported below + } + + response.init(); + *response.getState() = *state.getState(); + return *state.getState() == want || *state.getState() == "error"; + }, 3000); + + if (!readError.isEmpty()) { + throw MCPToolError(QString("%1 was requested but the feature state could not be read back: %2").arg(run == 1 ? "Start" : "Stop").arg(readError)); + } + + if (!reached) { + result["warning"] = QString("The feature did not reach the %1 state within 3 seconds. The state reported here is the last one observed").arg(want); + } + } + + result["state"] = *response.getState(); + return result; +} + +// Resolves group name + name (and optionally centre frequency and type) to the full preset identifier +// SDRangel needs. For a save, the identifier of the current device is used when no matching preset exists. +QJsonObject MCPTools::presetIdentifier(const QJsonObject& args, int deviceSetIndex, bool forSave) +{ + QString groupName = argString(args, "groupName"); + QString name = argString(args, "name"); + QString type = argString(args, "type", false); + bool hasFrequency = hasArg(args, "centerFrequency"); + qint64 centerFrequency = argInt64(args, "centerFrequency", false, 0); + + QJsonObject deviceSet; + QString deviceType; + qint64 deviceFrequency = 0; + + if (forSave) + { + deviceSet = getDeviceSet(deviceSetIndex); + QJsonObject sampling = deviceSet["samplingDevice"].toObject(); + deviceFrequency = (qint64) sampling["centerFrequency"].toDouble(); + int direction = sampling["direction"].toInt(0); + deviceType = direction == 0 ? "R" : (direction == 1 ? "T" : "M"); + } + + QJsonArray candidates; + + for (const auto& groupValue : getPresets()["groups"].toArray()) + { + QJsonObject group = groupValue.toObject(); + + if (group["groupName"].toString() != groupName) { + continue; + } + + for (const auto& presetValue : group["presets"].toArray()) + { + QJsonObject preset = presetValue.toObject(); + + if (preset["name"].toString() != name) { + continue; + } + if (!type.isEmpty() && (preset["type"].toString() != type)) { + continue; + } + if (hasFrequency && ((qint64) preset["centerFrequency"].toDouble() != centerFrequency)) { + continue; + } + if (forSave && (preset["type"].toString() != deviceType)) { + continue; + } + + candidates.append(preset); + } + } + + QJsonObject identifier; + identifier["groupName"] = groupName; + identifier["name"] = name; + + if (candidates.count() == 1) + { + QJsonObject preset = candidates.first().toObject(); + identifier["type"] = preset["type"].toString(); + identifier["centerFrequency"] = preset["centerFrequency"].toDouble(); + identifier["exists"] = true; + } + else if (candidates.count() > 1) + { + throw MCPToolError(QString("Several presets match group %1 name %2. Specify centerFrequency and type to choose one of: %3") + .arg(groupName).arg(name).arg(compact(candidates))); + } + else if (forSave) + { + identifier["type"] = deviceType; + identifier["centerFrequency"] = (double) deviceFrequency; + identifier["exists"] = false; + } + else + { + throw MCPToolError(QString("No preset with group %1 and name %2. Call list_presets to see what exists").arg(groupName).arg(name)); + } + + return identifier; +} + +// --------------------------------------------------------------------------- +// Tool registration +// --------------------------------------------------------------------------- + +void MCPTools::registerInstanceTools() +{ + add("get_instance_summary", + "Get an overview of the SDRangel instance: version, all device sets with their sampling device and channels, and all features. " + "Call this first to learn the current state and the indexes to use with other tools.", + schema(QJsonObject()), + [this](const QJsonObject&) { return getInstanceSummary(); }); + + add("list_available_devices", + "List the SDR hardware and software sources/sinks that can be selected in a device set. Each entry gives hwType (used by " + "set_device and describe_settings), serial, sequence and index. Physical devices must be plugged in before SDRangel starts.", + schema({{"direction", directionProp("Only list devices for this direction (rx, tx or mimo). Default: all directions")}}), + [this](const QJsonObject& args) { return getAvailableDevices(argDirection(args, "direction", false, -1)); }); + + add("list_channel_types", + "List the channel plugins (demodulators for rx, modulators for tx) that can be added to a device set. The id is the channelType " + "to pass to add_channel and describe_settings.", + schema({{"direction", directionProp("Only list channels for this direction (rx, tx or mimo). Default: all directions")}}), + [this](const QJsonObject& args) { return getAvailableChannels(argDirection(args, "direction", false, -1)); }); + + add("list_feature_types", + "List the feature plugins that can be added with add_feature. The id is the featureType.", + schema(QJsonObject()), + [this](const QJsonObject&) { return getAvailableFeatures(); }); + + add("describe_settings", + "Get the documentation (OpenAPI YAML) of the settings, report and actions keys of a device, channel or feature type, " + "or of the spectrum display: what each key means, its units, range and enumeration values. Not needed for common keys; " + "call it when a set_* tool reports an unknown key, or before setting a key whose values are codes, such as a style or " + "mode. The output can run to a few thousand tokens.", + schema({ + {"type", strProp("Type identifier: a device hwType such as RTLSDR or TestSource, a channelType such as ADSBDemod or NFMDemod, " + "a featureType such as Map, or spectrum for the spectrum display")}, + {"kind", strProp("Optional: device, channel, feature or spectrum, to disambiguate when the same id exists for several kinds")} + }, {"type"}), + [this](const QJsonObject& args) { return QJsonValue(describeType(argString(args, "type"), argString(args, "kind", false))); }); + + add("get_receiving_guide", + "Read the receiving guide: which demodulator and frequency to use for a given signal or protocol (ADS-B, AIS, APRS, " + "radiosondes, weather satellites, broadcast FM, LoRa, pagers and more), the minimum device sample rate some modes need, " + "and the usual reasons nothing is received. Read this before setting up a receiver for a named signal, rather than " + "guessing frequencies.", + schema(QJsonObject()), + [this](const QJsonObject&) { return QJsonValue(m_docs.guide()); }); + + add("list_docs", + "List the user documentation (readme) available for the device, channel and feature plugins registered in this instance, " + "and for the GUI's own pages such as the spectrum display, with the section headings of each. Use get_docs to read one.", + schema({{"kind", strProp("Optional: only list device, channel, feature or gui docs")}}), + [this](const QJsonObject& args) + { + QString kind = argString(args, "kind", false).trimmed().toLower(); + QJsonObject index = m_docs.index(); + + if (kind.isEmpty()) { + return index; + } + + QJsonArray filtered; + + for (const auto& value : index["docs"].toArray()) + { + if (value.toObject()["kind"].toString() == kind) { + filtered.append(value); + } + } + + QJsonObject result; + result["count"] = filtered.count(); + result["docs"] = filtered; + return result; + }); + + add("get_docs", + "Read the user documentation (readme, as markdown) of a device, channel or feature plugin, or of a GUI page such as the " + "spectrum display: what it does, what each setting means, frequencies and sample rates it needs, and how to use it. Pass " + "section to get just one section (matched against the headings listed by list_docs) as the full documents can be long.", + schema({ + {"type", strProp("Plugin id (e.g. ADSBDemod, RTLSDR, Map), its displayed name (e.g. \"ADS-B Demodulator\"), or a GUI page: " + "spectrum, spectrummarkers, spectrummeasurements, spectrumcalibration, mainspectrum, audio, configurations, deviceuserargs, transverter")}, + {"kind", strProp("Optional: device, channel, feature or gui, to disambiguate")}, + {"section", strProp("Optional: text of a heading; only that section is returned")} + }, {"type"}), + [this](const QJsonObject& args) + { + QString type = argString(args, "type"); + QString kind = argString(args, "kind", false); + const MCPDocs::Doc *doc = m_docs.find(type, kind); + + if (!doc) { + throw MCPToolError(QString("No documentation found for %1. Call list_docs to see what is available").arg(type)); + } + + QString section = argString(args, "section", false); + QString text = m_docs.text(*doc, section); + + if (text.isEmpty()) { + throw MCPToolError(QString("No section matching \"%1\" in the %2 documentation. Sections: %3").arg(section).arg(doc->id).arg(doc->headings.join(" | "))); + } + + return QJsonValue(text); + }); + + add("get_packets", + "Get recently decoded packets from packet-oriented demodulators (AIS, APRS/AX.25 packet, LoRa/ChirpChat, M17, Meshtastic, " + "MeshCore, Inmarsat, radiosonde). Each packet has the raw bytes (hex and printable text) and, where SDRangel can decode it, " + "a decoded object: AIS message type, MMSI, position, course and speed; AX.25 from/to/via and data with APRS position and " + "comment; RS41 radiosonde serial, position and height. Packets are kept in a buffer of the last 1000; use sinceSequence " + "with the lastSequence of a previous call to read only new packets.", + schema({ + {"source", strProp("Only packets from this channel, e.g. \"R0:1\" (device set 0, channel 1)")}, + {"type", strProp("Only packets from channels of this type, e.g. AISDemod, PacketDemod, RadiosondeDemod")}, + {"limit", bounded(intProp("Maximum number of packets to return, most recent first. Default 50"), 1, MCPDataFeed::m_maxPackets)}, + {"sinceSequence", intProp("Only packets with a sequence number greater than this")} + }), + [this](const QJsonObject& args) + { + return m_dataFeed.getPackets(argString(args, "source", false), argString(args, "type", false), + argInt(args, "limit", false, 50), argInt64(args, "sinceSequence", false, 0)); + }); + + add("clear_packets", + "Discard all buffered packets.", + schema(QJsonObject()), + [this](const QJsonObject&) + { + m_dataFeed.clearPackets(); + QJsonObject result; + result["cleared"] = true; + return result; + }); + + add("get_map_items", + "Get the objects currently plotted on the map by the running plugins: aircraft from ADS-B, ships from AIS, APRS stations, " + "radiosondes, satellites, the Sun and Moon from the star tracker, VOR/ILS beacons and so on. Each item has a name, position, " + "altitude, heading, the label and text shown on the map, and for aircraft the full ADS-B state. Only sources that are " + "running produce items; items disappear when their source removes them.", + schema({ + {"source", strProp("Only items from this channel or feature id (e.g. \"R0:0\", \"F:1\") or plugin type (e.g. ADSBDemod, AIS)")}, + {"name", strProp("Only items whose name contains this text, e.g. an ICAO address, MMSI or callsign")}, + {"limit", bounded(intProp("Maximum number of items to return. Default 200"), 1, 5000)}, + {"includeTrack", prop("boolean", "Include the position history of each item. Default false, as tracks can be long")} + }), + [this](const QJsonObject& args) + { + bool includeTrack = argBool(args, "includeTrack", false); + return m_dataFeed.getMapItems(argString(args, "source", false), argString(args, "name", false), + argInt(args, "limit", false, 200), includeTrack); + }); + + add("list_audio_devices", + "List the audio input and output devices available to SDRangel.", + schema(QJsonObject()), + [this](const QJsonObject&) + { + SWGSDRangel::SWGAudioDevices response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->instanceAudioGet(response, error), error, "List audio devices"); + return toJson(response); + }); + + add("get_location", + "Get the station location (latitude and longitude in degrees) used by features such as the Map and satellite tracker.", + schema(QJsonObject()), + [this](const QJsonObject&) + { + SWGSDRangel::SWGLocationInformation response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->instanceLocationGet(response, error), error, "Get location"); + return toJson(response); + }); + + add("set_location", + "Set the station location.", + schema({ + {"latitude", bounded(numProp("Latitude in degrees, positive north"), -90.0, 90.0)}, + {"longitude", bounded(numProp("Longitude in degrees, positive east"), -180.0, 180.0)} + }, {"latitude", "longitude"}), + [this](const QJsonObject& args) + { + SWGSDRangel::SWGLocationInformation response; + response.setLatitude((float) argDouble(args, "latitude")); + response.setLongitude((float) argDouble(args, "longitude")); + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->instanceLocationPut(response, error), error, "Set location"); + return toJson(response); + }); +} + +void MCPTools::registerDeviceSetTools() +{ + add("add_deviceset", + "Create a new device set and optionally select its sampling device in one go. Returns the index of the new device set. " + "Identify the device with hwType and/or serial (from list_available_devices), or deviceIndex (its index in that list). " + "Without a device the new device set uses the first available device of that direction.", + schema({ + {"direction", directionProp("rx for a receiver (default), tx for a transmitter, mimo for a MIMO device")}, + {"hwType", strProp("Hardware type of the device to select, e.g. RTLSDR, HackRF, TestSource")}, + {"serial", strProp("Serial number of the device to select")}, + {"sequence", intProp("Sequence number of the device, to distinguish identical devices")}, + {"displayedName", strProp("Displayed name of the device, as listed by list_available_devices")}, + {"deviceIndex", intProp("Index of the device in the list_available_devices list for this direction")} + }), + [this](const QJsonObject& args) + { + int direction = argDirection(args, "direction", false, 0); + int deviceSetIndex = addDeviceSetAndWait(direction); + + if (hasArg(args, "hwType") || hasArg(args, "serial") || hasArg(args, "displayedName") || hasArg(args, "deviceIndex")) + { + try + { + return selectDevice(deviceSetIndex, args); + } + catch (const MCPToolError& e) + { + throw MCPToolError(QString("Device set %1 was created but the requested device could not be selected: %2. " + "Use set_device on that device set, or remove_last_deviceset. Do not call add_deviceset again.") + .arg(deviceSetIndex).arg(e.message)); + } + } + + QJsonObject result; + result["deviceSetIndex"] = deviceSetIndex; + result["deviceSet"] = getDeviceSet(deviceSetIndex); + return result; + }); + + add("remove_last_deviceset", + "Remove the device set with the highest index. In the GUI the first device set (R0) cannot be removed.", + schema(QJsonObject()), + [this](const QJsonObject&) + { + int before = m_events.m_deviceSetRemoved.loadAcquire(); + SWGSDRangel::SWGSuccessResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->instanceDeviceSetDelete(response, error), error, "Remove device set"); + + if (!waitFor([&]() { return m_events.m_deviceSetRemoved.loadAcquire() > before; })) { + throw MCPToolError("Timed out waiting for the device set to be removed; get_instance_summary shows whether it went"); + } + + QJsonObject result; + result["deviceSetCount"] = deviceSetCount(); + return result; + }); + + add("get_deviceset", + "Get a device set: its sampling device (hwType, serial, centre frequency, state) and the list of its channels with their reports.", + schema({{"deviceSetIndex", deviceSetIndexProp}}, {"deviceSetIndex"}), + [this](const QJsonObject& args) { return getDeviceSet(argInt(args, "deviceSetIndex")); }); + + add("set_device", + "Change the sampling device of an existing device set. Identify the device with hwType and/or serial (from list_available_devices), " + "or deviceIndex. Waits for the change to complete.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"hwType", strProp("Hardware type of the device to select, e.g. RTLSDR")}, + {"serial", strProp("Serial number of the device to select")}, + {"sequence", intProp("Sequence number of the device, to distinguish identical devices")}, + {"displayedName", strProp("Displayed name of the device")}, + {"deviceIndex", intProp("Index of the device in the list_available_devices list for the device set direction")} + }, {"deviceSetIndex"}), + [this](const QJsonObject& args) { return selectDevice(argInt(args, "deviceSetIndex"), args); }); + + add("get_device_settings", + "Get the settings of the sampling device of a device set (centre frequency, sample rate, gain...). The keys depend on the device type.", + schema({{"deviceSetIndex", deviceSetIndexProp}}, {"deviceSetIndex"}), + [this](const QJsonObject& args) { return getDeviceSettings(argInt(args, "deviceSetIndex")); }); + + add("set_device_settings", + "Change some settings of the sampling device of a device set. Give only the keys to change, e.g. {\"centerFrequency\": 1090000000, \"gain\": 400}. " + "Use describe_settings with the device hwType to learn the valid keys, units and value ranges. Returns the keys changed with their applied values.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"settings", objProp("Object with the settings keys to change and their new values")} + }, {"deviceSetIndex", "settings"}), + [this](const QJsonObject& args) { return patchDeviceSettings(argInt(args, "deviceSetIndex"), argObject(args, "settings")); }); + + add("set_center_frequency", + "Tune the sampling device of a device set to a centre frequency in Hz. Channels keep their inputFrequencyOffset relative to it.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"frequency", numProp("Centre frequency in Hz")} + }, {"deviceSetIndex", "frequency"}), + [this](const QJsonObject& args) + { + QJsonObject settings; + settings["centerFrequency"] = (double) argInt64(args, "frequency"); + return patchDeviceSettings(argInt(args, "deviceSetIndex"), settings); + }); + + add("start_device", + "Start the sampling device of a device set so that it streams samples and its channels run. Returns the resulting state.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"subsystemIndex", bounded(intProp("MIMO devices only: 0 for the rx subsystem, 1 for tx. Default 0"), 0, 1)} + }, {"deviceSetIndex"}), + [this](const QJsonObject& args) + { + int deviceSetIndex = argInt(args, "deviceSetIndex"); + QJsonObject state = deviceState(deviceSetIndex, argInt(args, "subsystemIndex", false, 0), 1); + QStringList warnings = basebandWarnings(deviceSetIndex); + + if (!warnings.isEmpty()) { + state["warning"] = warnings.join(" "); + } + + return QJsonValue(state); + }); + + add("stop_device", + "Stop the sampling device of a device set.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"subsystemIndex", bounded(intProp("MIMO devices only: 0 for the rx subsystem, 1 for tx. Default 0"), 0, 1)} + }, {"deviceSetIndex"}), + [this](const QJsonObject& args) { return deviceState(argInt(args, "deviceSetIndex"), argInt(args, "subsystemIndex", false, 0), 0); }); + + add("get_device_report", + "Get the live report of the sampling device of a device set (for example the actual sample rate, gain values, " + "or for file inputs the playback position). Keys depend on the device type.", + schema({{"deviceSetIndex", deviceSetIndexProp}}, {"deviceSetIndex"}), + [this](const QJsonObject& args) + { + SWGSDRangel::SWGDeviceReport response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->devicesetDeviceReportGet(argInt(args, "deviceSetIndex"), response, error), error, "Get device report"); + return toJson(response); + }); + + add("device_action", + "Trigger an action on the sampling device of a device set. Only some device types have actions. Use describe_settings to find " + "the actions keys of the device type; pass them as the actions object, e.g. {\"record\": 1}.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"actions", objProp("Object with the action keys and values for this device type")} + }, {"deviceSetIndex", "actions"}), + [this](const QJsonObject& args) + { + int deviceSetIndex = argInt(args, "deviceSetIndex"); + QJsonObject actions = argObject(args, "actions"); + QJsonObject settings = getDeviceSettings(deviceSetIndex); + QString hwType = settings["deviceHwType"].toString(); + int direction = settings["direction"].toInt(0); + const QMap& map = direction == 0 ? WebAPIUtils::m_sourceDeviceHwIdToActionsKey + : (direction == 1 ? WebAPIUtils::m_sinkDeviceHwIdToActionsKey : WebAPIUtils::m_mimoDeviceHwIdToActionsKey); + + if (!map.contains(hwType)) { + throw MCPToolError(QString("Device type %1 has no actions").arg(hwType)); + } + + QJsonObject json; + json["deviceHwType"] = hwType; + json["direction"] = direction; + json[map[hwType]] = actions.contains(map[hwType]) ? actions[map[hwType]].toObject() : actions; + QStringList keys; + extractKeys(json[map[hwType]].toObject(), keys); + + SWGSDRangel::SWGDeviceActions query; + query.init(); + query.fromJsonObject(json); + SWGSDRangel::SWGSuccessResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->devicesetDeviceActionsPost(deviceSetIndex, keys, query, response, error), error, "Device action"); + return toJson(response); + }); + + add("get_spectrum_settings", + "Get the settings of the main spectrum display of a device set, including FFT and scale, 2D/3D spectrum display, waterfall history, measurements and statistics, math, and saved-memory display settings.", + schema({{"deviceSetIndex", deviceSetIndexProp}}, {"deviceSetIndex"}), + [this](const QJsonObject& args) + { + SWGSDRangel::SWGGLSpectrum response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->devicesetSpectrumSettingsGet(argInt(args, "deviceSetIndex"), response, error), error, "Get spectrum settings"); + return toJson(response); + }); + + add("set_spectrum_settings", + "Change selected settings of the main spectrum display of a device set. Supports FFT and scale, 2D/3D spectrum display, waterfall history, measurements and statistics, math, and saved-memory display settings. Give only the keys to change (see get_spectrum_settings for the keys). " + "Keys whose values are codes are documented by describe_settings with type spectrum: for instance spectrumStyle is 0 line, 1 filled solid colour, 2 filled colour gradient, and colorMap names the gradient. " + "To smooth the trace set both averagingMode (1 moving) and averagingValue (the number of FFTs, e.g. 10): a mode with the value left at 1 averages nothing.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"settings", objProp("Object with the spectrum settings keys to change")} + }, {"deviceSetIndex", "settings"}), + [this](const QJsonObject& args) + { + int deviceSetIndex = argInt(args, "deviceSetIndex"); + QJsonObject partial = argObject(args, "settings"); + QStringList unknownKeys; + + auto read = [&]() + { + SWGSDRangel::SWGGLSpectrum current; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->devicesetSpectrumSettingsGet(deviceSetIndex, current, error), error, "Get spectrum settings"); + return toJson(current); + }; + + const QJsonObject before = read(); + patchSpectrumSettings(deviceSetIndex, partial, &unknownKeys); + + // Read back rather than echo the request: some values are rounded to what the + // display offers, and the caller should see what it got. The patch is applied by + // message, so give it a moment to land: until every key given has either moved or + // was already where it was asked to be + QJsonObject after = read(); + + for (int attempt = 0; attempt < 10; attempt++) + { + bool landed = true; + + for (const QString& key : partial.keys()) + { + if (after.contains(key) && (after[key] == before[key]) && (after[key] != partial[key])) { + landed = false; + } + } + + if (landed) { + break; + } + + QThread::msleep(50); + after = read(); + } + + QJsonObject changed; + QStringList notes; + + for (const QString& key : partial.keys()) + { + if (after.contains(key)) + { + changed[key] = after[key]; + + if (after[key].isDouble() && partial[key].isDouble() && (after[key].toDouble() != partial[key].toDouble())) { + notes.append(QString("%1 was rounded to %2, one of the values the display offers.").arg(key).arg(after[key].toDouble())); + } + } + } + + // A mode with a count of one averages nothing, which is easy to leave that way + if ((after["averagingMode"].toInt() != 0) && (after["averagingValue"].toInt() <= 1)) { + notes.append("averagingMode is set but averagingValue is 1, so no averaging is happening: set averagingValue as well, " + "10 to smooth a trace or 50 to measure a floor. The values available are 1, 2, 5, 10, 20, 50, 100 and so on."); + } + + QJsonObject result; + result["changed"] = changed; + + if (!unknownKeys.isEmpty()) { + result["warning"] = QString("Ignored unknown keys: %1. describe_settings lists the valid ones.").arg(unknownKeys.join(", ")); + } + + if (!notes.isEmpty()) { + result["note"] = notes.join(" "); + } + + return result; + }); + + + add("get_spectrum_report", + "Get the latest spectrum measurement results of a device set: peaks, channel power, adjacent channel power, occupied " + "bandwidth, 3 dB bandwidth, or SNR with THD and SINAD, depending on which measurement is selected with " + "set_spectrum_settings. Only the fields the selected measurement produces are returned, so an absent field was not " + "measured rather than measured as zero. With no measurement selected only measurement 0 comes back. The figures are " + "those of the spectrum as displayed, so they follow the zoom.", + schema({{"deviceSetIndex", deviceSetIndexProp}}, {"deviceSetIndex"}), + [this](const QJsonObject& args) + { + SWGSDRangel::SWGGLSpectrumReport response; + SWGSDRangel::SWGErrorResponse error; + response.init(); + error.init(); + check(m_adapter->devicesetSpectrumReportGet(argInt(args, "deviceSetIndex"), response, error), error, "Get spectrum report"); + return toJson(response); + }); + + + add("get_spectrum_data", + "Get the current power spectrum of a device set, reduced to the number of bins asked for. Use it to see what is on a band " + "without looking at the screen: which parts are occupied, how strong, and where the edges are. Each value covers " + "binBandwidth Hz starting at startFrequency. Reduction is by max, which keeps a narrow carrier that averaging would bury " + "in its neighbours; mean is better for measuring a noise floor. Every value costs tokens, so ask for the coarsest that " + "answers the question and narrow the frequency range instead of asking for more bins.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"bins", bounded(intProp("Number of values to return, most recent spectrum. Default 64"), 1, 512)}, + {"startFrequency", numProp("Only from this frequency in Hz. Default the start of the spectrum")}, + {"stopFrequency", numProp("Only up to this frequency in Hz. Default the end of the spectrum")}, + {"reduce", strProp("max to keep peaks, the default, or mean to average")} + }, {"deviceSetIndex"}), + [this](const QJsonObject& args) + { + SWGSDRangel::SWGGLSpectrumData response; + SWGSDRangel::SWGErrorResponse error; + response.init(); + error.init(); + check(m_adapter->devicesetSpectrumDataGet( + argInt(args, "deviceSetIndex"), + argInt(args, "bins", false, 64), + argInt64(args, "startFrequency", false, 0), + argInt64(args, "stopFrequency", false, 0), + argString(args, "reduce", false, "max"), + response, error), + error, "Get spectrum data"); + QJsonObject json = toJson(response); + + // The generated serialiser drops a list of plain floats, so the values go in by hand + QJsonArray power; + + if (response.getPower()) + { + for (float v : *response.getPower()) { + power.append(std::round((double) v * 10.0) / 10.0); + } + } + + json["power"] = power; + return json; + }); + + add("get_spectrum_history", + "What has been on a band over the last while, from the spectrum history the GUI keeps for scrolling: per bin " + "maximum, mean and occupancy (the fraction of the time the bin was above the noise floor by threshold dB), and a " + "signalList of every run of bins that rose above it, each with its frequency, width, peak, dutyCycle (1 for a " + "continuous carrier, small for bursts) and when it was first and last seen. This is the way to tell a continuous " + "signal from an intermittent one, find where transmissions are without stepping a scanner over them, and measure " + "a floor over time rather than from one snapshot. Only rows taken with the device tuned and sampling as it is now " + "count; after a retune, wait for new history. Scrolling is switched on if it is off, and then there is nothing to " + "report until some has accumulated, so call again after a few seconds. Every bin costs tokens: ask for the coarsest " + "that answers the question.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"seconds", numProp("How far back to look, in seconds. Default 60")}, + {"bins", bounded(intProp("Number of bins to reduce the spectrum to. Default 64"), 1, 512)}, + {"startFrequency", numProp("Only from this frequency in Hz. Default the start of the spectrum")}, + {"stopFrequency", numProp("Only up to this frequency in Hz. Default the end of the spectrum")}, + {"threshold", numProp("dB above the measured floor for a bin to count as occupied. Default 6")} + }, {"deviceSetIndex"}), + [this](const QJsonObject& args) + { + const int deviceSetIndex = argInt(args, "deviceSetIndex"); + const double seconds = argDouble(args, "seconds", false, 60.0); + const QString enabled = ensureSpectrumHistory(deviceSetIndex, seconds); + SWGSDRangel::SWGGLSpectrumHistory response; + SWGSDRangel::SWGErrorResponse error; + response.init(); + error.init(); + const int status = m_adapter->devicesetSpectrumHistoryGet(deviceSetIndex, seconds, + argInt(args, "bins", false, 64), argInt64(args, "startFrequency", false, 0), argInt64(args, "stopFrequency", false, 0), + argDouble(args, "threshold", false, 6.0), response, error); + + if (!enabled.isEmpty() && (status == 404)) + { + QJsonObject result; + result["rows"] = 0; + result["note"] = enabled + " Call again in a few seconds, once some has accumulated."; + return result; + } + + check(status, error, "Get spectrum history"); + QJsonObject json = toJson(response); + QJsonArray maxDb, meanDb, occupancy; + + for (float v : *response.getMaxDb()) { + maxDb.append(std::round((double) v * 10.0) / 10.0); + } + + for (float v : *response.getMeanDb()) { + meanDb.append(std::round((double) v * 10.0) / 10.0); + } + + for (float v : *response.getOccupancy()) { + occupancy.append(std::round((double) v * 100.0) / 100.0); + } + + json["maxDb"] = maxDb; + json["meanDb"] = meanDb; + json["occupancy"] = occupancy; + + if (!enabled.isEmpty()) { + json["note"] = enabled; + } + + return json; + }); + + add("get_waterfall_image", + "A picture of the spectrum history, the waterfall, as a greyscale image: frequency across, time down with the newest " + "row at the bottom, black a little below the noise floor and white at the strongest signal. Use it when the shape of " + "activity matters more than the numbers: a hopping signal, a drifting carrier, a burst pattern, or to see a whole band " + "at once. The reply's text gives the frequency and time extents so the picture can be read. get_spectrum_history " + "gives the same history as numbers. Scrolling is switched on if it is off, and then there is nothing to show until " + "some has accumulated.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"seconds", numProp("How far back to look, in seconds. Default 60")}, + {"width", bounded(intProp("Width in pixels, one per bin. Default 512"), 16, 2048)}, + {"height", bounded(intProp("At most this many rows, the most recent. Default 512"), 16, 2000)}, + {"startFrequency", numProp("Only from this frequency in Hz. Default the start of the spectrum")}, + {"stopFrequency", numProp("Only up to this frequency in Hz. Default the end of the spectrum")} + }, {"deviceSetIndex"}), + [this](const QJsonObject& args) + { + const int deviceSetIndex = argInt(args, "deviceSetIndex"); + const double seconds = argDouble(args, "seconds", false, 60.0); + const QString enabled = ensureSpectrumHistory(deviceSetIndex, seconds); + QByteArray png; + QJsonObject description; + SWGSDRangel::SWGErrorResponse error; + error.init(); + const int status = m_adapter->devicesetSpectrumHistoryImageGet(deviceSetIndex, seconds, + argInt(args, "width", false, 512), argInt64(args, "startFrequency", false, 0), argInt64(args, "stopFrequency", false, 0), + argInt(args, "height", false, 512), png, description, error); + + if (!enabled.isEmpty() && (status == 404)) + { + QJsonObject result; + result["note"] = enabled + " Call again in a few seconds, once some has accumulated."; + return result; + } + + check(status, error, "Get waterfall image"); + QJsonObject image; + image["data"] = QString(png.toBase64()); + image["mimeType"] = "image/png"; + description["_image"] = image; + description["note"] = QString("Frequency runs left to right from %1 to %2 MHz, time top to bottom from %3 to %4 with the newest row at the bottom; black is %5 dB and white %6 dB.%7") + .arg(description["startFrequency"].toDouble() / 1e6, 0, 'f', 4).arg(description["stopFrequency"].toDouble() / 1e6, 0, 'f', 4) + .arg(description["firstTime"].toString()).arg(description["lastTime"].toString()) + .arg(description["blackDb"].toDouble(), 0, 'f', 1).arg(description["whiteDb"].toDouble(), 0, 'f', 1) + .arg(enabled.isEmpty() ? QString() : " " + enabled); + return description; + }); + + add("spectrum_action", + "Act on the main spectrum of a device set. autoscale sets the reference level and range from what is on screen, " + "clearSpectrum discards the histogram and max hold traces, resetMeasurements starts the measurement statistics again, " + "freeze stops spectrum processing and unfreezing resumes it, and gotoMarker retunes to one of the annotations. " + "Everything except freeze acts on the display and so needs the GUI.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"autoscale", prop("boolean", "Set the reference level and range from the spectrum currently displayed")}, + {"clearSpectrum", prop("boolean", "Discard the accumulated histogram and max hold traces")}, + {"resetMeasurements", prop("boolean", "Discard the accumulated measurement statistics")}, + {"freeze", prop("boolean", "True to stop spectrum processing, false to resume it")}, + {"gotoMarker", intProp("Retune to the annotation at this index, counting from 0")} + }, {"deviceSetIndex"}), + [this](const QJsonObject& args) + { + int deviceSetIndex = argInt(args, "deviceSetIndex"); + QJsonObject actions; + + for (const QString& key : {QString("autoscale"), QString("clearSpectrum"), QString("resetMeasurements"), QString("freeze")}) + { + if (hasArg(args, key)) { + actions[key] = argBool(args, key, false) ? 1 : 0; + } + } + + if (hasArg(args, "gotoMarker")) { + actions["gotoMarker"] = argInt(args, "gotoMarker"); + } + + if (actions.isEmpty()) { + throw MCPToolError("Give at least one of autoscale, clearSpectrum, resetMeasurements, freeze or gotoMarker"); + } + + QStringList keys; + extractKeys(actions, keys); + + // fromJsonObject takes its argument by non-const reference and looks every field up + // with operator[], which inserts a null for each one that is absent, so what is echoed + // back is taken before the call rather than after it + QJsonObject applied = actions; + SWGSDRangel::SWGSpectrumActions query; + query.init(); + query.fromJsonObject(actions); + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->devicesetSpectrumActionsPost(deviceSetIndex, keys, query, error), error, "Spectrum action"); + + QJsonObject result; + result["deviceSetIndex"] = deviceSetIndex; + result["applied"] = applied; + return result; + }); + + add("add_annotation", + "Add a labelled annotation to the main spectrum of a device set, for instance the name of the station a channel is tuned to. " + "Appends to the annotations already there instead of replacing them, and turns annotation display on if it is off. " + "Give centerFrequency, which is usually what you want as the bandwidth is then centred on it, or startFrequency.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"text", strProp("Label shown against the annotation, e.g. the RDS programme service name of a broadcast station")}, + {"centerFrequency", numProp("Centre frequency of the annotation in Hz. Give this or startFrequency")}, + {"startFrequency", numProp("Start frequency of the annotation in Hz. Give this or centerFrequency")}, + {"bandwidth", intProp("Width of the annotation in Hz. Default 0, which marks a single frequency")}, + {"color", intProp("Colour packed as blue*65536 + green*256 + red, each component 0 to 255. Default yellow")}, + {"show", bounded(intProp("0 hidden, 1 top marker only, 2 full with text and limits, 3 text only. Default 2"), 0, 3)} + }, {"deviceSetIndex", "text"}), + [this](const QJsonObject& args) + { + int deviceSetIndex = argInt(args, "deviceSetIndex"); + int bandwidth = argInt(args, "bandwidth", false, 0); + + if (bandwidth < 0) { + throw MCPToolError("bandwidth cannot be negative"); + } + + qint64 startFrequency; + + if (hasArg(args, "startFrequency")) { + startFrequency = argInt64(args, "startFrequency"); + } else if (hasArg(args, "centerFrequency")) { + startFrequency = argInt64(args, "centerFrequency") - bandwidth / 2; + } else { + throw MCPToolError("Give either centerFrequency or startFrequency"); + } + + QJsonObject marker; + marker["startFrequency"] = startFrequency; + marker["bandwidth"] = bandwidth; + marker["markerColor"] = argInt(args, "color", false, 65535); // Yellow + marker["show"] = argInt(args, "show", false, 2); + marker["text"] = argString(args, "text"); + + QJsonObject current = getSpectrumSettings(deviceSetIndex); + + // Appended by the settings themselves rather than by reading the list, adding to it and + // writing it back, which would lose an annotation added by anything else in between + QJsonArray markers; + markers.append(marker); + + QJsonObject patch; + patch["annotationMarkers"] = markers; + patch["annotationMarkersMode"] = 1; + // Annotations are drawn only when their bit of markersDisplay is set, so an annotation + // added while it is clear would otherwise be invisible with nothing to say why + patch["markersDisplay"] = current.value("markersDisplay").toInt(0) | 0x2; + + QJsonObject after = patchSpectrumSettings(deviceSetIndex, patch); + QJsonObject result; + result["added"] = marker; + result["annotationMarkers"] = after.value("annotationMarkers").toArray(); + return result; + }); + + add("remove_annotation", + "Remove annotations from the main spectrum of a device set. Give text to remove the annotations carrying that label, " + "frequency to remove those whose span covers it, or all to remove every annotation. Returns what was removed and what is left.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"text", strProp("Remove annotations whose label is exactly this")}, + {"frequency", numProp("Remove annotations whose span covers this frequency in Hz")}, + {"all", prop("boolean", "Remove every annotation. Default false")} + }, {"deviceSetIndex"}), + [this](const QJsonObject& args) + { + int deviceSetIndex = argInt(args, "deviceSetIndex"); + bool all = argBool(args, "all", false); + bool byText = hasArg(args, "text"); + bool byFrequency = hasArg(args, "frequency"); + + // Without a criterion the intent is ambiguous, and either reading of it, removing + // nothing or removing everything, would be wrong often enough to be worth refusing + if (!all && !byText && !byFrequency) { + throw MCPToolError("Give text, frequency or all to say which annotations to remove"); + } + + QString text = argString(args, "text", false); + qint64 frequency = argInt64(args, "frequency", false); + QJsonArray markers = getSpectrumSettings(deviceSetIndex).value("annotationMarkers").toArray(); + QJsonArray kept; + QJsonArray removed; + + for (const QJsonValue& value : markers) + { + QJsonObject marker = value.toObject(); + qint64 start = (qint64) marker.value("startFrequency").toDouble(); + qint64 stop = start + (qint64) marker.value("bandwidth").toDouble(); + bool matches = all + || (byText && (marker.value("text").toString() == text)) + || (byFrequency && (frequency >= start) && (frequency <= stop)); + + if (matches) { + removed.append(marker); + } else { + kept.append(marker); + } + } + + QJsonObject result; + result["removed"] = removed; + + if (removed.isEmpty()) + { + result["annotationMarkers"] = markers; + result["warning"] = "No annotation matched, so nothing was removed"; + return result; + } + + QJsonObject patch; + patch["annotationMarkers"] = kept; + QJsonObject after = patchSpectrumSettings(deviceSetIndex, patch); + result["annotationMarkers"] = after.value("annotationMarkers").toArray(); + return result; + }); +} + +void MCPTools::registerChannelTools() +{ + add("add_channel", + "Add a channel (demodulator or modulator) to a device set and optionally apply initial settings. Returns the index of the new channel. " + "channelType is an id from list_channel_types, e.g. ADSBDemod, NFMDemod, AMDemod, BFMDemod, SSBDemod, AISDemod, PacketDemod, FileSink.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"channelType", strProp("Channel type id from list_channel_types")}, + {"settings", objProp("Optional initial settings for the channel, e.g. {\"inputFrequencyOffset\": 0}. Use describe_settings for the keys")} + }, {"deviceSetIndex", "channelType"}), + [this](const QJsonObject& args) + { + int deviceSetIndex = argInt(args, "deviceSetIndex"); + QString channelType = argString(args, "channelType"); + int channelIndex = addChannelAndWait(deviceSetIndex, channelType); + QJsonObject result; + result["deviceSetIndex"] = deviceSetIndex; + result["channelIndex"] = channelIndex; + QString warning = basebandWarning(deviceSetIndex, channelType); + + if (!warning.isEmpty()) { + result["warning"] = warning; + } + QJsonObject settings = argObject(args, "settings", false); + + if (!settings.isEmpty()) + { + QJsonObject patched; + + try + { + patched = patchChannelSettings(deviceSetIndex, channelIndex, settings); + } + catch (const MCPToolError& e) + { + // The channel exists even though its settings were refused. Say so and give + // its index, otherwise a retry would leave a second one behind. + throw MCPToolError(QString("The %1 channel was created as channel %2 of device set %3, but its initial " + "settings were refused, so it is left with defaults: %4. Use set_channel_settings to correct it, " + "or delete_channel to remove it. Do not call add_channel again.") + .arg(channelType).arg(channelIndex).arg(deviceSetIndex).arg(e.message)); + } + + result["changed"] = patched["changed"]; + + if (patched.contains("warning")) { + result["warning"] = patched["warning"]; + } + } + + return result; + }); + + add("delete_channel", + "Remove a channel from a device set. Channels with a higher index are renumbered down by one.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"channelIndex", channelIndexProp} + }, {"deviceSetIndex", "channelIndex"}), + [this](const QJsonObject& args) + { + int deviceSetIndex = argInt(args, "deviceSetIndex"); + + // Waits for the channel itself to disappear. Waiting for the removed signal would + // sit out the whole timeout for the last channel of a device set, which the device + // set drops from its list before MainCore can look it up to signal it. + deleteChannelAndWait(deviceSetIndex, argInt(args, "channelIndex")); + QJsonObject result; + result["deviceSetIndex"] = deviceSetIndex; + result["channelCount"] = channelCount(deviceSetIndex); + return result; + }); + + add("get_channel_settings", + "Get the settings of a channel. The keys depend on the channel type. inputFrequencyOffset is the channel frequency relative to the device centre frequency in Hz.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"channelIndex", channelIndexProp} + }, {"deviceSetIndex", "channelIndex"}), + [this](const QJsonObject& args) { return getChannelSettings(argInt(args, "deviceSetIndex"), argInt(args, "channelIndex")); }); + + add("set_channel_settings", + "Change some settings of a channel. Give only the keys to change, e.g. {\"inputFrequencyOffset\": 25000, \"squelch\": -40}. " + "Use describe_settings with the channel type to learn the valid keys. Returns the keys changed with their applied values.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"channelIndex", channelIndexProp}, + {"settings", objProp("Object with the settings keys to change and their new values")} + }, {"deviceSetIndex", "channelIndex", "settings"}), + [this](const QJsonObject& args) + { + return patchChannelSettings(argInt(args, "deviceSetIndex"), argInt(args, "channelIndex"), argObject(args, "settings")); + }); + + add("get_channel_report", + "Get the live report of a channel: signal level, squelch state, decoder statistics and so on, depending on the channel type. " + "Omit channelIndex for the reports of every channel of the device set. " + "For DAB, wait briefly after selecting a programme or changing receiver gain and then read the report again. Do not accept " + "sync or audioActive alone as proof of clean reception: if synchronized audio has SNR at or below 0 dB, RTL-SDR overload " + "is likely, so reduce gain through its supported values and keep the setting that gives the best positive SNR.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"channelIndex", intProp("Index of the channel within the device set; omit for all channels")} + }, {"deviceSetIndex"}), + [this](const QJsonObject& args) + { + int deviceSetIndex = argInt(args, "deviceSetIndex"); + SWGSDRangel::SWGErrorResponse error; + error.init(); + + if (hasArg(args, "channelIndex")) + { + int channelIndex = argInt(args, "channelIndex"); + SWGSDRangel::SWGChannelReport response; + check(m_adapter->devicesetChannelReportGet(deviceSetIndex, channelIndex, response, error), error, "Get channel report"); + QJsonObject report = toJson(response); + addRdsHint(report, report.value("channelType").toString(), deviceSetIndex, channelIndex); + return report; + } + + SWGSDRangel::SWGChannelsDetail response; + check(m_adapter->devicesetChannelsReportGet(deviceSetIndex, response, error), error, "Get channels report"); + QJsonObject json = toJson(response); + QJsonArray channels = json.value("channels").toArray(); + + for (int i = 0; i < channels.size(); i++) + { + QJsonObject channel = channels.at(i).toObject(); + QJsonObject report = channel.value("report").toObject(); + // The channel type is on the entry here rather than on the report it carries + addRdsHint(report, channel.value("id").toString(), deviceSetIndex, channel.value("index").toInt()); + channel["report"] = report; + channels[i] = channel; + } + + json["channels"] = channels; + return json; + }); + + add("channel_action", + "Trigger an action on a channel. Only some channel types have actions. Use describe_settings to find the actions keys of the " + "channel type; pass them as the actions object.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"channelIndex", channelIndexProp}, + {"actions", objProp("Object with the action keys and values for this channel type")} + }, {"deviceSetIndex", "channelIndex", "actions"}), + [this](const QJsonObject& args) + { + int deviceSetIndex = argInt(args, "deviceSetIndex"); + int channelIndex = argInt(args, "channelIndex"); + QJsonObject actions = argObject(args, "actions"); + QJsonObject settings = getChannelSettings(deviceSetIndex, channelIndex); + QString channelType = settings["channelType"].toString(); + + if (!WebAPIUtils::m_channelTypeToActionsKey.contains(channelType)) { + throw MCPToolError(QString("Channel type %1 has no actions").arg(channelType)); + } + + QString actionsKey = WebAPIUtils::m_channelTypeToActionsKey[channelType]; + QJsonObject json; + json["channelType"] = channelType; + json["direction"] = settings["direction"].toInt(0); + json[actionsKey] = actions.contains(actionsKey) ? actions[actionsKey].toObject() : actions; + QStringList keys; + extractKeys(json[actionsKey].toObject(), keys); + + SWGSDRangel::SWGChannelActions query; + query.init(); + query.fromJsonObject(json); + SWGSDRangel::SWGSuccessResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->devicesetChannelActionsPost(deviceSetIndex, channelIndex, keys, query, response, error), error, "Channel action"); + return toJson(response); + }); +} + +void MCPTools::registerFeatureTools() +{ + add("add_feature", + "Add a feature (device independent plugin such as Map, AIS, APRS, SatelliteTracker) and optionally apply initial settings. " + "Returns the index of the new feature. featureType is an id from list_feature_types.", + schema({ + {"featureType", strProp("Feature type id from list_feature_types")}, + {"settings", objProp("Optional initial settings for the feature. Use describe_settings for the keys")} + }, {"featureType"}), + [this](const QJsonObject& args) + { + QString featureType = argString(args, "featureType"); + int featureIndex = addFeatureAndWait(featureType); + QJsonObject result; + result["featureIndex"] = featureIndex; + QJsonObject settings = argObject(args, "settings", false); + + if (!settings.isEmpty()) + { + QJsonObject patched; + + try + { + patched = patchFeatureSettings(featureIndex, settings); + } + catch (const MCPToolError& e) + { + throw MCPToolError(QString("The %1 feature was created as feature %2, but its initial settings were " + "refused, so it is left with defaults: %3. Use set_feature_settings to correct it, or " + "delete_feature to remove it. Do not call add_feature again.") + .arg(featureType).arg(featureIndex).arg(e.message)); + } + + result["changed"] = patched["changed"]; + + if (patched.contains("warning")) { + result["warning"] = patched["warning"]; + } + } + + return result; + }); + + add("delete_feature", + "Remove a feature. Features with a higher index are renumbered down by one.", + schema({{"featureIndex", featureIndexProp}}, {"featureIndex"}), + [this](const QJsonObject& args) + { + int featureIndex = argInt(args, "featureIndex"); + QMutexLocker deletionLock(&m_deletionMutex); + requireNotSelf(featureIndex, "deleted"); + const uint64_t target = featureUidAt(featureIndex); + SWGSDRangel::SWGSuccessResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->featuresetFeatureDelete(0, featureIndex, response, error), error, "Delete feature"); + + // FeatureSet drops the feature from its own list before MainCore looks it up, so + // removing the last feature emits no featureRemoved. Watch the feature itself go. + if (!waitFor([&]() { return !featureUids().contains(target); })) { + throw MCPToolError(QString("Timed out waiting for feature %1 to be removed").arg(featureIndex)); + } + + QJsonObject result; + result["featureCount"] = featureCount(); + return result; + }); + + add("get_feature_settings", + "Get the settings of a feature. The keys depend on the feature type.", + schema({{"featureIndex", featureIndexProp}}, {"featureIndex"}), + [this](const QJsonObject& args) { return getFeatureSettings(argInt(args, "featureIndex")); }); + + add("set_feature_settings", + "Change some settings of a feature. Give only the keys to change. Use describe_settings with the feature type to learn the valid keys.", + schema({ + {"featureIndex", featureIndexProp}, + {"settings", objProp("Object with the settings keys to change and their new values")} + }, {"featureIndex", "settings"}), + [this](const QJsonObject& args) { return patchFeatureSettings(argInt(args, "featureIndex"), argObject(args, "settings")); }); + + add("get_feature_report", + "Get the live report of a feature, depending on the feature type.", + schema({{"featureIndex", featureIndexProp}}, {"featureIndex"}), + [this](const QJsonObject& args) + { + SWGSDRangel::SWGFeatureReport response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->featuresetFeatureReportGet(0, argInt(args, "featureIndex"), response, error), error, "Get feature report"); + return toJson(response); + }); + + add("start_feature", + "Start a feature. Most features must be started to do anything, but the passive ones - AIS, AMBE, AntennaTools, " + "APRS, FreqDisplay, LimeRFE, Map, Radiosonde, RemoteControl and SkyMap - have no run state, work as soon as they " + "are configured and always report idle. Starting one of those is answered without doing anything.", + schema({{"featureIndex", featureIndexProp}}, {"featureIndex"}), + [this](const QJsonObject& args) { return featureState(argInt(args, "featureIndex"), 1); }); + + add("stop_feature", + "Stop a feature.", + schema({{"featureIndex", featureIndexProp}}, {"featureIndex"}), + [this](const QJsonObject& args) + { + int featureIndex = argInt(args, "featureIndex"); + requireNotSelf(featureIndex, "stopped"); + return featureState(featureIndex, 0); + }); + + add("feature_action", + "Trigger an action on a feature. Use describe_settings to find the actions keys of the feature type; pass them as the actions object.", + schema({ + {"featureIndex", featureIndexProp}, + {"actions", objProp("Object with the action keys and values for this feature type")} + }, {"featureIndex", "actions"}), + [this](const QJsonObject& args) + { + int featureIndex = argInt(args, "featureIndex"); + QJsonObject actions = argObject(args, "actions"); + QJsonObject settings = getFeatureSettings(featureIndex); + QString featureType = settings["featureType"].toString(); + + if (!WebAPIUtils::m_featureTypeToActionsKey.contains(featureType)) { + throw MCPToolError(QString("Feature type %1 has no actions").arg(featureType)); + } + + QString actionsKey = WebAPIUtils::m_featureTypeToActionsKey[featureType]; + QJsonObject json; + json["featureType"] = featureType; + json[actionsKey] = actions.contains(actionsKey) ? actions[actionsKey].toObject() : actions; + QStringList keys; + extractKeys(json[actionsKey].toObject(), keys); + + SWGSDRangel::SWGFeatureActions query; + query.init(); + query.fromJsonObject(json); + SWGSDRangel::SWGSuccessResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->featuresetFeatureActionsPost(0, featureIndex, keys, query, response, error), error, "Feature action"); + return toJson(response); + }); +} + +void MCPTools::registerPresetTools() +{ + add("list_presets", + "List the saved device set presets. A preset stores a device set's device and channel settings and is identified by group name, " + "name, centre frequency and type (R for rx, T for tx, M for MIMO).", + schema(QJsonObject()), + [this](const QJsonObject&) { return getPresets(); }); + + add("load_preset", + "Load a preset into a device set, replacing its device settings and channels. The preset type must match the device set direction.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"groupName", strProp("Preset group name")}, + {"name", strProp("Preset name")}, + {"centerFrequency", numProp("Preset centre frequency in Hz. Only needed when several presets share the group and name")}, + {"type", strProp("Preset type R, T or M. Only needed when several presets share the group and name")} + }, {"deviceSetIndex", "groupName", "name"}), + [this](const QJsonObject& args) + { + int deviceSetIndex = argInt(args, "deviceSetIndex"); + QJsonObject identifier = presetIdentifier(args, deviceSetIndex, false); + SWGSDRangel::SWGPresetTransfer query; + query.setDeviceSetIndex(deviceSetIndex); + SWGSDRangel::SWGPresetIdentifier *preset = new SWGSDRangel::SWGPresetIdentifier(); + preset->setGroupName(new QString(identifier["groupName"].toString())); + preset->setName(new QString(identifier["name"].toString())); + preset->setType(new QString(identifier["type"].toString())); + preset->setCenterFrequency((qint64) identifier["centerFrequency"].toDouble()); + query.setPreset(preset); + SWGSDRangel::SWGPresetIdentifier response; + response.init(); + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->instancePresetPatch(query, response, error), error, "Load preset"); + pause(500); // Loading replaces the channels; give it a moment before the caller looks + QJsonObject result; + result["loaded"] = toJson(response); + result["deviceSet"] = getDeviceSet(deviceSetIndex); + return result; + }); + + add("save_preset", + "Save the current device settings and channels of a device set as a preset. Updates the preset if one with the same group, name, " + "centre frequency and type exists, otherwise creates it.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"groupName", strProp("Preset group name")}, + {"name", strProp("Preset name")} + }, {"deviceSetIndex", "groupName", "name"}), + [this](const QJsonObject& args) + { + int deviceSetIndex = argInt(args, "deviceSetIndex"); + QJsonObject identifier = presetIdentifier(args, deviceSetIndex, true); + SWGSDRangel::SWGPresetTransfer query; + query.setDeviceSetIndex(deviceSetIndex); + SWGSDRangel::SWGPresetIdentifier *preset = new SWGSDRangel::SWGPresetIdentifier(); + preset->setGroupName(new QString(identifier["groupName"].toString())); + preset->setName(new QString(identifier["name"].toString())); + preset->setType(new QString(identifier["type"].toString())); + preset->setCenterFrequency((qint64) identifier["centerFrequency"].toDouble()); + query.setPreset(preset); + SWGSDRangel::SWGPresetIdentifier response; + response.init(); + SWGSDRangel::SWGErrorResponse error; + error.init(); + bool exists = identifier["exists"].toBool(); + + if (exists) { + check(m_adapter->instancePresetPut(query, response, error), error, "Update preset"); + } else { + check(m_adapter->instancePresetPost(query, response, error), error, "Create preset"); + } + + QJsonObject result; + result["preset"] = toJson(response); + result["created"] = !exists; + return result; + }); + + add("list_configurations", + "List the saved configurations. A configuration stores the whole instance: all device sets, features and workspaces.", + schema(QJsonObject()), + [this](const QJsonObject&) { return getConfigurations(); }); + + add("load_configuration", + "Load a saved configuration, replacing all current device sets and features.", + schema({ + {"groupName", strProp("Configuration group name")}, + {"name", strProp("Configuration name")} + }, {"groupName", "name"}), + [this](const QJsonObject& args) + { + SWGSDRangel::SWGConfigurationIdentifier response; + response.setGroupName(new QString(argString(args, "groupName"))); + response.setName(new QString(argString(args, "name"))); + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->instanceConfigurationPatch(response, error), error, "Load configuration"); + pause(1000); // Loading rebuilds everything + QJsonObject result; + result["configuration"] = toJson(response); + result["instance"] = getInstanceSummary(); + return result; + }); + + add("save_configuration", + "Save the whole current instance as a configuration. Updates the configuration if one with the same group and name exists, otherwise creates it.", + schema({ + {"groupName", strProp("Configuration group name")}, + {"name", strProp("Configuration name")} + }, {"groupName", "name"}), + [this](const QJsonObject& args) + { + QString groupName = argString(args, "groupName"); + QString name = argString(args, "name"); + bool exists = false; + + for (const auto& groupValue : getConfigurations()["groups"].toArray()) + { + QJsonObject group = groupValue.toObject(); + + if (group["groupName"].toString() != groupName) { + continue; + } + + for (const auto& item : group["configurations"].toArray()) + { + if (item.toObject()["name"].toString() == name) { + exists = true; + } + } + } + + SWGSDRangel::SWGConfigurationIdentifier response; + response.setGroupName(new QString(groupName)); + response.setName(new QString(name)); + SWGSDRangel::SWGErrorResponse error; + error.init(); + + if (exists) { + check(m_adapter->instanceConfigurationPut(response, error), error, "Update configuration"); + } else { + check(m_adapter->instanceConfigurationPost(response, error), error, "Create configuration"); + } + + QJsonObject result; + result["configuration"] = toJson(response); + result["created"] = !exists; + return result; + }); +} + +void MCPTools::registerWorkspaceTools() +{ + add("add_workspace", + "GUI only: add a new workspace (a tabbed area holding device, channel and feature windows). Workspaces are numbered from 0.", + schema(QJsonObject()), + [this](const QJsonObject&) + { + SWGSDRangel::SWGSuccessResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->instanceWorkspacePost(response, error), error, "Add workspace"); + return toJson(response); + }); + + add("delete_empty_workspaces", + "GUI only: remove all workspaces that contain no windows.", + schema(QJsonObject()), + [this](const QJsonObject&) + { + SWGSDRangel::SWGSuccessResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->instanceWorkspaceDelete(response, error), error, "Delete empty workspaces"); + return toJson(response); + }); + + add("arrange_workspace", + "GUI only: arrange the windows of a workspace, as its title bar buttons do. cascade, tile, stackVertical and stack " + "rearrange them once and turn auto stacking and tabs off; autostack stacks them now and again whenever a window is " + "added or resized, until another arrangement is asked for; tab shows one window at a time with a tab for each. " + "stack is the usual choice: devices, spectra and channels in columns.", + schema({ + {"workspaceIndex", intProp("Index of the workspace, from 0")}, + {"arrange", enumProp("cascade, tile, stackVertical, stack, autostack or tab", {"cascade", "tile", "stackVertical", "stack", "autostack", "tab"})} + }, {"workspaceIndex", "arrange"}), + [this](const QJsonObject& args) + { + SWGSDRangel::SWGWorkspaceActions query; + query.init(); + query.setArrange(new QString(argString(args, "arrange"))); + SWGSDRangel::SWGSuccessResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->workspaceActionsPost(argInt(args, "workspaceIndex"), query, response, error), error, "Arrange workspace"); + return toJson(response); + }); + + add("list_windows", + "GUI only: every window, with its kind (device, spectrum, channel or feature), indices, title, workspace and whether it " + "is hidden. A hidden window is still running; set_workspace with hidden false shows it again.", + schema({}), + [this](const QJsonObject&) + { + SWGSDRangel::SWGWindowList response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->instanceWindowsGet(response, error), error, "List windows"); + return toJson(response); + }); + + add("set_workspace", + "GUI only: move a window to a workspace, hide it, or show it again. kind is device, spectrum or channel (with " + "deviceSetIndex, plus channelIndex for a channel) or feature (with featureIndex). Give workspaceIndex to move, hidden " + "to hide (true) or show (false), or both. Showing a window raises it and shows the workspace holding it. Hiding a " + "window does not stop it: a hidden demodulator still plays audio. list_windows shows what is hidden.", + schema({ + {"kind", strProp("device, spectrum, channel or feature")}, + {"workspaceIndex", intProp("Workspace to move the window to. Optional")}, + {"hidden", prop("boolean", "true hides the window, false shows it. Optional")}, + {"deviceSetIndex", intProp("For device, spectrum and channel")}, + {"channelIndex", intProp("For channel")}, + {"featureIndex", intProp("For feature")} + }, {"kind"}), + [this](const QJsonObject& args) + { + QString kind = argString(args, "kind").trimmed().toLower(); + + if (!hasArg(args, "workspaceIndex") && !hasArg(args, "hidden")) { + throw MCPToolError("Give workspaceIndex to move the window, hidden to hide or show it, or both"); + } + + // -1 for what was not asked for, as the Web API's own validator passes it + SWGSDRangel::SWGWorkspaceInfo query; + query.setIndex(hasArg(args, "workspaceIndex") ? argInt(args, "workspaceIndex") : -1); + query.setHidden(hasArg(args, "hidden") ? (argBool(args, "hidden", false) ? 1 : 0) : -1); + SWGSDRangel::SWGSuccessResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + + if (kind == "device") { + check(m_adapter->devicesetDeviceWorkspacePut(argInt(args, "deviceSetIndex"), query, response, error), error, "Set device workspace"); + } else if (kind == "spectrum") { + check(m_adapter->devicesetSpectrumWorkspacePut(argInt(args, "deviceSetIndex"), query, response, error), error, "Set spectrum workspace"); + } else if (kind == "channel") { + check(m_adapter->devicesetChannelWorkspacePut(argInt(args, "deviceSetIndex"), argInt(args, "channelIndex"), query, response, error), error, "Set channel workspace"); + } else if (kind == "feature") { + check(m_adapter->featuresetFeatureWorkspacePut(argInt(args, "featureIndex"), query, response, error), error, "Set feature workspace"); + } else { + throw MCPToolError("kind must be device, spectrum, channel or feature"); + } + + return toJson(response); + }); +} + +void MCPTools::registerCaptureTools() +{ + + add("get_server_status", + "This server's own state, in one call: the capture directory and any recordings running; which channels and features " + "feed packets and map items and how much has arrived; and the client event streams (open streams, subscriptions, " + "notifications sent). Open a stream with an HTTP GET on the MCP endpoint with Accept: text/event-stream, then " + "resources/subscribe.", + schema(QJsonObject()), + [this](const QJsonObject&) + { + QJsonObject result; + result["capture"] = m_capture.status(); + result["dataFeed"] = m_dataFeed.getStatus(); + result["streams"] = m_streams ? m_streams->status() : QJsonObject(); + return result; + }); + + add("capture_audio", + QString("Record the demodulated audio of a channel to a WAV file and report where it went, how loud it was and whether it " + "was silent. Works with demodulators that feed the Demod Analyzer, such as NFMDemod, AMDemod, SSBDemod, WFMDemod, " + "BFMDemod, DSDDemod and M17Demod. The device must be running. This call blocks for the duration, so it is limited " + "to %1 seconds. Set inline to true (up to %2 seconds) to also get the audio back as base64 for playing directly: " + "a mono 16 kHz copy, small enough for a tool result, while the file keeps the full rate.") + .arg(MCPCapture::m_maxBlockingSeconds).arg(MCPCapture::m_maxInlineSeconds), + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"channelIndex", channelIndexProp}, + {"seconds", bounded(numProp(QString("How long to record for, up to %1").arg(MCPCapture::m_maxBlockingSeconds)), 0.1, MCPCapture::m_maxBlockingSeconds)}, + {"fileName", strProp("File name relative to the capture directory. The .wav extension is added. Default: audio_")}, + {"inline", prop("boolean", QString("Also return the audio as base64 in audioBase64, as a mono 16 kHz WAV. Only for clips of %1 seconds or less. Default false").arg(MCPCapture::m_maxInlineSeconds))} + }, {"deviceSetIndex", "channelIndex", "seconds"}), + [this](const QJsonObject& args) + { + int deviceSetIndex = argInt(args, "deviceSetIndex"); + int channelIndex = argInt(args, "channelIndex"); + double seconds = argDouble(args, "seconds"); + bool inlineAudio = argBool(args, "inline", false); + + if ((seconds <= 0) || (seconds > MCPCapture::m_maxBlockingSeconds)) { + throw MCPToolError(QString("seconds must be between 0 and %1").arg(MCPCapture::m_maxBlockingSeconds)); + } + + if (inlineAudio && (seconds > MCPCapture::m_maxInlineSeconds)) { + throw MCPToolError(QString("inline audio is only available for %1 seconds or less").arg(MCPCapture::m_maxInlineSeconds)); + } + + QJsonObject state = deviceState(deviceSetIndex, 0, -1); + + if (state["state"].toString() != "running") { + throw MCPToolError("The device is not running, so there is no audio to record. Call start_device first."); + } + + return m_capture.captureAudio(deviceSetIndex, channelIndex, seconds, + argString(args, "fileName", false), inlineAudio); + }); + + add("start_iq_recording", + "Start recording baseband IQ samples to a file. Adds a FileSink channel to the device set unless channelIndex names an " + "existing one, and starts it recording. The device must be running for samples to be written. Recording continues until " + "stop_iq_recording, so use this for long captures and record_iq for short ones. Files are written under the capture " + "directory shown by get_server_status; fileName is relative to it.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"fileName", strProp("File name relative to the capture directory. A timestamp and the .sdriq extension are added. Default: iq_")}, + {"frequencyOffset", intProp("Channel frequency offset from the device centre frequency in Hz. Default 0, which records the full baseband centred on the device frequency")}, + {"log2Decim", bounded(intProp("Decimation as a power of two: 0 records at the device sample rate, 1 halves it, and so on. Default 0"), 0, 6)}, + {"channelIndex", intProp("Use this existing FileSink channel instead of adding one")} + }, {"deviceSetIndex"}), + [this](const QJsonObject& args) + { + int deviceSetIndex = argInt(args, "deviceSetIndex"); + bool created = !hasArg(args, "channelIndex"); + + // A bad file name is refused before a channel is added for it + m_capture.checkFileName(argString(args, "fileName", false), "iq"); + + int channelIndex = created ? addChannelAndWait(deviceSetIndex, "FileSink") : argInt(args, "channelIndex"); + const uint64_t channel = created ? channelUidAt(deviceSetIndex, channelIndex) : 0; + + try + { + QJsonObject result = m_capture.startIQRecording(deviceSetIndex, channelIndex, + argString(args, "fileName", false), argInt(args, "frequencyOffset", false, 0), + argInt(args, "log2Decim", false, 0)); + result["channelCreated"] = created; + QJsonObject state = deviceState(deviceSetIndex, 0, -1); + + if (state["state"].toString() != "running") { + result["warning"] = "The device is not running, so no samples will be recorded. Call start_device."; + } + + return result; + } + catch (const MCPToolError&) + { + // Do not leave a channel behind when the recording could not be set up. By + // identity: a concurrent listen or scan may have renumbered it meanwhile + if (created) { + try { deleteChannelObjectAndWait(channel); } catch (const MCPToolError&) {} + } + + throw; + } + }); + + add("stop_iq_recording", + "Stop an IQ recording started with start_iq_recording and report the files written, with their size and duration.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"channelIndex", intProp("Index of the FileSink channel that is recording")}, + {"deleteChannel", prop("boolean", "Delete the FileSink channel afterwards. Default false")} + }, {"deviceSetIndex", "channelIndex"}), + [this](const QJsonObject& args) + { + int deviceSetIndex = argInt(args, "deviceSetIndex"); + int channelIndex = argInt(args, "channelIndex"); + const uint64_t channel = channelUidAt(deviceSetIndex, channelIndex); + QJsonObject result = m_capture.stopIQRecording(deviceSetIndex, channelIndex); + bool deleteChannel = argBool(args, "deleteChannel", false); + + if (deleteChannel) + { + deleteChannelObjectAndWait(channel); + result["channelDeleted"] = true; + } + + return result; + }); + + add("record_iq", + QString("Record baseband IQ samples for a fixed number of seconds and return the files written. Adds a FileSink channel, " + "records, stops and removes the channel again. This call blocks for the duration, so it is limited to %1 seconds; " + "for longer captures use start_iq_recording and stop_iq_recording. The device must already be running. " + "Note that IQ files are large: roughly 4 bytes per sample per second of the device sample rate.") + .arg(MCPCapture::m_maxBlockingSeconds), + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"seconds", bounded(numProp(QString("How long to record for, up to %1").arg(MCPCapture::m_maxBlockingSeconds)), 0.1, MCPCapture::m_maxBlockingSeconds)}, + {"fileName", strProp("File name relative to the capture directory. A timestamp and the .sdriq extension are added")}, + {"frequencyOffset", intProp("Channel frequency offset from the device centre frequency in Hz. Default 0")}, + {"log2Decim", bounded(intProp("Decimation as a power of two. Default 0"), 0, 6)} + }, {"deviceSetIndex", "seconds"}), + [this](const QJsonObject& args) + { + int deviceSetIndex = argInt(args, "deviceSetIndex"); + double seconds = argDouble(args, "seconds"); + + if ((seconds <= 0) || (seconds > MCPCapture::m_maxBlockingSeconds)) + { + throw MCPToolError(QString("seconds must be between 0 and %1. For a longer capture use start_iq_recording and stop_iq_recording") + .arg(MCPCapture::m_maxBlockingSeconds)); + } + + QJsonObject state = deviceState(deviceSetIndex, 0, -1); + + if (state["state"].toString() != "running") { + throw MCPToolError("The device is not running, so there is nothing to record. Call start_device first."); + } + + // A bad file name is refused before a channel is added for it + m_capture.checkFileName(argString(args, "fileName", false), "iq"); + + int channelIndex = addChannelAndWait(deviceSetIndex, "FileSink"); + + // This call sleeps for up to half a minute and is not serialised against the other + // tools, so another request can delete a channel and renumber this one meanwhile. + // Everything after the sleep therefore works from the channel's UID, not its index. + const uint64_t channel = channelUidAt(deviceSetIndex, channelIndex); + + if (channel == 0) // cannot happen, but do not leave the channel behind if it does + { + try { deleteChannelAndWait(deviceSetIndex, channelIndex); } catch (const MCPToolError&) {} + + throw MCPToolError("The FileSink channel went away as soon as it was added"); + } + + QJsonObject result; + + try + { + QJsonObject started = m_capture.startIQRecording(deviceSetIndex, channelIndex, + argString(args, "fileName", false), argInt(args, "frequencyOffset", false, 0), + argInt(args, "log2Decim", false, 0)); + pause((int) (seconds * 1000.0)); + result = m_capture.stopIQRecording(channel); + result["fileBase"] = started["fileBase"]; + result["requestedSeconds"] = seconds; + } + catch (const MCPToolError&) + { + try { deleteChannelObjectAndWait(channel); } catch (const MCPToolError&) {} + throw; + } + + deleteChannelObjectAndWait(channel); + + if (result["files"].toArray().isEmpty()) { + result["warning"] = "No files were written. Check that the device is running and producing samples."; + } + + return result; + }); +} + +// --------------------------------------------------------------------------- +// Intent level tools: a whole task in one call +// +// Setting up a receiver with the object level tools takes an agent around ten round trips, +// each one a model turn. These do the common tasks in one, using the same helpers, and reply +// with a short summary rather than the objects they created. +// --------------------------------------------------------------------------- + +namespace { + +// What "listen to X in mode Y" needs: the demodulator, its initial settings and the smallest +// baseband that carries it. Values are the ones the receiving guide and readmes give. +struct ListenMode +{ + const char *m_alias; + const char *m_channelType; + int m_rfBandwidth; //!< Hz. Negative selects the lower sideband, as the SSB demodulator does + int m_minBaseband; //!< Hz + const char *m_settings; //!< JSON of further initial settings + int m_scanStep; //!< Hz. The channel spacing scan steps by unless told otherwise; 0 for a mode on fixed frequencies, which is not scanned for + const char *m_feature; //!< A feature the mode's output goes to, added if absent; null for none + int m_pairOffset; //!< Hz. Non-zero for a mode on two channels this far either side of the frequency, one demodulator each +}; + +const char *const bfmSettings = "{\"afBandwidth\":15000,\"audioStereo\":1,\"rdsActive\":1,\"volume\":4,\"squelch\":-60}"; +const char *const amSettings = "{\"afBandwidth\":3000,\"bandpassEnable\":1,\"volume\":4,\"squelch\":-60}"; + +const ListenMode listenModes[] = { + // Broadcast FM asks for twice the baseband its channel needs: a 180 kHz channel in a 256 kS/s + // baseband sits against the edge of the decimation filters, and RDS suffers first; it also + // leaves room to put the channel clear of the device's DC spike + {"bfm", "BFMDemod", 180000, 512000, bfmSettings, 100000, nullptr, 0}, + {"fm", "BFMDemod", 180000, 512000, bfmSettings, 100000, nullptr, 0}, + {"wfm", "WFMDemod", 150000, 512000, "{\"volume\":2,\"squelch\":-60}", 100000, nullptr, 0}, + {"nfm", "NFMDemod", 12500, 48000, "{\"afBandwidth\":3000,\"volume\":2}", 12500, nullptr, 0}, + {"am", "AMDemod", 8000, 48000, amSettings, 25000, nullptr, 0}, + {"airband", "AMDemod", 8000, 48000, amSettings, 25000, nullptr, 0}, + {"ssb", "SSBDemod", 3000, 48000, "{\"volume\":2}", 3000, nullptr, 0}, + {"usb", "SSBDemod", 3000, 48000, "{\"volume\":2}", 3000, nullptr, 0}, + {"lsb", "SSBDemod", -3000, 48000, "{\"volume\":2}", 3000, nullptr, 0}, + {"dab", "DABDemod", 0, 2048000, "{}", 0, nullptr, 0}, + {"adsb", "ADSBDemod", 0, 2400000, "{}", 0, nullptr, 0}, + {"ais", "AISDemod", 0, 128000, "{}", 0, "AIS", 25000}, + {"dsc", "DSCDemod", 450, 48000, "{}", 0, nullptr, 0}, + // Digital voice: the DSD demodulator decides the standard from the baud rate, and its + // discriminator wants the maximum deviation of the standard, the readme's table: DMR 5.4, + // dPMR 2.7, D-Star 3.5, YSF 7.0, NXDN 2.7 kHz. dsd alone is the plugin's defaults, which + // are D-Star's, set explicitly so that a retuned demodulator gets them too. DMR carries + // two time slots, so both are switched on + {"dsd", "DSDDemod", 12500, 48000, "{\"fmDeviation\":3500,\"baudRate\":4800}", 12500, nullptr, 0}, + {"dmr", "DSDDemod", 12500, 48000, "{\"fmDeviation\":5400,\"baudRate\":4800,\"slot1On\":1,\"slot2On\":1}", 12500, nullptr, 0}, + {"dpmr", "DSDDemod", 6250, 48000, "{\"fmDeviation\":2700,\"baudRate\":2400}", 6250, nullptr, 0}, + {"dstar", "DSDDemod", 12500, 48000, "{\"fmDeviation\":3500,\"baudRate\":4800}", 12500, nullptr, 0}, + {"ysf", "DSDDemod", 12500, 48000, "{\"fmDeviation\":7000,\"baudRate\":4800}", 12500, nullptr, 0}, + {"nxdn", "DSDDemod", 12500, 48000, "{\"fmDeviation\":2700,\"baudRate\":4800}", 12500, nullptr, 0}, + {"nxdn24", "DSDDemod", 6250, 48000, "{\"fmDeviation\":2700,\"baudRate\":2400}", 6250, nullptr, 0}, + {"pager", "PagerDemod", 20000, 48000, "{}", 12500, nullptr, 0}, + {"pocsag", "PagerDemod", 20000, 48000, "{}", 12500, nullptr, 0}, + {"sonde", "RadiosondeDemod", 9600, 48000, "{}", 10000, "Radiosonde", 0}, + {"radiosonde", "RadiosondeDemod", 9600, 48000, "{}", 10000, "Radiosonde", 0}, + // AX.25 packet at 1200 baud AFSK. APRS is the same signal on a fixed regional frequency, + // with the APRS feature to plot the stations + {"packet", "PacketDemod", 12500, 48000, "{}", 0, nullptr, 0}, + {"aprs", "PacketDemod", 12500, 48000, "{}", 0, "APRS", 0}, +}; + +const char *const listenModeList = "bfm, wfm, nfm, am, ssb, usb, lsb, dab, adsb, ais, dsc, dsd, dmr, dpmr, dstar, ysf, nxdn, pager, sonde, packet, aprs"; + +// The feature a demodulator of this type feeds, by the modes that add one; null for none +const char *featureForChannelType(const QString& channelType) +{ + for (const ListenMode& mode : listenModes) + { + if (mode.m_feature && (channelType == QLatin1String(mode.m_channelType))) { + return mode.m_feature; + } + } + + return nullptr; +} + +// What listen and scan say about the features a reclaim took away +QStringList featureNotes(const QStringList& reclaimedFeatures) +{ + if (reclaimedFeatures.isEmpty()) { + return QStringList(); + } + + return QStringList(QString("Removed the %1 feature%2 an earlier listen added, as nothing feeds %3 now.") + .arg(reclaimedFeatures.join(" and ")).arg(reclaimedFeatures.size() == 1 ? "" : "s") + .arg(reclaimedFeatures.size() == 1 ? "it" : "them")); +} + +const ListenMode *findListenMode(const QString& alias) +{ + for (const ListenMode& mode : listenModes) + { + if (alias.compare(QLatin1String(mode.m_alias), Qt::CaseInsensitive) == 0) { + return &mode; + } + } + + return nullptr; +} + +// The device rate and decimation that give at least the wanted baseband. These are the rates +// an RTL-SDR runs reliably; DAB needs exactly 2.048 MS/s. +void rateFor(int minBaseband, int& devSampleRate, int& log2Decim) +{ + if (minBaseband <= 256000) { devSampleRate = 1024000; log2Decim = 2; } + else if (minBaseband <= 512000) { devSampleRate = 1024000; log2Decim = 1; } + else if (minBaseband <= 1024000) { devSampleRate = 1024000; log2Decim = 0; } + else if (minBaseband <= 2048000) { devSampleRate = 2048000; log2Decim = 0; } + else { devSampleRate = 2400000; log2Decim = 0; } +} + +// The baseband a channel type needs, from the table listen uses, so that there is one set of +// numbers rather than two that can disagree. 0 when the type is not in it. +int minimumBasebandFor(const QString& channelType) +{ + for (const ListenMode& mode : listenModes) + { + if (channelType.compare(QLatin1String(mode.m_channelType), Qt::CaseInsensitive) == 0) { + return mode.m_minBaseband; + } + } + + return 0; +} + +// Devices that are not radios attached to this machine, skipped when choosing one automatically +const QStringList virtualDeviceTypes = { + "TestSource", "FileInput", "SigMFFileInput", "LocalInput", "RemoteInput", "RemoteTCPInput", + "KiwiSDR", "AudioInput", "AaroniaRTSA", "AndroidSdrDriverInput" +}; + +// The type specific sub-object of a settings reply, e.g. the rtlSdrSettings of a device +QJsonObject settingsOf(const QJsonObject& reply) +{ + return reply[findSettingsKey(reply)].toObject(); +} + +// A signal level from a channel report, whatever the plugin calls it +bool signalLevel(const QJsonObject& report, double& db) +{ + for (const QString& key : report.keys()) + { + if (!key.endsWith("Report") || !report[key].isObject()) { + continue; + } + + QJsonObject sub = report[key].toObject(); + + for (const QString& k : sub.keys()) + { + if ((k.contains("PowerDB", Qt::CaseInsensitive) || (k == "rssi")) && sub[k].isDouble()) + { + db = sub[k].toDouble(); + return true; + } + } + } + + return false; +} + +} // namespace + +// A channel whose baseband is too narrow produces nothing, or silence, with no error anywhere: +// the demodulator simply never sees the signal. The rule is in this server's instructions, but +// it is read once at the start of a conversation and needed much later, so it is repeated here, +// where the numbers are known and the fix can be named. +QString MCPTools::basebandWarning(int deviceSetIndex, const QString& channelType) +{ + int needed = minimumBasebandFor(channelType); + + if (needed <= 0) { + return QString(); // nothing known about what this type needs + } + + QJsonObject settings; + + try + { + settings = settingsOf(getDeviceSettings(deviceSetIndex)); + } + catch (const MCPToolError&) + { + return QString(); // no device, or it cannot be read: not this call's problem to report + } + + // Only devices that express their rate this way can be checked. Saying nothing is better + // than guessing at a device whose keys are not these + if (!settings.contains("devSampleRate") || !settings.contains("log2Decim")) { + return QString(); + } + + int baseband = settings["devSampleRate"].toInt() >> settings["log2Decim"].toInt(); + + if (baseband >= needed) { + return QString(); + } + + int wantedRate = 0; + int wantedDecim = 0; + rateFor(needed, wantedRate, wantedDecim); + + return QString("%1 needs a baseband of at least %2 Hz, but device set %3 provides %4 Hz, so the channel " + "cannot work as it stands. Call set_device_settings with devSampleRate %5 and log2Decim %6.") + .arg(channelType).arg(needed).arg(deviceSetIndex).arg(baseband).arg(wantedRate).arg(wantedDecim); +} + +QStringList MCPTools::basebandWarnings(int deviceSetIndex) +{ + QStringList warnings; + QJsonObject deviceSet; + + try + { + deviceSet = getDeviceSet(deviceSetIndex); + } + catch (const MCPToolError&) + { + return warnings; + } + + QSet seen; + + for (const QJsonValue& value : deviceSet["channels"].toArray()) + { + QString channelType = value.toObject()["id"].toString(); + + if (channelType.isEmpty() || seen.contains(channelType)) { + continue; // several of a type would repeat the same sentence + } + + seen.insert(channelType); + QString warning = basebandWarning(deviceSetIndex, channelType); + + if (!warning.isEmpty()) { + warnings.append(warning); + } + } + + return warnings; +} + +QStringList MCPTools::channelTypeIds(int direction) +{ + SWGSDRangel::SWGInstanceChannelsResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->instanceChannels(direction, response, error), error, "List channel types"); + QStringList ids; + + for (const QJsonValue& v : toJson(response)["channels"].toArray()) { + ids.append(v.toObject()["id"].toString()); + } + + return ids; +} + +void MCPTools::relocateChannel(uint64_t channelUid, int& deviceSetIndex, int& channelIndex, const QString& what) +{ + if (!MCPCapture::locateChannel(channelUid, deviceSetIndex, channelIndex)) { + throw MCPToolError(QString("The %1 channel no longer exists: another request removed it, or its device set, " + "while this call was running").arg(what)); + } +} + +void MCPTools::trackIntentChannel(uint64_t channelUid) +{ + if (channelUid == 0) { + return; + } + + QMutexLocker locker(&m_intentMutex); + m_intentChannels.insert(channelUid); +} + +void MCPTools::untrackIntentChannel(uint64_t channelUid) +{ + QMutexLocker locker(&m_intentMutex); + m_intentChannels.remove(channelUid); +} + +QSet MCPTools::intentChannels() +{ + QMutexLocker locker(&m_intentMutex); + return m_intentChannels; +} + +// What a device set carries besides one channel, and which of it listen or scan put there. +// Read from the live device set rather than any earlier snapshot, as a reclaim in between +// changes both the indices and the answer +QList MCPTools::channelNotes(int deviceSetIndex, const QSet& except) +{ + const QSet intent = intentChannels(); + QList notes; + + for (const QJsonValue& v : getDeviceSet(deviceSetIndex)["channels"].toArray()) + { + QJsonObject channel = v.toObject(); + int index = channel["index"].toInt(); + const uint64_t uid = channelUidAt(deviceSetIndex, index); + + if ((uid != 0) && !except.contains(uid)) { + notes.append({uid, index, channel["id"].toString(), intent.contains(uid)}); + } + } + + return notes; +} + +QStringList MCPTools::reclaimIntentChannels(int deviceSetIndex, const QSet& keep) +{ + QStringList removed; + + // Each is deleted by identity, wherever it has been renumbered to by then, and highest + // index first so that the ids come out in the order the device set listed them + QList notes = channelNotes(deviceSetIndex); + + for (int i = notes.size() - 1; i >= 0; i--) + { + if (!notes[i].m_intent || keep.contains(notes[i].m_uid)) { + continue; + } + + try + { + deleteChannelObjectAndWait(notes[i].m_uid); + removed.prepend(notes[i].m_id); + } + catch (const MCPToolError&) {} + + // Tracked no longer either way: if it could not be deleted now it will not be later + untrackIntentChannel(notes[i].m_uid); + } + + return removed; +} + +// Retuning the demodulator a previous listen added is what a person would do, and spares the +// audio device and the GUI a close and reopen. Only when the intent channels of that type are +// exactly the count the mode uses (one, or two for a paired mode such as AIS), and no scan's +// FreqScanner is there to be driving them. The first is returned; a paired mode finds the +// other among the intent channels of the type +uint64_t MCPTools::reusableIntentChannel(int deviceSetIndex, const QString& channelType, int& channelIndex, int wanted) +{ + uint64_t candidate = 0; + int candidates = 0; + + for (const ChannelNote& note : channelNotes(deviceSetIndex)) + { + if (!note.m_intent) { + continue; + } + + if (note.m_id == "FreqScanner") { + return 0; + } + + if (note.m_id == channelType) + { + if (candidate == 0) + { + candidate = note.m_uid; + channelIndex = note.m_index; + } + + candidates++; + } + } + + return (candidates == wanted) ? candidate : 0; +} + +// A retune moves every channel on the device set, since each is an offset from the centre. A +// channel the user added is kept on the frequency it had when the new baseband holds it; an +// audio demodulator it cannot hold is removed, as all it could do is play noise; anything else +// is left, with a note, since a file sink or an analyser may be wanted regardless +MCPTools::RetuneOutcome MCPTools::retuneOtherChannels(int deviceSetIndex, double previousCentre, double centre, int baseband) +{ + RetuneOutcome outcome; + + if ((qint64) previousCentre == (qint64) centre) { + return outcome; + } + + static const QStringList audioDemods = { + "AMDemod", "BFMDemod", "DABDemod", "DATVDemod", "DSDDemod", "FreeDVDemod", "ILSDemod", "M17Demod", + "NFMDemod", "SSBDemod", "VORDemod", "VORDemodMC", "WFMDemod", "WDSPRx" + }; + + const QSet intent = intentChannels(); + QJsonObject set = getDeviceSet(deviceSetIndex); + + if (baseband <= 0) { + baseband = set["samplingDevice"].toObject()["bandwidth"].toInt(); + } + + struct Item { int m_index; QString m_id; uint64_t m_uid; qint64 m_offset; }; + QList items; + + for (const QJsonValue& v : set["channels"].toArray()) + { + QJsonObject channel = v.toObject(); + const int index = channel["index"].toInt(); + const uint64_t uid = channelUidAt(deviceSetIndex, index); + + if ((uid != 0) && !intent.contains(uid)) { + items.append({index, channel["id"].toString(), uid, (qint64) channel["deltaFrequency"].toDouble()}); + } + } + + // Highest index first, so that a removal does not renumber one still to be visited + for (int i = items.size() - 1; i >= 0; i--) + { + const Item& item = items[i]; + const qint64 wanted = (qint64) previousCentre + item.m_offset; // where it was listening + const qint64 offset = wanted - (qint64) centre; + const QString where = QString("%1 at %2 MHz").arg(item.m_id).arg(wanted / 1e6, 0, 'f', 3); + + // The offset key differs by type: most have inputFrequencyOffset, the Channel Analyzer + // frequency, ATV intFrequencyOffset, DATV centerFrequency; a sink or a scanner has none + // and is left alone. Read the live settings to find which, rather than guess + QString offsetKey; + + if ((baseband > 0) && (qAbs(offset) <= baseband * 0.45)) // a tenth kept clear at each edge + { + try + { + QJsonObject current = settingsOf(getChannelSettings(deviceSetIndex, item.m_index)); + + for (const char *key : {"inputFrequencyOffset", "frequency", "intFrequencyOffset", "centerFrequency"}) + { + if (current.contains(key)) + { + offsetKey = key; + break; + } + } + } + catch (const MCPToolError&) {} + } + + if (!offsetKey.isEmpty()) + { + try + { + QJsonObject partial; + partial[offsetKey] = (double) offset; + patchChannelSettings(deviceSetIndex, item.m_index, partial); + outcome.m_kept.append(where); + } + catch (const MCPToolError&) + { + outcome.m_stranded.append(where); + } + } + else if ((baseband > 0) && audioDemods.contains(item.m_id)) + { + try + { + deleteChannelObjectAndWait(item.m_uid); + outcome.m_removed.append(where); + } + catch (const MCPToolError&) + { + outcome.m_stranded.append(where); + } + } + else + { + outcome.m_stranded.append(where); + } + } + + return outcome; +} + +QStringList MCPTools::intentNotes(int deviceSetIndex, const QSet& added, const QStringList& reclaimed, + bool reused, double previousCentre, double centre, const RetuneOutcome& outcome) +{ + QStringList notes; + + if (!reclaimed.isEmpty()) + { + notes.append(QString("Removed %1 channel%2 (%3) that earlier listen or scan calls added to device set %4; pass replace false to keep them.") + .arg(reclaimed.size()).arg(reclaimed.size() == 1 ? "" : "s").arg(reclaimed.join(", ")).arg(deviceSetIndex)); + } + + // Read from the live device set rather than the snapshot pickReceiver made, which still + // lists whatever the reclaim has since removed + QStringList leftovers; + QStringList others; + + for (const ChannelNote& note : channelNotes(deviceSetIndex, added)) { + (note.m_intent ? leftovers : others).append(note.m_id); + } + + // Only possible with replace false, and then it is the caller's own trail + if (!leftovers.isEmpty()) + { + notes.append(QString("Device set %1 still has %2 channel%3 (%4) from earlier listen or scan calls, any audio ones still playing; cleanup removes them.") + .arg(deviceSetIndex).arg(leftovers.size()).arg(leftovers.size() == 1 ? "" : "s").arg(leftovers.join(", "))); + } + + // What the retune did to the channels the user added, and how to put back what it took + if (reused && ((qint64) previousCentre != (qint64) centre) + && !(outcome.m_kept.isEmpty() && outcome.m_removed.isEmpty() && outcome.m_stranded.isEmpty())) + { + QString note = QString("Retuned device set %1 from %2 to %3 MHz.").arg(deviceSetIndex) + .arg(previousCentre / 1e6, 0, 'f', 3).arg(centre / 1e6, 0, 'f', 3); + + if (!outcome.m_kept.isEmpty()) { + note += QString(" Kept %1 other channel%2 on frequency by moving the offset: %3.") + .arg(outcome.m_kept.size()).arg(outcome.m_kept.size() == 1 ? "" : "s").arg(outcome.m_kept.join(", ")); + } + + if (!outcome.m_removed.isEmpty()) { + note += QString(" Removed %1 audio demodulator%2 the new baseband could not hold, which would only have played noise: %3. " + "They were not added by listen or scan; add_channel puts one back.") + .arg(outcome.m_removed.size()).arg(outcome.m_removed.size() == 1 ? "" : "s").arg(outcome.m_removed.join(", ")); + } + + if (!outcome.m_stranded.isEmpty()) { + note += QString(" Left %1 other channel%2 that the new baseband does not hold, not being audio: %3. " + "set_channel_settings inputFrequencyOffset retunes one, delete_channel removes it.") + .arg(outcome.m_stranded.size()).arg(outcome.m_stranded.size() == 1 ? "" : "s").arg(outcome.m_stranded.join(", ")); + } + + notes.append(note); + } + + (void) others; + return notes; +} + +QJsonObject MCPTools::channelReport(int deviceSetIndex, int channelIndex) +{ + SWGSDRangel::SWGChannelReport response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->devicesetChannelReportGet(deviceSetIndex, channelIndex, response, error), error, "Get channel report"); + return toJson(response); +} + +void MCPTools::postChannelAction(int deviceSetIndex, int channelIndex, const QJsonObject& actions) +{ + QJsonObject settings = getChannelSettings(deviceSetIndex, channelIndex); + QString channelType = settings["channelType"].toString(); + + if (!WebAPIUtils::m_channelTypeToActionsKey.contains(channelType)) { + throw MCPToolError(QString("Channel type %1 has no actions").arg(channelType)); + } + + QJsonObject json; + json["channelType"] = channelType; + json["direction"] = settings["direction"].toInt(0); + json[WebAPIUtils::m_channelTypeToActionsKey[channelType]] = actions; + QStringList keys; + extractKeys(actions, keys); + + SWGSDRangel::SWGChannelActions query; + query.init(); + query.fromJsonObject(json); + SWGSDRangel::SWGSuccessResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->devicesetChannelActionsPost(deviceSetIndex, channelIndex, keys, query, response, error), error, "Channel action"); +} + +// Finds or creates a receive device set holding a suitable device and sets its sample rate. +// An existing set holding the same device is reused rather than fought for the hardware; the +// caller tunes the centre frequency and is told what else that set carries. +// Takes away the device set listen or scan created when the call fails before it is done +// with it, so a retry does not build another beside a half made one. Cleared on success +class NewDeviceSetGuard +{ +public: + NewDeviceSetGuard(MCPTools *tools, int deviceSetIndex) : + m_tools(tools), + m_deviceSetIndex(deviceSetIndex), + m_identity(deviceSetIndex >= 0 ? tools->deviceSetIdentity(deviceSetIndex) : 0) + {} + ~NewDeviceSetGuard() + { + if (m_deviceSetIndex >= 0) { + m_tools->discardNewDeviceSet(m_deviceSetIndex, m_identity); + } + } + void keep() { m_deviceSetIndex = -1; } + +private: + MCPTools *m_tools; + int m_deviceSetIndex; + uint64_t m_identity; //!< Of the set as it was when this call made it +}; + +QJsonObject MCPTools::pickReceiver(const QJsonObject& args, int minBaseband, const QSet& doomed, bool profileGain) +{ + SWGSDRangel::SWGInstanceDevicesResponse devicesResponse; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->instanceDevices(0, devicesResponse, error), error, "List devices"); + QJsonArray devices = toJson(devicesResponse)["devices"].toArray(); + + // Which device: the one the caller named; else the first real radio that was actually + // enumerated, which is the one with a serial number - some plugins list a placeholder + // entry for hardware that is not attached, and it has none; else anything + QJsonObject chosen; + QJsonObject fallback; + QString wanted = argString(args, "device", false).trimmed(); + + for (const QJsonValue& v : devices) + { + QJsonObject d = v.toObject(); + + if (!wanted.isEmpty()) + { + if ((d["serial"].toString().compare(wanted, Qt::CaseInsensitive) == 0) + || (d["displayedName"].toString().compare(wanted, Qt::CaseInsensitive) == 0) + || (d["hwType"].toString().compare(wanted, Qt::CaseInsensitive) == 0)) + { + chosen = d; + break; + } + } + else if (!virtualDeviceTypes.contains(d["hwType"].toString())) + { + if (!d["serial"].toString().isEmpty()) { chosen = d; break; } + if (fallback.isEmpty()) { fallback = d; } + } + } + + if (chosen.isEmpty() && wanted.isEmpty()) { + chosen = fallback.isEmpty() && !devices.isEmpty() ? devices.first().toObject() : fallback; + } + + if (chosen.isEmpty()) { + throw MCPToolError(QString("No receive device matches %1. list_available_devices shows what there is.").arg(wanted.isEmpty() ? "anything" : wanted)); + } + + QString hwType = chosen["hwType"].toString(); + QString serial = chosen["serial"].toString(); + + // Reuse a device set that already holds this device + int deviceSetIndex = -1; + QJsonArray otherChannels; + QJsonArray deviceSets = getInstanceSummary()["devicesetlist"].toObject()["deviceSets"].toArray(); + + for (const QJsonValue& v : deviceSets) + { + QJsonObject ds = v.toObject(); + QJsonObject sd = ds["samplingDevice"].toObject(); + + if (sd["direction"].toInt() != 0) { + continue; + } + + bool same = serial.isEmpty() ? (sd["hwType"].toString() == hwType) : (sd["serial"].toString() == serial); + + if (same) + { + deviceSetIndex = sd["index"].toInt(); + + // Channels the caller is about to remove are not ones the set has to go on + // serving, so they neither hold the baseband width up nor count as carried + for (const QJsonValue& c : ds["channels"].toArray()) + { + QJsonObject channel = c.toObject(); + + if (!doomed.contains(channelUidAt(deviceSetIndex, channel["index"].toInt()))) { + otherChannels.append(channel["id"].toString()); + } + } + + break; + } + } + + bool reused = deviceSetIndex >= 0; + + if (!reused) { + deviceSetIndex = addDeviceSetAndWait(0); + } + + // Until the caller has it, a set made here that cannot be finished is this function's to + // take away again + NewDeviceSetGuard newDeviceSet(this, reused ? -1 : deviceSetIndex); + + if (!reused) + { + QJsonObject select; + select["hwType"] = hwType; + + if (!serial.isEmpty()) { + select["serial"] = serial; + } + + selectDevice(deviceSetIndex, select); + } + + QJsonObject before = settingsOf(getDeviceSettings(deviceSetIndex)); + + // Only the devices whose rate keys and supported rates are known are set; others keep + // their configured rate and the caller is told to check it + QString rateKey; + + if (hwType == "RTLSDR") { + rateKey = "devSampleRate"; + } else if (hwType == "TestSource") { + rateKey = "sampleRate"; + } + + // A reused device set is already feeding its other channels the width it has. Widening it for + // the new channel leaves them working, narrowing it to what only the new one needs takes their + // signal away, so the width already configured is a floor rather than something to overwrite + int existingBaseband = 0; + + if (reused && !otherChannels.isEmpty() && !rateKey.isEmpty()) + { + int rate = before[rateKey].toInt(); + + if (rate > 0) { + existingBaseband = rate >> before["log2Decim"].toInt(); + } + } + + int devSampleRate = 0; + int log2Decim = 0; + rateFor(qMax(minBaseband, existingBaseband), devSampleRate, log2Decim); + QJsonObject partial; + QString rateNote; + int baseband = 0; + + if (!rateKey.isEmpty()) + { + baseband = devSampleRate >> log2Decim; + + if (baseband < existingBaseband) + { + // Wider than rateFor is able to ask for, so leave the rate alone altogether + baseband = existingBaseband; + rateNote = QString("Device set %1 was left at %2 S/s of baseband, which its other channels need.") + .arg(deviceSetIndex).arg(existingBaseband); + } + else + { + partial[rateKey] = devSampleRate; + partial["log2Decim"] = log2Decim; + + if (existingBaseband > minBaseband) { + rateNote = QString("Device set %1 was kept at %2 S/s of baseband rather than the %3 this channel needs, for its other channels.") + .arg(deviceSetIndex).arg(baseband).arg(minBaseband); + } + } + } + + // Only a device set this call created gets the receiver profile: one that was found is the + // user's, and its gain stays whatever they set + if (!reused && (hwType == "RTLSDR")) + { + partial["dcBlock"] = 1; + partial["iqImbalance"] = 1; + + // A fixed 40 dB when the caller is not about to measure one: the tuner's own AGC is + // unreliable on weak signals, and the default gain left the airband 35 dB down on what + // a hand-set receiver saw + if (profileGain) + { + partial["agc"] = 0; + partial["gain"] = 402; + rateNote = (rateNote.isEmpty() ? QString() : rateNote + " ") + + QString("Device set %1 is new, so its RTL-SDR was set to 40 dB gain with AGC off; set_device_settings changes it.") + .arg(deviceSetIndex); + } + } + + if (!partial.isEmpty()) { + patchDeviceSettings(deviceSetIndex, partial); + } + + QJsonObject result; + result["deviceSetIndex"] = deviceSetIndex; + result["hwType"] = hwType; + result["device"] = chosen["displayedName"].toString(); + result["reused"] = reused; + result["previousCentre"] = before["centerFrequency"].toDouble(); + result["otherChannels"] = otherChannels; + result["baseband"] = baseband; + result["rateNote"] = rateNote; + newDeviceSet.keep(); + return result; +} + +// The tune_gain tool, also run by listen and scan when they set up a receiver on a new +// device set or move one to another band +QJsonObject MCPTools::tuneGain(const QJsonObject& args) +{ + int deviceSetIndex = argInt(args, "deviceSetIndex"); + QJsonObject reply = getDeviceSettings(deviceSetIndex); + const QString hwType = reply["deviceHwType"].toString(); + QJsonObject settings = settingsOf(reply); + + if (deviceState(deviceSetIndex, 0, -1)["state"].toString() != "running") { + throw MCPToolError("The device is not running, so there is nothing to measure. start_device first."); + } + + // What this knows about each device's gain: the key, its manual AGC setting, and the + // values to try. Where a device has several gain stages the one before the mixer is + // tuned, as that is where overload happens; the rest keep their settings + struct Knob { QString key; QString agcKey; int agcOff; QList values; QString unit; QString note; }; + Knob knob; + const bool custom = hasArg(args, "gainKey"); + + if (custom) + { + knob.key = argString(args, "gainKey"); + knob.agcKey = argString(args, "agcKey", false); + knob.agcOff = 0; + knob.unit = "the key's own units"; + + for (const QJsonValue& v : args["values"].toArray()) { + knob.values.append(v.toDouble()); + } + + if (knob.values.size() < 2) { + throw MCPToolError("Give at least two values to try with gainKey"); + } + } + else if (hwType == "RTLSDR") + { + // The tuner takes only the values it lists, in tenths of a decibel + knob = {"gain", "agc", 0, {}, "tenths of a dB", "The tuner's AGC is off, as it must be for the gain to hold"}; + SWGSDRangel::SWGDeviceReport report; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->devicesetDeviceReportGet(deviceSetIndex, report, error), error, "Get device report"); + QJsonObject json = toJson(report); + + for (const QString& key : json.keys()) + { + for (const QJsonValue& g : json[key].toObject()["gains"].toArray()) { + knob.values.append(g.toObject()["gainCB"].toDouble()); + } + } + + if (knob.values.isEmpty()) { + throw MCPToolError("The RTL-SDR reported no supported gain values; is the device open?"); + } + } + else if (hwType == "HackRF") { + knob = {"lnaGain", "", 0, {0, 8, 16, 24, 32, 40}, "dB", "Only the LNA is stepped; vgaGain is left as it is"}; + } + else if (hwType == "Airspy") { + knob = {"lnaGain", "lnaAGC", 0, {0, 2, 4, 6, 8, 10, 12, 14}, "steps", "Only the LNA is stepped; mixerGain and vgaGain are left as they are, with the LNA AGC off"}; + } + else if (hwType == "LimeSDR") { + knob = {"gain", "gainMode", 1, {0, 10, 20, 30, 40, 50, 60, 70}, "dB", "gainMode set to manual"}; + } + else if (hwType == "PlutoSDR") { + knob = {"gain", "gainMode", 0, {0, 10, 20, 30, 40, 50, 60, 70}, "dB", "gainMode set to manual"}; + } + else if (hwType == "USRP") { + knob = {"gain", "gainMode", 1, {0, 10, 20, 30, 40, 50, 60, 70}, "dB", "gainMode set to manual"}; + } + else + { + throw MCPToolError(QString("tune_gain does not know the gain settings of a %1. Read them with describe_settings and " + "give gainKey, values and, if it has one, agcKey.").arg(hwType)); + } + + std::sort(knob.values.begin(), knob.values.end()); + knob.values.erase(std::unique(knob.values.begin(), knob.values.end()), knob.values.end()); + + // Spread the steps over the range rather than trying every value a tuner offers + const int steps = qBound(3, argInt(args, "steps", false, 8), 16); + QList candidates; + + if (knob.values.size() <= steps) { + candidates = knob.values; + } + else + { + for (int i = 0; i < steps; i++) { + candidates.append(knob.values[(int) std::round(i * (knob.values.size() - 1) / (double) (steps - 1))]); + } + } + + const bool apply = argBool(args, "apply", true); + + // A key the device does not have would be patched away as unknown at every step, and the + // sweep would then measure the same gain six times and report a choice it never made + if (!settings.contains(knob.key)) { + throw MCPToolError(QString("%1 has no %2 setting; describe_settings shows its keys").arg(hwType).arg(knob.key)); + } + + if (!knob.agcKey.isEmpty() && !settings.contains(knob.agcKey)) { + throw MCPToolError(QString("%1 has no %2 setting; describe_settings shows its keys").arg(hwType).arg(knob.agcKey)); + } + + const double previous = settings[knob.key].toDouble(); + const double previousAgc = knob.agcKey.isEmpty() ? 0 : settings[knob.agcKey].toDouble(); + const qint64 frequency = (qint64) argDouble(args, "frequency", false, 0); + const qint64 bandwidth = (qint64) argDouble(args, "bandwidth", false, 200000); + + // One reading: the floor is the median over the baseband, the signal the strongest bin, + // in the window asked for or anywhere. Max reduction keeps a narrow carrier + auto measure = [&](double& floorDb, double& peakDb) + { + SWGSDRangel::SWGGLSpectrumData response; + SWGSDRangel::SWGErrorResponse error; + response.init(); + error.init(); + check(m_adapter->devicesetSpectrumDataGet(deviceSetIndex, 256, 0, 0, "max", response, error), error, "Get spectrum data"); + // Read from the object: the generated JSON serialiser drops a list of plain floats + const bool linear = response.getLinear() != 0; + QList powers; + + if (response.getPower()) + { + for (float v : *response.getPower()) { + powers.append(linear ? 10.0 * std::log10(std::max((double) v, 1e-20)) : (double) v); + } + } + + if (powers.isEmpty()) { + throw MCPToolError("The spectrum returned no data"); + } + + QList sorted = powers; + std::sort(sorted.begin(), sorted.end()); + floorDb = sorted[sorted.size() / 2]; + + if (frequency > 0) + { + // The data call clamps to the baseband, which would silently measure noise at + // its edge for a frequency outside it + const qint64 low = response.getCenterFrequency() - response.getBandwidth() / 2; + const qint64 high = response.getCenterFrequency() + response.getBandwidth() / 2; + + if ((frequency < low) || (frequency > high)) + { + throw MCPToolError(QString("%1 MHz is outside the baseband, which covers %2 to %3 MHz; tune the device so that it is inside, or leave frequency out") + .arg(frequency / 1e6, 0, 'f', 3).arg(low / 1e6, 0, 'f', 3).arg(high / 1e6, 0, 'f', 3)); + } + + SWGSDRangel::SWGGLSpectrumData window; + SWGSDRangel::SWGErrorResponse windowError; + window.init(); + windowError.init(); + check(m_adapter->devicesetSpectrumDataGet(deviceSetIndex, 32, frequency - bandwidth / 2, frequency + bandwidth / 2, "max", window, windowError), + windowError, "Get spectrum data"); + peakDb = -1e9; + + if (window.getPower()) + { + for (float v : *window.getPower()) { + peakDb = std::max(peakDb, linear ? 10.0 * std::log10(std::max((double) v, 1e-20)) : (double) v); + } + } + + if (peakDb < -1e8) { + throw MCPToolError("The spectrum has no bins at that frequency; it must be inside the baseband"); + } + } + else + { + peakDb = sorted.last(); + } + }; + + struct Row { double gain; double floorDb; double peakDb; double snrDb; }; + QList rows; + + auto setGain = [&](double gain, bool agcOff) + { + QJsonObject partial; + partial[knob.key] = gain; + + if (!knob.agcKey.isEmpty()) { + partial[knob.agcKey] = agcOff ? knob.agcOff : previousAgc; + } + + patchDeviceSettings(deviceSetIndex, partial); + }; + + try + { + for (double gain : candidates) + { + setGain(gain, true); + pause(700); // the tuner, the spectrum averaging and a stale FFT + double floorSum = 0.0; + double peakSum = 0.0; + const int samples = 3; + + for (int i = 0; i < samples; i++) + { + if (i > 0) { + pause(250); + } + + double floorDb, peakDb; + measure(floorDb, peakDb); + floorSum += floorDb; + peakSum += peakDb; + } + + rows.append({gain, floorSum / samples, peakSum / samples, (peakSum - floorSum) / samples}); + } + } + catch (const MCPToolError&) + { + setGain(previous, false); // as it was, AGC included + throw; + } + + auto toDb = [&](double gain) { return (knob.unit == "tenths of a dB") ? gain / 10.0 : gain; }; + + // Overload shows as the floor climbing faster than the gain did. The first step + // where it does bounds the usable range from above + QStringList notes; + int compressed = 0; + int overloadFrom = rows.size(); // index of the first row that is overloaded + + for (int i = 1; i < rows.size(); i++) + { + const double gainStep = toDb(rows[i].gain) - toDb(rows[i - 1].gain); + + if ((gainStep > 0) && (rows[i].floorDb - rows[i - 1].floorDb > gainStep + 3.0)) + { + compressed++; + overloadFrom = std::min(overloadFrom, i); + } + } + + if (compressed > 0) { + notes.append(QString("The noise floor rose faster than the gain over %1 step%2, which is the front end overloading; the higher gains are not usable here.") + .arg(compressed).arg(compressed == 1 ? "" : "s")); + } + + // Best SNR, then the lowest gain within a decibel of it + double best = -1e9; + for (const Row& r : rows) { best = std::max(best, r.snrDb); } + const Row *chosen = nullptr; + QString judgedBy = frequency > 0 ? QString("the signal at %1 MHz").arg(frequency / 1e6, 0, 'f', 3) : QString("the strongest signal in the baseband"); + + if (best >= 6.0) + { + for (const Row& r : rows) { if ((r.snrDb >= best - 1.0) && !chosen) { chosen = &r; } } + } + else + { + // Nothing stood clear of the floor, so the floor itself has to decide: at low gain + // it is the converter's own noise and does not move; as gain rises the antenna's + // noise comes through and lifts it, which is when weak signals become receivable; + // and past overload it lifts faster than the gain. Take the lowest gain that puts + // the floor 8 dB above the converter's, which is the antenna's noise dominating + // by the usual 10 dB rule with a little allowance for the steps being coarse, or + // the last gain before overload if none does + double adcFloor = 1e9; + for (const Row& r : rows) { adcFloor = std::min(adcFloor, r.floorDb); } + const int lastUsable = std::max(0, overloadFrom - 1); + static const double antennaDominates = 8.0; + + for (int i = 0; (i <= lastUsable) && !chosen; i++) + { + if (rows[i].floorDb >= adcFloor + antennaDominates) { + chosen = &rows[i]; + } + } + + if (!chosen) { + chosen = &rows[lastUsable]; + } + + judgedBy = "the noise floor alone, as no signal stood clear of it"; + notes.append(QString("No signal stood more than 6 dB above the floor, so the gain is set from the floor instead: %1.") + .arg((rows[lastUsable].floorDb < adcFloor + antennaDominates) + ? "the floor never rose 8 dB above the converter's own noise before overload, so the last gain before overload is taken; check the antenna if that seems low" + : "the lowest gain at which the antenna's noise, not the converter's, sets the floor")); + } + + if (chosen == &rows.last()) { + notes.append("The best was the highest gain tried: the signal is weak or the site quiet, and more gain would not overload yet."); + } else if (chosen == &rows.first()) { + notes.append("The best was the lowest gain tried: a strong-signal site. Consider an attenuator if the floor still rises with the lowest gain."); + } + + bool autoscaled = false; + + if (apply) + { + setGain(chosen->gain, true); + + // The spectrum was scaled for the gain it had, and a change of tens of decibels + // leaves the trace off the top or along the bottom of the display. Once the new gain + // has reached the trace, the range is set from it, as the GUI's autoscale button does + if (argBool(args, "autoscale", true)) + { + try + { + pause(700); + autoscaleSpectrum(deviceSetIndex); + autoscaled = true; + } + catch (const MCPToolError& e) + { + notes.append(QString("The spectrum could not be autoscaled: %1").arg(e.message)); + } + } + } + else + { + setGain(previous, false); + notes.append("Not applied: the gain is back as it was."); + } + + if (!knob.note.isEmpty()) { + notes.append(knob.note + "."); + } + + QJsonObject result; + result["deviceSetIndex"] = deviceSetIndex; + result["hwType"] = hwType; + result["autoscaled"] = autoscaled; + result["gainKey"] = knob.key; + result["unit"] = knob.unit; + result["previous"] = previous; + result["chosen"] = chosen->gain; + result["applied"] = apply; + result["bestSnrDb"] = chosen->snrDb; + result["judgedBy"] = judgedBy; + QJsonArray table; + + for (const Row& r : rows) + { + QJsonObject o; + o["gain"] = r.gain; + o["floorDb"] = std::round(r.floorDb * 10) / 10; + o["signalDb"] = std::round(r.peakDb * 10) / 10; + o["snrDb"] = std::round(r.snrDb * 10) / 10; + table.append(o); + } + + result["table"] = table; + + if (!notes.isEmpty()) { + result["note"] = notes.join(" "); + } + + return result; +} + +// A mode whose output is only useful through a feature, such as AIS to the AIS feature's ship +// list and the map, gets that feature added with the demodulator. One that is there already is +// left alone, whatever it is set to +int MCPTools::ensureFeature(const QString& featureType, int& featureIndex) +{ + for (const QJsonValue& v : getInstanceSummary()["featureset"].toObject()["features"].toArray()) + { + QJsonObject f = v.toObject(); + + if (f["id"].toString() == featureType) + { + featureIndex = f["index"].toInt(); + return 0; + } + } + + featureIndex = addFeatureAndWait(featureType); + trackIntentFeature(featureUidAt(featureIndex)); + return 1; +} + +void MCPTools::trackIntentFeature(uint64_t featureUid) +{ + if (featureUid == 0) { + return; + } + + QMutexLocker locker(&m_intentMutex); + m_intentFeatures.insert(featureUid); +} + +// A feature listen added goes with the demodulators that fed it: once the last of those is +// reclaimed, on whichever device set, it would only show stale data. One the next mode +// needs, or that a demodulator anywhere still feeds, stays: the user may have added their own +// decoder since and be reading the feature through it +QStringList MCPTools::reclaimIntentFeatures(const QString& keepType) +{ + QSet tracked; + { + QMutexLocker locker(&m_intentMutex); + tracked = m_intentFeatures; + } + + if (tracked.isEmpty()) { + return QStringList(); + } + + // The feature types the remaining channels feed, whoever added them + QSet needed; + + if (!keepType.isEmpty()) { + needed.insert(keepType); + } + + for (int deviceSetIndex = 0; deviceSetIndex < deviceSetCount(); deviceSetIndex++) + { + for (const ChannelNote& note : channelNotes(deviceSetIndex)) + { + const char *feature = featureForChannelType(note.m_id); + + if (feature) { + needed.insert(QString(feature)); + } + } + } + + QStringList removed; + const std::vector& featureSets = MainCore::instance()->getFeatureeSets(); + + if (featureSets.empty()) { + return removed; + } + + // Collected first: deleting renumbers the rest, and by UID, as each deletion waits + QList> doomed; + + for (int i = 0; i < featureSets[0]->getNumberOfFeatures(); i++) + { + const Feature *feature = featureSets[0]->getFeatureAt(i); + + if (feature && tracked.contains(feature->getUID()) && !needed.contains(feature->getIdentifier())) { + doomed.append(qMakePair(feature->getUID(), feature->getIdentifier())); + } + } + + for (const auto& feature : doomed) + { + try + { + deleteFeatureObjectAndWait(feature.first); + removed.append(feature.second); + } + catch (const MCPToolError&) {} + } + + // Tracked no longer: those removed, and any the user had already deleted + QMutexLocker locker(&m_intentMutex); + + for (uint64_t uid : tracked) + { + bool present = false; + + for (int i = 0; i < featureSets[0]->getNumberOfFeatures(); i++) + { + const Feature *feature = featureSets[0]->getFeatureAt(i); + + if (feature && (feature->getUID() == uid)) + { + present = true; + break; + } + } + + if (!present) { + m_intentFeatures.remove(uid); + } + } + + return removed; +} + +void MCPTools::deleteFeatureObjectAndWait(uint64_t featureUid) +{ + QMutexLocker deletionLock(&m_deletionMutex); + int featureIndex = -1; + const std::vector& featureSets = MainCore::instance()->getFeatureeSets(); + + if (!featureSets.empty() && (featureUid != 0)) + { + for (int i = 0; i < featureSets[0]->getNumberOfFeatures(); i++) + { + const Feature *feature = featureSets[0]->getFeatureAt(i); + + if (feature && (feature->getUID() == featureUid)) + { + featureIndex = i; + break; + } + } + } + + if (featureIndex < 0) { + return; // Already gone + } + + requireNotSelf(featureIndex, "deleted"); + SWGSDRangel::SWGSuccessResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->featuresetFeatureDelete(0, featureIndex, response, error), error, "Delete feature"); + + if (!waitFor([&]() { return !featureUids().contains(featureUid); })) { + throw MCPToolError(QString("Timed out waiting for feature %1 to be removed").arg(featureIndex)); + } +} + +void MCPTools::autoscaleSpectrum(int deviceSetIndex) +{ + QJsonObject actions; + actions["autoscale"] = 1; + QStringList keys; + extractKeys(actions, keys); + SWGSDRangel::SWGSpectrumActions query; + query.init(); + query.fromJsonObject(actions); + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->devicesetSpectrumActionsPost(deviceSetIndex, keys, query, error), error, "Autoscale spectrum"); +} + +// The history the spectrum tools read is the display's scroll buffer, which fills only while +// scrolling is on. Switched on here with a length that covers what was asked for at a +// typical refresh rate, and at least a couple of minutes; a longer length the user has set +// is left alone +QString MCPTools::ensureSpectrumHistory(int deviceSetIndex, double seconds) +{ + QJsonObject settings = getSpectrumSettings(deviceSetIndex); + const bool scrolling = settings["scrollBar"].toInt() != 0; + const int length = settings["scrollLength"].toInt(); + const int wanted = qBound(1200, (int) (seconds * 20.0), 4000); + + if (scrolling && (length >= wanted)) { + return QString(); + } + + QJsonObject partial; + partial["scrollBar"] = 1; + partial["scrollLength"] = qMax(length, wanted); + patchSpectrumSettings(deviceSetIndex, partial); + return scrolling + ? QString("The spectrum history was lengthened to %1 rows to cover %2 seconds.").arg(qMax(length, wanted)).arg(seconds) + : QString("Spectrum scrolling was switched on, as the history the spectrum keeps for it is what this reads; it starts now."); +} + +// The gain suits a band and an antenna, not a mode: a device set that was just created has +// whatever gain it came with, and one moved to another band has the gain of the last one. A +// move within a band, or a change of mode on the same frequency, needs no new measurement +bool MCPTools::gainWorthTuning(bool reused, double previousCentre, double centre) +{ + if (!reused) { + return true; + } + + return std::abs(centre - previousCentre) > 0.1 * std::max(centre, previousCentre); +} + +void MCPTools::registerIntentTools() +{ + static const QString deviceHint = "Optional: which device, by serial, displayed name or type (e.g. RTLSDR) as shown by " + "list_available_devices. Default: the first radio attached to this machine"; + + add("listen", + "Receive a frequency in one call: picks a device, creates or reuses its device set, sets the sample rate, adds the " + "demodulator with sensible settings, starts the device and reports the signal level. Audio plays on the default output. " + "Use the individual tools afterwards to adjust, e.g. set_channel_settings for squelch or volume. Modes whose output " + "goes to a feature add it too: ais adds the AIS feature, sonde the Radiosonde feature and aprs the APRS feature, whose " + "reports and map items carry what was decoded; a later listen or scan removes the feature again once nothing it added " + "feeds it. ais is received on two channels, so give 162000000 and it puts a demodulator on each of 161.975 and " + "162.025 MHz.", + schema({ + {"frequency", numProp("Frequency to receive in Hz, e.g. 97300000 for 97.3 MHz")}, + {"mode", strProp("bfm (broadcast FM with stereo and RDS), wfm, nfm, am or airband, ssb/usb, lsb, dab, adsb, ais, dsc, dsd/dmr, " + "dmr, dpmr, dstar, ysf, nxdn or nxdn24 (digital voice through the DSD demodulator with the deviation and baud rate of that standard), " + "pager (POCSAG), sonde (RS41 radiosondes), packet (AX.25), aprs (APRS with its feature), or any channel type id from list_channel_types. Default nfm")}, + {"device", strProp(deviceHint)}, + {"replace", prop("boolean", "Retune the demodulator a previous listen added to this device set when it is of the same type, and remove every other channel earlier listen and scan calls added there, so that exploring a band does not leave a trail of demodulators all playing audio and mis-tuned for the current centre frequency. Channels added any other way are kept on their frequency where the baseband still holds them; audio demodulators it cannot hold are removed, anything else is left and named. Default true")}, + {"tuneGain", prop("boolean", "Measure and set the receiver gain, as tune_gain does, when the device set is new or the retune is to another band (more than a tenth of the frequency away). Adds several seconds in those cases and none otherwise. false leaves the gain as it is. Default true")} + }, {"frequency"}), + [this](const QJsonObject& args) + { + qint64 frequency = (qint64) argDouble(args, "frequency"); + QString modeName = argString(args, "mode", false, "nfm").trimmed(); + const ListenMode *mode = findListenMode(modeName); + QString channelType; + int rfBandwidth = 0; + int minBaseband = 256000; + QJsonObject initial; + QString companionFeature; + int pairOffset = 0; + + if (mode) + { + channelType = mode->m_channelType; + rfBandwidth = mode->m_rfBandwidth; + minBaseband = mode->m_minBaseband; + initial = QJsonDocument::fromJson(mode->m_settings).object(); + companionFeature = mode->m_feature ? QString(mode->m_feature) : QString(); + pairOffset = mode->m_pairOffset; + } + else + { + for (const QString& id : channelTypeIds(0)) + { + if (id.compare(modeName, Qt::CaseInsensitive) == 0) { + channelType = id; + } + } + + if (channelType.isEmpty()) { + throw MCPToolError(QString("Unknown mode %1. Use one of %2, or a channel type from list_channel_types").arg(modeName).arg(listenModeList)); + } + } + + const bool replace = argBool(args, "replace", true); + const bool wantTuneGain = argBool(args, "tuneGain", true); + QJsonObject receiver = pickReceiver(args, minBaseband, replace ? intentChannels() : QSet(), !wantTuneGain); + int deviceSetIndex = receiver["deviceSetIndex"].toInt(); + + // A device set this call created and cannot finish is taken away again, or a retry + // would build another beside it + NewDeviceSetGuard newDeviceSet(this, receiver["reused"].toBool() ? -1 : deviceSetIndex); + int baseband = receiver["baseband"].toInt(); + + // Keep the channel off the device's DC spike when the baseband has room for it: far + // enough that the spike falls outside the channel, or not at all. A spike inside a + // wide FM channel is an interferer 25 kHz from the carrier, which is worse than one + // on the carrier itself + int offset = 0; + + if ((pairOffset == 0) && (rfBandwidth != 0) && (baseband > 0)) + { + const int clear = qAbs(rfBandwidth) / 2 + 25000; // spike 25 kHz beyond the channel edge + + if (baseband / 2 >= clear + qAbs(rfBandwidth) / 2) { + offset = -clear; + } + } + + // A paired mode, such as AIS on 161.975 and 162.025 MHz, centres the device on the + // frequency asked for and puts a demodulator either side of it + const qint64 centre = (pairOffset != 0) ? frequency : frequency - offset; + + if (pairOffset != 0) { + offset = -pairOffset; + } + + // A demodulator of the right type that a previous listen added is retuned rather + // than replaced; anything else the intent tools added goes as before + int channelIndex = -1; + uint64_t channel = replace ? reusableIntentChannel(deviceSetIndex, channelType, channelIndex, pairOffset != 0 ? 2 : 1) : 0; + const bool retuned = channel != 0; + + // A paired mode keeps its other demodulator through the reclaim as well + QSet kept; + + if (retuned) + { + kept.insert(channel); + + if (pairOffset != 0) + { + for (const ChannelNote& note : channelNotes(deviceSetIndex, {channel})) + { + if (note.m_intent && (note.m_id == channelType)) + { + kept.insert(note.m_uid); + break; + } + } + } + } + + const QStringList reclaimed = replace ? reclaimIntentChannels(deviceSetIndex, kept) : QStringList(); + const QStringList reclaimedFeatures = replace ? reclaimIntentFeatures(companionFeature) : QStringList(); + + // The device is retuned only once the reclaim is done: a scanner an earlier scan + // left running would otherwise step the device on again between the two, and the + // demodulator would be added against a centre the scanner chose + QJsonObject tune; + tune["centerFrequency"] = (double) centre; + patchDeviceSettings(deviceSetIndex, tune); + const RetuneOutcome outcome = receiver["reused"].toBool() + ? retuneOtherChannels(deviceSetIndex, receiver["previousCentre"].toDouble(), (double) centre, baseband) + : RetuneOutcome(); + + if (retuned) + { + // The reclaim may have renumbered it + relocateChannel(channel, deviceSetIndex, channelIndex, "demodulator"); + } + else + { + channelIndex = addChannelAndWait(deviceSetIndex, channelType); + channel = channelUidAt(deviceSetIndex, channelIndex); + trackIntentChannel(channel); + } + + initial["inputFrequencyOffset"] = offset; + + if (rfBandwidth != 0) { + initial["rfBandwidth"] = rfBandwidth; + } + + QJsonObject patched; + QString state; + + // Do not leave a half configured channel behind if setting it up fails. One that was + // there already stays, as the previous listen left it + try + { + patched = patchChannelSettings(deviceSetIndex, channelIndex, initial); + state = deviceState(deviceSetIndex, 0, 1)["state"].toString(); + } + catch (const MCPToolError&) + { + if (!retuned) + { + try { deleteChannelObjectAndWait(channel); } catch (const MCPToolError&) {} + untrackIntentChannel(channel); + } + + throw; + } + + QJsonObject result; + result["deviceSetIndex"] = deviceSetIndex; + result["channelIndex"] = channelIndex; + result["device"] = receiver["device"]; + result["frequency"] = (double) frequency; + result["mode"] = modeName; + result["channelType"] = channelType; + result["state"] = state; + QStringList notes; + + if (retuned) + { + result["retuned"] = true; + notes.append(QString("Retuned the %1 a previous listen added to device set %2 rather than adding another; its other settings are as they were.") + .arg(channelType).arg(deviceSetIndex)); + } + + // The second demodulator of a paired mode, on the other channel. A retuned first + // one may already have its partner from the previous listen; a fresh one needs it + uint64_t partner = 0; + + if (pairOffset != 0) + { + int partnerIndex = -1; + + for (const ChannelNote& note : channelNotes(deviceSetIndex, {channel})) + { + if (note.m_intent && (note.m_id == channelType)) + { + partnerIndex = note.m_index; + partner = note.m_uid; + break; + } + } + + if (partner == 0) + { + partnerIndex = addChannelAndWait(deviceSetIndex, channelType); + partner = channelUidAt(deviceSetIndex, partnerIndex); + trackIntentChannel(partner); + } + + QJsonObject partnerSettings = initial; + partnerSettings["inputFrequencyOffset"] = pairOffset; + + try + { + patchChannelSettings(deviceSetIndex, partnerIndex, partnerSettings); + } + catch (const MCPToolError& e) + { + notes.append(QString("The second %1 could not be configured: %2").arg(channelType).arg(e.message)); + } + + relocateChannel(partner, deviceSetIndex, partnerIndex, "second demodulator"); + relocateChannel(channel, deviceSetIndex, channelIndex, "demodulator"); + result["channelIndex"] = channelIndex; + result["secondChannelIndex"] = partnerIndex; + QJsonArray frequencies; + frequencies.append((double) (frequency - pairOffset)); + frequencies.append((double) (frequency + pairOffset)); + result["frequencies"] = frequencies; + notes.append(QString("%1 is received on two channels, so there are two %2: channel %3 on %4 MHz and channel %5 on %6 MHz, with the device centred between them.") + .arg(modeName.toUpper()).arg(channelType).arg(channelIndex).arg((frequency - pairOffset) / 1e6, 0, 'f', 3) + .arg(partnerIndex).arg((frequency + pairOffset) / 1e6, 0, 'f', 3)); + } + + // The feature the mode's output goes to, so that the decoded data has somewhere to be + // read from and shown + if (!companionFeature.isEmpty()) + { + try + { + int featureIndex = -1; + const int added = ensureFeature(companionFeature, featureIndex); + result["featureIndex"] = featureIndex; + result["featureType"] = companionFeature; + notes.append(added + ? QString("Added the %1 feature (F%2), which collects what the demodulator decodes; get_feature_report reads it, and it feeds the map.").arg(companionFeature).arg(featureIndex) + : QString("The %1 feature (F%2) is already there and collects what the demodulator decodes.").arg(companionFeature).arg(featureIndex)); + } + catch (const MCPToolError& e) + { + notes.append(QString("The %1 feature could not be added: %2").arg(companionFeature).arg(e.message)); + } + } + + if (state == "running") + { + // A new device set, or one moved to another band, has no gain to speak of yet + if (wantTuneGain && gainWorthTuning(receiver["reused"].toBool(), receiver["previousCentre"].toDouble(), (double) centre)) + { + QJsonObject gainArgs; + gainArgs["deviceSetIndex"] = deviceSetIndex; + gainArgs["frequency"] = (double) frequency; + gainArgs["bandwidth"] = (double) (rfBandwidth != 0 ? qAbs(rfBandwidth) : 2000000); + gainArgs["steps"] = 6; + + try + { + QJsonObject tuned = tuneGain(gainArgs); + QJsonObject gain; + gain["key"] = tuned["gainKey"]; + gain["value"] = tuned["chosen"]; + gain["unit"] = tuned["unit"]; + gain["snrDb"] = tuned["bestSnrDb"]; + result["gain"] = gain; + notes.append(QString("Gain measured and set to %1 (%2), judged by %3, as %4%5; tune_gain shows the table, and tuneGain false leaves the gain alone.") + .arg(tuned["chosen"].toDouble()).arg(tuned["unit"].toString()).arg(tuned["judgedBy"].toString()) + .arg(receiver["reused"].toBool() ? "the retune was to another band" : "the device set is new") + .arg(tuned["autoscaled"].toBool() ? ", and the spectrum autoscaled to suit it" : "")); + } + catch (const MCPToolError& e) + { + notes.append(QString("The gain was not measured: %1").arg(e.message)); + } + } + + pause(1500); + // The channel may have been renumbered while we waited + relocateChannel(channel, deviceSetIndex, channelIndex, "demodulator"); + result["deviceSetIndex"] = deviceSetIndex; + result["channelIndex"] = channelIndex; + + // The power measurement sits at the channel's floor until the demodulator has run + // for a moment, and a floor reading looks exactly like an empty band. Wait for a + // real one: reporting the floor has sent callers away from a signal that was + // decoding perfectly well. CalcDb::dbPower returns 10*log10(floor) while there is + // nothing to measure, which is -100 dB or below for every floor in use here + double db = 0.0; + bool measured = false; + bool noReport = false; + QElapsedTimer settling; + settling.start(); + + while (true) + { + QJsonObject report; + + // A demodulator with no report at all (APT, ATV) is not a failure of the + // receiver that was just built + try + { + report = channelReport(deviceSetIndex, channelIndex); + } + catch (const MCPToolError&) + { + noReport = true; + break; + } + + if (signalLevel(report, db)) + { + measured = true; + + if (db > -100.0) { + break; + } + } + + if (settling.elapsed() > 4000) { + break; + } + + pause(250); + } + + if (noReport) + { + notes.append(QString("%1 has no channel report, so there is no signal level to give; %2.") + .arg(channelType) + .arg(companionFeature.isEmpty() ? QString("get_spectrum_data shows whether there is a signal") + : QString("what it decodes appears in the %1 feature's report and in get_packets").arg(companionFeature))); + } + else if (measured) + { + result["signalDb"] = db; + + if (db <= -100.0) { + notes.append("signalDb is still at the measurement floor, which usually means the channel " + "has not settled rather than that the band is empty. Read get_channel_report again in " + "a few seconds before concluding nothing is there."); + } + } + } + else + { + notes.append("The device did not start. If another device set holds the same hardware, stop it first, or pass a different device."); + } + + if (baseband > 0) { + result["basebandSampleRate"] = baseband; + } else { + notes.append(QString("The sample rate of a %1 was left as configured; check it exceeds %2 S/s with get_device_settings.").arg(receiver["hwType"].toString()).arg(minBaseband)); + } + + if (!receiver["rateNote"].toString().isEmpty()) { + notes.append(receiver["rateNote"].toString()); + } + + notes.append(intentNotes(deviceSetIndex, partner ? QSet({channel, partner}) : QSet({channel}), + reclaimed, receiver["reused"].toBool(), + receiver["previousCentre"].toDouble(), (double) centre, outcome)); + notes.append(featureNotes(reclaimedFeatures)); + + if (patched.contains("warning")) { + notes.append(patched["warning"].toString()); + } + + if (!notes.isEmpty()) { + result["note"] = notes.join(" "); + } + + newDeviceSet.keep(); + return result; + }); + + QJsonObject frequencyList = prop("array", "Frequencies to scan in Hz. Alternatively give startFrequency, stopFrequency and stepFrequency"); + QJsonObject items; + items["type"] = "number"; + frequencyList["items"] = items; + + add("scan", + "Scan a set of frequencies for activity and listen to whichever is active, in one call: sets up a receiver, a demodulator " + "and a Frequency Scanner, starts scanning, watches for a while and reports what it found. active lists every frequency " + "above the threshold with its level, strongest first; that is the list to use for stations and other continuous " + "signals. heard lists where the scanner parked and for how long, which only tells intermittent signals apart, since " + "on a continuous carrier it parks on the first and stays. " + "The scanner keeps running afterwards; get_channel_report on the scanner channel shows its state (2 scanning, 3 receiving, " + "4 holding), channel_action {\"run\": 0} stops it. The demodulator and scanner it added stay on the device set until the " + "next listen or scan there replaces them, or cleanup removes them; they are not removed when this call returns. " + "Blocks for the watch period, so it is capped at 30 seconds.", + schema({ + {"frequencies", frequencyList}, + {"startFrequency", numProp("Start of a range in Hz, with stopFrequency and stepFrequency")}, + {"stopFrequency", numProp("End of the range in Hz, inclusive")}, + {"stepFrequency", numProp("Channel spacing in Hz. Optional: without it the spacing usual for the mode is used (bfm 100 kHz, am 25 kHz, " + "nfm/dsd/pager 12.5 kHz, sonde 10 kHz, ssb 3 kHz), which is the right choice unless the band is known to differ, " + "e.g. 8333 for airband 8.33 kHz channels in Europe. Broadcast FM stations sit on a 100 kHz raster everywhere; only " + "the Americas confine them to the odd tenths, so bfm/wfm ranges are scanned at 100 kHz whatever step is given")}, + {"mode", strProp("Demodulator, as for listen: bfm, wfm, nfm, am, ssb/usb/lsb, dsd, pager, sonde. Modes on fixed frequencies (adsb, ais, " + "dab, dsc) cannot be scanned for; listen to those directly. Default am")}, + {"threshold", numProp("Power in dB above which a frequency counts as active. Leave it out unless you have a reason: the scale " + "depends on the device and its gain, so by default the noise floor is measured first and the threshold set " + "12 dB above it. Both are reported, so a second scan can adjust")}, + {"seconds", bounded(numProp("How long to watch before replying, 3 to 30. Default 10"), 3, 30)}, + {"device", strProp(deviceHint)}, + {"replace", prop("boolean", "Remove every channel earlier listen and scan calls added to this device set first, as listen does. Channels added any other way are kept on their frequency where the baseband still holds them; audio demodulators it cannot hold are removed, anything else is left and named. Default true")}, + {"tuneGain", prop("boolean", "Measure and set the receiver gain first, as tune_gain does, when the device set is new or the retune is to another band. Adds several seconds in those cases and none otherwise. false leaves the gain as it is. Default true")} + }), + [this](const QJsonObject& args) + { + QList frequencies; + const bool fromRange = !hasArg(args, "frequencies"); + qint64 rangeStart = 0; + qint64 rangeStop = 0; + qint64 rangeStep = 0; // as given; zero to step by the mode's usual channel spacing + + if (fromRange) + { + rangeStart = (qint64) argDouble(args, "startFrequency"); + rangeStop = (qint64) argDouble(args, "stopFrequency"); + rangeStep = hasArg(args, "stepFrequency") ? (qint64) argDouble(args, "stepFrequency") : 0; + + if ((rangeStep < 0) || (rangeStop < rangeStart)) { + throw MCPToolError("stepFrequency must be positive and stopFrequency at least startFrequency"); + } + } + else + { + for (const QJsonValue& v : args["frequencies"].toArray()) { + frequencies.append((qint64) v.toDouble()); + } + + if (frequencies.isEmpty()) { + throw MCPToolError("Give frequencies, or startFrequency and stopFrequency"); + } + } + + QString modeName = argString(args, "mode", false, "am").trimmed(); + const ListenMode *mode = findListenMode(modeName); + + if (!mode) { + throw MCPToolError(QString("Unknown mode %1. Use one of %2").arg(modeName).arg(listenModeList)); + } + + // A mode on fixed frequencies has nothing to be found by stepping + if (mode->m_scanStep == 0) + { + throw MCPToolError(QString("%1 is received on fixed frequencies, so there is nothing to scan for: listen to them directly. " + "get_receiving_guide lists them (ADS-B 1090 MHz; AIS 161.975 and 162.025 MHz; DSC 2187.5 kHz, 8414.5 kHz, " + "16804.5 kHz and 156.525 MHz; DAB on the Band III blocks, one dab channel per block).").arg(mode->m_channelType)); + } + + // Without a threshold, measure the noise floor first and sit 12 dB above it: the + // level scale depends on the device and its gain, so no fixed number suits all + bool autoThreshold = !hasArg(args, "threshold"); + double threshold = autoThreshold ? -100.0 : argDouble(args, "threshold"); + int seconds = qBound(3, (int) argDouble(args, "seconds", false, 10.0), 30); + int channelBandwidth = qAbs(mode->m_rfBandwidth) > 0 ? qAbs(mode->m_rfBandwidth) : 8000; + + // Broadcast FM stations sit on a 100 kHz raster everywhere but the Americas, where + // they keep to the odd tenths. A 200 kHz step from 87.5 MHz, the usual assumption, + // lands beside every even-tenth station: with a channel this wide the station still + // shows up, 100 kHz off and weaker, and then nothing decodes. So a coarser step on + // a broadcast range is scanned at 100 kHz, which loses nothing where the odd tenths + // are the rule + const bool broadcast = (mode->m_channelType == "BFMDemod") || (mode->m_channelType == "WFMDemod"); + QString rasterNote; + + if (fromRange) + { + qint64 step = (rangeStep > 0) ? rangeStep : mode->m_scanStep; + + if (broadcast && (step > 100000)) + { + step = 100000; + rasterNote = QString("Scanned at 100 kHz rather than the %1 kHz step given: broadcast FM stations are on a 100 kHz raster " + "outside the Americas, and a coarser step lands beside them rather than on them.").arg(rangeStep / 1000.0, 0, 'g', 4); + } + else if (rangeStep > mode->m_scanStep) + { + rasterNote = QString("The %1 kHz step given is coarser than the %2 kHz channel spacing usual for %3, so channels between the steps were not seen.") + .arg(rangeStep / 1000.0, 0, 'g', 4).arg(mode->m_scanStep / 1000.0, 0, 'g', 4).arg(modeName); + } + else if (rangeStep == 0) + { + rasterNote = QString("Stepped by %1 kHz, the channel spacing usual for %2; give stepFrequency for another.") + .arg(step / 1000.0, 0, 'g', 4).arg(modeName); + } + + // Counted before it is built: a step given in kHz by mistake, 12 Hz for 12.5, + // would otherwise fill millions of entries before the limit was looked at + const qint64 count = (rangeStop - rangeStart) / step + 1; + + if (count > 2000) { + throw MCPToolError(QString("%1 frequencies is too many; use a coarser step or a narrower range (2000 at most)").arg(count)); + } + + for (qint64 f = rangeStart; f <= rangeStop; f += step) { + frequencies.append(f); + } + } + + if (frequencies.size() > 2000) { + throw MCPToolError(QString("%1 frequencies is too many; use a coarser step or a narrower range (2000 at most)").arg(frequencies.size())); + } + + std::sort(frequencies.begin(), frequencies.end()); + + // A wide baseband means fewer retunes per sweep + const bool replace = argBool(args, "replace", true); + const bool wantTuneGain = argBool(args, "tuneGain", true); + QJsonObject receiver = pickReceiver(args, 2400000, replace ? intentChannels() : QSet(), !wantTuneGain); + int deviceSetIndex = receiver["deviceSetIndex"].toInt(); + NewDeviceSetGuard newDeviceSet(this, receiver["reused"].toBool() ? -1 : deviceSetIndex); + + // The reclaim comes before the retune: a scanner an earlier scan left running would + // otherwise move the device again between the two + const QStringList reclaimed = replace ? reclaimIntentChannels(deviceSetIndex) : QStringList(); + const QStringList reclaimedFeatures = replace ? reclaimIntentFeatures() : QStringList(); + QJsonObject tune; + tune["centerFrequency"] = (double) ((frequencies.first() + frequencies.last()) / 2); + patchDeviceSettings(deviceSetIndex, tune); + const RetuneOutcome outcome = receiver["reused"].toBool() + ? retuneOtherChannels(deviceSetIndex, receiver["previousCentre"].toDouble(), tune["centerFrequency"].toDouble(), receiver["baseband"].toInt()) + : RetuneOutcome(); + + int demod = addChannelAndWait(deviceSetIndex, mode->m_channelType); + const uint64_t demodChannel = channelUidAt(deviceSetIndex, demod); + trackIntentChannel(demodChannel); + int scanner = -1; + uint64_t scannerChannel = 0; + + // Anything that fails from here on removes both channels rather than leaving a + // half built scanner running on the user's radio + auto discard = [&]() + { + if (scannerChannel != 0) + { + try { deleteChannelObjectAndWait(scannerChannel); } catch (const MCPToolError&) {} + untrackIntentChannel(scannerChannel); + } + + try { deleteChannelObjectAndWait(demodChannel); } catch (const MCPToolError&) {} + untrackIntentChannel(demodChannel); + }; + + try + { + QJsonObject initial = QJsonDocument::fromJson(mode->m_settings).object(); + initial["inputFrequencyOffset"] = 0; + + if (mode->m_rfBandwidth != 0) { + initial["rfBandwidth"] = mode->m_rfBandwidth; + } + + patchChannelSettings(deviceSetIndex, demod, initial); + scanner = addChannelAndWait(deviceSetIndex, "FreqScanner"); + scannerChannel = channelUidAt(deviceSetIndex, scanner); + trackIntentChannel(scannerChannel); + } + catch (const MCPToolError&) + { + discard(); + throw; + } + + // Everything up to the scanner running with its threshold is set up, and a failure + // anywhere in it, the device not starting, the scanner refusing its settings or + // its run action, or measuring nothing, removes both channels the same way + QString gainNote; + double measuredFloor = 0.0; + bool haveFloor = false; + + try + { + QString state = deviceState(deviceSetIndex, 0, 1)["state"].toString(); + + if (state != "running") { + throw MCPToolError(QString("The device did not start (state %1), so the demodulator and scanner were removed again.").arg(state)); + } + + // Before the scanner measures anything: the gain sets the floor it measures against + if (wantTuneGain && gainWorthTuning(receiver["reused"].toBool(), receiver["previousCentre"].toDouble(), tune["centerFrequency"].toDouble())) + { + QJsonObject gainArgs; + gainArgs["deviceSetIndex"] = deviceSetIndex; + gainArgs["steps"] = 6; + + try + { + QJsonObject tuned = tuneGain(gainArgs); + gainNote = QString("Gain measured and set to %1 (%2) first, as %3%4; tuneGain false leaves it alone.") + .arg(tuned["chosen"].toDouble()).arg(tuned["unit"].toString()) + .arg(receiver["reused"].toBool() ? "the retune was to another band" : "the device set is new") + .arg(tuned["autoscaled"].toBool() ? ", and the spectrum autoscaled to suit it" : ""); + } + catch (const MCPToolError& e) + { + gainNote = QString("The gain was not measured: %1").arg(e.message); + } + } + + // The scanner's baseband only takes settings while it is running, so configure it + // after the device has started + pause(1500); + relocateChannel(demodChannel, deviceSetIndex, demod, "demodulator"); + relocateChannel(scannerChannel, deviceSetIndex, scanner, "scanner"); + QJsonArray list; + + for (qint64 f : frequencies) + { + QJsonObject entry; + entry["frequency"] = (double) f; + entry["enabled"] = 1; + list.append(entry); + } + + QJsonObject scannerSettings; + scannerSettings["channel"] = QString("R%1:%2").arg(deviceSetIndex).arg(demod); + scannerSettings["channelBandwidth"] = channelBandwidth; + scannerSettings["channelFrequencyOffset"] = 25000; + scannerSettings["threshold"] = threshold; + scannerSettings["scanTime"] = 0.1; + scannerSettings["tuneTime"] = 250; + scannerSettings["retransmitTime"] = 2.5; + scannerSettings["priority"] = 0; + scannerSettings["measurement"] = 0; + scannerSettings["mode"] = autoThreshold ? 2 : 1; // scan only while measuring, else continuous + scannerSettings["frequencies"] = list; + patchChannelSettings(deviceSetIndex, scanner, scannerSettings); + QJsonObject run; + run["run"] = 1; + postChannelAction(deviceSetIndex, scanner, run); + + if (autoThreshold) + { + // The power scale depends on the device and its gain, so the only threshold that + // is right everywhere is one measured here: the median over the frequencies is + // the floor, as most of any band is empty. Wait for the first sweep to have + // measured every frequency rather than guess after a fixed time; a long list + // at a low sample rate takes a while + QList powers; + + for (int attempt = 0; (attempt < 30) && (powers.size() < frequencies.size()); attempt++) + { + pause(500); + relocateChannel(scannerChannel, deviceSetIndex, scanner, "scanner"); + powers.clear(); + + for (const QJsonValue& v : channelReport(deviceSetIndex, scanner)["FreqScannerReport"].toObject()["channelState"].toArray()) + { + QJsonObject s = v.toObject(); + + if (s.contains("power")) { + powers.append(s["power"].toDouble()); + } + } + } + + if (powers.isEmpty()) { + throw MCPToolError("The scanner measured nothing in 15 seconds, so no threshold could be set. " + "Check the device is running and producing samples, or give threshold explicitly."); + } + + std::sort(powers.begin(), powers.end()); + measuredFloor = powers[powers.size() / 2]; + haveFloor = true; + threshold = measuredFloor + 12.0; + + // Changing the mode restarts the scan with the new threshold + QJsonObject arm; + arm["threshold"] = threshold; + arm["mode"] = 1; + patchChannelSettings(deviceSetIndex, scanner, arm); + } + } + catch (const MCPToolError&) + { + discard(); + throw; + } + + // Watch: where it parks, and how strong each channel got + QMap heard; + QMap strongest; + + for (int i = 0; i < seconds; i++) + { + pause(1000); + relocateChannel(scannerChannel, deviceSetIndex, scanner, "scanner"); + relocateChannel(demodChannel, deviceSetIndex, demod, "demodulator"); + QJsonObject report = channelReport(deviceSetIndex, scanner)["FreqScannerReport"].toObject(); + int scanState = report["scanState"].toInt(); + + for (const QJsonValue& v : report["channelState"].toArray()) + { + QJsonObject s = v.toObject(); + qint64 f = (qint64) s["frequency"].toDouble(); + strongest[f] = qMax(strongest.value(f, -999.0), s["power"].toDouble()); + } + + if ((scanState == 3) || (scanState == 4)) + { + // One snapshot for both halves of the sum: read separately, a retune + // between them would pair a new centre with an old offset + QJsonObject set = getDeviceSet(deviceSetIndex); + qint64 centre = (qint64) set["samplingDevice"].toObject()["centerFrequency"].toDouble(); + + for (const QJsonValue& v : set["channels"].toArray()) + { + QJsonObject ch = v.toObject(); + + if (ch["index"].toInt() == demod) { + heard[centre + (qint64) ch["deltaFrequency"].toDouble()] += 1; + } + } + } + } + + QJsonObject result; + result["deviceSetIndex"] = deviceSetIndex; + result["demodChannelIndex"] = demod; + result["scannerChannelIndex"] = scanner; + result["device"] = receiver["device"]; + result["frequencies"] = frequencies.size(); + result["threshold"] = threshold; + result["secondsWatched"] = seconds; + + // A channel this wide takes in a station on the neighbouring raster steps as well, + // weaker and off frequency, so of the neighbours within a channel of each other + // only the strongest is a station; the rest are its skirts + auto isLocalPeak = [&](qint64 f) + { + const double power = strongest.value(f, -999.0); + + for (auto it = strongest.lowerBound(f - channelBandwidth); (it != strongest.end()) && (it.key() <= f + channelBandwidth); ++it) + { + if ((it.key() != f) && ((it.value() > power) || ((it.value() == power) && (it.key() < f)))) { + return false; + } + } + + return true; + }; + + QList> byTime; + for (auto it = heard.begin(); it != heard.end(); ++it) { if (isLocalPeak(it.key())) { byTime.append(qMakePair(it.value(), it.key())); } } + std::sort(byTime.begin(), byTime.end(), [](const QPair& a, const QPair& b) { return a.first > b.first; }); + QJsonArray heardArray; + + for (const auto& p : byTime) + { + QJsonObject h; + h["frequency"] = (double) p.second; + h["seconds"] = p.first; + heardArray.append(h); + } + + result["heard"] = heardArray; + + QList> byPower; + QList allPowers; // every frequency, for the floor estimate + for (auto it = strongest.begin(); it != strongest.end(); ++it) { allPowers.append(it.value()); if (isLocalPeak(it.key())) { byPower.append(qMakePair(it.value(), it.key())); } } + std::sort(byPower.begin(), byPower.end(), [](const QPair& a, const QPair& b) { return a.first > b.first; }); + std::sort(allPowers.begin(), allPowers.end()); + // Everything above the threshold, strongest first: for a band of continuous carriers + // this is the answer, as the scanner parks on the first one it finds and never gets + // to the rest. Capped well above any real band's station count, so that a threshold + // set too low on a long list cannot flood the reply + QJsonArray activeArray; + QJsonArray strongestArray; + static const int activeCap = 100; + + for (int i = 0; i < byPower.size(); i++) + { + QJsonObject s; + s["frequency"] = (double) byPower[i].second; + s["dB"] = byPower[i].first; + + if (i < 5) { + strongestArray.append(s); + } + + if ((byPower[i].first >= threshold) && (activeArray.size() < activeCap)) { + activeArray.append(s); + } + } + + result["active"] = activeArray; + result["activeCount"] = activeArray.size(); + result["strongest"] = strongestArray; + + if (haveFloor) { + result["noiseFloorDb"] = measuredFloor; + } else if (!allPowers.isEmpty()) { + result["noiseFloorDb"] = allPowers[allPowers.size() / 2]; + } + + if (autoThreshold) { + result["thresholdAuto"] = true; + } + + QStringList notes; + + if (!rasterNote.isEmpty()) { + notes.append(rasterNote); + } + + if (!gainNote.isEmpty()) { + notes.append(gainNote); + } + + if (!receiver["rateNote"].toString().isEmpty()) { + notes.append(receiver["rateNote"].toString()); + } + + if (activeArray.isEmpty()) { + notes.append("Nothing exceeded the threshold. Compare threshold with noiseFloorDb and the strongest channels; a second scan with threshold given lowers it."); + } else if (heardArray.isEmpty()) { + notes.append("The scanner did not park on any of the active frequencies while watching; active is still the list of what was found."); + } + + notes.append(intentNotes(deviceSetIndex, {demodChannel, scannerChannel}, reclaimed, receiver["reused"].toBool(), + receiver["previousCentre"].toDouble(), tune["centerFrequency"].toDouble(), outcome)); + notes.append(featureNotes(reclaimedFeatures)); + + if (!notes.isEmpty()) { + result["note"] = notes.join(" "); + } + + newDeviceSet.keep(); + return result; + }); + + add("cleanup", + "Remove the channels that listen and scan added, on one device set or all of them, and the features listen added " + "for them (AIS, Radiosonde, APRS) once nothing feeds them. Each is otherwise left running, every demodulator playing " + "audio, until the next listen or scan on the same device set replaces it. Channels and features added any other way " + "are left alone; delete_channel and delete_feature remove those.", + schema({ + {"deviceSetIndex", intProp("Only this device set. Default: every device set")} + }), + [this](const QJsonObject& args) + { + QList deviceSetIndices; + + if (hasArg(args, "deviceSetIndex")) + { + deviceSetIndices.append(argInt(args, "deviceSetIndex")); + } + else + { + for (const QJsonValue& v : getInstanceSummary()["devicesetlist"].toObject()["deviceSets"].toArray()) { + deviceSetIndices.append(v.toObject()["samplingDevice"].toObject()["index"].toInt()); + } + } + + QJsonArray removed; + int count = 0; + + for (int deviceSetIndex : deviceSetIndices) + { + for (const QString& id : reclaimIntentChannels(deviceSetIndex)) + { + removed.append(QString("R%1:%2").arg(deviceSetIndex).arg(id)); + count++; + } + } + + QJsonArray features; + + for (const QString& id : reclaimIntentFeatures()) + { + features.append(id); + count++; + } + + QJsonObject result; + result["removed"] = count; + result["channels"] = removed; + result["features"] = features; + + if (count == 0) { + result["note"] = "Nothing to remove: no channel or feature added by listen or scan is still there."; + } + + return result; + }); + + add("tune_gain", + "Find the receiver gain that gives the best signal to noise ratio and apply it: steps the device through its gain range " + "and at each step measures the noise floor and the strongest signal on the main spectrum. Too little gain leaves weak " + "signals under the converter's own noise; too much overloads the front end, which raises the floor faster than the " + "signal and adds spurious products, so the best gain is where the difference between them peaks, and of gains within a " + "decibel of that the lowest is taken, for headroom. On a quiet band, where no signal stands clear of the floor, the " + "floor alone decides: the lowest gain at which the antenna's noise rather than the converter's sets it, short of " + "overload. Turns the device's AGC off, as it has to for a manual gain to mean " + "anything. The device must be running. Blocks for a few seconds per step; the reply carries the whole table so the " + "choice can be judged. Give frequency to judge by a particular signal rather than the strongest one. Once the gain " + "is applied the main spectrum is autoscaled to suit it, unless autoscale is false.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"frequency", numProp("Judge by the signal at this frequency in Hz rather than the strongest in the baseband. It must be inside the baseband")}, + {"bandwidth", numProp("Width in Hz around frequency to look for the signal in. Default 200000")}, + {"steps", bounded(intProp("How many gain values to try, spread over the range. Default 8"), 3, 16)}, + {"apply", prop("boolean", "Apply the chosen gain. false measures and reports but puts the gain back as it was. Default true")}, + {"autoscale", prop("boolean", "Once the chosen gain is applied, set the main spectrum's reference level and range from what it then shows, as spectrum_action autoscale does, so the display suits the new gain. Default true")}, + {"gainKey", strProp("For a device type this does not know: the settings key of its gain, from describe_settings. Then give values too")}, + {"values", prop("array", "For a device type this does not know: the gain values to try, in the key's own units, lowest first")}, + {"agcKey", strProp("For a device type this does not know: the settings key that turns its AGC off when set to 0")} + }, {"deviceSetIndex"}), + [this](const QJsonObject& args) { return tuneGain(args); }); + + add("get_status", + "One line per device set and feature: device, frequency, run state and channels. The cheapest way to see what is going on.", + schema(QJsonObject()), + [this](const QJsonObject&) + { + QJsonObject summary = getInstanceSummary(); + QStringList lines; + + for (const QJsonValue& v : summary["devicesetlist"].toObject()["deviceSets"].toArray()) + { + QJsonObject ds = v.toObject(); + QJsonObject sd = ds["samplingDevice"].toObject(); + QStringList channels; + + for (const QJsonValue& c : ds["channels"].toArray()) + { + QJsonObject ch = c.toObject(); + channels.append(QString("%1 %2%3k").arg(ch["id"].toString()) + .arg(ch["deltaFrequency"].toDouble() >= 0 ? "+" : "").arg(ch["deltaFrequency"].toDouble() / 1000.0, 0, 'f', 1)); + } + + static const char *const prefixes[] = {"R", "T", "M"}; + lines.append(QString("%1%2 %3 %4 %5 MHz %6%7") + .arg(prefixes[qBound(0, sd["direction"].toInt(), 2)]).arg(sd["index"].toInt()) + .arg(sd["hwType"].toString()).arg(sd["serial"].toString()) + .arg(sd["centerFrequency"].toDouble() / 1e6, 0, 'f', 3).arg(sd["state"].toString()) + .arg(channels.isEmpty() ? QString() : ": " + channels.join(", "))); + } + + for (const QJsonValue& v : summary["featureset"].toObject()["features"].toArray()) + { + QJsonObject f = v.toObject(); + int index = f["index"].toInt(); + lines.append(QString("F%1 %2 %3").arg(index).arg(f["id"].toString()).arg(featureState(index, -1)["state"].toString())); + } + + return QJsonValue(lines.isEmpty() ? QString("Nothing configured") : lines.join("\n")); + }); +} diff --git a/plugins/feature/mcpserver/mcptools.h b/plugins/feature/mcpserver/mcptools.h index db2f6bdb8..29cd49bd5 100644 --- a/plugins/feature/mcpserver/mcptools.h +++ b/plugins/feature/mcpserver/mcptools.h @@ -1,299 +1,299 @@ -/////////////////////////////////////////////////////////////////////////////////// -// Copyright (C) 2026 Jon Beniston, M7RCE // -// Some code by AI // -// // -// This program is free software; you can redistribute it and/or modify // -// it under the terms of the GNU General Public License as published by // -// the Free Software Foundation as version 3 of the License, or // -// (at your option) any later version. // -// // -// This program is distributed in the hope that it will be useful, // -// but WITHOUT ANY WARRANTY; without even the implied warranty of // -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // -// GNU General Public License V3 for more details. // -// // -// You should have received a copy of the GNU General Public License // -// along with this program. If not, see . // -/////////////////////////////////////////////////////////////////////////////////// - -#ifndef INCLUDE_FEATURE_MCPTOOLS_H_ -#define INCLUDE_FEATURE_MCPTOOLS_H_ - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#include "mcperror.h" -#include "mcpdocs.h" -#include "mcpdatafeed.h" -#include "mcpcapture.h" - -//!< A settings definition's properties, read from the swagger YAML that describe_settings serves. -//!< The current value of a setting cannot serve this purpose: generated SWG objects omit empty -//!< strings, so a blank setting is indistinguishable from a key that does not exist -struct SettingsSchema -{ - bool m_known = false; //!< False when the definition was not found, so nothing can be judged - QMap m_types; //!< Property name -> YAML type: integer, number, string, array or object -}; - -class WebAPIAdapterInterface; -class MCPStreams; -class DeviceAPI; -class ChannelAPI; -class Feature; - -namespace SWGSDRangel { - class SWGObject; - class SWGErrorResponse; -} - -// Counts MainCore structural change signals so that tool handlers running on HTTP threads -// can wait for asynchronous operations (which complete on the main thread) to finish. -// Lives in the main thread; the counters are read from other threads. -class MCPEventCounter : public QObject -{ - Q_OBJECT -public: - MCPEventCounter(); - - QAtomicInt m_deviceSetAdded; - QAtomicInt m_deviceSetRemoved; - QAtomicInt m_deviceChanged; - QAtomicInt m_channelAdded; - QAtomicInt m_channelRemoved; - QAtomicInt m_featureAdded; - QAtomicInt m_featureRemoved; - -private slots: - void onDeviceSetAdded(int index, DeviceAPI *device); - void onDeviceSetRemoved(int index); - void onDeviceChanged(int index); - void onChannelAdded(int deviceSetIndex, ChannelAPI *channel); - void onChannelRemoved(int deviceSetIndex, ChannelAPI *channel); - void onFeatureAdded(int featureSetIndex, Feature *feature); - void onFeatureRemoved(int featureSetIndex, Feature *feature); -}; - -// The set of MCP tools that control SDRangel. Everything goes through the -// in-process Web API adapter, so what the tools can do matches the REST API, -// plus waiting for asynchronous operations to complete. -class MCPTools -{ -public: - struct Tool - { - QString name; - QString description; - QJsonObject inputSchema; - std::function handler; - }; - - explicit MCPTools(WebAPIAdapterInterface *webAPIAdapterInterface); - - QJsonArray listTools() const; - QJsonObject callTool(const QString& name, const QJsonObject& arguments); - - // Data also served as resources - QJsonObject getInstanceSummary(); - QJsonObject getAvailableDevices(int direction = -1); //!< -1 for all directions - QJsonObject getAvailableChannels(int direction = -1); - QJsonObject getAvailableFeatures(); - QJsonObject getPresets(); - QJsonObject getConfigurations(); - QJsonObject getDeviceSet(int deviceSetIndex); - int deviceSetCount() const; - QString describeType(const QString& type, const QString& kind); - MCPDocs& docs() { return m_docs; } - MCPDataFeed& dataFeed() { return m_dataFeed; } - MCPCapture& capture() { return m_capture; } - void setStreams(MCPStreams *streams) { m_streams = streams; } - //!< The feature that owns this server, so it can refuse to delete or stop itself - void setOwnerFeature(const QObject *feature) { m_ownerFeature = feature; } - //!< Set by the server, on the main thread, before it waits for the HTTP threads to finish. - //!< Every wait and sleep in the tools then ends at once with a tool error, since the main - //!< thread they would otherwise be waiting on is the one waiting for them - void setStopping(bool stopping); - -private: - WebAPIAdapterInterface *m_adapter; - MCPEventCounter m_events; - MCPDocs m_docs; - MCPDataFeed m_dataFeed; - MCPCapture m_capture; - MCPStreams *m_streams; - - // Creating an object and working out which one is new must not overlap with another - // creation, or two callers snapshot the same state and both claim the same object. - // The capture tools run without the dispatch lock, so this is reachable. - QMutex m_creationMutex; - // Deletion is by index, and the index is resolved just before the delete is posted for - // the main thread to do later. Two calls deleting on one device set unserialised can post - // two indices that were right when read and wrong once the first delete has renumbered - // the rest, taking a channel neither meant. Held from the lookup to the object being gone - QMutex m_deletionMutex; - // The channels listen and scan have added, so that the next of either on the same device - // set can take them away again and cleanup can remove them all. Held by uid rather than - // pointer: a channel removed from the GUI frees its address for the next one created, - // which must not then be taken for one of these. They run without the dispatch lock, so - // this has a lock of its own, which is never held across addChannelAndWait or a delete: - // those take m_creationMutex or wait - QMutex m_intentMutex; - QSet m_intentChannels; - // The features listen added for a mode's output (AIS, Radiosonde, APRS), removed again once no - // channel it added still feeds them. A feature that was already there is never among these - QSet m_intentFeatures; - const QObject *m_ownerFeature; - QAtomicInt m_stopping; - QList m_tools; - // The definitions are loaded on first use and the parsed schemas cached as they are asked - // for, from whichever thread asks. The settings tools run under the dispatch lock but - // listen and scan do not, and they patch settings too, so these have a lock of their own, - // taken by describeType and settingsSchema; the helpers they call expect it held - QMutex m_schemaMutex; - QMap m_yamlDefinitions; //!< Swagger definition name -> YAML text - QMap m_yamlDefinitionsByLower; //!< Lower cased name -> the name as written - QMap m_schemaCache; //!< Parsed form of the above, by definition name - bool m_yamlLoaded; - - void add(const QString& name, const QString& description, const QJsonObject& inputSchema, - std::function handler); - - void registerInstanceTools(); - void registerDeviceSetTools(); - void registerChannelTools(); - void registerFeatureTools(); - void registerPresetTools(); - void registerWorkspaceTools(); - void registerCaptureTools(); - void registerIntentTools(); - - //!< Polls until the condition holds, at most timeoutMs. False on timeout; throws when the - //!< server is stopping, as nothing waited for on the main thread will happen then - bool waitFor(const std::function& condition, int timeoutMs = m_waitTimeoutMs) const; - //!< A sleep that a stop cuts short, with the same tool error - void pause(int ms) const; - static const int m_waitTimeoutMs = 5000; - - // Device set helpers - int channelCount(int deviceSetIndex) const; - int featureCount() const; - int deviceSetDirection(int deviceSetIndex); - QJsonObject selectDevice(int deviceSetIndex, const QJsonObject& args); - QJsonObject getDeviceSettings(int deviceSetIndex); - QJsonObject patchDeviceSettings(int deviceSetIndex, const QJsonObject& partial); - int addChannelAndWait(int deviceSetIndex, const QString& channelType); - int addFeatureAndWait(const QString& featureType); - int addDeviceSetAndWait(int direction); - //!< Identity of the current channels, features or device sets, to spot which one is new. - //!< Channels and features are identified by UID throughout: a pointer to one is only ever - //!< good until the next wait, since a deleted object's address is reused by the next one - //!< created, and every tool here waits - QSet channelUids(int deviceSetIndex) const; - QSet featureUids() const; - QSet deviceSetPointers() const; - void deleteChannelAndWait(int deviceSetIndex, int channelIndex); - void deleteChannelLocked(int deviceSetIndex, int channelIndex); //!< With m_deletionMutex held - //!< Removes a device set that listen or scan created and could not finish setting up, if it - //!< is still the last one, which is the only one the API can remove - void discardNewDeviceSet(int deviceSetIndex, uint64_t identity); - //!< What tells one device set from another that has since taken its index: the engine's UID - //!< together with the object's address. Zero when there is no such device set - uint64_t deviceSetIdentity(int deviceSetIndex) const; - friend class NewDeviceSetGuard; - //!< Deletes a channel wherever it has moved to, for callers that held on to it across a wait - void deleteChannelObjectAndWait(uint64_t channelUid); - const void *featureAt(int featureIndex) const; - //!< The UID of the feature or channel at an index, 0 when there is none - uint64_t featureUidAt(int featureIndex) const; - uint64_t channelUidAt(int deviceSetIndex, int channelIndex) const; - void requireNotSelf(int featureIndex, const QString& action) const; - QJsonObject getChannelSettings(int deviceSetIndex, int channelIndex); - QJsonObject patchChannelSettings(int deviceSetIndex, int channelIndex, const QJsonObject& partial); - //!< The property names and types of one settings definition. Used to tell a misspelled key from - //!< a valid one, and to reject a value of the wrong type before it reaches the SWG object - SettingsSchema settingsSchema(const QString& definition); - QString resolveDefinition(const QString& name); //!< Call with m_schemaMutex held - QJsonObject getSpectrumSettings(int deviceSetIndex); - //!< unknownKeys, when given, receives the patch keys the schema does not define - QJsonObject patchSpectrumSettings(int deviceSetIndex, const QJsonObject& partial, QStringList *unknownKeys = nullptr); - //!< Explains an rdsReport that is absent because RDS decoding is switched off, rather than - //!< because nothing has been decoded yet - void addRdsHint(QJsonObject& report, const QString& channelType, int deviceSetIndex, int channelIndex); - QJsonObject getFeatureSettings(int featureIndex); - QJsonObject patchFeatureSettings(int featureIndex, const QJsonObject& partial); - QJsonObject deviceState(int deviceSetIndex, int subsystemIndex, int run); //!< run: 1 start, 0 stop, -1 query - //!< Empty unless the device set's baseband is too narrow for this channel type - QString basebandWarning(int deviceSetIndex, const QString& channelType); - //!< The same for every channel a device set holds - QStringList basebandWarnings(int deviceSetIndex); - QJsonObject featureState(int featureIndex, int run); - QJsonObject presetIdentifier(const QJsonObject& args, int deviceSetIndex, bool forSave); - - // Shared by the intent level tools - QJsonObject channelReport(int deviceSetIndex, int channelIndex); - void postChannelAction(int deviceSetIndex, int channelIndex, const QJsonObject& actions); - //!< doomed: uids of channels the caller is about to remove, which the reused set is not counted as carrying. - //!< profileGain: give a device set this creates the fixed receiver gain profile; false when the gain is about to be measured - QJsonObject pickReceiver(const QJsonObject& args, int minBaseband, const QSet& doomed = QSet(), bool profileGain = true); - //!< The tune_gain tool: sweeps the gain and applies the best, with the table it measured - QJsonObject tuneGain(const QJsonObject& args); - //!< Sets the main spectrum's reference level and range from what it shows, as the GUI's autoscale button does - void autoscaleSpectrum(int deviceSetIndex); - //!< Turns spectrum scrolling on if it is off, which is what keeps the history the spectrum - //!< history tools read. Returns a note when it did, empty otherwise - QString ensureSpectrumHistory(int deviceSetIndex, double seconds); - //!< The index of a feature of this type, adding one if there is none. Returns whether it was added - int ensureFeature(const QString& featureType, int& featureIndex); - void trackIntentFeature(uint64_t featureUid); - //!< Removes the features listen added that no channel it added still feeds, except one of keepType. - //!< Returns the types of those removed - QStringList reclaimIntentFeatures(const QString& keepType = QString()); - //!< Deletes a feature wherever it has been renumbered to - void deleteFeatureObjectAndWait(uint64_t featureUid); - //!< Whether listen or scan should measure the gain: a device set they created, or a retune to another band - static bool gainWorthTuning(bool reused, double previousCentre, double centre); - void trackIntentChannel(uint64_t channelUid); - void untrackIntentChannel(uint64_t channelUid); - QSet intentChannels(); - //!< A channel's type id and whether listen or scan added it, for the notes the intent tools leave - struct ChannelNote { uint64_t m_uid; int m_index; QString m_id; bool m_intent; }; - QList channelNotes(int deviceSetIndex, const QSet& except = QSet()); - //!< Removes the channels listen and scan added to a device set, except keep. Returns the ids of those removed - QStringList reclaimIntentChannels(int deviceSetIndex, const QSet& keep = QSet()); - //!< The channel a previous listen added that a new one of this type can retune instead of replacing, or 0. - //!< wanted: how many of the type the mode uses, 2 for a paired mode - uint64_t reusableIntentChannel(int deviceSetIndex, const QString& channelType, int& channelIndex, int wanted = 1); - //!< What a retune of a reused device set did to the channels listen and scan did not add - struct RetuneOutcome - { - QStringList m_kept; //!< Re-offset so that they stay on the frequency they had - QStringList m_removed; //!< Audio demodulators the new baseband could not hold, which would only have made noise - QStringList m_stranded; //!< Left where they were: not audio, or the baseband unknown - }; - RetuneOutcome retuneOtherChannels(int deviceSetIndex, double previousCentre, double centre, int baseband); - //!< What listen and scan tell the caller about the rest of the device set once their own channels are in - QStringList intentNotes(int deviceSetIndex, const QSet& added, const QStringList& reclaimed, - bool reused, double previousCentre, double centre, const RetuneOutcome& outcome); - //!< Channel type ids for a direction, independent of how list_channel_types formats them - QStringList channelTypeIds(int direction); - //!< Where a channel is now. The intent tools sleep for many seconds without holding the - //!< protocol mutex, and a concurrent request that deletes a lower numbered channel - //!< renumbers everything above it, so their indices have to be resolved again before use. - void relocateChannel(uint64_t channelUid, int& deviceSetIndex, int& channelIndex, const QString& what); - - void loadYamlDefinitions(); //!< Call with m_schemaMutex held -}; - -#endif // INCLUDE_FEATURE_MCPTOOLS_H_ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// (at your option) any later version. // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_FEATURE_MCPTOOLS_H_ +#define INCLUDE_FEATURE_MCPTOOLS_H_ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "mcperror.h" +#include "mcpdocs.h" +#include "mcpdatafeed.h" +#include "mcpcapture.h" + +//!< A settings definition's properties, read from the swagger YAML that describe_settings serves. +//!< The current value of a setting cannot serve this purpose: generated SWG objects omit empty +//!< strings, so a blank setting is indistinguishable from a key that does not exist +struct SettingsSchema +{ + bool m_known = false; //!< False when the definition was not found, so nothing can be judged + QMap m_types; //!< Property name -> YAML type: integer, number, string, array or object +}; + +class WebAPIAdapterInterface; +class MCPStreams; +class DeviceAPI; +class ChannelAPI; +class Feature; + +namespace SWGSDRangel { + class SWGObject; + class SWGErrorResponse; +} + +// Counts MainCore structural change signals so that tool handlers running on HTTP threads +// can wait for asynchronous operations (which complete on the main thread) to finish. +// Lives in the main thread; the counters are read from other threads. +class MCPEventCounter : public QObject +{ + Q_OBJECT +public: + MCPEventCounter(); + + QAtomicInt m_deviceSetAdded; + QAtomicInt m_deviceSetRemoved; + QAtomicInt m_deviceChanged; + QAtomicInt m_channelAdded; + QAtomicInt m_channelRemoved; + QAtomicInt m_featureAdded; + QAtomicInt m_featureRemoved; + +private slots: + void onDeviceSetAdded(int index, DeviceAPI *device); + void onDeviceSetRemoved(int index); + void onDeviceChanged(int index); + void onChannelAdded(int deviceSetIndex, ChannelAPI *channel); + void onChannelRemoved(int deviceSetIndex, ChannelAPI *channel); + void onFeatureAdded(int featureSetIndex, Feature *feature); + void onFeatureRemoved(int featureSetIndex, Feature *feature); +}; + +// The set of MCP tools that control SDRangel. Everything goes through the +// in-process Web API adapter, so what the tools can do matches the REST API, +// plus waiting for asynchronous operations to complete. +class MCPTools +{ +public: + struct Tool + { + QString name; + QString description; + QJsonObject inputSchema; + std::function handler; + }; + + explicit MCPTools(WebAPIAdapterInterface *webAPIAdapterInterface); + + QJsonArray listTools() const; + QJsonObject callTool(const QString& name, const QJsonObject& arguments); + + // Data also served as resources + QJsonObject getInstanceSummary(); + QJsonObject getAvailableDevices(int direction = -1); //!< -1 for all directions + QJsonObject getAvailableChannels(int direction = -1); + QJsonObject getAvailableFeatures(); + QJsonObject getPresets(); + QJsonObject getConfigurations(); + QJsonObject getDeviceSet(int deviceSetIndex); + int deviceSetCount() const; + QString describeType(const QString& type, const QString& kind); + MCPDocs& docs() { return m_docs; } + MCPDataFeed& dataFeed() { return m_dataFeed; } + MCPCapture& capture() { return m_capture; } + void setStreams(MCPStreams *streams) { m_streams = streams; } + //!< The feature that owns this server, so it can refuse to delete or stop itself + void setOwnerFeature(const QObject *feature) { m_ownerFeature = feature; } + //!< Set by the server, on the main thread, before it waits for the HTTP threads to finish. + //!< Every wait and sleep in the tools then ends at once with a tool error, since the main + //!< thread they would otherwise be waiting on is the one waiting for them + void setStopping(bool stopping); + +private: + WebAPIAdapterInterface *m_adapter; + MCPEventCounter m_events; + MCPDocs m_docs; + MCPDataFeed m_dataFeed; + MCPCapture m_capture; + MCPStreams *m_streams; + + // Creating an object and working out which one is new must not overlap with another + // creation, or two callers snapshot the same state and both claim the same object. + // The capture tools run without the dispatch lock, so this is reachable. + QMutex m_creationMutex; + // Deletion is by index, and the index is resolved just before the delete is posted for + // the main thread to do later. Two calls deleting on one device set unserialised can post + // two indices that were right when read and wrong once the first delete has renumbered + // the rest, taking a channel neither meant. Held from the lookup to the object being gone + QMutex m_deletionMutex; + // The channels listen and scan have added, so that the next of either on the same device + // set can take them away again and cleanup can remove them all. Held by uid rather than + // pointer: a channel removed from the GUI frees its address for the next one created, + // which must not then be taken for one of these. They run without the dispatch lock, so + // this has a lock of its own, which is never held across addChannelAndWait or a delete: + // those take m_creationMutex or wait + QMutex m_intentMutex; + QSet m_intentChannels; + // The features listen added for a mode's output (AIS, Radiosonde, APRS), removed again once no + // channel it added still feeds them. A feature that was already there is never among these + QSet m_intentFeatures; + const QObject *m_ownerFeature; + QAtomicInt m_stopping; + QList m_tools; + // The definitions are loaded on first use and the parsed schemas cached as they are asked + // for, from whichever thread asks. The settings tools run under the dispatch lock but + // listen and scan do not, and they patch settings too, so these have a lock of their own, + // taken by describeType and settingsSchema; the helpers they call expect it held + QMutex m_schemaMutex; + QMap m_yamlDefinitions; //!< Swagger definition name -> YAML text + QMap m_yamlDefinitionsByLower; //!< Lower cased name -> the name as written + QMap m_schemaCache; //!< Parsed form of the above, by definition name + bool m_yamlLoaded; + + void add(const QString& name, const QString& description, const QJsonObject& inputSchema, + std::function handler); + + void registerInstanceTools(); + void registerDeviceSetTools(); + void registerChannelTools(); + void registerFeatureTools(); + void registerPresetTools(); + void registerWorkspaceTools(); + void registerCaptureTools(); + void registerIntentTools(); + + //!< Polls until the condition holds, at most timeoutMs. False on timeout; throws when the + //!< server is stopping, as nothing waited for on the main thread will happen then + bool waitFor(const std::function& condition, int timeoutMs = m_waitTimeoutMs) const; + //!< A sleep that a stop cuts short, with the same tool error + void pause(int ms) const; + static const int m_waitTimeoutMs = 5000; + + // Device set helpers + int channelCount(int deviceSetIndex) const; + int featureCount() const; + int deviceSetDirection(int deviceSetIndex); + QJsonObject selectDevice(int deviceSetIndex, const QJsonObject& args); + QJsonObject getDeviceSettings(int deviceSetIndex); + QJsonObject patchDeviceSettings(int deviceSetIndex, const QJsonObject& partial); + int addChannelAndWait(int deviceSetIndex, const QString& channelType); + int addFeatureAndWait(const QString& featureType); + int addDeviceSetAndWait(int direction); + //!< Identity of the current channels, features or device sets, to spot which one is new. + //!< Channels and features are identified by UID throughout: a pointer to one is only ever + //!< good until the next wait, since a deleted object's address is reused by the next one + //!< created, and every tool here waits + QSet channelUids(int deviceSetIndex) const; + QSet featureUids() const; + QSet deviceSetPointers() const; + void deleteChannelAndWait(int deviceSetIndex, int channelIndex); + void deleteChannelLocked(int deviceSetIndex, int channelIndex); //!< With m_deletionMutex held + //!< Removes a device set that listen or scan created and could not finish setting up, if it + //!< is still the last one, which is the only one the API can remove + void discardNewDeviceSet(int deviceSetIndex, uint64_t identity); + //!< What tells one device set from another that has since taken its index: the engine's UID + //!< together with the object's address. Zero when there is no such device set + uint64_t deviceSetIdentity(int deviceSetIndex) const; + friend class NewDeviceSetGuard; + //!< Deletes a channel wherever it has moved to, for callers that held on to it across a wait + void deleteChannelObjectAndWait(uint64_t channelUid); + const void *featureAt(int featureIndex) const; + //!< The UID of the feature or channel at an index, 0 when there is none + uint64_t featureUidAt(int featureIndex) const; + uint64_t channelUidAt(int deviceSetIndex, int channelIndex) const; + void requireNotSelf(int featureIndex, const QString& action) const; + QJsonObject getChannelSettings(int deviceSetIndex, int channelIndex); + QJsonObject patchChannelSettings(int deviceSetIndex, int channelIndex, const QJsonObject& partial); + //!< The property names and types of one settings definition. Used to tell a misspelled key from + //!< a valid one, and to reject a value of the wrong type before it reaches the SWG object + SettingsSchema settingsSchema(const QString& definition); + QString resolveDefinition(const QString& name); //!< Call with m_schemaMutex held + QJsonObject getSpectrumSettings(int deviceSetIndex); + //!< unknownKeys, when given, receives the patch keys the schema does not define + QJsonObject patchSpectrumSettings(int deviceSetIndex, const QJsonObject& partial, QStringList *unknownKeys = nullptr); + //!< Explains an rdsReport that is absent because RDS decoding is switched off, rather than + //!< because nothing has been decoded yet + void addRdsHint(QJsonObject& report, const QString& channelType, int deviceSetIndex, int channelIndex); + QJsonObject getFeatureSettings(int featureIndex); + QJsonObject patchFeatureSettings(int featureIndex, const QJsonObject& partial); + QJsonObject deviceState(int deviceSetIndex, int subsystemIndex, int run); //!< run: 1 start, 0 stop, -1 query + //!< Empty unless the device set's baseband is too narrow for this channel type + QString basebandWarning(int deviceSetIndex, const QString& channelType); + //!< The same for every channel a device set holds + QStringList basebandWarnings(int deviceSetIndex); + QJsonObject featureState(int featureIndex, int run); + QJsonObject presetIdentifier(const QJsonObject& args, int deviceSetIndex, bool forSave); + + // Shared by the intent level tools + QJsonObject channelReport(int deviceSetIndex, int channelIndex); + void postChannelAction(int deviceSetIndex, int channelIndex, const QJsonObject& actions); + //!< doomed: uids of channels the caller is about to remove, which the reused set is not counted as carrying. + //!< profileGain: give a device set this creates the fixed receiver gain profile; false when the gain is about to be measured + QJsonObject pickReceiver(const QJsonObject& args, int minBaseband, const QSet& doomed = QSet(), bool profileGain = true); + //!< The tune_gain tool: sweeps the gain and applies the best, with the table it measured + QJsonObject tuneGain(const QJsonObject& args); + //!< Sets the main spectrum's reference level and range from what it shows, as the GUI's autoscale button does + void autoscaleSpectrum(int deviceSetIndex); + //!< Turns spectrum scrolling on if it is off, which is what keeps the history the spectrum + //!< history tools read. Returns a note when it did, empty otherwise + QString ensureSpectrumHistory(int deviceSetIndex, double seconds); + //!< The index of a feature of this type, adding one if there is none. Returns whether it was added + int ensureFeature(const QString& featureType, int& featureIndex); + void trackIntentFeature(uint64_t featureUid); + //!< Removes the features listen added that no channel it added still feeds, except one of keepType. + //!< Returns the types of those removed + QStringList reclaimIntentFeatures(const QString& keepType = QString()); + //!< Deletes a feature wherever it has been renumbered to + void deleteFeatureObjectAndWait(uint64_t featureUid); + //!< Whether listen or scan should measure the gain: a device set they created, or a retune to another band + static bool gainWorthTuning(bool reused, double previousCentre, double centre); + void trackIntentChannel(uint64_t channelUid); + void untrackIntentChannel(uint64_t channelUid); + QSet intentChannels(); + //!< A channel's type id and whether listen or scan added it, for the notes the intent tools leave + struct ChannelNote { uint64_t m_uid; int m_index; QString m_id; bool m_intent; }; + QList channelNotes(int deviceSetIndex, const QSet& except = QSet()); + //!< Removes the channels listen and scan added to a device set, except keep. Returns the ids of those removed + QStringList reclaimIntentChannels(int deviceSetIndex, const QSet& keep = QSet()); + //!< The channel a previous listen added that a new one of this type can retune instead of replacing, or 0. + //!< wanted: how many of the type the mode uses, 2 for a paired mode + uint64_t reusableIntentChannel(int deviceSetIndex, const QString& channelType, int& channelIndex, int wanted = 1); + //!< What a retune of a reused device set did to the channels listen and scan did not add + struct RetuneOutcome + { + QStringList m_kept; //!< Re-offset so that they stay on the frequency they had + QStringList m_removed; //!< Audio demodulators the new baseband could not hold, which would only have made noise + QStringList m_stranded; //!< Left where they were: not audio, or the baseband unknown + }; + RetuneOutcome retuneOtherChannels(int deviceSetIndex, double previousCentre, double centre, int baseband); + //!< What listen and scan tell the caller about the rest of the device set once their own channels are in + QStringList intentNotes(int deviceSetIndex, const QSet& added, const QStringList& reclaimed, + bool reused, double previousCentre, double centre, const RetuneOutcome& outcome); + //!< Channel type ids for a direction, independent of how list_channel_types formats them + QStringList channelTypeIds(int direction); + //!< Where a channel is now. The intent tools sleep for many seconds without holding the + //!< protocol mutex, and a concurrent request that deletes a lower numbered channel + //!< renumbers everything above it, so their indices have to be resolved again before use. + void relocateChannel(uint64_t channelUid, int& deviceSetIndex, int& channelIndex, const QString& what); + + void loadYamlDefinitions(); //!< Call with m_schemaMutex held +}; + +#endif // INCLUDE_FEATURE_MCPTOOLS_H_ diff --git a/plugins/feature/mcpserver/readme.md b/plugins/feature/mcpserver/readme.md index 7dc8ba3c6..5e6fe9d0c 100644 --- a/plugins/feature/mcpserver/readme.md +++ b/plugins/feature/mcpserver/readme.md @@ -1,171 +1,171 @@ -

MCP Server Feature Plugin

- -

Introduction

- -This feature exposes SDRangel to AI agents through the [Model Context Protocol](https://modelcontextprotocol.io/) (MCP), so that an assistant such as Claude or ChatGPT/Codex can inspect and control SDRangel: create device sets, select SDR hardware, tune, add demodulators, change settings, read reports, load presets and so on. - -The plugin runs an MCP server using the Streamable HTTP transport. MCP clients connect to `http://address:port/mcp`. - -[Tutorial Video](https://youtu.be/G0FmiX7zwb8) - -

Interface

- -![MCP Server feature plugin GUI](../../../doc/img/MCPServer_plugin.png) - -

1: Start/Stop

- -Starts or stops the MCP server. The button is green when the server is listening and red if it could not listen on the requested address and port. - -

2: Endpoint URL

- -The URL to give to MCP clients. - -

3: Address

- -IP address to listen on. The default of 127.0.0.1 only accepts connections from the local computer. Use 0.0.0.0 to accept connections from any network interface, in which case a token should be set. - -

4: Port

- -TCP port to listen on. The default is 8092. - -

5: Capture directory

- -Directory that the capture tools write IQ and audio files to. It defaults to `SDRangel/captures` under your documents folder. File names given to the capture tools are relative to it, and names that would write outside it are refused, so a connected agent cannot write anywhere else on the machine. - -

6: Token

- -Optional bearer token. When set, clients must send an `Authorization: Bearer ` HTTP header. Leave empty for no authentication. - -

7: Add to Codex

- -Writes this server into Codex's `config.toml`. -Codex reads its configuration at startup, so restart it afterwards. - -

8: Add to Claude Desktop

- -Opens the extension bundle with Claude Desktop, which then shows its own dialog asking whether to install it. - -

9: Status

- -Number of MCP requests served since the server was started and the last request received. - -

Connecting a client

- -

Claude Code

- -For clients that support remote (HTTP) MCP servers, add the endpoint URL directly: - - claude mcp add --transport http sdrangel http://127.0.0.1:8092/mcp - -

Claude Desktop

- -Claude Desktop cannot connect directly to a HTTP server. -Install the SDRangel extension, which carries a small [bridge](bridge/readme.md) that relays the stdio -transport Claude Desktop does support to this server. Press Add to Claude Desktop (8) to hand -it the bundle; on Windows the installer also offers to do this at the end of a fresh install. -Failing either, take `sdrangel--.mcpb` from the release and open it with -Claude Desktop, or drag it onto Settings > Extensions. Set the port in the extension's -settings if it is not the default 8092. - -For other clients that only support local stdio servers, run the same bridge directly, in: - -- Windows: %APPDATA%\Claude\claude_desktop_config.json -- Linux: ~/.config/Claude/claude_desktop_config.json -- macOS: ~/Library/Application Support/Claude/claude_desktop_config.json - -``` - "mcpServers": { - "sdrangel": { - "command": "C:\\Program Files\\SDRangel\\sdrangel-mcp-bridge.exe", - "args": ["--port", "8092"] - } - } -``` - -`npx -y mcp-remote http://127.0.0.1:8092/mcp` does the same job for a client that has no -bridge built for its platform, at the cost of needing Node.js installed. - -

ChatGPT/Codex

- -Codex supports the HTTP transport, so does not need a bridge. Press Add to Codex (7) to have the -server's address written to its configuration file, or add the following by hand to: - -- Windows: %USERPROFILE%\.codex\config.toml -- macOS/Linux: ~/.codex/config.toml - -``` - [mcp_servers.sdrangel] - url = "http://127.0.0.1:8092/mcp" -``` - -With a token set, the header goes alongside it: - -``` - [mcp_servers.sdrangel] - url = "http://127.0.0.1:8092/mcp" - http_headers = { "Authorization" = "Bearer " } -``` - -

Tools

- -The intent tools do a whole task in one call: `listen` sets up a receiver on a frequency in a given mode, `scan` sets up a Frequency Scanner over a list or range of frequencies and reports every frequency above the threshold with its level (and, for intermittent signals, where the scanner parked), stepping by the channel spacing usual for the mode unless told otherwise and refusing modes that live on fixed frequencies, and `get_status` returns one line per device set and feature. Both `listen` and `scan` keep track of the channels they add: by default the next of either on the same device set removes them first, so that exploring a band does not leave a trail of demodulators all playing audio, and `cleanup` removes them all. A `listen` that finds a demodulator of the type it needs among them retunes it instead, as a person would, so stepping through a band in one mode keeps one channel open throughout. Both measure and set the receiver gain, as `tune_gain` does, when they create a device set or move one to another band, and leave it alone otherwise or when told `tuneGain` false. A mode whose output goes to a feature (AIS, radiosondes, APRS) has `listen` add that feature when it is absent, and remove it again, along with the channels, once nothing it added feeds it; a feature that was already there is left alone. AIS gets a demodulator on each of its two channels with the device centred between them. Channels added any other way are kept on the frequency they had, by moving their offset, when the retuned baseband still holds them; an audio demodulator it cannot hold is removed, since all it could do is play noise, while anything else (a file sink, an analyser) is left in place and named in the reply. The rest mirror the Web API. Creation tools wait for SDRangel to complete the operation and return the index of the new object; the `set_*` tools reply with only the keys that were changed, since a client carries every reply in its context for the rest of the conversation. - -| Area | Tools | -|------|-------| -| Intent | `listen`, `scan`, `cleanup`, `tune_gain`, `get_status` | -| Discovery | `get_instance_summary`, `list_available_devices`, `list_channel_types`, `list_feature_types`, `describe_settings`, `get_receiving_guide`, `list_docs`, `get_docs`, `list_audio_devices`, `get_location`, `set_location` | -| Device sets | `add_deviceset`, `remove_last_deviceset`, `get_deviceset`, `set_device`, `get_device_settings`, `set_device_settings`, `set_center_frequency`, `start_device`, `stop_device`, `get_device_report`, `device_action`, `get_spectrum_settings`, `set_spectrum_settings`, `get_spectrum_data`, `get_spectrum_history`, `get_waterfall_image`, `spectrum_action` | -| Channels | `add_channel`, `delete_channel`, `get_channel_settings`, `set_channel_settings`, `get_channel_report`, `channel_action` | -| Features | `add_feature`, `delete_feature`, `get_feature_settings`, `set_feature_settings`, `get_feature_report`, `start_feature`, `stop_feature`, `feature_action` | -| Presets | `list_presets`, `load_preset`, `save_preset`, `list_configurations`, `load_configuration`, `save_configuration` | -| Workspaces (GUI only) | `add_workspace`, `delete_empty_workspaces`, `list_windows`, `set_workspace` (move, hide or show a window), `arrange_workspace` | -| Live data | `get_packets`, `clear_packets`, `get_map_items` | -| Capture | `capture_audio`, `record_iq`, `start_iq_recording`, `stop_iq_recording` | -| Server | `get_server_status` (open streams, capture directory and active recordings, data feed sources) | - -Each tool carries MCP annotations: whether it only reads, whether it overwrites state rather than only adding to it, whether repeating it lands in the same place, and whether it reaches beyond this application, which covers commanding the radio and data received from transmitters SDRangel does not control. - -`describe_settings` returns the OpenAPI documentation of the settings, report and actions keys of a device, channel or feature type, so that an agent can learn the valid keys rather than guess them. The `set_*_settings` tools accept a partial settings object containing only the keys to change. - -`get_packets` returns the packets received on the `packets`, `ais` and `radiosonde` message pipes of the packet, ChirpChat, M17, Meshtastic, MeshCore, Inmarsat, AIS and radiosonde demodulators, kept in a buffer of the last 1000. Each packet carries the raw bytes and, where possible, a decode: AIS message type, MMSI, position, course and speed; AX.25 addresses and data with the APRS position and comment; RS41 serial, position and height. `get_map_items` returns the objects that the same channels and features that feed the Map send on the `mapitems` pipe (aircraft, ships, APRS stations, radiosondes, satellites, Sun and Moon, beacons), with the image, text and, on request, the track. Items are removed when their source removes them or is deleted. Both work whether or not a Map or AIS/APRS feature is present. - -`record_iq` records baseband IQ to an `.sdriq` file for a fixed number of seconds and returns the files written; `start_iq_recording` and `stop_iq_recording` do the same without a time limit for longer captures. Both work by adding a File Sink channel to the device set, so the recording has the offset and decimation the tools are given. `capture_audio` records the demodulated audio of a channel to a WAV file, and reports the sample rate, the peak level and whether the audio was silent, which tells an agent that a squelch is closed rather than that nothing is wrong. It works with demodulators that feed the Demod Analyzer, such as NFMDemod, AMDemod, SSBDemod, WFMDemod and BFMDemod. With `inline` true it also returns the audio as base64, as a mono 16 kHz copy, since MCP clients refuse a tool result over about a megabyte and ten seconds at 48 kHz would exceed that once encoded; the file keeps the full rate. Both blocking tools are capped at 30 seconds so they cannot hold an MCP client's connection open indefinitely. - -`get_receiving_guide` serves a hand written guide in `bandguide.md`: which demodulator and frequency to use for each signal SDRangel can receive, the minimum device sample rate that ADS-B, DAB and broadcast FM need, and the usual reasons nothing is received. Its frequencies come from the plugin readmes, and a test checks that every channel id it names is registered in the build. Edit that file to correct or extend it; it is compiled into the plugin, so re-run cmake after changing it. - -`list_docs` and `get_docs` serve the readme of every plugin registered in the running instance, and the GUI's own pages for what no plugin owns: the spectrum display (`spectrum`, with `spectrummarkers`, `spectrummeasurements` and `spectrumcalibration`), the main spectrum window, audio management, configurations, device user arguments and the transverter dialog. The readmes are compiled into this plugin at build time (re-run cmake after adding a plugin), converted to plain markdown with images removed, and matched to plugin ids by name; the GUI pages are listed in `CMakeLists.txt` and given their ids in `MCPDocs::addGuiDocs`. `get_docs` accepts a plugin id or its displayed name and an optional section heading, so an agent can read just the part it needs from a long document. - -

Event stream

- -A client can be told when a resource changes instead of polling for it. An HTTP GET on the endpoint with `Accept: text/event-stream` opens a Server-Sent Events stream, and `resources/subscribe` asks for a resource on it. Updates arrive as `notifications/resources/updated`, at most once a second per resource so that a busy decoder cannot flood the stream. `sdrangel://instance`, `sdrangel://packets`, `sdrangel://map/items` and `sdrangel://deviceset/{index}` can be subscribed to; the other resources never change. - -`initialize` returns an `Mcp-Session-Id` header. A client that sends it back keeps its own subscriptions and stream, and can end them with an HTTP DELETE. Clients that ignore it share an anonymous session, which works fully for one client at a time. A client keeps one stream: opening a second replaces the first, so a notification is never delivered twice. That applies to clients that send no session id as well, since they already share the anonymous subscriptions. Sessions with no stream are dropped after a day idle, and at most 32 are kept, each with at most 32 subscriptions. Up to eight streams may be open at once, and a stream is closed after ten minutes so that a client which vanished without closing its connection cannot hold a thread forever; clients reconnect. - -

Resources

- -| URI | Content | -|-----|---------| -| `sdrangel://instance` | Instance summary | -| `sdrangel://plugins/devices` | Available sampling devices | -| `sdrangel://plugins/channels` | Available channel types | -| `sdrangel://plugins/features` | Available feature types | -| `sdrangel://presets` | Saved presets | -| `sdrangel://configurations` | Saved configurations | -| `sdrangel://deviceset/{index}` | A device set | -| `sdrangel://schema/{type}` | Settings documentation for a type | -| `sdrangel://packets` | The 100 most recent decoded packets, from a buffer of the last 1000 | -| `sdrangel://map/items` | Objects currently plotted on the map | -| `sdrangel://guide` | The receiving guide | -| `sdrangel://docs` | Index of plugin and GUI documentation with section headings | -| `sdrangel://docs/{kind}/{id}` | A document as markdown, e.g. `sdrangel://docs/channel/ADSBDemod` or `sdrangel://docs/gui/spectrum` | - -

Prompts

- -`setup_receiver`, `record_iq` and `explain_configuration` are prompt templates that guide an agent through common tasks. - -

Security

- -The server has no access control beyond the optional bearer token, and an agent connected to it can change anything in SDRangel. Keep the address at 127.0.0.1 unless a token is set. - -To keep web pages from driving the server through a browser, requests carrying an `Origin` header are only accepted from an `http` or `https` localhost origin (the opaque `null` origin is rejected), and the request body must be declared as `application/json`. - +

MCP Server Feature Plugin

+ +

Introduction

+ +This feature exposes SDRangel to AI agents through the [Model Context Protocol](https://modelcontextprotocol.io/) (MCP), so that an assistant such as Claude or ChatGPT/Codex can inspect and control SDRangel: create device sets, select SDR hardware, tune, add demodulators, change settings, read reports, load presets and so on. + +The plugin runs an MCP server using the Streamable HTTP transport. MCP clients connect to `http://address:port/mcp`. + +[Tutorial Video](https://youtu.be/G0FmiX7zwb8) + +

Interface

+ +![MCP Server feature plugin GUI](../../../doc/img/MCPServer_plugin.png) + +

1: Start/Stop

+ +Starts or stops the MCP server. The button is green when the server is listening and red if it could not listen on the requested address and port. + +

2: Endpoint URL

+ +The URL to give to MCP clients. + +

3: Address

+ +IP address to listen on. The default of 127.0.0.1 only accepts connections from the local computer. Use 0.0.0.0 to accept connections from any network interface, in which case a token should be set. + +

4: Port

+ +TCP port to listen on. The default is 8092. + +

5: Capture directory

+ +Directory that the capture tools write IQ and audio files to. It defaults to `SDRangel/captures` under your documents folder. File names given to the capture tools are relative to it, and names that would write outside it are refused, so a connected agent cannot write anywhere else on the machine. + +

6: Token

+ +Optional bearer token. When set, clients must send an `Authorization: Bearer ` HTTP header. Leave empty for no authentication. + +

7: Add to Codex

+ +Writes this server into Codex's `config.toml`. +Codex reads its configuration at startup, so restart it afterwards. + +

8: Add to Claude Desktop

+ +Opens the extension bundle with Claude Desktop, which then shows its own dialog asking whether to install it. + +

9: Status

+ +Number of MCP requests served since the server was started and the last request received. + +

Connecting a client

+ +

Claude Code

+ +For clients that support remote (HTTP) MCP servers, add the endpoint URL directly: + + claude mcp add --transport http sdrangel http://127.0.0.1:8092/mcp + +

Claude Desktop

+ +Claude Desktop cannot connect directly to a HTTP server. +Install the SDRangel extension, which carries a small [bridge](bridge/readme.md) that relays the stdio +transport Claude Desktop does support to this server. Press Add to Claude Desktop (8) to hand +it the bundle; on Windows the installer also offers to do this at the end of a fresh install. +Failing either, take `sdrangel--.mcpb` from the release and open it with +Claude Desktop, or drag it onto Settings > Extensions. Set the port in the extension's +settings if it is not the default 8092. + +For other clients that only support local stdio servers, run the same bridge directly, in: + +- Windows: %APPDATA%\Claude\claude_desktop_config.json +- Linux: ~/.config/Claude/claude_desktop_config.json +- macOS: ~/Library/Application Support/Claude/claude_desktop_config.json + +``` + "mcpServers": { + "sdrangel": { + "command": "C:\\Program Files\\SDRangel\\sdrangel-mcp-bridge.exe", + "args": ["--port", "8092"] + } + } +``` + +`npx -y mcp-remote http://127.0.0.1:8092/mcp` does the same job for a client that has no +bridge built for its platform, at the cost of needing Node.js installed. + +

ChatGPT/Codex

+ +Codex supports the HTTP transport, so does not need a bridge. Press Add to Codex (7) to have the +server's address written to its configuration file, or add the following by hand to: + +- Windows: %USERPROFILE%\.codex\config.toml +- macOS/Linux: ~/.codex/config.toml + +``` + [mcp_servers.sdrangel] + url = "http://127.0.0.1:8092/mcp" +``` + +With a token set, the header goes alongside it: + +``` + [mcp_servers.sdrangel] + url = "http://127.0.0.1:8092/mcp" + http_headers = { "Authorization" = "Bearer " } +``` + +

Tools

+ +The intent tools do a whole task in one call: `listen` sets up a receiver on a frequency in a given mode, `scan` sets up a Frequency Scanner over a list or range of frequencies and reports every frequency above the threshold with its level (and, for intermittent signals, where the scanner parked), stepping by the channel spacing usual for the mode unless told otherwise and refusing modes that live on fixed frequencies, and `get_status` returns one line per device set and feature. Both `listen` and `scan` keep track of the channels they add: by default the next of either on the same device set removes them first, so that exploring a band does not leave a trail of demodulators all playing audio, and `cleanup` removes them all. A `listen` that finds a demodulator of the type it needs among them retunes it instead, as a person would, so stepping through a band in one mode keeps one channel open throughout. Both measure and set the receiver gain, as `tune_gain` does, when they create a device set or move one to another band, and leave it alone otherwise or when told `tuneGain` false. A mode whose output goes to a feature (AIS, radiosondes, APRS) has `listen` add that feature when it is absent, and remove it again, along with the channels, once nothing it added feeds it; a feature that was already there is left alone. AIS gets a demodulator on each of its two channels with the device centred between them. Channels added any other way are kept on the frequency they had, by moving their offset, when the retuned baseband still holds them; an audio demodulator it cannot hold is removed, since all it could do is play noise, while anything else (a file sink, an analyser) is left in place and named in the reply. The rest mirror the Web API. Creation tools wait for SDRangel to complete the operation and return the index of the new object; the `set_*` tools reply with only the keys that were changed, since a client carries every reply in its context for the rest of the conversation. + +| Area | Tools | +|------|-------| +| Intent | `listen`, `scan`, `cleanup`, `tune_gain`, `get_status` | +| Discovery | `get_instance_summary`, `list_available_devices`, `list_channel_types`, `list_feature_types`, `describe_settings`, `get_receiving_guide`, `list_docs`, `get_docs`, `list_audio_devices`, `get_location`, `set_location` | +| Device sets | `add_deviceset`, `remove_last_deviceset`, `get_deviceset`, `set_device`, `get_device_settings`, `set_device_settings`, `set_center_frequency`, `start_device`, `stop_device`, `get_device_report`, `device_action`, `get_spectrum_settings`, `set_spectrum_settings`, `get_spectrum_data`, `get_spectrum_history`, `get_waterfall_image`, `spectrum_action` | +| Channels | `add_channel`, `delete_channel`, `get_channel_settings`, `set_channel_settings`, `get_channel_report`, `channel_action` | +| Features | `add_feature`, `delete_feature`, `get_feature_settings`, `set_feature_settings`, `get_feature_report`, `start_feature`, `stop_feature`, `feature_action` | +| Presets | `list_presets`, `load_preset`, `save_preset`, `list_configurations`, `load_configuration`, `save_configuration` | +| Workspaces (GUI only) | `add_workspace`, `delete_empty_workspaces`, `list_windows`, `set_workspace` (move, hide or show a window), `arrange_workspace` | +| Live data | `get_packets`, `clear_packets`, `get_map_items` | +| Capture | `capture_audio`, `record_iq`, `start_iq_recording`, `stop_iq_recording` | +| Server | `get_server_status` (open streams, capture directory and active recordings, data feed sources) | + +Each tool carries MCP annotations: whether it only reads, whether it overwrites state rather than only adding to it, whether repeating it lands in the same place, and whether it reaches beyond this application, which covers commanding the radio and data received from transmitters SDRangel does not control. + +`describe_settings` returns the OpenAPI documentation of the settings, report and actions keys of a device, channel or feature type, so that an agent can learn the valid keys rather than guess them. The `set_*_settings` tools accept a partial settings object containing only the keys to change. + +`get_packets` returns the packets received on the `packets`, `ais` and `radiosonde` message pipes of the packet, ChirpChat, M17, Meshtastic, MeshCore, Inmarsat, AIS and radiosonde demodulators, kept in a buffer of the last 1000. Each packet carries the raw bytes and, where possible, a decode: AIS message type, MMSI, position, course and speed; AX.25 addresses and data with the APRS position and comment; RS41 serial, position and height. `get_map_items` returns the objects that the same channels and features that feed the Map send on the `mapitems` pipe (aircraft, ships, APRS stations, radiosondes, satellites, Sun and Moon, beacons), with the image, text and, on request, the track. Items are removed when their source removes them or is deleted. Both work whether or not a Map or AIS/APRS feature is present. + +`record_iq` records baseband IQ to an `.sdriq` file for a fixed number of seconds and returns the files written; `start_iq_recording` and `stop_iq_recording` do the same without a time limit for longer captures. Both work by adding a File Sink channel to the device set, so the recording has the offset and decimation the tools are given. `capture_audio` records the demodulated audio of a channel to a WAV file, and reports the sample rate, the peak level and whether the audio was silent, which tells an agent that a squelch is closed rather than that nothing is wrong. It works with demodulators that feed the Demod Analyzer, such as NFMDemod, AMDemod, SSBDemod, WFMDemod and BFMDemod. With `inline` true it also returns the audio as base64, as a mono 16 kHz copy, since MCP clients refuse a tool result over about a megabyte and ten seconds at 48 kHz would exceed that once encoded; the file keeps the full rate. Both blocking tools are capped at 30 seconds so they cannot hold an MCP client's connection open indefinitely. + +`get_receiving_guide` serves a hand written guide in `bandguide.md`: which demodulator and frequency to use for each signal SDRangel can receive, the minimum device sample rate that ADS-B, DAB and broadcast FM need, and the usual reasons nothing is received. Its frequencies come from the plugin readmes, and a test checks that every channel id it names is registered in the build. Edit that file to correct or extend it; it is compiled into the plugin, so re-run cmake after changing it. + +`list_docs` and `get_docs` serve the readme of every plugin registered in the running instance, and the GUI's own pages for what no plugin owns: the spectrum display (`spectrum`, with `spectrummarkers`, `spectrummeasurements` and `spectrumcalibration`), the main spectrum window, audio management, configurations, device user arguments and the transverter dialog. The readmes are compiled into this plugin at build time (re-run cmake after adding a plugin), converted to plain markdown with images removed, and matched to plugin ids by name; the GUI pages are listed in `CMakeLists.txt` and given their ids in `MCPDocs::addGuiDocs`. `get_docs` accepts a plugin id or its displayed name and an optional section heading, so an agent can read just the part it needs from a long document. + +

Event stream

+ +A client can be told when a resource changes instead of polling for it. An HTTP GET on the endpoint with `Accept: text/event-stream` opens a Server-Sent Events stream, and `resources/subscribe` asks for a resource on it. Updates arrive as `notifications/resources/updated`, at most once a second per resource so that a busy decoder cannot flood the stream. `sdrangel://instance`, `sdrangel://packets`, `sdrangel://map/items` and `sdrangel://deviceset/{index}` can be subscribed to; the other resources never change. + +`initialize` returns an `Mcp-Session-Id` header. A client that sends it back keeps its own subscriptions and stream, and can end them with an HTTP DELETE. Clients that ignore it share an anonymous session, which works fully for one client at a time. A client keeps one stream: opening a second replaces the first, so a notification is never delivered twice. That applies to clients that send no session id as well, since they already share the anonymous subscriptions. Sessions with no stream are dropped after a day idle, and at most 32 are kept, each with at most 32 subscriptions. Up to eight streams may be open at once, and a stream is closed after ten minutes so that a client which vanished without closing its connection cannot hold a thread forever; clients reconnect. + +

Resources

+ +| URI | Content | +|-----|---------| +| `sdrangel://instance` | Instance summary | +| `sdrangel://plugins/devices` | Available sampling devices | +| `sdrangel://plugins/channels` | Available channel types | +| `sdrangel://plugins/features` | Available feature types | +| `sdrangel://presets` | Saved presets | +| `sdrangel://configurations` | Saved configurations | +| `sdrangel://deviceset/{index}` | A device set | +| `sdrangel://schema/{type}` | Settings documentation for a type | +| `sdrangel://packets` | The 100 most recent decoded packets, from a buffer of the last 1000 | +| `sdrangel://map/items` | Objects currently plotted on the map | +| `sdrangel://guide` | The receiving guide | +| `sdrangel://docs` | Index of plugin and GUI documentation with section headings | +| `sdrangel://docs/{kind}/{id}` | A document as markdown, e.g. `sdrangel://docs/channel/ADSBDemod` or `sdrangel://docs/gui/spectrum` | + +

Prompts

+ +`setup_receiver`, `record_iq` and `explain_configuration` are prompt templates that guide an agent through common tasks. + +

Security

+ +The server has no access control beyond the optional bearer token, and an agent connected to it can change anything in SDRangel. Keep the address at 127.0.0.1 unless a token is set. + +To keep web pages from driving the server through a browser, requests carrying an `Origin` header are only accepted from an `http` or `https` localhost origin (the opaque `null` origin is rejected), and the request body must be declared as `application/json`. + diff --git a/plugins/feature/mcpserver/toolsdump.cpp b/plugins/feature/mcpserver/toolsdump.cpp index 0590c153f..65dbc0e43 100644 --- a/plugins/feature/mcpserver/toolsdump.cpp +++ b/plugins/feature/mcpserver/toolsdump.cpp @@ -1,83 +1,83 @@ -/////////////////////////////////////////////////////////////////////////////////// -// Copyright (C) 2026 Jon Beniston, M7RCE // -// Some code by AI // -// // -// This program is free software; you can redistribute it and/or modify // -// it under the terms of the GNU General Public License as published by // -// the Free Software Foundation as version 3 of the License, or // -// (at your option) any later version. // -// // -// This program is distributed in the hope that it will be useful, // -// but WITHOUT ANY WARRANTY; without even the implied warranty of // -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // -// GNU General Public License V3 for more details. // -// // -// You should have received a copy of the GNU General Public License // -// along with this program. If not, see . // -/////////////////////////////////////////////////////////////////////////////////// - -// Writes the MCP tool list to a file at build time, so that the Claude Desktop extension can -// carry the real list rather than inventing one. A client that starts before SDRangel reads -// the tool list once and does not ask again, so the bridge has to be able to answer with the -// tools this very build of the server provides, before it has ever spoken to it. -// -// The registry is metadata and handler functions: building it touches neither the Web API nor -// any device, so a null adapter is all it needs. - -#include -#include - -#ifdef _WIN32 -#include -#endif - -#include -#include -#include -#include - -#include "mcptools.h" - -int main(int argc, char *argv[]) -{ - QCoreApplication application(argc, argv); - - if (argc < 2) - { - std::fprintf(stderr, "usage: %s \n", argv[0]); - return 2; - } - - std::fprintf(stderr, "toolsdump: application up\n"); - MCPTools tools(nullptr); - std::fprintf(stderr, "toolsdump: registry built\n"); - - QJsonObject result; - result["tools"] = tools.listTools(); - std::fprintf(stderr, "toolsdump: listed\n"); - - QFile file(QString::fromLocal8Bit(argv[1])); - - if (!file.open(QIODevice::WriteOnly)) - { - std::fprintf(stderr, "cannot write %s: %s\n", argv[1], qPrintable(file.errorString())); - return 1; - } - - file.write(QJsonDocument(result).toJson(QJsonDocument::Compact)); - file.close(); - std::fprintf(stderr, "toolsdump: written\n"); - - std::fprintf(stderr, "%s: %d tools\n", argv[1], result["tools"].toArray().size()); - - // The registry brings background threads up with it and they do not all stop when main - // returns, which leaves the process, and so the build, hanging. Even _Exit does not get - // out, since the runtime's own teardown waits on them, so end the process from the kernel - // side. The file is written and flushed by this point - std::fflush(nullptr); - -#ifdef _WIN32 - TerminateProcess(GetCurrentProcess(), 0); -#endif - std::_Exit(0); -} +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// (at your option) any later version. // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +// Writes the MCP tool list to a file at build time, so that the Claude Desktop extension can +// carry the real list rather than inventing one. A client that starts before SDRangel reads +// the tool list once and does not ask again, so the bridge has to be able to answer with the +// tools this very build of the server provides, before it has ever spoken to it. +// +// The registry is metadata and handler functions: building it touches neither the Web API nor +// any device, so a null adapter is all it needs. + +#include +#include + +#ifdef _WIN32 +#include +#endif + +#include +#include +#include +#include + +#include "mcptools.h" + +int main(int argc, char *argv[]) +{ + QCoreApplication application(argc, argv); + + if (argc < 2) + { + std::fprintf(stderr, "usage: %s \n", argv[0]); + return 2; + } + + std::fprintf(stderr, "toolsdump: application up\n"); + MCPTools tools(nullptr); + std::fprintf(stderr, "toolsdump: registry built\n"); + + QJsonObject result; + result["tools"] = tools.listTools(); + std::fprintf(stderr, "toolsdump: listed\n"); + + QFile file(QString::fromLocal8Bit(argv[1])); + + if (!file.open(QIODevice::WriteOnly)) + { + std::fprintf(stderr, "cannot write %s: %s\n", argv[1], qPrintable(file.errorString())); + return 1; + } + + file.write(QJsonDocument(result).toJson(QJsonDocument::Compact)); + file.close(); + std::fprintf(stderr, "toolsdump: written\n"); + + std::fprintf(stderr, "%s: %d tools\n", argv[1], result["tools"].toArray().size()); + + // The registry brings background threads up with it and they do not all stop when main + // returns, which leaves the process, and so the build, hanging. Even _Exit does not get + // out, since the runtime's own teardown waits on them, so end the process from the kernel + // side. The file is written and flushed by this point + std::fflush(nullptr); + +#ifdef _WIN32 + TerminateProcess(GetCurrentProcess(), 0); +#endif + std::_Exit(0); +} diff --git a/plugins/feature/morsedecoder/morsedecoder.cpp b/plugins/feature/morsedecoder/morsedecoder.cpp index f5f3bb1b7..ba90b18aa 100644 --- a/plugins/feature/morsedecoder/morsedecoder.cpp +++ b/plugins/feature/morsedecoder/morsedecoder.cpp @@ -100,6 +100,7 @@ void MorseDecoder::start() qDebug("MorseDecoder::start"); m_thread = new QThread(); + m_thread->setObjectName("MorseDecoder"); m_worker = new MorseDecoderWorker(); m_worker->moveToThread(m_thread); diff --git a/plugins/feature/pertester/pertester.cpp b/plugins/feature/pertester/pertester.cpp index 1155bba05..82564bec6 100644 --- a/plugins/feature/pertester/pertester.cpp +++ b/plugins/feature/pertester/pertester.cpp @@ -77,6 +77,7 @@ void PERTester::start() qDebug("PERTester::start"); m_thread = new QThread(); + m_thread->setObjectName("PERTester"); m_worker = new PERTesterWorker(); m_worker->moveToThread(m_thread); diff --git a/plugins/feature/remotecontrol/remotecontrol.cpp b/plugins/feature/remotecontrol/remotecontrol.cpp index c3a5c5d46..638f73963 100644 --- a/plugins/feature/remotecontrol/remotecontrol.cpp +++ b/plugins/feature/remotecontrol/remotecontrol.cpp @@ -54,6 +54,7 @@ void RemoteControl::start() qDebug() << "RemoteControl::start"; m_thread = new QThread(); + m_thread->setObjectName("RemoteControl"); m_worker = new RemoteControlWorker(); m_worker->moveToThread(m_thread); diff --git a/plugins/feature/rigctlserver/rigctlserver.cpp b/plugins/feature/rigctlserver/rigctlserver.cpp index 332f7895a..87febeba8 100644 --- a/plugins/feature/rigctlserver/rigctlserver.cpp +++ b/plugins/feature/rigctlserver/rigctlserver.cpp @@ -43,6 +43,7 @@ RigCtlServer::RigCtlServer(WebAPIAdapterInterface *webAPIAdapterInterface) : { qDebug("RigCtlServer::RigCtlServer: webAPIAdapterInterface: %p", webAPIAdapterInterface); setObjectName(m_featureId); + m_thread.setObjectName("RigCtlServerBB"); m_worker = new RigCtlServerWorker(webAPIAdapterInterface); m_worker->moveToThread(&m_thread); setState(StIdle); diff --git a/plugins/feature/satellitetracker/satellitetracker.cpp b/plugins/feature/satellitetracker/satellitetracker.cpp index a82232e7f..d2908a673 100644 --- a/plugins/feature/satellitetracker/satellitetracker.cpp +++ b/plugins/feature/satellitetracker/satellitetracker.cpp @@ -90,6 +90,7 @@ void SatelliteTracker::start() } m_thread = new QThread(); + m_thread->setObjectName("SatTracker"); m_worker = new SatelliteTrackerWorker(this, m_webAPIAdapterInterface); m_worker->moveToThread(m_thread); diff --git a/plugins/feature/sid/icons/delta.svg b/plugins/feature/sid/icons/delta.svg index 53e96bb9b..4d8d96098 100644 --- a/plugins/feature/sid/icons/delta.svg +++ b/plugins/feature/sid/icons/delta.svg @@ -1,19 +1,19 @@ - - - - - - - - - - - - - - + + + + + + + + + + + + + + diff --git a/plugins/feature/sid/icons/gamma.svg b/plugins/feature/sid/icons/gamma.svg index 90de948d4..ce3cdad76 100644 --- a/plugins/feature/sid/icons/gamma.svg +++ b/plugins/feature/sid/icons/gamma.svg @@ -1,22 +1,22 @@ - - - - - - - - - - - - - - + + + + + + + + + + + + + + diff --git a/plugins/feature/sid/icons/proton.svg b/plugins/feature/sid/icons/proton.svg index fca02154c..9c9c50f24 100644 --- a/plugins/feature/sid/icons/proton.svg +++ b/plugins/feature/sid/icons/proton.svg @@ -1,37 +1,37 @@ - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/feature/sid/icons/solar-orbiter.svg b/plugins/feature/sid/icons/solar-orbiter.svg index 6c5373978..981e951b9 100644 --- a/plugins/feature/sid/icons/solar-orbiter.svg +++ b/plugins/feature/sid/icons/solar-orbiter.svg @@ -27,4 +27,4 @@ - \ No newline at end of file + diff --git a/plugins/feature/sid/icons/xlp.svg b/plugins/feature/sid/icons/xlp.svg index fb2d86505..2cc7fbd0d 100644 --- a/plugins/feature/sid/icons/xlp.svg +++ b/plugins/feature/sid/icons/xlp.svg @@ -1,45 +1,45 @@ - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/feature/sid/icons/xls.svg b/plugins/feature/sid/icons/xls.svg index 6f2fc9919..fb91cf5d2 100644 --- a/plugins/feature/sid/icons/xls.svg +++ b/plugins/feature/sid/icons/xls.svg @@ -1,53 +1,53 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/feature/sid/icons/xsp.svg b/plugins/feature/sid/icons/xsp.svg index e3cb553a1..f374d3ea1 100644 --- a/plugins/feature/sid/icons/xsp.svg +++ b/plugins/feature/sid/icons/xsp.svg @@ -1,48 +1,48 @@ - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/feature/sid/icons/xss.svg b/plugins/feature/sid/icons/xss.svg index adf398da0..8fa2f1b99 100644 --- a/plugins/feature/sid/icons/xss.svg +++ b/plugins/feature/sid/icons/xss.svg @@ -1,56 +1,56 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/feature/sid/sid.cpp b/plugins/feature/sid/sid.cpp index 7617b54ff..74ebc7d83 100644 --- a/plugins/feature/sid/sid.cpp +++ b/plugins/feature/sid/sid.cpp @@ -71,6 +71,7 @@ void SIDMain::start() { qDebug("SIDMain::start"); m_thread = new QThread(); + m_thread->setObjectName("SIDMain"); m_worker = new SIDWorker(this, m_webAPIAdapterInterface); m_worker->moveToThread(m_thread); QObject::connect(m_thread, &QThread::started, m_worker, &SIDWorker::startWork); diff --git a/plugins/feature/simpleptt/simpleptt.cpp b/plugins/feature/simpleptt/simpleptt.cpp index 5d991e3da..7faf0dff3 100644 --- a/plugins/feature/simpleptt/simpleptt.cpp +++ b/plugins/feature/simpleptt/simpleptt.cpp @@ -81,6 +81,7 @@ void SimplePTT::start() qDebug("SimplePTT::start"); m_thread = new QThread(); + m_thread->setObjectName("SimplePTT"); m_worker = new SimplePTTWorker(getWebAPIAdapterInterface()); m_worker->moveToThread(m_thread); diff --git a/plugins/feature/skymap/html/aladin.html b/plugins/feature/skymap/html/aladin.html index dbba8975b..4fd328901 100644 --- a/plugins/feature/skymap/html/aladin.html +++ b/plugins/feature/skymap/html/aladin.html @@ -1,101 +1,101 @@ - - - - SDRangel Aladin - - - - - -
- - - - + + + - - + } else { + console.log(`Unknown command ${command.command}`); + } + + } catch (e) { + console.log(`Erroring processing received message:\n${e}\n${event.data}`); + } + }; + + function createAntennaFoV() { + antennaOverlay = A.graphicOverlay({ color: '#ffffff', lineWidth: 1 }); + aladin.addOverlay(antennaOverlay); + const [ra, dec] = aladin.getRaDec(); + antennaCircle = A.circle(ra, dec, antennaHpbw); + antennaOverlay.add(antennaCircle); + } + + function showAntennaFoV() { + antennaCircle.show(); + } + + function hideAntennaFoV() { + antennaCircle.hide(); + } + + function reportReady() { + console.log("reportReady " + socket.readyState); + + createAntennaFoV(); + + if (socket.readyState === 1) { + socket.send(JSON.stringify({ + event: "ready" + })); + } else { + setTimeout(reportReady, 100); + } + } + + function reportView() { + if (socket.readyState === 1) { + const [ra, dec] = aladin.getRaDec(); + const [fovX, fovY] = aladin.getFov(); + socket.send(JSON.stringify({ + event: "view", + ra: ra / 15.0, // Convert RA from degrees to hours + dec: dec, + fov: fovX + })); + + antennaCircle.setCenter([ra, dec]); + } + } + + + + diff --git a/plugins/feature/startracker/spiceephemerides.cpp b/plugins/feature/startracker/spiceephemerides.cpp index 4b1e6fcec..883608f5e 100644 --- a/plugins/feature/startracker/spiceephemerides.cpp +++ b/plugins/feature/startracker/spiceephemerides.cpp @@ -144,4 +144,4 @@ QStringList SpiceEphemerides::getTargets(const QStringList &emphemeridesURLs) targets.removeDuplicates(); return targets; -} \ No newline at end of file +} diff --git a/plugins/feature/startracker/startracker.cpp b/plugins/feature/startracker/startracker.cpp index 94e38ea94..ebf16e9ea 100644 --- a/plugins/feature/startracker/startracker.cpp +++ b/plugins/feature/startracker/startracker.cpp @@ -106,6 +106,7 @@ void StarTracker::start() qDebug("StarTracker::start"); m_thread = new QThread(); + m_thread->setObjectName("StarTracker"); m_worker = new StarTrackerWorker(this, m_webAPIAdapterInterface); m_worker->moveToThread(m_thread); diff --git a/plugins/feature/vorlocalizer/vorlocalizer.cpp b/plugins/feature/vorlocalizer/vorlocalizer.cpp index 113d8ae3c..1398dea0d 100644 --- a/plugins/feature/vorlocalizer/vorlocalizer.cpp +++ b/plugins/feature/vorlocalizer/vorlocalizer.cpp @@ -99,6 +99,7 @@ void VORLocalizer::start() qDebug("VORLocalizer::start"); m_thread = new QThread(); + m_thread->setObjectName("VORLocalizer"); m_worker = new VorLocalizerWorker(getWebAPIAdapterInterface()); m_worker->moveToThread(m_thread); diff --git a/plugins/samplemimo/audiocatsiso/audiocatsiso.cpp b/plugins/samplemimo/audiocatsiso/audiocatsiso.cpp index 70d295ae1..f2f08092d 100644 --- a/plugins/samplemimo/audiocatsiso/audiocatsiso.cpp +++ b/plugins/samplemimo/audiocatsiso/audiocatsiso.cpp @@ -131,6 +131,7 @@ bool AudioCATSISO::startRx() audioDeviceManager->addAudioSource(&m_inputFifo, getInputMessageQueue(), m_rxAudioDeviceIndex); m_inputWorkerThread = new QThread(); + m_inputWorkerThread->setObjectName(QString("AudCATrx:%1").arg(m_rxAudioDeviceIndex)); m_inputWorker = new AudioCATInputWorker(&m_sampleMIFifo, &m_inputFifo); m_inputWorker->moveToThread(m_inputWorkerThread); @@ -147,6 +148,7 @@ bool AudioCATSISO::startRx() qDebug() << "AudioCATSISO::startRx: start CAT"; m_catWorkerThread = new QThread(); + m_catWorkerThread->setObjectName(QString("AudCATwk:%1").arg(m_rxAudioDeviceIndex)); m_catWorker = new AudioCATSISOCATWorker(); m_catWorker->moveToThread(m_catWorkerThread); @@ -193,6 +195,7 @@ bool AudioCATSISO::startTx() audioDeviceManager->addAudioSink(&m_outputFifo, getInputMessageQueue(), m_txAudioDeviceIndex); m_outputWorkerThread = new QThread(); + m_outputWorkerThread->setObjectName(QString("AudCATtx:%1").arg(m_txAudioDeviceIndex)); m_outputWorker = new AudioCATOutputWorker(&m_sampleMOFifo, &m_outputFifo); m_outputWorker->moveToThread(m_outputWorkerThread); diff --git a/plugins/samplemimo/bladerf2mimo/bladerf2mithread.cpp b/plugins/samplemimo/bladerf2mimo/bladerf2mithread.cpp index c88938886..d4f2df51b 100644 --- a/plugins/samplemimo/bladerf2mimo/bladerf2mithread.cpp +++ b/plugins/samplemimo/bladerf2mimo/bladerf2mithread.cpp @@ -31,6 +31,7 @@ BladeRF2MIThread::BladeRF2MIThread(struct bladerf* dev, QObject* parent) : m_fcPos(0), m_iqOrder(true) { + setObjectName("BladeRF2MI"); qDebug("BladeRF2MIThread::BladeRF2MIThread"); m_buf = new qint16[2*DeviceBladeRF2::blockSize*2]; diff --git a/plugins/samplemimo/bladerf2mimo/bladerf2mothread.cpp b/plugins/samplemimo/bladerf2mimo/bladerf2mothread.cpp index 4c9591e8b..365d2075a 100644 --- a/plugins/samplemimo/bladerf2mimo/bladerf2mothread.cpp +++ b/plugins/samplemimo/bladerf2mimo/bladerf2mothread.cpp @@ -28,6 +28,7 @@ BladeRF2MOThread::BladeRF2MOThread(struct bladerf* dev, QObject* parent) : m_log2Interp(0), m_fcPos(0) { + setObjectName("BladeRF2MO"); qDebug("BladeRF2MOThread::BladeRF2MOThread"); m_buf = new qint16[2*DeviceBladeRF2::blockSize*2]; } diff --git a/plugins/samplemimo/limesdrmimo/limesdrmithread.cpp b/plugins/samplemimo/limesdrmimo/limesdrmithread.cpp index c4d15861d..46e244a48 100644 --- a/plugins/samplemimo/limesdrmimo/limesdrmithread.cpp +++ b/plugins/samplemimo/limesdrmimo/limesdrmithread.cpp @@ -27,6 +27,7 @@ LimeSDRMIThread::LimeSDRMIThread(lms_stream_t* stream0, lms_stream_t* stream1, Q m_sampleFifo(nullptr), m_iqOrder(true) { + setObjectName("LimeSDRMI"); qDebug("LimeSDRMIThread::LimeSDRMIThread"); for (unsigned int i = 0; i < 2; i++) { diff --git a/plugins/samplemimo/plutosdrmimo/plutosdrmithread.cpp b/plugins/samplemimo/plutosdrmimo/plutosdrmithread.cpp index bcadfee9d..39c841579 100644 --- a/plugins/samplemimo/plutosdrmimo/plutosdrmithread.cpp +++ b/plugins/samplemimo/plutosdrmimo/plutosdrmithread.cpp @@ -29,6 +29,7 @@ PlutoSDRMIThread::PlutoSDRMIThread(DevicePlutoSDRBox* plutoBox, QObject* parent) m_fcPos(0), m_iqOrder(true) { + setObjectName("PlutoSDRMI"); qDebug("PlutoSDRMIThread::PlutoSDRMIThread"); m_buf[0] = new qint16[2*m_plutoSDRBlockSizeSamples]; m_buf[1] = new qint16[2*m_plutoSDRBlockSizeSamples]; diff --git a/plugins/samplemimo/plutosdrmimo/plutosdrmothread.cpp b/plugins/samplemimo/plutosdrmimo/plutosdrmothread.cpp index 7a2014e2c..baf7cebb0 100644 --- a/plugins/samplemimo/plutosdrmimo/plutosdrmothread.cpp +++ b/plugins/samplemimo/plutosdrmimo/plutosdrmothread.cpp @@ -29,6 +29,7 @@ PlutoSDRMOThread::PlutoSDRMOThread(DevicePlutoSDRBox* plutoBox, QObject* parent) m_log2Interp(0), m_fcPos(0) { + setObjectName("PlutoSDRMO"); qDebug("PlutoSDRMOThread::PlutoSDRMOThread"); m_buf[0] = new qint16[2*PlutoSDRMIMOSettings::m_plutoSDRBlockSizeSamples]; m_buf[1] = new qint16[2*PlutoSDRMIMOSettings::m_plutoSDRBlockSizeSamples]; diff --git a/plugins/samplemimo/testmi/testmi.cpp b/plugins/samplemimo/testmi/testmi.cpp index 7934a9eb6..8feade0e7 100644 --- a/plugins/samplemimo/testmi/testmi.cpp +++ b/plugins/samplemimo/testmi/testmi.cpp @@ -95,11 +95,13 @@ bool TestMI::startRx() qDebug("TestMI::startRx"); m_testSourceWorkers.push_back(new TestMIWorker(&m_sampleMIFifo, 0)); m_testSourceWorkerThreads.push_back(new QThread()); + m_testSourceWorkerThreads.back()->setObjectName("TestMI:0"); m_testSourceWorkers.back()->moveToThread(m_testSourceWorkerThreads.back()); m_testSourceWorkers.back()->setSamplerate(m_settings.m_streams[0].m_sampleRate); m_testSourceWorkers.push_back(new TestMIWorker(&m_sampleMIFifo, 1)); m_testSourceWorkerThreads.push_back(new QThread()); + m_testSourceWorkerThreads.back()->setObjectName("TestMI:1"); m_testSourceWorkers.back()->moveToThread(m_testSourceWorkerThreads.back()); m_testSourceWorkers.back()->setSamplerate(m_settings.m_streams[1].m_sampleRate); diff --git a/plugins/samplemimo/testmosync/testmosync.cpp b/plugins/samplemimo/testmosync/testmosync.cpp index b316b3c47..e8bd2f027 100644 --- a/plugins/samplemimo/testmosync/testmosync.cpp +++ b/plugins/samplemimo/testmosync/testmosync.cpp @@ -74,6 +74,7 @@ bool TestMOSync::startTx() qDebug("TestMOSync::startTx"); m_sinkWorkerThread = new QThread(); + m_sinkWorkerThread->setObjectName("TestMOSync"); m_sinkWorker = new TestMOSyncWorker(); m_sinkWorker->moveToThread(m_sinkWorkerThread); diff --git a/plugins/samplemimo/xtrxmimo/xtrxmithread.cpp b/plugins/samplemimo/xtrxmimo/xtrxmithread.cpp index 5080c3cac..060b0fe58 100644 --- a/plugins/samplemimo/xtrxmimo/xtrxmithread.cpp +++ b/plugins/samplemimo/xtrxmimo/xtrxmithread.cpp @@ -30,6 +30,7 @@ XTRXMIThread::XTRXMIThread(struct xtrx_dev *dev, QObject* parent) : m_sampleFifo(nullptr), m_iqOrder(true) { + setObjectName("XTRXMI"); qDebug("XTRXMIThread::XTRXMIThread"); for (unsigned int i = 0; i < 2; i++) { diff --git a/plugins/samplemimo/xtrxmimo/xtrxmothread.cpp b/plugins/samplemimo/xtrxmimo/xtrxmothread.cpp index dd011d06c..5ab258085 100644 --- a/plugins/samplemimo/xtrxmimo/xtrxmothread.cpp +++ b/plugins/samplemimo/xtrxmimo/xtrxmothread.cpp @@ -29,6 +29,7 @@ XTRXMOThread::XTRXMOThread(struct xtrx_dev *dev, QObject* parent) : m_dev(dev), m_sampleFifo(nullptr) { + setObjectName("XTRXMO"); qDebug("XTRXMOThread::XTRXMOThread"); m_buf = new qint16[2*DeviceXTRX::blockSize*2]; std::fill(m_buf, m_buf + 2*DeviceXTRX::blockSize*2, 0); diff --git a/plugins/samplesink/aaroniartsaoutput/aaroniartsaoutput.cpp b/plugins/samplesink/aaroniartsaoutput/aaroniartsaoutput.cpp index 1f556aa2d..383507d8b 100644 --- a/plugins/samplesink/aaroniartsaoutput/aaroniartsaoutput.cpp +++ b/plugins/samplesink/aaroniartsaoutput/aaroniartsaoutput.cpp @@ -93,6 +93,7 @@ bool AaroniaRTSAOutput::start() qDebug() << "AaroniaRTSAOutput::start"; m_workerThread = new QThread(); + m_workerThread->setObjectName("AaroniaRTSAOut"); m_worker = new AaroniaRTSAOutputWorker(&m_sampleSourceFifo); m_worker->moveToThread(m_workerThread); diff --git a/plugins/samplesink/audiooutput/audiooutput.cpp b/plugins/samplesink/audiooutput/audiooutput.cpp index 2978c1f5e..fd99ad57c 100644 --- a/plugins/samplesink/audiooutput/audiooutput.cpp +++ b/plugins/samplesink/audiooutput/audiooutput.cpp @@ -85,6 +85,7 @@ bool AudioOutput::start() audioDeviceManager->addAudioSink(&m_audioFifo, getInputMessageQueue(), m_audioDeviceIndex); m_workerThread = new QThread(); + m_workerThread->setObjectName("AudioOutput:wrk"); m_worker = new AudioOutputWorker(&m_sampleSourceFifo, &m_audioFifo); m_worker->moveToThread(m_workerThread); diff --git a/plugins/samplesink/bladerf1output/bladerf1outputthread.cpp b/plugins/samplesink/bladerf1output/bladerf1outputthread.cpp index 922bc7c46..6da2f40f8 100644 --- a/plugins/samplesink/bladerf1output/bladerf1outputthread.cpp +++ b/plugins/samplesink/bladerf1output/bladerf1outputthread.cpp @@ -30,6 +30,7 @@ Bladerf1OutputThread::Bladerf1OutputThread(struct bladerf* dev, SampleSourceFifo m_sampleFifo(sampleFifo), m_log2Interp(0) { + setObjectName("Bladerf1Output"); std::fill(m_buf, m_buf + 2*BLADERFOUTPUT_BLOCKSIZE, 0); } diff --git a/plugins/samplesink/bladerf2output/bladerf2outputthread.cpp b/plugins/samplesink/bladerf2output/bladerf2outputthread.cpp index 3869d3274..fd4f4c5d7 100644 --- a/plugins/samplesink/bladerf2output/bladerf2outputthread.cpp +++ b/plugins/samplesink/bladerf2output/bladerf2outputthread.cpp @@ -27,6 +27,7 @@ BladeRF2OutputThread::BladeRF2OutputThread(struct bladerf* dev, unsigned int nbT m_dev(dev), m_nbChannels(nbTxChannels) { + setObjectName("BladeRF2Output"); qDebug("BladeRF2OutputThread::BladeRF2OutputThread"); m_channels = new Channel[nbTxChannels]; m_buf = new qint16[2*DeviceBladeRF2::blockSize*nbTxChannels]; diff --git a/plugins/samplesink/fileoutput/fileoutput.cpp b/plugins/samplesink/fileoutput/fileoutput.cpp index f9544c0f2..f9a013805 100644 --- a/plugins/samplesink/fileoutput/fileoutput.cpp +++ b/plugins/samplesink/fileoutput/fileoutput.cpp @@ -49,6 +49,7 @@ FileOutput::FileOutput(DeviceAPI *deviceAPI) : m_deviceDescription("FileOutput"), m_masterTimer(deviceAPI->getMasterTimer()) { + m_fileOutputWorkerThread.setObjectName("FileOutputWrk"); m_deviceAPI->setNbSinkStreams(1); m_networkManager = new QNetworkAccessManager(); } diff --git a/plugins/samplesink/hackrfoutput/hackrfoutputthread.cpp b/plugins/samplesink/hackrfoutput/hackrfoutputthread.cpp index 82d3076e0..fd182ae62 100644 --- a/plugins/samplesink/hackrfoutput/hackrfoutputthread.cpp +++ b/plugins/samplesink/hackrfoutput/hackrfoutputthread.cpp @@ -30,6 +30,7 @@ HackRFOutputThread::HackRFOutputThread(hackrf_device* dev, SampleSourceFifo* sam m_log2Interp(0), m_fcPos(2) { + setObjectName("HackRFOutput"); std::fill(m_buf, m_buf + 2*HACKRF_BLOCKSIZE, 0); } diff --git a/plugins/samplesink/limesdroutput/limesdroutputthread.cpp b/plugins/samplesink/limesdroutput/limesdroutputthread.cpp index e7bb34219..f07901fb3 100644 --- a/plugins/samplesink/limesdroutput/limesdroutputthread.cpp +++ b/plugins/samplesink/limesdroutput/limesdroutputthread.cpp @@ -29,6 +29,7 @@ LimeSDROutputThread::LimeSDROutputThread(lms_stream_t* stream, SampleSourceFifo* m_sampleFifo(sampleFifo), m_log2Interp(0) { + setObjectName("LimeSDROutput"); std::fill(m_buf, m_buf + 2*DeviceLimeSDR::blockSize, 0); } diff --git a/plugins/samplesink/plutosdroutput/plutosdroutputthread.cpp b/plugins/samplesink/plutosdroutput/plutosdroutputthread.cpp index 6fe5a5e30..0b2edd286 100644 --- a/plugins/samplesink/plutosdroutput/plutosdroutputthread.cpp +++ b/plugins/samplesink/plutosdroutput/plutosdroutputthread.cpp @@ -27,6 +27,7 @@ PlutoSDROutputThread::PlutoSDROutputThread(uint32_t blocksizeSamples, DevicePlut m_sampleFifo(sampleFifo), m_log2Interp(0) { + setObjectName("PlutoSDROutput"); m_buf = new qint16[blocksizeSamples*2]; } diff --git a/plugins/samplesink/remoteoutput/remoteoutput.cpp b/plugins/samplesink/remoteoutput/remoteoutput.cpp index e39eb9218..34a22ae8b 100644 --- a/plugins/samplesink/remoteoutput/remoteoutput.cpp +++ b/plugins/samplesink/remoteoutput/remoteoutput.cpp @@ -50,6 +50,7 @@ RemoteOutput::RemoteOutput(DeviceAPI *deviceAPI) : m_settings(), m_masterTimer(deviceAPI->getMasterTimer()) { + m_remoteOutputWorkerThread.setObjectName("RemoteOutputWrk"); m_deviceAPI->setNbSinkStreams(1); m_networkManager = new QNetworkAccessManager(); QObject::connect( diff --git a/plugins/samplesink/remoteoutput/udpsinkfec.cpp b/plugins/samplesink/remoteoutput/udpsinkfec.cpp index 2de770f08..4f9b40b9c 100644 --- a/plugins/samplesink/remoteoutput/udpsinkfec.cpp +++ b/plugins/samplesink/remoteoutput/udpsinkfec.cpp @@ -46,6 +46,7 @@ UDPSinkFEC::UDPSinkFEC() : m_currentMetaFEC.init(); m_senderThread = new QThread(this); + m_senderThread->setObjectName("UDPSinkFEC"); m_remoteOutputSender = new RemoteOutputSender(); m_remoteOutputSender->moveToThread(m_senderThread); } diff --git a/plugins/samplesink/soapysdroutput/soapysdroutputthread.cpp b/plugins/samplesink/soapysdroutput/soapysdroutputthread.cpp index 24663b40d..091d37457 100644 --- a/plugins/samplesink/soapysdroutput/soapysdroutputthread.cpp +++ b/plugins/samplesink/soapysdroutput/soapysdroutputthread.cpp @@ -36,6 +36,7 @@ SoapySDROutputThread::SoapySDROutputThread(SoapySDR::Device* dev, unsigned int n m_errors(0), m_consecutiveErrors(0) { + setObjectName("SoapySDROutput"); qDebug("SoapySDROutputThread::SoapySDROutputThread"); m_channels = new Channel[nbTxChannels]; } diff --git a/plugins/samplesink/testsink/testsinkoutput.cpp b/plugins/samplesink/testsink/testsinkoutput.cpp index 0fc27f2ed..51dab516b 100644 --- a/plugins/samplesink/testsink/testsinkoutput.cpp +++ b/plugins/samplesink/testsink/testsinkoutput.cpp @@ -72,6 +72,7 @@ bool TestSinkOutput::start() qDebug() << "TestSinkOutput::start"; m_testSinkWorkerThread = new QThread(); + m_testSinkWorkerThread->setObjectName("TestSinkOutput"); m_testSinkWorker = new TestSinkWorker(&m_sampleSourceFifo); m_testSinkWorker->moveToThread(m_testSinkWorkerThread); diff --git a/plugins/samplesink/usrpoutput/usrpoutputthread.cpp b/plugins/samplesink/usrpoutput/usrpoutputthread.cpp index 2c9bcc20e..ceac5c6f4 100644 --- a/plugins/samplesink/usrpoutput/usrpoutputthread.cpp +++ b/plugins/samplesink/usrpoutput/usrpoutputthread.cpp @@ -36,6 +36,7 @@ USRPOutputThread::USRPOutputThread(uhd::tx_streamer::sptr stream, size_t bufSamp m_sampleFifo(sampleFifo), m_log2Interp(0) { + setObjectName("USRPOutput"); // *2 as samples are I+Q m_buf = new qint16[2 * bufSamples]; std::fill(m_buf, m_buf + 2 * bufSamples, 0); diff --git a/plugins/samplesink/xtrxoutput/xtrxoutputthread.cpp b/plugins/samplesink/xtrxoutput/xtrxoutputthread.cpp index ce9adc4b8..9f92e91c0 100644 --- a/plugins/samplesink/xtrxoutput/xtrxoutputthread.cpp +++ b/plugins/samplesink/xtrxoutput/xtrxoutputthread.cpp @@ -31,6 +31,7 @@ XTRXOutputThread::XTRXOutputThread(struct xtrx_dev *dev, unsigned int nbChannels m_nbChannels(nbChannels), m_uniqueChannelIndex(uniqueChannelIndex) { + setObjectName("XTRXOutput"); qDebug("XTRXOutputThread::XTRXOutputThread: nbChannels: %u uniqueChannelIndex: %u", nbChannels, uniqueChannelIndex); m_channels = new Channel[2]; } diff --git a/plugins/samplesource/aaroniartsainput/aaroniartsainput.cpp b/plugins/samplesource/aaroniartsainput/aaroniartsainput.cpp index 93ed2382c..c5383c59f 100644 --- a/plugins/samplesource/aaroniartsainput/aaroniartsainput.cpp +++ b/plugins/samplesource/aaroniartsainput/aaroniartsainput.cpp @@ -101,6 +101,7 @@ bool AaroniaRTSAInput::start() } m_aaroniaRTSAWorkerThread = new QThread(); + m_aaroniaRTSAWorkerThread->setObjectName("AaroniaRTSAIn"); m_aaroniaRTSAWorker = new AaroniaRTSAInputWorker(&m_sampleFifo); m_aaroniaRTSAWorker->setInputMessageQueue(getInputMessageQueue()); m_aaroniaRTSAWorker->moveToThread(m_aaroniaRTSAWorkerThread); diff --git a/plugins/samplesource/airspy/airspyinput.cpp b/plugins/samplesource/airspy/airspyinput.cpp index 2941db548..97677a3d8 100644 --- a/plugins/samplesource/airspy/airspyinput.cpp +++ b/plugins/samplesource/airspy/airspyinput.cpp @@ -206,6 +206,7 @@ bool AirspyInput::start() } m_airspyWorkerThread = new QThread(); + m_airspyWorkerThread->setObjectName("AirspyInput"); m_airspyWorker = new AirspyWorker(m_dev, &m_sampleFifo); m_airspyWorker->moveToThread(m_airspyWorkerThread); diff --git a/plugins/samplesource/airspyhf/airspyhfinput.cpp b/plugins/samplesource/airspyhf/airspyhfinput.cpp index d8c8e6aa4..592026dd0 100644 --- a/plugins/samplesource/airspyhf/airspyhfinput.cpp +++ b/plugins/samplesource/airspyhf/airspyhfinput.cpp @@ -180,6 +180,7 @@ bool AirspyHFInput::start() } m_airspyHFWorkerThread = new QThread(); + m_airspyHFWorkerThread->setObjectName("AirspyHFInput"); m_airspyHFWorker = new AirspyHFWorker(m_dev, &m_sampleFifo, &m_replayBuffer); m_airspyHFWorker->moveToThread(m_airspyHFWorkerThread); int sampleRateIndex = m_settings.m_devSampleRateIndex; diff --git a/plugins/samplesource/androidsdrdriverinput/androidsdrdriverinput.cpp b/plugins/samplesource/androidsdrdriverinput/androidsdrdriverinput.cpp index 7b1647fde..7dad3df00 100644 --- a/plugins/samplesource/androidsdrdriverinput/androidsdrdriverinput.cpp +++ b/plugins/samplesource/androidsdrdriverinput/androidsdrdriverinput.cpp @@ -49,6 +49,7 @@ AndroidSDRDriverInput::AndroidSDRDriverInput(DeviceAPI *deviceAPI) : m_androidSDRDriverInputTCPPHandler(nullptr), m_deviceDescription("AndroidSDRDriverInput") { + m_thread.setObjectName("AndroidSDRBB"); m_sampleFifo.setLabel(m_deviceDescription); m_sampleFifo.setSize(48000 * 8); m_androidSDRDriverInputTCPPHandler = new AndroidSDRDriverInputTCPHandler(&m_sampleFifo, m_deviceAPI); diff --git a/plugins/samplesource/audioinput/audioinput.cpp b/plugins/samplesource/audioinput/audioinput.cpp index ca0e8744c..7c0d81934 100644 --- a/plugins/samplesource/audioinput/audioinput.cpp +++ b/plugins/samplesource/audioinput/audioinput.cpp @@ -107,6 +107,7 @@ bool AudioInput::start() audioDeviceManager->addAudioSource(&m_fifo, getInputMessageQueue(), m_audioDeviceIndex); m_workerThread = new QThread(); + m_workerThread->setObjectName("AudioInput"); m_worker = new AudioInputWorker(&m_sampleFifo, &m_fifo); m_worker->moveToThread(m_workerThread); diff --git a/plugins/samplesource/bladerf1input/bladerf1inputthread.cpp b/plugins/samplesource/bladerf1input/bladerf1inputthread.cpp index 58d393d0b..eff99ae50 100644 --- a/plugins/samplesource/bladerf1input/bladerf1inputthread.cpp +++ b/plugins/samplesource/bladerf1input/bladerf1inputthread.cpp @@ -37,6 +37,7 @@ Bladerf1InputThread::Bladerf1InputThread(struct bladerf* dev, SampleSinkFifo* sa m_fcPos(0), m_iqOrder(true) { + setObjectName("Bladerf1Input"); std::fill(m_buf, m_buf + 2*BLADERF_BLOCKSIZE, 0); } diff --git a/plugins/samplesource/bladerf2input/bladerf2inputthread.cpp b/plugins/samplesource/bladerf2input/bladerf2inputthread.cpp index 34ba363fb..36b77b346 100644 --- a/plugins/samplesource/bladerf2input/bladerf2inputthread.cpp +++ b/plugins/samplesource/bladerf2input/bladerf2inputthread.cpp @@ -26,6 +26,7 @@ BladeRF2InputThread::BladeRF2InputThread(struct bladerf* dev, unsigned int nbRxC m_nbChannels(nbRxChannels), m_iqOrder(true) { + setObjectName("BladeRF2Input"); qDebug("BladeRF2InputThread::BladeRF2InputThread"); m_channels = new Channel[nbRxChannels]; diff --git a/plugins/samplesource/fcdpro/fcdprothread.cpp b/plugins/samplesource/fcdpro/fcdprothread.cpp index a3c16600d..1438b15c5 100644 --- a/plugins/samplesource/fcdpro/fcdprothread.cpp +++ b/plugins/samplesource/fcdpro/fcdprothread.cpp @@ -40,6 +40,7 @@ FCDProThread::FCDProThread(SampleSinkFifo* sampleFifo, AudioFifo *fcdFIFO, QObje m_convertBuffer(fcd_traits::convBufSize), m_sampleFifo(sampleFifo) { + setObjectName("FCDPro"); start(); } diff --git a/plugins/samplesource/fcdproplus/fcdproplusthread.cpp b/plugins/samplesource/fcdproplus/fcdproplusthread.cpp index 072f74005..3de662d46 100644 --- a/plugins/samplesource/fcdproplus/fcdproplusthread.cpp +++ b/plugins/samplesource/fcdproplus/fcdproplusthread.cpp @@ -40,6 +40,7 @@ FCDProPlusThread::FCDProPlusThread(SampleSinkFifo* sampleFifo, AudioFifo *fcdFIF m_convertBuffer(fcd_traits::convBufSize), m_sampleFifo(sampleFifo) { + setObjectName("FCDProPlus"); start(); } diff --git a/plugins/samplesource/fileinput/fileinput.cpp b/plugins/samplesource/fileinput/fileinput.cpp index eca61566e..4f1113aad 100644 --- a/plugins/samplesource/fileinput/fileinput.cpp +++ b/plugins/samplesource/fileinput/fileinput.cpp @@ -64,6 +64,7 @@ FileInput::FileInput(DeviceAPI *deviceAPI) : m_recordLengthMuSec(0), m_startingTimeStamp(0) { + m_fileInputWorkerThread.setObjectName("FileInputWrk"); m_sampleFifo.setLabel(m_deviceDescription); m_deviceAPI->setNbSourceStreams(1); qDebug("FileInput::FileInput: device source engine: %p", m_deviceAPI->getDeviceSourceEngine()); diff --git a/plugins/samplesource/fobos/fobosinput.cpp b/plugins/samplesource/fobos/fobosinput.cpp index 291d857ba..b043d4cf7 100644 --- a/plugins/samplesource/fobos/fobosinput.cpp +++ b/plugins/samplesource/fobos/fobosinput.cpp @@ -125,6 +125,7 @@ bool FOBOSInput::start() } m_workerThread = new QThread(); + m_workerThread->setObjectName("FOBOSInput"); m_worker = new FOBOSWorker(&m_sampleFifo); m_worker->moveToThread(m_workerThread); diff --git a/plugins/samplesource/hackrfinput/hackrfinputthread.cpp b/plugins/samplesource/hackrfinput/hackrfinputthread.cpp index 54d27c870..2fb18f13d 100644 --- a/plugins/samplesource/hackrfinput/hackrfinputthread.cpp +++ b/plugins/samplesource/hackrfinput/hackrfinputthread.cpp @@ -34,6 +34,7 @@ HackRFInputThread::HackRFInputThread(hackrf_device* dev, SampleSinkFifo* sampleF m_fcPos(0), m_iqOrder(true) { + setObjectName("HackRFInput"); std::fill(m_buf, m_buf + 2*HACKRF_BLOCKSIZE, 0); } diff --git a/plugins/samplesource/kiwisdr/kiwisdrinput.cpp b/plugins/samplesource/kiwisdr/kiwisdrinput.cpp index 8aec9769c..702359d7a 100644 --- a/plugins/samplesource/kiwisdr/kiwisdrinput.cpp +++ b/plugins/samplesource/kiwisdr/kiwisdrinput.cpp @@ -103,6 +103,7 @@ bool KiwiSDRInput::start() } m_kiwiSDRWorkerThread = new QThread(); + m_kiwiSDRWorkerThread->setObjectName("KiwiSDRInput"); m_kiwiSDRWorker = new KiwiSDRWorker(&m_sampleFifo); m_kiwiSDRWorker->setInputMessageQueue(getInputMessageQueue()); m_kiwiSDRWorker->moveToThread(m_kiwiSDRWorkerThread); diff --git a/plugins/samplesource/perseus/perseusinput.cpp b/plugins/samplesource/perseus/perseusinput.cpp index fb27c2715..a5367533a 100644 --- a/plugins/samplesource/perseus/perseusinput.cpp +++ b/plugins/samplesource/perseus/perseusinput.cpp @@ -88,6 +88,7 @@ bool PerseusInput::start() // start / stop streaming is done in the thread. m_perseusWorkerThread = new QThread(); + m_perseusWorkerThread->setObjectName("PerseusInput"); m_perseusWorker = new PerseusWorker(m_perseusDescriptor, &m_sampleFifo); m_perseusWorker->moveToThread(m_perseusWorkerThread); qDebug("PerseusInput::start: worker created"); diff --git a/plugins/samplesource/plutosdrinput/plutosdrinputthread.cpp b/plugins/samplesource/plutosdrinput/plutosdrinputthread.cpp index 2a38ed5c5..05bfc61ad 100644 --- a/plugins/samplesource/plutosdrinput/plutosdrinputthread.cpp +++ b/plugins/samplesource/plutosdrinput/plutosdrinputthread.cpp @@ -33,6 +33,7 @@ PlutoSDRInputThread::PlutoSDRInputThread(uint32_t blocksizeSamples, DevicePlutoS m_phasor(0), m_iqOrder(true) { + setObjectName("PlutoSDRInput"); m_buf = new qint16[blocksizeSamples*2]; // (I,Q) -> 2 * int16_t m_bufConv = new qint16[blocksizeSamples*2]; // (I,Q) -> 2 * int16_t } diff --git a/plugins/samplesource/remotetcpinput/remotetcpinput.cpp b/plugins/samplesource/remotetcpinput/remotetcpinput.cpp index 9b90f0fad..5f1c9d894 100644 --- a/plugins/samplesource/remotetcpinput/remotetcpinput.cpp +++ b/plugins/samplesource/remotetcpinput/remotetcpinput.cpp @@ -58,6 +58,7 @@ RemoteTCPInput::RemoteTCPInput(DeviceAPI *deviceAPI) : m_azimuth(std::numeric_limits::quiet_NaN()), m_elevation(std::numeric_limits::quiet_NaN()) { + m_thread.setObjectName("RemoteTCPInBB"); m_sampleFifo.setLabel(m_deviceDescription); m_sampleFifo.setSize(48000 * 8); m_remoteInputTCPPHandler = new RemoteTCPInputTCPHandler(&m_sampleFifo, m_deviceAPI, &m_replayBuffer); diff --git a/plugins/samplesource/rtlsdr/rtlsdrthread.cpp b/plugins/samplesource/rtlsdr/rtlsdrthread.cpp index db1cc1eec..a4c0a05ff 100644 --- a/plugins/samplesource/rtlsdr/rtlsdrthread.cpp +++ b/plugins/samplesource/rtlsdr/rtlsdrthread.cpp @@ -38,6 +38,7 @@ RTLSDRThread::RTLSDRThread(rtlsdr_dev_t* dev, SampleSinkFifo* sampleFifo, Replay m_sampleFifo(sampleFifo), m_replayBuffer(replayBuffer) { + setObjectName("RTLSDR"); applySettings(settings, QStringList(), true); connect(&m_inputMessageQueue, &MessageQueue::messageEnqueued, this, &RTLSDRThread::handleInputMessages); } diff --git a/plugins/samplesource/sdrplay/sdrplaythread.cpp b/plugins/samplesource/sdrplay/sdrplaythread.cpp index ce35a8baa..e47b1ff35 100644 --- a/plugins/samplesource/sdrplay/sdrplaythread.cpp +++ b/plugins/samplesource/sdrplay/sdrplaythread.cpp @@ -31,6 +31,7 @@ SDRPlayThread::SDRPlayThread(mirisdr_dev_t* dev, SampleSinkFifo* sampleFifo, QOb m_fcPos(0), m_iqOrder(true) { + setObjectName("SDRPlay"); } SDRPlayThread::~SDRPlayThread() diff --git a/plugins/samplesource/sigmffileinput/sigmffileinput.cpp b/plugins/samplesource/sigmffileinput/sigmffileinput.cpp index d4a893cb9..f307dc75c 100644 --- a/plugins/samplesource/sigmffileinput/sigmffileinput.cpp +++ b/plugins/samplesource/sigmffileinput/sigmffileinput.cpp @@ -64,6 +64,7 @@ SigMFFileInput::SigMFFileInput(DeviceAPI *deviceAPI) : m_settings() { m_sampleFifo.setLabel(m_deviceDescription); + m_fileInputWorkerThread.setObjectName("SigMFInputWrk"); m_deviceAPI->setNbSourceStreams(1); qDebug("SigMFFileInput::SigMFFileInput: device source engine: %p", m_deviceAPI->getDeviceSourceEngine()); qDebug("SigMFFileInput::SigMFFileInput: device source engine message queue: %p", m_deviceAPI->getDeviceEngineInputMessageQueue()); diff --git a/plugins/samplesource/soapysdrinput/soapysdrinputthread.cpp b/plugins/samplesource/soapysdrinput/soapysdrinputthread.cpp index a1296c7d3..1b0aa839c 100644 --- a/plugins/samplesource/soapysdrinput/soapysdrinputthread.cpp +++ b/plugins/samplesource/soapysdrinput/soapysdrinputthread.cpp @@ -36,6 +36,7 @@ SoapySDRInputThread::SoapySDRInputThread(SoapySDR::Device* dev, unsigned int nbR m_decimatorType(DecimatorFloat), m_iqOrder(true) { + setObjectName("SoapySDRInput"); qDebug("SoapySDRInputThread::SoapySDRInputThread"); m_channels = new Channel[nbRxChannels]; } diff --git a/plugins/samplesource/testsource/testsourceinput.cpp b/plugins/samplesource/testsource/testsourceinput.cpp index 488d7c25c..0141a8577 100644 --- a/plugins/samplesource/testsource/testsourceinput.cpp +++ b/plugins/samplesource/testsource/testsourceinput.cpp @@ -98,6 +98,7 @@ bool TestSourceInput::start() } m_testSourceWorkerThread = new QThread(); + m_testSourceWorkerThread->setObjectName("TestSourceInput"); m_testSourceWorker = new TestSourceWorker(&m_sampleFifo); m_testSourceWorker->moveToThread(m_testSourceWorkerThread); diff --git a/plugins/samplesource/usrpinput/usrpinputthread.cpp b/plugins/samplesource/usrpinput/usrpinputthread.cpp index 5a5209109..aea4a2f74 100644 --- a/plugins/samplesource/usrpinput/usrpinputthread.cpp +++ b/plugins/samplesource/usrpinput/usrpinputthread.cpp @@ -39,6 +39,7 @@ USRPInputThread::USRPInputThread(uhd::rx_streamer::sptr stream, size_t bufSample m_replayBuffer(replayBuffer), m_log2Decim(0) { + setObjectName("USRPInput"); // *2 as samples are I+Q m_buf = new qint16[2*bufSamples]; std::fill(m_buf, m_buf + 2*bufSamples, 0); diff --git a/plugins/samplesource/xtrxinput/xtrxinputthread.cpp b/plugins/samplesource/xtrxinput/xtrxinputthread.cpp index de1ee8071..c93c7a3ba 100644 --- a/plugins/samplesource/xtrxinput/xtrxinputthread.cpp +++ b/plugins/samplesource/xtrxinput/xtrxinputthread.cpp @@ -31,6 +31,7 @@ XTRXInputThread::XTRXInputThread(struct xtrx_dev *dev, unsigned int nbChannels, m_uniqueChannelIndex(uniqueChannelIndex), m_iqOrder(true) { + setObjectName("XTRXInput"); qDebug("XTRXInputThread::XTRXInputThread: nbChannels: %u uniqueChannelIndex: %u", nbChannels, uniqueChannelIndex); m_channels = new Channel[2]; diff --git a/scriptsapi/requirements.txt b/scriptsapi/requirements.txt index 836866ef8..4ee2b5db6 100644 --- a/scriptsapi/requirements.txt +++ b/scriptsapi/requirements.txt @@ -3,4 +3,4 @@ Flask numpy websockets websocket-client -mock \ No newline at end of file +mock diff --git a/sdrbase/audio/audiodevicemanager.cpp b/sdrbase/audio/audiodevicemanager.cpp index 97414ce79..e89a95ba0 100644 --- a/sdrbase/audio/audiodevicemanager.cpp +++ b/sdrbase/audio/audiodevicemanager.cpp @@ -290,6 +290,7 @@ void AudioDeviceManager::addAudioSink(AudioFifo* audioFifo, MessageQueue *sample if (m_audioOutputs.find(outputDeviceIndex) == m_audioOutputs.end()) { QThread *thread = new QThread(); + thread->setObjectName(QString("AudioOut:%1").arg(outputDeviceIndex)); AudioOutputDevice *audioOutputDevice = new AudioOutputDevice(); m_audioOutputs[outputDeviceIndex] = audioOutputDevice; m_audioOutputThreads[outputDeviceIndex] = thread; @@ -383,6 +384,7 @@ void AudioDeviceManager::addAudioSource(AudioFifo* audioFifo, MessageQueue *samp if (m_audioInputs.find(inputDeviceIndex) == m_audioInputs.end()) { QThread *thread = new QThread(); + thread->setObjectName(QString("AudioIn:%1").arg(inputDeviceIndex)); AudioInputDevice *audioInputDevice = new AudioInputDevice(); m_audioInputs[inputDeviceIndex] = audioInputDevice; m_audioInputThreads[inputDeviceIndex] = thread; diff --git a/sdrbase/dsp/spectrumvis.h b/sdrbase/dsp/spectrumvis.h index e11ef2bb0..325402d90 100644 --- a/sdrbase/dsp/spectrumvis.h +++ b/sdrbase/dsp/spectrumvis.h @@ -207,7 +207,7 @@ public: int webapiSpectrumDataGet(int bins, qint64 startFrequency, qint64 stopFrequency, const QString& reduce, SWGSDRangel::SWGGLSpectrumData& response, QString& errorMessage) const; - static const int m_maxDataBins = 4096; //!< A reduced spectrum any larger is not a summary + static constexpr int m_maxDataBins = 4096; //!< A reduced spectrum any larger is not a summary //!< Statistics over the spectrum history the display keeps for scrolling: per bin max, mean //!< and occupancy, and the signals found. thresholdDb is above the measured floor @@ -216,7 +216,7 @@ public: //!< The same history as a greyscale PNG, newest row at the bottom, bins wide and one row per pixel up to maxRows int webapiSpectrumHistoryImageGet(double seconds, int bins, qint64 startFrequency, qint64 stopFrequency, int maxRows, QByteArray& png, QJsonObject& description, QString& errorMessage) const; - static const int m_maxHistoryRows = 4000; + static constexpr int m_maxHistoryRows = 4000; private: struct ReducedHistory; diff --git a/sdrbase/pipes/datapipes.cpp b/sdrbase/pipes/datapipes.cpp index 749dc44ea..0406e9539 100644 --- a/sdrbase/pipes/datapipes.cpp +++ b/sdrbase/pipes/datapipes.cpp @@ -23,6 +23,7 @@ DataPipes::DataPipes() : m_registrations(&m_dataFifoStore) { + m_gcThread.setObjectName("DataPipes:gc"); m_gcWorker = new DataPipesGCWorker(m_registrations); m_gcWorker->moveToThread(&m_gcThread); startGC(); diff --git a/sdrbase/pipes/messagepipes.cpp b/sdrbase/pipes/messagepipes.cpp index 1d3146d0d..9a469757f 100644 --- a/sdrbase/pipes/messagepipes.cpp +++ b/sdrbase/pipes/messagepipes.cpp @@ -23,6 +23,7 @@ MessagePipes::MessagePipes() : m_registrations(&m_messageQueueStore) { + m_gcThread.setObjectName("MessagePipes:gc"); m_gcWorker = new MessagePipesGCWorker(m_registrations); m_gcWorker->moveToThread(&m_gcThread); startGC(); diff --git a/sdrbase/pipes/messagepipeslegacy.cpp b/sdrbase/pipes/messagepipeslegacy.cpp index a563efcb3..220faaf4d 100644 --- a/sdrbase/pipes/messagepipeslegacy.cpp +++ b/sdrbase/pipes/messagepipeslegacy.cpp @@ -26,6 +26,7 @@ MessagePipesLegacy::MessagePipesLegacy() { + m_gcThread.setObjectName("LgcyMsgPipe:gc"); m_gcWorker = new MessagePipesLegacyGCWorker(); m_gcWorker->setC2FRegistrations( m_registrations.getMutex(), diff --git a/sdrbase/resources/webapi/index.html b/sdrbase/resources/webapi/index.html index a64e4c92d..65b017f78 100644 --- a/sdrbase/resources/webapi/index.html +++ b/sdrbase/resources/webapi/index.html @@ -49,4 +49,4 @@

Click on links on the left for various types of documentation

- \ No newline at end of file + diff --git a/sdrgui/gui/checklist.cpp b/sdrgui/gui/checklist.cpp index 419599523..89b00f295 100644 --- a/sdrgui/gui/checklist.cpp +++ b/sdrgui/gui/checklist.cpp @@ -1,172 +1,172 @@ -#include "checklist.h" - -CheckList::CheckList(QWidget* parent) : - QComboBox(parent) -{ - m_model = new QStandardItemModel(); - setModel(m_model); - - setEditable(true); - lineEdit()->setReadOnly(true); - lineEdit()->installEventFilter(this); - setItemDelegate(new QCheckListStyledItemDelegate(this)); - - connect(lineEdit(), &QLineEdit::selectionChanged, lineEdit(), &QLineEdit::deselect); - connect((QListView*) view(), SIGNAL(pressed(QModelIndex)), this, SLOT(on_itemPressed(QModelIndex))); - connect(m_model, SIGNAL(dataChanged(QModelIndex, QModelIndex, QVector)), this, SLOT(on_modelDataChanged())); -} - -CheckList::~CheckList() -{ - delete m_model; -} - -void CheckList::setText(const QString &text) -{ - m_text = text; - updateText(); -} - -void CheckList::setAllCheckedText(const QString &text) -{ - m_allCheckedText = text; - updateText(); -} - -void CheckList::setNoneCheckedText(const QString &text) -{ - m_noneCheckedText = text; - updateText(); -} - -void CheckList::setUnknownlyCheckedText(const QString &text) -{ - m_unknownlyCheckedText = text; - updateText(); -} - -void CheckList::setSortRole(int role) -{ - m_model->setSortRole(role); -} - -QStandardItem* CheckList::addCheckItem(const QString &label, const QVariant &data, const Qt::CheckState checkState) -{ - QStandardItem* item = new QStandardItem(label); - item->setCheckState(checkState); - item->setData(data); - item->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled); - - m_model->appendRow(item); - - updateText(); - - return item; -} - -int CheckList::globalCheckState() -{ - int nbRows = m_model->rowCount(), nbChecked = 0, nbUnchecked = 0; - - if (nbRows == 0) - { - return StateUnknown; - } - - for (int i = 0; i < nbRows; i++) - { - if (m_model->item(i)->checkState() == Qt::Checked) - { - nbChecked++; - } - else if (m_model->item(i)->checkState() == Qt::Unchecked) - { - nbUnchecked++; - } - else - { - return StateUnknown; - } - } - - return nbChecked == nbRows ? Qt::Checked : nbUnchecked == nbRows ? Qt::Unchecked : Qt::PartiallyChecked; -} - -bool CheckList::eventFilter(QObject* _object, QEvent* _event) -{ - if (_object == lineEdit() && _event->type() == QEvent::MouseButtonPress) - { - showPopup(); - return true; - } - - return false; -} - -void CheckList::updateText() -{ - QString text; - - if (m_text.isEmpty()) - { - switch (globalCheckState()) - { - case Qt::Checked: - text = m_allCheckedText; - break; - - case Qt::Unchecked: - text = m_noneCheckedText; - break; - - case Qt::PartiallyChecked: - for (int i = 0; i < m_model->rowCount(); i++) - { - if (m_model->item(i)->checkState() == Qt::Checked) - { - if (!text.isEmpty()) - { - text+= ", "; - } - - text+= m_model->item(i)->text(); - } - } - break; - - default: - text = m_unknownlyCheckedText; - } - } - else - { - text = m_text; - } - - lineEdit()->setText(text); -} - -void CheckList::on_modelDataChanged() -{ - updateText(); - emit globalCheckStateChanged(globalCheckState()); -} - -void CheckList::on_itemPressed(const QModelIndex &index) -{ - QStandardItem* item = m_model->itemFromIndex(index); - - if (item->checkState() == Qt::Checked) - { - item->setCheckState(Qt::Unchecked); - } - else - { - item->setCheckState(Qt::Checked); - } -} - -bool CheckList::isChecked(int index) const -{ - return m_model->item(index)->checkState() == Qt::Checked; -} +#include "checklist.h" + +CheckList::CheckList(QWidget* parent) : + QComboBox(parent) +{ + m_model = new QStandardItemModel(); + setModel(m_model); + + setEditable(true); + lineEdit()->setReadOnly(true); + lineEdit()->installEventFilter(this); + setItemDelegate(new QCheckListStyledItemDelegate(this)); + + connect(lineEdit(), &QLineEdit::selectionChanged, lineEdit(), &QLineEdit::deselect); + connect((QListView*) view(), SIGNAL(pressed(QModelIndex)), this, SLOT(on_itemPressed(QModelIndex))); + connect(m_model, SIGNAL(dataChanged(QModelIndex, QModelIndex, QVector)), this, SLOT(on_modelDataChanged())); +} + +CheckList::~CheckList() +{ + delete m_model; +} + +void CheckList::setText(const QString &text) +{ + m_text = text; + updateText(); +} + +void CheckList::setAllCheckedText(const QString &text) +{ + m_allCheckedText = text; + updateText(); +} + +void CheckList::setNoneCheckedText(const QString &text) +{ + m_noneCheckedText = text; + updateText(); +} + +void CheckList::setUnknownlyCheckedText(const QString &text) +{ + m_unknownlyCheckedText = text; + updateText(); +} + +void CheckList::setSortRole(int role) +{ + m_model->setSortRole(role); +} + +QStandardItem* CheckList::addCheckItem(const QString &label, const QVariant &data, const Qt::CheckState checkState) +{ + QStandardItem* item = new QStandardItem(label); + item->setCheckState(checkState); + item->setData(data); + item->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled); + + m_model->appendRow(item); + + updateText(); + + return item; +} + +int CheckList::globalCheckState() +{ + int nbRows = m_model->rowCount(), nbChecked = 0, nbUnchecked = 0; + + if (nbRows == 0) + { + return StateUnknown; + } + + for (int i = 0; i < nbRows; i++) + { + if (m_model->item(i)->checkState() == Qt::Checked) + { + nbChecked++; + } + else if (m_model->item(i)->checkState() == Qt::Unchecked) + { + nbUnchecked++; + } + else + { + return StateUnknown; + } + } + + return nbChecked == nbRows ? Qt::Checked : nbUnchecked == nbRows ? Qt::Unchecked : Qt::PartiallyChecked; +} + +bool CheckList::eventFilter(QObject* _object, QEvent* _event) +{ + if (_object == lineEdit() && _event->type() == QEvent::MouseButtonPress) + { + showPopup(); + return true; + } + + return false; +} + +void CheckList::updateText() +{ + QString text; + + if (m_text.isEmpty()) + { + switch (globalCheckState()) + { + case Qt::Checked: + text = m_allCheckedText; + break; + + case Qt::Unchecked: + text = m_noneCheckedText; + break; + + case Qt::PartiallyChecked: + for (int i = 0; i < m_model->rowCount(); i++) + { + if (m_model->item(i)->checkState() == Qt::Checked) + { + if (!text.isEmpty()) + { + text+= ", "; + } + + text+= m_model->item(i)->text(); + } + } + break; + + default: + text = m_unknownlyCheckedText; + } + } + else + { + text = m_text; + } + + lineEdit()->setText(text); +} + +void CheckList::on_modelDataChanged() +{ + updateText(); + emit globalCheckStateChanged(globalCheckState()); +} + +void CheckList::on_itemPressed(const QModelIndex &index) +{ + QStandardItem* item = m_model->itemFromIndex(index); + + if (item->checkState() == Qt::Checked) + { + item->setCheckState(Qt::Unchecked); + } + else + { + item->setCheckState(Qt::Checked); + } +} + +bool CheckList::isChecked(int index) const +{ + return m_model->item(index)->checkState() == Qt::Checked; +} diff --git a/sdrgui/gui/checklist.h b/sdrgui/gui/checklist.h index 08b8c732f..396dbf2ef 100644 --- a/sdrgui/gui/checklist.h +++ b/sdrgui/gui/checklist.h @@ -1,105 +1,105 @@ -#ifndef CHECKLIST -#define CHECKLIST - -#include -#include -#include -#include -#include -#include -#include - -#include "export.h" - -/** -* @brief QComboBox with support of checkboxes -* http://stackoverflow.com/questions/8422760/combobox-of-checkboxes -*/ -class SDRGUI_API CheckList : public QComboBox -{ - Q_OBJECT - -public: - /** - * @brief Additional value to Qt::CheckState when some checkboxes are Qt::PartiallyChecked - */ - static const int StateUnknown = 3; - -private: - QStandardItemModel* m_model; - /** - * @brief Text to display regardless of what is checked - */ - QString m_text; - /** - * @brief Text displayed when no item is checked - */ - QString m_noneCheckedText; - /** - * @brief Text displayed when all items are checked - */ - QString m_allCheckedText; - /** - * @brief Text displayed when some items are partially checked - */ - QString m_unknownlyCheckedText; - -signals: - void globalCheckStateChanged(int); - -public: - CheckList(QWidget* parent = nullptr); - ~CheckList(); - - void setText(const QString &text); - void setAllCheckedText(const QString &text); - void setNoneCheckedText(const QString &text); - void setUnknownlyCheckedText(const QString &text); - - bool isChecked(int index) const; - - void setSortRole(int role); - - /** - * @brief Adds a item to the checklist - * @return the new QStandardItem - */ - QStandardItem* addCheckItem(const QString &label, const QVariant &data, const Qt::CheckState checkState); - - /** - * @brief Computes the global state of the checklist : - * - if there is no item: StateUnknown - * - if there is at least one item partially checked: StateUnknown - * - if all items are checked: Qt::Checked - * - if no item is checked: Qt::Unchecked - * - else: Qt::PartiallyChecked - */ - int globalCheckState(); - -protected: - bool eventFilter(QObject* _object, QEvent* _event); - -private: - void updateText(); - -private slots: - void on_modelDataChanged(); - - void on_itemPressed(const QModelIndex &index); - -public: - class QCheckListStyledItemDelegate : public QStyledItemDelegate - { - public: - QCheckListStyledItemDelegate(QObject* parent = 0) : QStyledItemDelegate(parent) {} - - void paint(QPainter * painter_, const QStyleOptionViewItem & option_, const QModelIndex & index_) const - { - QStyleOptionViewItem & refToNonConstOption = const_cast(option_); - refToNonConstOption.showDecorationSelected = false; - QStyledItemDelegate::paint(painter_, refToNonConstOption, index_); - } - }; -}; - -#endif +#ifndef CHECKLIST +#define CHECKLIST + +#include +#include +#include +#include +#include +#include +#include + +#include "export.h" + +/** +* @brief QComboBox with support of checkboxes +* http://stackoverflow.com/questions/8422760/combobox-of-checkboxes +*/ +class SDRGUI_API CheckList : public QComboBox +{ + Q_OBJECT + +public: + /** + * @brief Additional value to Qt::CheckState when some checkboxes are Qt::PartiallyChecked + */ + static const int StateUnknown = 3; + +private: + QStandardItemModel* m_model; + /** + * @brief Text to display regardless of what is checked + */ + QString m_text; + /** + * @brief Text displayed when no item is checked + */ + QString m_noneCheckedText; + /** + * @brief Text displayed when all items are checked + */ + QString m_allCheckedText; + /** + * @brief Text displayed when some items are partially checked + */ + QString m_unknownlyCheckedText; + +signals: + void globalCheckStateChanged(int); + +public: + CheckList(QWidget* parent = nullptr); + ~CheckList(); + + void setText(const QString &text); + void setAllCheckedText(const QString &text); + void setNoneCheckedText(const QString &text); + void setUnknownlyCheckedText(const QString &text); + + bool isChecked(int index) const; + + void setSortRole(int role); + + /** + * @brief Adds a item to the checklist + * @return the new QStandardItem + */ + QStandardItem* addCheckItem(const QString &label, const QVariant &data, const Qt::CheckState checkState); + + /** + * @brief Computes the global state of the checklist : + * - if there is no item: StateUnknown + * - if there is at least one item partially checked: StateUnknown + * - if all items are checked: Qt::Checked + * - if no item is checked: Qt::Unchecked + * - else: Qt::PartiallyChecked + */ + int globalCheckState(); + +protected: + bool eventFilter(QObject* _object, QEvent* _event); + +private: + void updateText(); + +private slots: + void on_modelDataChanged(); + + void on_itemPressed(const QModelIndex &index); + +public: + class QCheckListStyledItemDelegate : public QStyledItemDelegate + { + public: + QCheckListStyledItemDelegate(QObject* parent = 0) : QStyledItemDelegate(parent) {} + + void paint(QPainter * painter_, const QStyleOptionViewItem & option_, const QModelIndex & index_) const + { + QStyleOptionViewItem & refToNonConstOption = const_cast(option_); + refToNonConstOption.showDecorationSelected = false; + QStyledItemDelegate::paint(painter_, refToNonConstOption, index_); + } + }; +}; + +#endif diff --git a/sdrgui/gui/samplingdevicedialog.cpp b/sdrgui/gui/samplingdevicedialog.cpp index 25a0eccd3..383d6eed9 100644 --- a/sdrgui/gui/samplingdevicedialog.cpp +++ b/sdrgui/gui/samplingdevicedialog.cpp @@ -145,6 +145,7 @@ void SamplingDeviceDialog::on_refreshDevices_clicked() m_progressDialog->show(); SamplingDeviceDialogWorker *worker = new SamplingDeviceDialogWorker(m_deviceType); QThread *thread = new QThread(); + thread->setObjectName(QString("Sampling:%1").arg(m_deviceType)); worker->moveToThread(thread); connect(thread, &QThread::started, worker, &SamplingDeviceDialogWorker::enumerateDevices); connect(worker, &SamplingDeviceDialogWorker::finishedWork, thread, &QThread::quit); diff --git a/swagger/docker/compose/login.sh b/swagger/docker/compose/login.sh index 4d2a973ee..94b68283d 100755 --- a/swagger/docker/compose/login.sh +++ b/swagger/docker/compose/login.sh @@ -1,2 +1,2 @@ #!/bin/bash -docker exec -it sdrangel_swgcodegen /bin/bash \ No newline at end of file +docker exec -it sdrangel_swgcodegen /bin/bash diff --git a/swagger/docker/server/run.sh b/swagger/docker/server/run.sh index a3a331e32..064e73156 100755 --- a/swagger/docker/server/run.sh +++ b/swagger/docker/server/run.sh @@ -48,4 +48,4 @@ docker run -it --rm \ --name ${container_name} \ ${http_port} \ -v="/opt/build/sdrangel:/opt/build/sdrangel:rw" \ - ${image_name}:${image_tag} \ No newline at end of file + ${image_name}:${image_tag} diff --git a/swagger/sdrangel/api/swagger/include/CWKeyer.yaml b/swagger/sdrangel/api/swagger/include/CWKeyer.yaml index 662d6ec6a..023f7b18e 100644 --- a/swagger/sdrangel/api/swagger/include/CWKeyer.yaml +++ b/swagger/sdrangel/api/swagger/include/CWKeyer.yaml @@ -43,4 +43,4 @@ CWKeyerSettings: dashKeyModifiers: description: > Modifiers for the dash key. Modifier keys held with the key, as a sum of flags: 33554432 (0x02000000) shift, 67108864 (0x04000000) control, 134217728 (0x08000000) alt, 268435456 (0x10000000) meta. 0 for no modifier. - type: integer \ No newline at end of file + type: integer