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/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/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/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/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/plugins/channelrx/demodadsb/sideviews/ReadMe.txt b/plugins/channelrx/demodadsb/sideviews/ReadMe.txt
index 5bc03889c..8f54542ed 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
+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
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..7d24bdd1b 100644
--- a/plugins/feature/mcpserver/bridge/CMakeLists.txt
+++ b/plugins/feature/mcpserver/bridge/CMakeLists.txt
@@ -1,129 +1,129 @@
-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)
+
+ 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