Normalize existing text files to LF to conform to the repository-wide line-ending policy defined by .gitattributes by: git add --renormalize . Signed-off-by: Robin Getz <rgetz503@gmail.com>chirpmodem-v8.0.0
@ -1,55 +1,55 @@
@@ -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 |
||||
|
||||
@ -1,76 +1,76 @@
@@ -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 |
||||
|
||||
@ -1,67 +1,67 @@
@@ -1,67 +1,67 @@
|
||||
<?xml version="1.0"?> |
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" |
||||
package="org.sdrangel" |
||||
android:installLocation="auto" |
||||
android:versionCode="13" |
||||
android:versionName="7.25.1.1"> |
||||
<uses-permission android:name="android.permission.INTERNET" /> |
||||
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> |
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> |
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> |
||||
<uses-permission android:name="android.permission.CAMERA" /> |
||||
<uses-permission android:name="android.permission.RECORD_AUDIO" /> |
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> |
||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> |
||||
<uses-permission android:name="android.permission.WAKE_LOCK" /> |
||||
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" /> |
||||
|
||||
<supports-screens |
||||
android:anyDensity="true" |
||||
android:largeScreens="true" |
||||
android:normalScreens="true" |
||||
android:smallScreens="true" /> |
||||
<application |
||||
android:name="org.qtproject.qt.android.bindings.QtApplication" |
||||
android:hardwareAccelerated="true" |
||||
android:label="SDRangel" |
||||
android:extractNativeLibs="true" |
||||
android:requestLegacyExternalStorage="true" |
||||
android:allowBackup="true" |
||||
android:fullBackupOnly="false" |
||||
android:icon="@mipmap/ic_launcher"> |
||||
<activity |
||||
android:name="org.sdrangel.SDRangelActivity" |
||||
android:configChanges="orientation|uiMode|screenLayout|screenSize|smallestScreenSize|layoutDirection|locale|fontScale|keyboard|keyboardHidden|navigation|mcc|mnc|density" |
||||
android:label="SDRangel" |
||||
android:launchMode="singleTop" |
||||
android:screenOrientation="unspecified" |
||||
android:exported="true"> |
||||
<intent-filter> |
||||
<action android:name="android.intent.action.MAIN" /> |
||||
<category android:name="android.intent.category.LAUNCHER" /> |
||||
</intent-filter> |
||||
|
||||
<meta-data |
||||
android:name="android.app.lib_name" |
||||
android:value="sdrangel" /> |
||||
|
||||
<meta-data |
||||
android:name="android.app.arguments" |
||||
android:value="" /> |
||||
|
||||
<meta-data |
||||
android:name="android.app.background_running" |
||||
android:value="true" /> |
||||
</activity> |
||||
|
||||
<provider |
||||
android:name="androidx.core.content.FileProvider" |
||||
android:authorities="${applicationId}.qtprovider" |
||||
android:exported="false" |
||||
android:grantUriPermissions="true"> |
||||
<meta-data |
||||
android:name="android.support.FILE_PROVIDER_PATHS" |
||||
android:resource="@xml/qtprovider_paths"/> |
||||
</provider> |
||||
</application> |
||||
</manifest> |
||||
<?xml version="1.0"?> |
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" |
||||
package="org.sdrangel" |
||||
android:installLocation="auto" |
||||
android:versionCode="13" |
||||
android:versionName="7.25.1.1"> |
||||
<uses-permission android:name="android.permission.INTERNET" /> |
||||
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> |
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> |
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> |
||||
<uses-permission android:name="android.permission.CAMERA" /> |
||||
<uses-permission android:name="android.permission.RECORD_AUDIO" /> |
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> |
||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> |
||||
<uses-permission android:name="android.permission.WAKE_LOCK" /> |
||||
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" /> |
||||
|
||||
<supports-screens |
||||
android:anyDensity="true" |
||||
android:largeScreens="true" |
||||
android:normalScreens="true" |
||||
android:smallScreens="true" /> |
||||
<application |
||||
android:name="org.qtproject.qt.android.bindings.QtApplication" |
||||
android:hardwareAccelerated="true" |
||||
android:label="SDRangel" |
||||
android:extractNativeLibs="true" |
||||
android:requestLegacyExternalStorage="true" |
||||
android:allowBackup="true" |
||||
android:fullBackupOnly="false" |
||||
android:icon="@mipmap/ic_launcher"> |
||||
<activity |
||||
android:name="org.sdrangel.SDRangelActivity" |
||||
android:configChanges="orientation|uiMode|screenLayout|screenSize|smallestScreenSize|layoutDirection|locale|fontScale|keyboard|keyboardHidden|navigation|mcc|mnc|density" |
||||
android:label="SDRangel" |
||||
android:launchMode="singleTop" |
||||
android:screenOrientation="unspecified" |
||||
android:exported="true"> |
||||
<intent-filter> |
||||
<action android:name="android.intent.action.MAIN" /> |
||||
<category android:name="android.intent.category.LAUNCHER" /> |
||||
</intent-filter> |
||||
|
||||
<meta-data |
||||
android:name="android.app.lib_name" |
||||
android:value="sdrangel" /> |
||||
|
||||
<meta-data |
||||
android:name="android.app.arguments" |
||||
android:value="" /> |
||||
|
||||
<meta-data |
||||
android:name="android.app.background_running" |
||||
android:value="true" /> |
||||
</activity> |
||||
|
||||
<provider |
||||
android:name="androidx.core.content.FileProvider" |
||||
android:authorities="${applicationId}.qtprovider" |
||||
android:exported="false" |
||||
android:grantUriPermissions="true"> |
||||
<meta-data |
||||
android:name="android.support.FILE_PROVIDER_PATHS" |
||||
android:resource="@xml/qtprovider_paths"/> |
||||
</provider> |
||||
</application> |
||||
</manifest> |
||||
|
||||
@ -1,26 +1,26 @@
@@ -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 <http://www.gnu.org/licenses/>. //
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#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 <http://www.gnu.org/licenses/>. //
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#pragma once |
||||
|
||||
#include "loggerwithfile.h" |
||||
|
||||
void installCrashHandler(qtwebapp::LoggerWithFile *logger); |
||||
|
||||
#ifdef _WIN32 |
||||
void logWindowsStackTrace(); |
||||
#endif |
||||
|
||||
@ -1,50 +1,50 @@
@@ -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 <http://www.gnu.org/licenses/>. //
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#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 <http://www.gnu.org/licenses/>. //
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#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; |
||||
} |
||||
|
||||
@ -1,46 +1,46 @@
@@ -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 <http://www.gnu.org/licenses/>. //
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#pragma once |
||||
|
||||
#include <QQueue> |
||||
|
||||
#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<QString> 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 <http://www.gnu.org/licenses/>. //
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#pragma once |
||||
|
||||
#include <QQueue> |
||||
|
||||
#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<QString> m_messages; // Queue containing last m_maxSize messages
|
||||
|
||||
}; |
||||
|
||||
} |
||||
|
||||
@ -1,18 +1,18 @@
@@ -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. |
||||
@ -1,23 +1,23 @@
@@ -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. |
||||
|
||||
@ -1,165 +1,165 @@
@@ -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; |
||||
} |
||||
} |
||||
|
||||
@ -1,129 +1,129 @@
@@ -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$<$<CONFIG:Debug>: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 $<TARGET_FILE:sdrangel-mcp-bridge> "${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 $<TARGET_FILE:sdrangel-mcp-tools-dump> "${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$<$<CONFIG:Debug>: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 $<TARGET_FILE:sdrangel-mcp-bridge> "${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 $<TARGET_FILE:sdrangel-mcp-tools-dump> "${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() |
||||
|
||||
@ -1,494 +1,494 @@
@@ -1,494 +1,494 @@
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
|
||||
// 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 <http://www.gnu.org/licenses/>. //
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#include "httpclient.h" |
||||
|
||||
#include <algorithm> |
||||
#include <cctype> |
||||
#include <cstdlib> |
||||
#include <cstring> |
||||
#include <string> |
||||
|
||||
#ifdef _WIN32 |
||||
#include <winsock2.h> |
||||
#include <ws2tcpip.h> |
||||
#else |
||||
#include <arpa/inet.h> |
||||
#include <errno.h> |
||||
#include <netdb.h> |
||||
#include <netinet/in.h> |
||||
#include <netinet/tcp.h> |
||||
#include <sys/socket.h> |
||||
#include <sys/types.h> |
||||
#include <unistd.h> |
||||
#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<char>(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<int>(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<const char *>(&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<DWORD>(timeoutMs); |
||||
setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<const char *>(&timeout), sizeof(timeout)); |
||||
setsockopt(m_socket, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast<const char *>(&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<int>(data.size() - sent), flags); |
||||
|
||||
if (count <= 0) |
||||
{ |
||||
error = "send failed (" + socketError() + ")"; |
||||
return false; |
||||
} |
||||
|
||||
sent += static_cast<size_t>(count); |
||||
} |
||||
|
||||
return true; |
||||
} |
||||
|
||||
bool HttpClient::send(const std::string& method, const std::string& path, const std::vector<Header>& 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<size_t>(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<size_t>(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<size_t>(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 <jon@beniston.com> //
|
||||
// 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 <http://www.gnu.org/licenses/>. //
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#include "httpclient.h" |
||||
|
||||
#include <algorithm> |
||||
#include <cctype> |
||||
#include <cstdlib> |
||||
#include <cstring> |
||||
#include <string> |
||||
|
||||
#ifdef _WIN32 |
||||
#include <winsock2.h> |
||||
#include <ws2tcpip.h> |
||||
#else |
||||
#include <arpa/inet.h> |
||||
#include <errno.h> |
||||
#include <netdb.h> |
||||
#include <netinet/in.h> |
||||
#include <netinet/tcp.h> |
||||
#include <sys/socket.h> |
||||
#include <sys/types.h> |
||||
#include <unistd.h> |
||||
#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<char>(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<int>(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<const char *>(&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<DWORD>(timeoutMs); |
||||
setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<const char *>(&timeout), sizeof(timeout)); |
||||
setsockopt(m_socket, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast<const char *>(&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<int>(data.size() - sent), flags); |
||||
|
||||
if (count <= 0) |
||||
{ |
||||
error = "send failed (" + socketError() + ")"; |
||||
return false; |
||||
} |
||||
|
||||
sent += static_cast<size_t>(count); |
||||
} |
||||
|
||||
return true; |
||||
} |
||||
|
||||
bool HttpClient::send(const std::string& method, const std::string& path, const std::vector<Header>& 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<size_t>(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<size_t>(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<size_t>(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(); |
||||
} |
||||
|
||||
@ -1,101 +1,101 @@
@@ -1,101 +1,101 @@
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
|
||||
// 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 <http://www.gnu.org/licenses/>. //
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#ifndef INCLUDE_MCPBRIDGE_HTTPCLIENT_H_ |
||||
#define INCLUDE_MCPBRIDGE_HTTPCLIENT_H_ |
||||
|
||||
#include <string> |
||||
#include <utility> |
||||
#include <vector> |
||||
|
||||
//!< 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<std::string, std::string>; |
||||
|
||||
struct Head |
||||
{ |
||||
int m_status = 0; |
||||
std::string m_reason; |
||||
std::vector<Header> 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<Header>& 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 <jon@beniston.com> //
|
||||
// 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 <http://www.gnu.org/licenses/>. //
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#ifndef INCLUDE_MCPBRIDGE_HTTPCLIENT_H_ |
||||
#define INCLUDE_MCPBRIDGE_HTTPCLIENT_H_ |
||||
|
||||
#include <string> |
||||
#include <utility> |
||||
#include <vector> |
||||
|
||||
//!< 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<std::string, std::string>; |
||||
|
||||
struct Head |
||||
{ |
||||
int m_status = 0; |
||||
std::string m_reason; |
||||
std::vector<Header> 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<Header>& 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_
|
||||
|
||||
@ -1,88 +1,88 @@
@@ -1,88 +1,88 @@
|
||||
<h1>SDRangel MCP stdio bridge</h1> |
||||
|
||||
<h2>Introduction</h2> |
||||
|
||||
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. |
||||
|
||||
<h2>Building</h2> |
||||
|
||||
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. |
||||
|
||||
<h2>Packaging</h2> |
||||
|
||||
cmake -S . -B build -DBUILD_MCP_BUNDLE=ON |
||||
cmake --build build --target mcpbundle |
||||
|
||||
produces `bin/sdrangel-<version>-<platform>.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 |
||||
|
||||
<h2>Running</h2> |
||||
|
||||
sdrangel-mcp-bridge [--host <address>] [--port <port>] [--path <path>] [--token <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"] |
||||
} |
||||
} |
||||
|
||||
<h2>How it works</h2> |
||||
|
||||
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. |
||||
|
||||
<h2>Testing</h2> |
||||
|
||||
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. |
||||
<h1>SDRangel MCP stdio bridge</h1> |
||||
|
||||
<h2>Introduction</h2> |
||||
|
||||
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. |
||||
|
||||
<h2>Building</h2> |
||||
|
||||
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. |
||||
|
||||
<h2>Packaging</h2> |
||||
|
||||
cmake -S . -B build -DBUILD_MCP_BUNDLE=ON |
||||
cmake --build build --target mcpbundle |
||||
|
||||
produces `bin/sdrangel-<version>-<platform>.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 |
||||
|
||||
<h2>Running</h2> |
||||
|
||||
sdrangel-mcp-bridge [--host <address>] [--port <port>] [--path <path>] [--token <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"] |
||||
} |
||||
} |
||||
|
||||
<h2>How it works</h2> |
||||
|
||||
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. |
||||
|
||||
<h2>Testing</h2> |
||||
|
||||
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. |
||||
|
||||
@ -1,340 +1,340 @@
@@ -1,340 +1,340 @@
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
|
||||
// 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 <http://www.gnu.org/licenses/>. //
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#include <QMessageBox> |
||||
#include <QFileDialog> |
||||
|
||||
#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<MCPServer*>(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<int>(&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 <jon@beniston.com> //
|
||||
// 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 <http://www.gnu.org/licenses/>. //
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#include <QMessageBox> |
||||
#include <QFileDialog> |
||||
|
||||
#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<MCPServer*>(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<int>(&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); |
||||
} |
||||
|
||||
@ -1,299 +1,299 @@
@@ -1,299 +1,299 @@
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
|
||||
// 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 <http://www.gnu.org/licenses/>. //
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#ifndef INCLUDE_FEATURE_MCPTOOLS_H_ |
||||
#define INCLUDE_FEATURE_MCPTOOLS_H_ |
||||
|
||||
#include <functional> |
||||
|
||||
#include <QJsonArray> |
||||
#include <QJsonObject> |
||||
#include <QJsonValue> |
||||
#include <QList> |
||||
#include <QMap> |
||||
#include <QString> |
||||
#include <QMutex> |
||||
#include <QSet> |
||||
#include <QStringList> |
||||
|
||||
#include <QAtomicInt> |
||||
#include <QObject> |
||||
|
||||
#include "mcperror.h" |
||||
#include "mcpdocs.h" |
||||
#include "mcpdatafeed.h" |
||||
#include "mcpcapture.h" |
||||
|
||||
//!< A settings definition's properties, read from the swagger YAML that describe_settings serves.
|
||||
//!< The current value of a setting cannot serve this purpose: generated SWG objects omit empty
|
||||
//!< strings, so a blank setting is indistinguishable from a key that does not exist
|
||||
struct SettingsSchema |
||||
{ |
||||
bool m_known = false; //!< False when the definition was not found, so nothing can be judged
|
||||
QMap<QString, QString> m_types; //!< Property name -> YAML type: integer, number, string, array or object
|
||||
}; |
||||
|
||||
class WebAPIAdapterInterface; |
||||
class MCPStreams; |
||||
class DeviceAPI; |
||||
class ChannelAPI; |
||||
class Feature; |
||||
|
||||
namespace SWGSDRangel { |
||||
class SWGObject; |
||||
class SWGErrorResponse; |
||||
} |
||||
|
||||
// Counts MainCore structural change signals so that tool handlers running on HTTP threads
|
||||
// can wait for asynchronous operations (which complete on the main thread) to finish.
|
||||
// Lives in the main thread; the counters are read from other threads.
|
||||
class MCPEventCounter : public QObject |
||||
{ |
||||
Q_OBJECT |
||||
public: |
||||
MCPEventCounter(); |
||||
|
||||
QAtomicInt m_deviceSetAdded; |
||||
QAtomicInt m_deviceSetRemoved; |
||||
QAtomicInt m_deviceChanged; |
||||
QAtomicInt m_channelAdded; |
||||
QAtomicInt m_channelRemoved; |
||||
QAtomicInt m_featureAdded; |
||||
QAtomicInt m_featureRemoved; |
||||
|
||||
private slots: |
||||
void onDeviceSetAdded(int index, DeviceAPI *device); |
||||
void onDeviceSetRemoved(int index); |
||||
void onDeviceChanged(int index); |
||||
void onChannelAdded(int deviceSetIndex, ChannelAPI *channel); |
||||
void onChannelRemoved(int deviceSetIndex, ChannelAPI *channel); |
||||
void onFeatureAdded(int featureSetIndex, Feature *feature); |
||||
void onFeatureRemoved(int featureSetIndex, Feature *feature); |
||||
}; |
||||
|
||||
// The set of MCP tools that control SDRangel. Everything goes through the
|
||||
// in-process Web API adapter, so what the tools can do matches the REST API,
|
||||
// plus waiting for asynchronous operations to complete.
|
||||
class MCPTools |
||||
{ |
||||
public: |
||||
struct Tool |
||||
{ |
||||
QString name; |
||||
QString description; |
||||
QJsonObject inputSchema; |
||||
std::function<QJsonValue(const QJsonObject& args)> handler; |
||||
}; |
||||
|
||||
explicit MCPTools(WebAPIAdapterInterface *webAPIAdapterInterface); |
||||
|
||||
QJsonArray listTools() const; |
||||
QJsonObject callTool(const QString& name, const QJsonObject& arguments); |
||||
|
||||
// Data also served as resources
|
||||
QJsonObject getInstanceSummary(); |
||||
QJsonObject getAvailableDevices(int direction = -1); //!< -1 for all directions
|
||||
QJsonObject getAvailableChannels(int direction = -1); |
||||
QJsonObject getAvailableFeatures(); |
||||
QJsonObject getPresets(); |
||||
QJsonObject getConfigurations(); |
||||
QJsonObject getDeviceSet(int deviceSetIndex); |
||||
int deviceSetCount() const; |
||||
QString describeType(const QString& type, const QString& kind); |
||||
MCPDocs& docs() { return m_docs; } |
||||
MCPDataFeed& dataFeed() { return m_dataFeed; } |
||||
MCPCapture& capture() { return m_capture; } |
||||
void setStreams(MCPStreams *streams) { m_streams = streams; } |
||||
//!< The feature that owns this server, so it can refuse to delete or stop itself
|
||||
void setOwnerFeature(const QObject *feature) { m_ownerFeature = feature; } |
||||
//!< Set by the server, on the main thread, before it waits for the HTTP threads to finish.
|
||||
//!< Every wait and sleep in the tools then ends at once with a tool error, since the main
|
||||
//!< thread they would otherwise be waiting on is the one waiting for them
|
||||
void setStopping(bool stopping); |
||||
|
||||
private: |
||||
WebAPIAdapterInterface *m_adapter; |
||||
MCPEventCounter m_events; |
||||
MCPDocs m_docs; |
||||
MCPDataFeed m_dataFeed; |
||||
MCPCapture m_capture; |
||||
MCPStreams *m_streams; |
||||
|
||||
// Creating an object and working out which one is new must not overlap with another
|
||||
// creation, or two callers snapshot the same state and both claim the same object.
|
||||
// The capture tools run without the dispatch lock, so this is reachable.
|
||||
QMutex m_creationMutex; |
||||
// Deletion is by index, and the index is resolved just before the delete is posted for
|
||||
// the main thread to do later. Two calls deleting on one device set unserialised can post
|
||||
// two indices that were right when read and wrong once the first delete has renumbered
|
||||
// the rest, taking a channel neither meant. Held from the lookup to the object being gone
|
||||
QMutex m_deletionMutex; |
||||
// The channels listen and scan have added, so that the next of either on the same device
|
||||
// set can take them away again and cleanup can remove them all. Held by uid rather than
|
||||
// pointer: a channel removed from the GUI frees its address for the next one created,
|
||||
// which must not then be taken for one of these. They run without the dispatch lock, so
|
||||
// this has a lock of its own, which is never held across addChannelAndWait or a delete:
|
||||
// those take m_creationMutex or wait
|
||||
QMutex m_intentMutex; |
||||
QSet<uint64_t> m_intentChannels; |
||||
// The features listen added for a mode's output (AIS, Radiosonde, APRS), removed again once no
|
||||
// channel it added still feeds them. A feature that was already there is never among these
|
||||
QSet<uint64_t> m_intentFeatures; |
||||
const QObject *m_ownerFeature; |
||||
QAtomicInt m_stopping; |
||||
QList<Tool> m_tools; |
||||
// The definitions are loaded on first use and the parsed schemas cached as they are asked
|
||||
// for, from whichever thread asks. The settings tools run under the dispatch lock but
|
||||
// listen and scan do not, and they patch settings too, so these have a lock of their own,
|
||||
// taken by describeType and settingsSchema; the helpers they call expect it held
|
||||
QMutex m_schemaMutex; |
||||
QMap<QString, QString> m_yamlDefinitions; //!< Swagger definition name -> YAML text
|
||||
QMap<QString, QString> m_yamlDefinitionsByLower; //!< Lower cased name -> the name as written
|
||||
QMap<QString, SettingsSchema> m_schemaCache; //!< Parsed form of the above, by definition name
|
||||
bool m_yamlLoaded; |
||||
|
||||
void add(const QString& name, const QString& description, const QJsonObject& inputSchema, |
||||
std::function<QJsonValue(const QJsonObject& args)> handler); |
||||
|
||||
void registerInstanceTools(); |
||||
void registerDeviceSetTools(); |
||||
void registerChannelTools(); |
||||
void registerFeatureTools(); |
||||
void registerPresetTools(); |
||||
void registerWorkspaceTools(); |
||||
void registerCaptureTools(); |
||||
void registerIntentTools(); |
||||
|
||||
//!< Polls until the condition holds, at most timeoutMs. False on timeout; throws when the
|
||||
//!< server is stopping, as nothing waited for on the main thread will happen then
|
||||
bool waitFor(const std::function<bool()>& condition, int timeoutMs = m_waitTimeoutMs) const; |
||||
//!< A sleep that a stop cuts short, with the same tool error
|
||||
void pause(int ms) const; |
||||
static const int m_waitTimeoutMs = 5000; |
||||
|
||||
// Device set helpers
|
||||
int channelCount(int deviceSetIndex) const; |
||||
int featureCount() const; |
||||
int deviceSetDirection(int deviceSetIndex); |
||||
QJsonObject selectDevice(int deviceSetIndex, const QJsonObject& args); |
||||
QJsonObject getDeviceSettings(int deviceSetIndex); |
||||
QJsonObject patchDeviceSettings(int deviceSetIndex, const QJsonObject& partial); |
||||
int addChannelAndWait(int deviceSetIndex, const QString& channelType); |
||||
int addFeatureAndWait(const QString& featureType); |
||||
int addDeviceSetAndWait(int direction); |
||||
//!< Identity of the current channels, features or device sets, to spot which one is new.
|
||||
//!< Channels and features are identified by UID throughout: a pointer to one is only ever
|
||||
//!< good until the next wait, since a deleted object's address is reused by the next one
|
||||
//!< created, and every tool here waits
|
||||
QSet<uint64_t> channelUids(int deviceSetIndex) const; |
||||
QSet<uint64_t> featureUids() const; |
||||
QSet<const void *> deviceSetPointers() const; |
||||
void deleteChannelAndWait(int deviceSetIndex, int channelIndex); |
||||
void deleteChannelLocked(int deviceSetIndex, int channelIndex); //!< With m_deletionMutex held
|
||||
//!< Removes a device set that listen or scan created and could not finish setting up, if it
|
||||
//!< is still the last one, which is the only one the API can remove
|
||||
void discardNewDeviceSet(int deviceSetIndex, uint64_t identity); |
||||
//!< What tells one device set from another that has since taken its index: the engine's UID
|
||||
//!< together with the object's address. Zero when there is no such device set
|
||||
uint64_t deviceSetIdentity(int deviceSetIndex) const; |
||||
friend class NewDeviceSetGuard; |
||||
//!< Deletes a channel wherever it has moved to, for callers that held on to it across a wait
|
||||
void deleteChannelObjectAndWait(uint64_t channelUid); |
||||
const void *featureAt(int featureIndex) const; |
||||
//!< The UID of the feature or channel at an index, 0 when there is none
|
||||
uint64_t featureUidAt(int featureIndex) const; |
||||
uint64_t channelUidAt(int deviceSetIndex, int channelIndex) const; |
||||
void requireNotSelf(int featureIndex, const QString& action) const; |
||||
QJsonObject getChannelSettings(int deviceSetIndex, int channelIndex); |
||||
QJsonObject patchChannelSettings(int deviceSetIndex, int channelIndex, const QJsonObject& partial); |
||||
//!< The property names and types of one settings definition. Used to tell a misspelled key from
|
||||
//!< a valid one, and to reject a value of the wrong type before it reaches the SWG object
|
||||
SettingsSchema settingsSchema(const QString& definition); |
||||
QString resolveDefinition(const QString& name); //!< Call with m_schemaMutex held
|
||||
QJsonObject getSpectrumSettings(int deviceSetIndex); |
||||
//!< unknownKeys, when given, receives the patch keys the schema does not define
|
||||
QJsonObject patchSpectrumSettings(int deviceSetIndex, const QJsonObject& partial, QStringList *unknownKeys = nullptr); |
||||
//!< Explains an rdsReport that is absent because RDS decoding is switched off, rather than
|
||||
//!< because nothing has been decoded yet
|
||||
void addRdsHint(QJsonObject& report, const QString& channelType, int deviceSetIndex, int channelIndex); |
||||
QJsonObject getFeatureSettings(int featureIndex); |
||||
QJsonObject patchFeatureSettings(int featureIndex, const QJsonObject& partial); |
||||
QJsonObject deviceState(int deviceSetIndex, int subsystemIndex, int run); //!< run: 1 start, 0 stop, -1 query
|
||||
//!< Empty unless the device set's baseband is too narrow for this channel type
|
||||
QString basebandWarning(int deviceSetIndex, const QString& channelType); |
||||
//!< The same for every channel a device set holds
|
||||
QStringList basebandWarnings(int deviceSetIndex); |
||||
QJsonObject featureState(int featureIndex, int run); |
||||
QJsonObject presetIdentifier(const QJsonObject& args, int deviceSetIndex, bool forSave); |
||||
|
||||
// Shared by the intent level tools
|
||||
QJsonObject channelReport(int deviceSetIndex, int channelIndex); |
||||
void postChannelAction(int deviceSetIndex, int channelIndex, const QJsonObject& actions); |
||||
//!< doomed: uids of channels the caller is about to remove, which the reused set is not counted as carrying.
|
||||
//!< profileGain: give a device set this creates the fixed receiver gain profile; false when the gain is about to be measured
|
||||
QJsonObject pickReceiver(const QJsonObject& args, int minBaseband, const QSet<uint64_t>& doomed = QSet<uint64_t>(), bool profileGain = true); |
||||
//!< The tune_gain tool: sweeps the gain and applies the best, with the table it measured
|
||||
QJsonObject tuneGain(const QJsonObject& args); |
||||
//!< Sets the main spectrum's reference level and range from what it shows, as the GUI's autoscale button does
|
||||
void autoscaleSpectrum(int deviceSetIndex); |
||||
//!< Turns spectrum scrolling on if it is off, which is what keeps the history the spectrum
|
||||
//!< history tools read. Returns a note when it did, empty otherwise
|
||||
QString ensureSpectrumHistory(int deviceSetIndex, double seconds); |
||||
//!< The index of a feature of this type, adding one if there is none. Returns whether it was added
|
||||
int ensureFeature(const QString& featureType, int& featureIndex); |
||||
void trackIntentFeature(uint64_t featureUid); |
||||
//!< Removes the features listen added that no channel it added still feeds, except one of keepType.
|
||||
//!< Returns the types of those removed
|
||||
QStringList reclaimIntentFeatures(const QString& keepType = QString()); |
||||
//!< Deletes a feature wherever it has been renumbered to
|
||||
void deleteFeatureObjectAndWait(uint64_t featureUid); |
||||
//!< Whether listen or scan should measure the gain: a device set they created, or a retune to another band
|
||||
static bool gainWorthTuning(bool reused, double previousCentre, double centre); |
||||
void trackIntentChannel(uint64_t channelUid); |
||||
void untrackIntentChannel(uint64_t channelUid); |
||||
QSet<uint64_t> intentChannels(); |
||||
//!< A channel's type id and whether listen or scan added it, for the notes the intent tools leave
|
||||
struct ChannelNote { uint64_t m_uid; int m_index; QString m_id; bool m_intent; }; |
||||
QList<ChannelNote> channelNotes(int deviceSetIndex, const QSet<uint64_t>& except = QSet<uint64_t>()); |
||||
//!< Removes the channels listen and scan added to a device set, except keep. Returns the ids of those removed
|
||||
QStringList reclaimIntentChannels(int deviceSetIndex, const QSet<uint64_t>& keep = QSet<uint64_t>()); |
||||
//!< The channel a previous listen added that a new one of this type can retune instead of replacing, or 0.
|
||||
//!< wanted: how many of the type the mode uses, 2 for a paired mode
|
||||
uint64_t reusableIntentChannel(int deviceSetIndex, const QString& channelType, int& channelIndex, int wanted = 1); |
||||
//!< What a retune of a reused device set did to the channels listen and scan did not add
|
||||
struct RetuneOutcome |
||||
{ |
||||
QStringList m_kept; //!< Re-offset so that they stay on the frequency they had
|
||||
QStringList m_removed; //!< Audio demodulators the new baseband could not hold, which would only have made noise
|
||||
QStringList m_stranded; //!< Left where they were: not audio, or the baseband unknown
|
||||
}; |
||||
RetuneOutcome retuneOtherChannels(int deviceSetIndex, double previousCentre, double centre, int baseband); |
||||
//!< What listen and scan tell the caller about the rest of the device set once their own channels are in
|
||||
QStringList intentNotes(int deviceSetIndex, const QSet<uint64_t>& added, const QStringList& reclaimed, |
||||
bool reused, double previousCentre, double centre, const RetuneOutcome& outcome); |
||||
//!< Channel type ids for a direction, independent of how list_channel_types formats them
|
||||
QStringList channelTypeIds(int direction); |
||||
//!< Where a channel is now. The intent tools sleep for many seconds without holding the
|
||||
//!< protocol mutex, and a concurrent request that deletes a lower numbered channel
|
||||
//!< renumbers everything above it, so their indices have to be resolved again before use.
|
||||
void relocateChannel(uint64_t channelUid, int& deviceSetIndex, int& channelIndex, const QString& what); |
||||
|
||||
void loadYamlDefinitions(); //!< Call with m_schemaMutex held
|
||||
}; |
||||
|
||||
#endif // INCLUDE_FEATURE_MCPTOOLS_H_
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
|
||||
// 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 <http://www.gnu.org/licenses/>. //
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#ifndef INCLUDE_FEATURE_MCPTOOLS_H_ |
||||
#define INCLUDE_FEATURE_MCPTOOLS_H_ |
||||
|
||||
#include <functional> |
||||
|
||||
#include <QJsonArray> |
||||
#include <QJsonObject> |
||||
#include <QJsonValue> |
||||
#include <QList> |
||||
#include <QMap> |
||||
#include <QString> |
||||
#include <QMutex> |
||||
#include <QSet> |
||||
#include <QStringList> |
||||
|
||||
#include <QAtomicInt> |
||||
#include <QObject> |
||||
|
||||
#include "mcperror.h" |
||||
#include "mcpdocs.h" |
||||
#include "mcpdatafeed.h" |
||||
#include "mcpcapture.h" |
||||
|
||||
//!< A settings definition's properties, read from the swagger YAML that describe_settings serves.
|
||||
//!< The current value of a setting cannot serve this purpose: generated SWG objects omit empty
|
||||
//!< strings, so a blank setting is indistinguishable from a key that does not exist
|
||||
struct SettingsSchema |
||||
{ |
||||
bool m_known = false; //!< False when the definition was not found, so nothing can be judged
|
||||
QMap<QString, QString> m_types; //!< Property name -> YAML type: integer, number, string, array or object
|
||||
}; |
||||
|
||||
class WebAPIAdapterInterface; |
||||
class MCPStreams; |
||||
class DeviceAPI; |
||||
class ChannelAPI; |
||||
class Feature; |
||||
|
||||
namespace SWGSDRangel { |
||||
class SWGObject; |
||||
class SWGErrorResponse; |
||||
} |
||||
|
||||
// Counts MainCore structural change signals so that tool handlers running on HTTP threads
|
||||
// can wait for asynchronous operations (which complete on the main thread) to finish.
|
||||
// Lives in the main thread; the counters are read from other threads.
|
||||
class MCPEventCounter : public QObject |
||||
{ |
||||
Q_OBJECT |
||||
public: |
||||
MCPEventCounter(); |
||||
|
||||
QAtomicInt m_deviceSetAdded; |
||||
QAtomicInt m_deviceSetRemoved; |
||||
QAtomicInt m_deviceChanged; |
||||
QAtomicInt m_channelAdded; |
||||
QAtomicInt m_channelRemoved; |
||||
QAtomicInt m_featureAdded; |
||||
QAtomicInt m_featureRemoved; |
||||
|
||||
private slots: |
||||
void onDeviceSetAdded(int index, DeviceAPI *device); |
||||
void onDeviceSetRemoved(int index); |
||||
void onDeviceChanged(int index); |
||||
void onChannelAdded(int deviceSetIndex, ChannelAPI *channel); |
||||
void onChannelRemoved(int deviceSetIndex, ChannelAPI *channel); |
||||
void onFeatureAdded(int featureSetIndex, Feature *feature); |
||||
void onFeatureRemoved(int featureSetIndex, Feature *feature); |
||||
}; |
||||
|
||||
// The set of MCP tools that control SDRangel. Everything goes through the
|
||||
// in-process Web API adapter, so what the tools can do matches the REST API,
|
||||
// plus waiting for asynchronous operations to complete.
|
||||
class MCPTools |
||||
{ |
||||
public: |
||||
struct Tool |
||||
{ |
||||
QString name; |
||||
QString description; |
||||
QJsonObject inputSchema; |
||||
std::function<QJsonValue(const QJsonObject& args)> handler; |
||||
}; |
||||
|
||||
explicit MCPTools(WebAPIAdapterInterface *webAPIAdapterInterface); |
||||
|
||||
QJsonArray listTools() const; |
||||
QJsonObject callTool(const QString& name, const QJsonObject& arguments); |
||||
|
||||
// Data also served as resources
|
||||
QJsonObject getInstanceSummary(); |
||||
QJsonObject getAvailableDevices(int direction = -1); //!< -1 for all directions
|
||||
QJsonObject getAvailableChannels(int direction = -1); |
||||
QJsonObject getAvailableFeatures(); |
||||
QJsonObject getPresets(); |
||||
QJsonObject getConfigurations(); |
||||
QJsonObject getDeviceSet(int deviceSetIndex); |
||||
int deviceSetCount() const; |
||||
QString describeType(const QString& type, const QString& kind); |
||||
MCPDocs& docs() { return m_docs; } |
||||
MCPDataFeed& dataFeed() { return m_dataFeed; } |
||||
MCPCapture& capture() { return m_capture; } |
||||
void setStreams(MCPStreams *streams) { m_streams = streams; } |
||||
//!< The feature that owns this server, so it can refuse to delete or stop itself
|
||||
void setOwnerFeature(const QObject *feature) { m_ownerFeature = feature; } |
||||
//!< Set by the server, on the main thread, before it waits for the HTTP threads to finish.
|
||||
//!< Every wait and sleep in the tools then ends at once with a tool error, since the main
|
||||
//!< thread they would otherwise be waiting on is the one waiting for them
|
||||
void setStopping(bool stopping); |
||||
|
||||
private: |
||||
WebAPIAdapterInterface *m_adapter; |
||||
MCPEventCounter m_events; |
||||
MCPDocs m_docs; |
||||
MCPDataFeed m_dataFeed; |
||||
MCPCapture m_capture; |
||||
MCPStreams *m_streams; |
||||
|
||||
// Creating an object and working out which one is new must not overlap with another
|
||||
// creation, or two callers snapshot the same state and both claim the same object.
|
||||
// The capture tools run without the dispatch lock, so this is reachable.
|
||||
QMutex m_creationMutex; |
||||
// Deletion is by index, and the index is resolved just before the delete is posted for
|
||||
// the main thread to do later. Two calls deleting on one device set unserialised can post
|
||||
// two indices that were right when read and wrong once the first delete has renumbered
|
||||
// the rest, taking a channel neither meant. Held from the lookup to the object being gone
|
||||
QMutex m_deletionMutex; |
||||
// The channels listen and scan have added, so that the next of either on the same device
|
||||
// set can take them away again and cleanup can remove them all. Held by uid rather than
|
||||
// pointer: a channel removed from the GUI frees its address for the next one created,
|
||||
// which must not then be taken for one of these. They run without the dispatch lock, so
|
||||
// this has a lock of its own, which is never held across addChannelAndWait or a delete:
|
||||
// those take m_creationMutex or wait
|
||||
QMutex m_intentMutex; |
||||
QSet<uint64_t> m_intentChannels; |
||||
// The features listen added for a mode's output (AIS, Radiosonde, APRS), removed again once no
|
||||
// channel it added still feeds them. A feature that was already there is never among these
|
||||
QSet<uint64_t> m_intentFeatures; |
||||
const QObject *m_ownerFeature; |
||||
QAtomicInt m_stopping; |
||||
QList<Tool> m_tools; |
||||
// The definitions are loaded on first use and the parsed schemas cached as they are asked
|
||||
// for, from whichever thread asks. The settings tools run under the dispatch lock but
|
||||
// listen and scan do not, and they patch settings too, so these have a lock of their own,
|
||||
// taken by describeType and settingsSchema; the helpers they call expect it held
|
||||
QMutex m_schemaMutex; |
||||
QMap<QString, QString> m_yamlDefinitions; //!< Swagger definition name -> YAML text
|
||||
QMap<QString, QString> m_yamlDefinitionsByLower; //!< Lower cased name -> the name as written
|
||||
QMap<QString, SettingsSchema> m_schemaCache; //!< Parsed form of the above, by definition name
|
||||
bool m_yamlLoaded; |
||||
|
||||
void add(const QString& name, const QString& description, const QJsonObject& inputSchema, |
||||
std::function<QJsonValue(const QJsonObject& args)> handler); |
||||
|
||||
void registerInstanceTools(); |
||||
void registerDeviceSetTools(); |
||||
void registerChannelTools(); |
||||
void registerFeatureTools(); |
||||
void registerPresetTools(); |
||||
void registerWorkspaceTools(); |
||||
void registerCaptureTools(); |
||||
void registerIntentTools(); |
||||
|
||||
//!< Polls until the condition holds, at most timeoutMs. False on timeout; throws when the
|
||||
//!< server is stopping, as nothing waited for on the main thread will happen then
|
||||
bool waitFor(const std::function<bool()>& condition, int timeoutMs = m_waitTimeoutMs) const; |
||||
//!< A sleep that a stop cuts short, with the same tool error
|
||||
void pause(int ms) const; |
||||
static const int m_waitTimeoutMs = 5000; |
||||
|
||||
// Device set helpers
|
||||
int channelCount(int deviceSetIndex) const; |
||||
int featureCount() const; |
||||
int deviceSetDirection(int deviceSetIndex); |
||||
QJsonObject selectDevice(int deviceSetIndex, const QJsonObject& args); |
||||
QJsonObject getDeviceSettings(int deviceSetIndex); |
||||
QJsonObject patchDeviceSettings(int deviceSetIndex, const QJsonObject& partial); |
||||
int addChannelAndWait(int deviceSetIndex, const QString& channelType); |
||||
int addFeatureAndWait(const QString& featureType); |
||||
int addDeviceSetAndWait(int direction); |
||||
//!< Identity of the current channels, features or device sets, to spot which one is new.
|
||||
//!< Channels and features are identified by UID throughout: a pointer to one is only ever
|
||||
//!< good until the next wait, since a deleted object's address is reused by the next one
|
||||
//!< created, and every tool here waits
|
||||
QSet<uint64_t> channelUids(int deviceSetIndex) const; |
||||
QSet<uint64_t> featureUids() const; |
||||
QSet<const void *> deviceSetPointers() const; |
||||
void deleteChannelAndWait(int deviceSetIndex, int channelIndex); |
||||
void deleteChannelLocked(int deviceSetIndex, int channelIndex); //!< With m_deletionMutex held
|
||||
//!< Removes a device set that listen or scan created and could not finish setting up, if it
|
||||
//!< is still the last one, which is the only one the API can remove
|
||||
void discardNewDeviceSet(int deviceSetIndex, uint64_t identity); |
||||
//!< What tells one device set from another that has since taken its index: the engine's UID
|
||||
//!< together with the object's address. Zero when there is no such device set
|
||||
uint64_t deviceSetIdentity(int deviceSetIndex) const; |
||||
friend class NewDeviceSetGuard; |
||||
//!< Deletes a channel wherever it has moved to, for callers that held on to it across a wait
|
||||
void deleteChannelObjectAndWait(uint64_t channelUid); |
||||
const void *featureAt(int featureIndex) const; |
||||
//!< The UID of the feature or channel at an index, 0 when there is none
|
||||
uint64_t featureUidAt(int featureIndex) const; |
||||
uint64_t channelUidAt(int deviceSetIndex, int channelIndex) const; |
||||
void requireNotSelf(int featureIndex, const QString& action) const; |
||||
QJsonObject getChannelSettings(int deviceSetIndex, int channelIndex); |
||||
QJsonObject patchChannelSettings(int deviceSetIndex, int channelIndex, const QJsonObject& partial); |
||||
//!< The property names and types of one settings definition. Used to tell a misspelled key from
|
||||
//!< a valid one, and to reject a value of the wrong type before it reaches the SWG object
|
||||
SettingsSchema settingsSchema(const QString& definition); |
||||
QString resolveDefinition(const QString& name); //!< Call with m_schemaMutex held
|
||||
QJsonObject getSpectrumSettings(int deviceSetIndex); |
||||
//!< unknownKeys, when given, receives the patch keys the schema does not define
|
||||
QJsonObject patchSpectrumSettings(int deviceSetIndex, const QJsonObject& partial, QStringList *unknownKeys = nullptr); |
||||
//!< Explains an rdsReport that is absent because RDS decoding is switched off, rather than
|
||||
//!< because nothing has been decoded yet
|
||||
void addRdsHint(QJsonObject& report, const QString& channelType, int deviceSetIndex, int channelIndex); |
||||
QJsonObject getFeatureSettings(int featureIndex); |
||||
QJsonObject patchFeatureSettings(int featureIndex, const QJsonObject& partial); |
||||
QJsonObject deviceState(int deviceSetIndex, int subsystemIndex, int run); //!< run: 1 start, 0 stop, -1 query
|
||||
//!< Empty unless the device set's baseband is too narrow for this channel type
|
||||
QString basebandWarning(int deviceSetIndex, const QString& channelType); |
||||
//!< The same for every channel a device set holds
|
||||
QStringList basebandWarnings(int deviceSetIndex); |
||||
QJsonObject featureState(int featureIndex, int run); |
||||
QJsonObject presetIdentifier(const QJsonObject& args, int deviceSetIndex, bool forSave); |
||||
|
||||
// Shared by the intent level tools
|
||||
QJsonObject channelReport(int deviceSetIndex, int channelIndex); |
||||
void postChannelAction(int deviceSetIndex, int channelIndex, const QJsonObject& actions); |
||||
//!< doomed: uids of channels the caller is about to remove, which the reused set is not counted as carrying.
|
||||
//!< profileGain: give a device set this creates the fixed receiver gain profile; false when the gain is about to be measured
|
||||
QJsonObject pickReceiver(const QJsonObject& args, int minBaseband, const QSet<uint64_t>& doomed = QSet<uint64_t>(), bool profileGain = true); |
||||
//!< The tune_gain tool: sweeps the gain and applies the best, with the table it measured
|
||||
QJsonObject tuneGain(const QJsonObject& args); |
||||
//!< Sets the main spectrum's reference level and range from what it shows, as the GUI's autoscale button does
|
||||
void autoscaleSpectrum(int deviceSetIndex); |
||||
//!< Turns spectrum scrolling on if it is off, which is what keeps the history the spectrum
|
||||
//!< history tools read. Returns a note when it did, empty otherwise
|
||||
QString ensureSpectrumHistory(int deviceSetIndex, double seconds); |
||||
//!< The index of a feature of this type, adding one if there is none. Returns whether it was added
|
||||
int ensureFeature(const QString& featureType, int& featureIndex); |
||||
void trackIntentFeature(uint64_t featureUid); |
||||
//!< Removes the features listen added that no channel it added still feeds, except one of keepType.
|
||||
//!< Returns the types of those removed
|
||||
QStringList reclaimIntentFeatures(const QString& keepType = QString()); |
||||
//!< Deletes a feature wherever it has been renumbered to
|
||||
void deleteFeatureObjectAndWait(uint64_t featureUid); |
||||
//!< Whether listen or scan should measure the gain: a device set they created, or a retune to another band
|
||||
static bool gainWorthTuning(bool reused, double previousCentre, double centre); |
||||
void trackIntentChannel(uint64_t channelUid); |
||||
void untrackIntentChannel(uint64_t channelUid); |
||||
QSet<uint64_t> intentChannels(); |
||||
//!< A channel's type id and whether listen or scan added it, for the notes the intent tools leave
|
||||
struct ChannelNote { uint64_t m_uid; int m_index; QString m_id; bool m_intent; }; |
||||
QList<ChannelNote> channelNotes(int deviceSetIndex, const QSet<uint64_t>& except = QSet<uint64_t>()); |
||||
//!< Removes the channels listen and scan added to a device set, except keep. Returns the ids of those removed
|
||||
QStringList reclaimIntentChannels(int deviceSetIndex, const QSet<uint64_t>& keep = QSet<uint64_t>()); |
||||
//!< The channel a previous listen added that a new one of this type can retune instead of replacing, or 0.
|
||||
//!< wanted: how many of the type the mode uses, 2 for a paired mode
|
||||
uint64_t reusableIntentChannel(int deviceSetIndex, const QString& channelType, int& channelIndex, int wanted = 1); |
||||
//!< What a retune of a reused device set did to the channels listen and scan did not add
|
||||
struct RetuneOutcome |
||||
{ |
||||
QStringList m_kept; //!< Re-offset so that they stay on the frequency they had
|
||||
QStringList m_removed; //!< Audio demodulators the new baseband could not hold, which would only have made noise
|
||||
QStringList m_stranded; //!< Left where they were: not audio, or the baseband unknown
|
||||
}; |
||||
RetuneOutcome retuneOtherChannels(int deviceSetIndex, double previousCentre, double centre, int baseband); |
||||
//!< What listen and scan tell the caller about the rest of the device set once their own channels are in
|
||||
QStringList intentNotes(int deviceSetIndex, const QSet<uint64_t>& added, const QStringList& reclaimed, |
||||
bool reused, double previousCentre, double centre, const RetuneOutcome& outcome); |
||||
//!< Channel type ids for a direction, independent of how list_channel_types formats them
|
||||
QStringList channelTypeIds(int direction); |
||||
//!< Where a channel is now. The intent tools sleep for many seconds without holding the
|
||||
//!< protocol mutex, and a concurrent request that deletes a lower numbered channel
|
||||
//!< renumbers everything above it, so their indices have to be resolved again before use.
|
||||
void relocateChannel(uint64_t channelUid, int& deviceSetIndex, int& channelIndex, const QString& what); |
||||
|
||||
void loadYamlDefinitions(); //!< Call with m_schemaMutex held
|
||||
}; |
||||
|
||||
#endif // INCLUDE_FEATURE_MCPTOOLS_H_
|
||||
|
||||
@ -1,171 +1,171 @@
@@ -1,171 +1,171 @@
|
||||
<h1>MCP Server Feature Plugin</h1> |
||||
|
||||
<h2>Introduction</h2> |
||||
|
||||
This feature exposes SDRangel to AI agents through the [Model Context Protocol](https://modelcontextprotocol.io/) (MCP), so that an assistant such as Claude or ChatGPT/Codex can inspect and control SDRangel: create device sets, select SDR hardware, tune, add demodulators, change settings, read reports, load presets and so on. |
||||
|
||||
The plugin runs an MCP server using the Streamable HTTP transport. MCP clients connect to `http://address:port/mcp`. |
||||
|
||||
[Tutorial Video](https://youtu.be/G0FmiX7zwb8) |
||||
|
||||
<h2>Interface</h2> |
||||
|
||||
 |
||||
|
||||
<h3>1: Start/Stop</h3> |
||||
|
||||
Starts or stops the MCP server. The button is green when the server is listening and red if it could not listen on the requested address and port. |
||||
|
||||
<h3>2: Endpoint URL</h3> |
||||
|
||||
The URL to give to MCP clients. |
||||
|
||||
<h3>3: Address</h3> |
||||
|
||||
IP address to listen on. The default of 127.0.0.1 only accepts connections from the local computer. Use 0.0.0.0 to accept connections from any network interface, in which case a token should be set. |
||||
|
||||
<h3>4: Port</h3> |
||||
|
||||
TCP port to listen on. The default is 8092. |
||||
|
||||
<h3>5: Capture directory</h3> |
||||
|
||||
Directory that the capture tools write IQ and audio files to. It defaults to `SDRangel/captures` under your documents folder. File names given to the capture tools are relative to it, and names that would write outside it are refused, so a connected agent cannot write anywhere else on the machine. |
||||
|
||||
<h3>6: Token</h3> |
||||
|
||||
Optional bearer token. When set, clients must send an `Authorization: Bearer <token>` HTTP header. Leave empty for no authentication. |
||||
|
||||
<h3>7: Add to Codex</h3> |
||||
|
||||
Writes this server into Codex's `config.toml`. |
||||
Codex reads its configuration at startup, so restart it afterwards. |
||||
|
||||
<h3>8: Add to Claude Desktop</h3> |
||||
|
||||
Opens the extension bundle with Claude Desktop, which then shows its own dialog asking whether to install it. |
||||
|
||||
<h3>9: Status</h3> |
||||
|
||||
Number of MCP requests served since the server was started and the last request received. |
||||
|
||||
<h2>Connecting a client</h2> |
||||
|
||||
<h3>Claude Code</h3> |
||||
|
||||
For clients that support remote (HTTP) MCP servers, add the endpoint URL directly: |
||||
|
||||
claude mcp add --transport http sdrangel http://127.0.0.1:8092/mcp |
||||
|
||||
<h3>Claude Desktop</h3> |
||||
|
||||
Claude Desktop cannot connect directly to a HTTP server. |
||||
Install the SDRangel extension, which carries a small [bridge](bridge/readme.md) that relays the stdio |
||||
transport Claude Desktop does support to this server. Press Add to Claude Desktop (8) to hand |
||||
it the bundle; on Windows the installer also offers to do this at the end of a fresh install. |
||||
Failing either, take `sdrangel-<version>-<platform>.mcpb` from the release and open it with |
||||
Claude Desktop, or drag it onto Settings > Extensions. Set the port in the extension's |
||||
settings if it is not the default 8092. |
||||
|
||||
For other clients that only support local stdio servers, run the same bridge directly, in: |
||||
|
||||
- Windows: %APPDATA%\Claude\claude_desktop_config.json |
||||
- Linux: ~/.config/Claude/claude_desktop_config.json |
||||
- macOS: ~/Library/Application Support/Claude/claude_desktop_config.json |
||||
|
||||
``` |
||||
"mcpServers": { |
||||
"sdrangel": { |
||||
"command": "C:\\Program Files\\SDRangel\\sdrangel-mcp-bridge.exe", |
||||
"args": ["--port", "8092"] |
||||
} |
||||
} |
||||
``` |
||||
|
||||
`npx -y mcp-remote http://127.0.0.1:8092/mcp` does the same job for a client that has no |
||||
bridge built for its platform, at the cost of needing Node.js installed. |
||||
|
||||
<h3>ChatGPT/Codex</h3> |
||||
|
||||
Codex supports the HTTP transport, so does not need a bridge. Press Add to Codex (7) to have the |
||||
server's address written to its configuration file, or add the following by hand to: |
||||
|
||||
- Windows: %USERPROFILE%\.codex\config.toml |
||||
- macOS/Linux: ~/.codex/config.toml |
||||
|
||||
``` |
||||
[mcp_servers.sdrangel] |
||||
url = "http://127.0.0.1:8092/mcp" |
||||
``` |
||||
|
||||
With a token set, the header goes alongside it: |
||||
|
||||
``` |
||||
[mcp_servers.sdrangel] |
||||
url = "http://127.0.0.1:8092/mcp" |
||||
http_headers = { "Authorization" = "Bearer <token>" } |
||||
``` |
||||
|
||||
<h2>Tools</h2> |
||||
|
||||
The intent tools do a whole task in one call: `listen` sets up a receiver on a frequency in a given mode, `scan` sets up a Frequency Scanner over a list or range of frequencies and reports every frequency above the threshold with its level (and, for intermittent signals, where the scanner parked), stepping by the channel spacing usual for the mode unless told otherwise and refusing modes that live on fixed frequencies, and `get_status` returns one line per device set and feature. Both `listen` and `scan` keep track of the channels they add: by default the next of either on the same device set removes them first, so that exploring a band does not leave a trail of demodulators all playing audio, and `cleanup` removes them all. A `listen` that finds a demodulator of the type it needs among them retunes it instead, as a person would, so stepping through a band in one mode keeps one channel open throughout. Both measure and set the receiver gain, as `tune_gain` does, when they create a device set or move one to another band, and leave it alone otherwise or when told `tuneGain` false. A mode whose output goes to a feature (AIS, radiosondes, APRS) has `listen` add that feature when it is absent, and remove it again, along with the channels, once nothing it added feeds it; a feature that was already there is left alone. AIS gets a demodulator on each of its two channels with the device centred between them. Channels added any other way are kept on the frequency they had, by moving their offset, when the retuned baseband still holds them; an audio demodulator it cannot hold is removed, since all it could do is play noise, while anything else (a file sink, an analyser) is left in place and named in the reply. The rest mirror the Web API. Creation tools wait for SDRangel to complete the operation and return the index of the new object; the `set_*` tools reply with only the keys that were changed, since a client carries every reply in its context for the rest of the conversation. |
||||
|
||||
| Area | Tools | |
||||
|------|-------| |
||||
| Intent | `listen`, `scan`, `cleanup`, `tune_gain`, `get_status` | |
||||
| Discovery | `get_instance_summary`, `list_available_devices`, `list_channel_types`, `list_feature_types`, `describe_settings`, `get_receiving_guide`, `list_docs`, `get_docs`, `list_audio_devices`, `get_location`, `set_location` | |
||||
| Device sets | `add_deviceset`, `remove_last_deviceset`, `get_deviceset`, `set_device`, `get_device_settings`, `set_device_settings`, `set_center_frequency`, `start_device`, `stop_device`, `get_device_report`, `device_action`, `get_spectrum_settings`, `set_spectrum_settings`, `get_spectrum_data`, `get_spectrum_history`, `get_waterfall_image`, `spectrum_action` | |
||||
| Channels | `add_channel`, `delete_channel`, `get_channel_settings`, `set_channel_settings`, `get_channel_report`, `channel_action` | |
||||
| Features | `add_feature`, `delete_feature`, `get_feature_settings`, `set_feature_settings`, `get_feature_report`, `start_feature`, `stop_feature`, `feature_action` | |
||||
| Presets | `list_presets`, `load_preset`, `save_preset`, `list_configurations`, `load_configuration`, `save_configuration` | |
||||
| Workspaces (GUI only) | `add_workspace`, `delete_empty_workspaces`, `list_windows`, `set_workspace` (move, hide or show a window), `arrange_workspace` | |
||||
| Live data | `get_packets`, `clear_packets`, `get_map_items` | |
||||
| Capture | `capture_audio`, `record_iq`, `start_iq_recording`, `stop_iq_recording` | |
||||
| Server | `get_server_status` (open streams, capture directory and active recordings, data feed sources) | |
||||
|
||||
Each tool carries MCP annotations: whether it only reads, whether it overwrites state rather than only adding to it, whether repeating it lands in the same place, and whether it reaches beyond this application, which covers commanding the radio and data received from transmitters SDRangel does not control. |
||||
|
||||
`describe_settings` returns the OpenAPI documentation of the settings, report and actions keys of a device, channel or feature type, so that an agent can learn the valid keys rather than guess them. The `set_*_settings` tools accept a partial settings object containing only the keys to change. |
||||
|
||||
`get_packets` returns the packets received on the `packets`, `ais` and `radiosonde` message pipes of the packet, ChirpChat, M17, Meshtastic, MeshCore, Inmarsat, AIS and radiosonde demodulators, kept in a buffer of the last 1000. Each packet carries the raw bytes and, where possible, a decode: AIS message type, MMSI, position, course and speed; AX.25 addresses and data with the APRS position and comment; RS41 serial, position and height. `get_map_items` returns the objects that the same channels and features that feed the Map send on the `mapitems` pipe (aircraft, ships, APRS stations, radiosondes, satellites, Sun and Moon, beacons), with the image, text and, on request, the track. Items are removed when their source removes them or is deleted. Both work whether or not a Map or AIS/APRS feature is present. |
||||
|
||||
`record_iq` records baseband IQ to an `.sdriq` file for a fixed number of seconds and returns the files written; `start_iq_recording` and `stop_iq_recording` do the same without a time limit for longer captures. Both work by adding a File Sink channel to the device set, so the recording has the offset and decimation the tools are given. `capture_audio` records the demodulated audio of a channel to a WAV file, and reports the sample rate, the peak level and whether the audio was silent, which tells an agent that a squelch is closed rather than that nothing is wrong. It works with demodulators that feed the Demod Analyzer, such as NFMDemod, AMDemod, SSBDemod, WFMDemod and BFMDemod. With `inline` true it also returns the audio as base64, as a mono 16 kHz copy, since MCP clients refuse a tool result over about a megabyte and ten seconds at 48 kHz would exceed that once encoded; the file keeps the full rate. Both blocking tools are capped at 30 seconds so they cannot hold an MCP client's connection open indefinitely. |
||||
|
||||
`get_receiving_guide` serves a hand written guide in `bandguide.md`: which demodulator and frequency to use for each signal SDRangel can receive, the minimum device sample rate that ADS-B, DAB and broadcast FM need, and the usual reasons nothing is received. Its frequencies come from the plugin readmes, and a test checks that every channel id it names is registered in the build. Edit that file to correct or extend it; it is compiled into the plugin, so re-run cmake after changing it. |
||||
|
||||
`list_docs` and `get_docs` serve the readme of every plugin registered in the running instance, and the GUI's own pages for what no plugin owns: the spectrum display (`spectrum`, with `spectrummarkers`, `spectrummeasurements` and `spectrumcalibration`), the main spectrum window, audio management, configurations, device user arguments and the transverter dialog. The readmes are compiled into this plugin at build time (re-run cmake after adding a plugin), converted to plain markdown with images removed, and matched to plugin ids by name; the GUI pages are listed in `CMakeLists.txt` and given their ids in `MCPDocs::addGuiDocs`. `get_docs` accepts a plugin id or its displayed name and an optional section heading, so an agent can read just the part it needs from a long document. |
||||
|
||||
<h2>Event stream</h2> |
||||
|
||||
A client can be told when a resource changes instead of polling for it. An HTTP GET on the endpoint with `Accept: text/event-stream` opens a Server-Sent Events stream, and `resources/subscribe` asks for a resource on it. Updates arrive as `notifications/resources/updated`, at most once a second per resource so that a busy decoder cannot flood the stream. `sdrangel://instance`, `sdrangel://packets`, `sdrangel://map/items` and `sdrangel://deviceset/{index}` can be subscribed to; the other resources never change. |
||||
|
||||
`initialize` returns an `Mcp-Session-Id` header. A client that sends it back keeps its own subscriptions and stream, and can end them with an HTTP DELETE. Clients that ignore it share an anonymous session, which works fully for one client at a time. A client keeps one stream: opening a second replaces the first, so a notification is never delivered twice. That applies to clients that send no session id as well, since they already share the anonymous subscriptions. Sessions with no stream are dropped after a day idle, and at most 32 are kept, each with at most 32 subscriptions. Up to eight streams may be open at once, and a stream is closed after ten minutes so that a client which vanished without closing its connection cannot hold a thread forever; clients reconnect. |
||||
|
||||
<h2>Resources</h2> |
||||
|
||||
| URI | Content | |
||||
|-----|---------| |
||||
| `sdrangel://instance` | Instance summary | |
||||
| `sdrangel://plugins/devices` | Available sampling devices | |
||||
| `sdrangel://plugins/channels` | Available channel types | |
||||
| `sdrangel://plugins/features` | Available feature types | |
||||
| `sdrangel://presets` | Saved presets | |
||||
| `sdrangel://configurations` | Saved configurations | |
||||
| `sdrangel://deviceset/{index}` | A device set | |
||||
| `sdrangel://schema/{type}` | Settings documentation for a type | |
||||
| `sdrangel://packets` | The 100 most recent decoded packets, from a buffer of the last 1000 | |
||||
| `sdrangel://map/items` | Objects currently plotted on the map | |
||||
| `sdrangel://guide` | The receiving guide | |
||||
| `sdrangel://docs` | Index of plugin and GUI documentation with section headings | |
||||
| `sdrangel://docs/{kind}/{id}` | A document as markdown, e.g. `sdrangel://docs/channel/ADSBDemod` or `sdrangel://docs/gui/spectrum` | |
||||
|
||||
<h2>Prompts</h2> |
||||
|
||||
`setup_receiver`, `record_iq` and `explain_configuration` are prompt templates that guide an agent through common tasks. |
||||
|
||||
<h2>Security</h2> |
||||
|
||||
The server has no access control beyond the optional bearer token, and an agent connected to it can change anything in SDRangel. Keep the address at 127.0.0.1 unless a token is set. |
||||
|
||||
To keep web pages from driving the server through a browser, requests carrying an `Origin` header are only accepted from an `http` or `https` localhost origin (the opaque `null` origin is rejected), and the request body must be declared as `application/json`. |
||||
|
||||
<h1>MCP Server Feature Plugin</h1> |
||||
|
||||
<h2>Introduction</h2> |
||||
|
||||
This feature exposes SDRangel to AI agents through the [Model Context Protocol](https://modelcontextprotocol.io/) (MCP), so that an assistant such as Claude or ChatGPT/Codex can inspect and control SDRangel: create device sets, select SDR hardware, tune, add demodulators, change settings, read reports, load presets and so on. |
||||
|
||||
The plugin runs an MCP server using the Streamable HTTP transport. MCP clients connect to `http://address:port/mcp`. |
||||
|
||||
[Tutorial Video](https://youtu.be/G0FmiX7zwb8) |
||||
|
||||
<h2>Interface</h2> |
||||
|
||||
 |
||||
|
||||
<h3>1: Start/Stop</h3> |
||||
|
||||
Starts or stops the MCP server. The button is green when the server is listening and red if it could not listen on the requested address and port. |
||||
|
||||
<h3>2: Endpoint URL</h3> |
||||
|
||||
The URL to give to MCP clients. |
||||
|
||||
<h3>3: Address</h3> |
||||
|
||||
IP address to listen on. The default of 127.0.0.1 only accepts connections from the local computer. Use 0.0.0.0 to accept connections from any network interface, in which case a token should be set. |
||||
|
||||
<h3>4: Port</h3> |
||||
|
||||
TCP port to listen on. The default is 8092. |
||||
|
||||
<h3>5: Capture directory</h3> |
||||
|
||||
Directory that the capture tools write IQ and audio files to. It defaults to `SDRangel/captures` under your documents folder. File names given to the capture tools are relative to it, and names that would write outside it are refused, so a connected agent cannot write anywhere else on the machine. |
||||
|
||||
<h3>6: Token</h3> |
||||
|
||||
Optional bearer token. When set, clients must send an `Authorization: Bearer <token>` HTTP header. Leave empty for no authentication. |
||||
|
||||
<h3>7: Add to Codex</h3> |
||||
|
||||
Writes this server into Codex's `config.toml`. |
||||
Codex reads its configuration at startup, so restart it afterwards. |
||||
|
||||
<h3>8: Add to Claude Desktop</h3> |
||||
|
||||
Opens the extension bundle with Claude Desktop, which then shows its own dialog asking whether to install it. |
||||
|
||||
<h3>9: Status</h3> |
||||
|
||||
Number of MCP requests served since the server was started and the last request received. |
||||
|
||||
<h2>Connecting a client</h2> |
||||
|
||||
<h3>Claude Code</h3> |
||||
|
||||
For clients that support remote (HTTP) MCP servers, add the endpoint URL directly: |
||||
|
||||
claude mcp add --transport http sdrangel http://127.0.0.1:8092/mcp |
||||
|
||||
<h3>Claude Desktop</h3> |
||||
|
||||
Claude Desktop cannot connect directly to a HTTP server. |
||||
Install the SDRangel extension, which carries a small [bridge](bridge/readme.md) that relays the stdio |
||||
transport Claude Desktop does support to this server. Press Add to Claude Desktop (8) to hand |
||||
it the bundle; on Windows the installer also offers to do this at the end of a fresh install. |
||||
Failing either, take `sdrangel-<version>-<platform>.mcpb` from the release and open it with |
||||
Claude Desktop, or drag it onto Settings > Extensions. Set the port in the extension's |
||||
settings if it is not the default 8092. |
||||
|
||||
For other clients that only support local stdio servers, run the same bridge directly, in: |
||||
|
||||
- Windows: %APPDATA%\Claude\claude_desktop_config.json |
||||
- Linux: ~/.config/Claude/claude_desktop_config.json |
||||
- macOS: ~/Library/Application Support/Claude/claude_desktop_config.json |
||||
|
||||
``` |
||||
"mcpServers": { |
||||
"sdrangel": { |
||||
"command": "C:\\Program Files\\SDRangel\\sdrangel-mcp-bridge.exe", |
||||
"args": ["--port", "8092"] |
||||
} |
||||
} |
||||
``` |
||||
|
||||
`npx -y mcp-remote http://127.0.0.1:8092/mcp` does the same job for a client that has no |
||||
bridge built for its platform, at the cost of needing Node.js installed. |
||||
|
||||
<h3>ChatGPT/Codex</h3> |
||||
|
||||
Codex supports the HTTP transport, so does not need a bridge. Press Add to Codex (7) to have the |
||||
server's address written to its configuration file, or add the following by hand to: |
||||
|
||||
- Windows: %USERPROFILE%\.codex\config.toml |
||||
- macOS/Linux: ~/.codex/config.toml |
||||
|
||||
``` |
||||
[mcp_servers.sdrangel] |
||||
url = "http://127.0.0.1:8092/mcp" |
||||
``` |
||||
|
||||
With a token set, the header goes alongside it: |
||||
|
||||
``` |
||||
[mcp_servers.sdrangel] |
||||
url = "http://127.0.0.1:8092/mcp" |
||||
http_headers = { "Authorization" = "Bearer <token>" } |
||||
``` |
||||
|
||||
<h2>Tools</h2> |
||||
|
||||
The intent tools do a whole task in one call: `listen` sets up a receiver on a frequency in a given mode, `scan` sets up a Frequency Scanner over a list or range of frequencies and reports every frequency above the threshold with its level (and, for intermittent signals, where the scanner parked), stepping by the channel spacing usual for the mode unless told otherwise and refusing modes that live on fixed frequencies, and `get_status` returns one line per device set and feature. Both `listen` and `scan` keep track of the channels they add: by default the next of either on the same device set removes them first, so that exploring a band does not leave a trail of demodulators all playing audio, and `cleanup` removes them all. A `listen` that finds a demodulator of the type it needs among them retunes it instead, as a person would, so stepping through a band in one mode keeps one channel open throughout. Both measure and set the receiver gain, as `tune_gain` does, when they create a device set or move one to another band, and leave it alone otherwise or when told `tuneGain` false. A mode whose output goes to a feature (AIS, radiosondes, APRS) has `listen` add that feature when it is absent, and remove it again, along with the channels, once nothing it added feeds it; a feature that was already there is left alone. AIS gets a demodulator on each of its two channels with the device centred between them. Channels added any other way are kept on the frequency they had, by moving their offset, when the retuned baseband still holds them; an audio demodulator it cannot hold is removed, since all it could do is play noise, while anything else (a file sink, an analyser) is left in place and named in the reply. The rest mirror the Web API. Creation tools wait for SDRangel to complete the operation and return the index of the new object; the `set_*` tools reply with only the keys that were changed, since a client carries every reply in its context for the rest of the conversation. |
||||
|
||||
| Area | Tools | |
||||
|------|-------| |
||||
| Intent | `listen`, `scan`, `cleanup`, `tune_gain`, `get_status` | |
||||
| Discovery | `get_instance_summary`, `list_available_devices`, `list_channel_types`, `list_feature_types`, `describe_settings`, `get_receiving_guide`, `list_docs`, `get_docs`, `list_audio_devices`, `get_location`, `set_location` | |
||||
| Device sets | `add_deviceset`, `remove_last_deviceset`, `get_deviceset`, `set_device`, `get_device_settings`, `set_device_settings`, `set_center_frequency`, `start_device`, `stop_device`, `get_device_report`, `device_action`, `get_spectrum_settings`, `set_spectrum_settings`, `get_spectrum_data`, `get_spectrum_history`, `get_waterfall_image`, `spectrum_action` | |
||||
| Channels | `add_channel`, `delete_channel`, `get_channel_settings`, `set_channel_settings`, `get_channel_report`, `channel_action` | |
||||
| Features | `add_feature`, `delete_feature`, `get_feature_settings`, `set_feature_settings`, `get_feature_report`, `start_feature`, `stop_feature`, `feature_action` | |
||||
| Presets | `list_presets`, `load_preset`, `save_preset`, `list_configurations`, `load_configuration`, `save_configuration` | |
||||
| Workspaces (GUI only) | `add_workspace`, `delete_empty_workspaces`, `list_windows`, `set_workspace` (move, hide or show a window), `arrange_workspace` | |
||||
| Live data | `get_packets`, `clear_packets`, `get_map_items` | |
||||
| Capture | `capture_audio`, `record_iq`, `start_iq_recording`, `stop_iq_recording` | |
||||
| Server | `get_server_status` (open streams, capture directory and active recordings, data feed sources) | |
||||
|
||||
Each tool carries MCP annotations: whether it only reads, whether it overwrites state rather than only adding to it, whether repeating it lands in the same place, and whether it reaches beyond this application, which covers commanding the radio and data received from transmitters SDRangel does not control. |
||||
|
||||
`describe_settings` returns the OpenAPI documentation of the settings, report and actions keys of a device, channel or feature type, so that an agent can learn the valid keys rather than guess them. The `set_*_settings` tools accept a partial settings object containing only the keys to change. |
||||
|
||||
`get_packets` returns the packets received on the `packets`, `ais` and `radiosonde` message pipes of the packet, ChirpChat, M17, Meshtastic, MeshCore, Inmarsat, AIS and radiosonde demodulators, kept in a buffer of the last 1000. Each packet carries the raw bytes and, where possible, a decode: AIS message type, MMSI, position, course and speed; AX.25 addresses and data with the APRS position and comment; RS41 serial, position and height. `get_map_items` returns the objects that the same channels and features that feed the Map send on the `mapitems` pipe (aircraft, ships, APRS stations, radiosondes, satellites, Sun and Moon, beacons), with the image, text and, on request, the track. Items are removed when their source removes them or is deleted. Both work whether or not a Map or AIS/APRS feature is present. |
||||
|
||||
`record_iq` records baseband IQ to an `.sdriq` file for a fixed number of seconds and returns the files written; `start_iq_recording` and `stop_iq_recording` do the same without a time limit for longer captures. Both work by adding a File Sink channel to the device set, so the recording has the offset and decimation the tools are given. `capture_audio` records the demodulated audio of a channel to a WAV file, and reports the sample rate, the peak level and whether the audio was silent, which tells an agent that a squelch is closed rather than that nothing is wrong. It works with demodulators that feed the Demod Analyzer, such as NFMDemod, AMDemod, SSBDemod, WFMDemod and BFMDemod. With `inline` true it also returns the audio as base64, as a mono 16 kHz copy, since MCP clients refuse a tool result over about a megabyte and ten seconds at 48 kHz would exceed that once encoded; the file keeps the full rate. Both blocking tools are capped at 30 seconds so they cannot hold an MCP client's connection open indefinitely. |
||||
|
||||
`get_receiving_guide` serves a hand written guide in `bandguide.md`: which demodulator and frequency to use for each signal SDRangel can receive, the minimum device sample rate that ADS-B, DAB and broadcast FM need, and the usual reasons nothing is received. Its frequencies come from the plugin readmes, and a test checks that every channel id it names is registered in the build. Edit that file to correct or extend it; it is compiled into the plugin, so re-run cmake after changing it. |
||||
|
||||
`list_docs` and `get_docs` serve the readme of every plugin registered in the running instance, and the GUI's own pages for what no plugin owns: the spectrum display (`spectrum`, with `spectrummarkers`, `spectrummeasurements` and `spectrumcalibration`), the main spectrum window, audio management, configurations, device user arguments and the transverter dialog. The readmes are compiled into this plugin at build time (re-run cmake after adding a plugin), converted to plain markdown with images removed, and matched to plugin ids by name; the GUI pages are listed in `CMakeLists.txt` and given their ids in `MCPDocs::addGuiDocs`. `get_docs` accepts a plugin id or its displayed name and an optional section heading, so an agent can read just the part it needs from a long document. |
||||
|
||||
<h2>Event stream</h2> |
||||
|
||||
A client can be told when a resource changes instead of polling for it. An HTTP GET on the endpoint with `Accept: text/event-stream` opens a Server-Sent Events stream, and `resources/subscribe` asks for a resource on it. Updates arrive as `notifications/resources/updated`, at most once a second per resource so that a busy decoder cannot flood the stream. `sdrangel://instance`, `sdrangel://packets`, `sdrangel://map/items` and `sdrangel://deviceset/{index}` can be subscribed to; the other resources never change. |
||||
|
||||
`initialize` returns an `Mcp-Session-Id` header. A client that sends it back keeps its own subscriptions and stream, and can end them with an HTTP DELETE. Clients that ignore it share an anonymous session, which works fully for one client at a time. A client keeps one stream: opening a second replaces the first, so a notification is never delivered twice. That applies to clients that send no session id as well, since they already share the anonymous subscriptions. Sessions with no stream are dropped after a day idle, and at most 32 are kept, each with at most 32 subscriptions. Up to eight streams may be open at once, and a stream is closed after ten minutes so that a client which vanished without closing its connection cannot hold a thread forever; clients reconnect. |
||||
|
||||
<h2>Resources</h2> |
||||
|
||||
| URI | Content | |
||||
|-----|---------| |
||||
| `sdrangel://instance` | Instance summary | |
||||
| `sdrangel://plugins/devices` | Available sampling devices | |
||||
| `sdrangel://plugins/channels` | Available channel types | |
||||
| `sdrangel://plugins/features` | Available feature types | |
||||
| `sdrangel://presets` | Saved presets | |
||||
| `sdrangel://configurations` | Saved configurations | |
||||
| `sdrangel://deviceset/{index}` | A device set | |
||||
| `sdrangel://schema/{type}` | Settings documentation for a type | |
||||
| `sdrangel://packets` | The 100 most recent decoded packets, from a buffer of the last 1000 | |
||||
| `sdrangel://map/items` | Objects currently plotted on the map | |
||||
| `sdrangel://guide` | The receiving guide | |
||||
| `sdrangel://docs` | Index of plugin and GUI documentation with section headings | |
||||
| `sdrangel://docs/{kind}/{id}` | A document as markdown, e.g. `sdrangel://docs/channel/ADSBDemod` or `sdrangel://docs/gui/spectrum` | |
||||
|
||||
<h2>Prompts</h2> |
||||
|
||||
`setup_receiver`, `record_iq` and `explain_configuration` are prompt templates that guide an agent through common tasks. |
||||
|
||||
<h2>Security</h2> |
||||
|
||||
The server has no access control beyond the optional bearer token, and an agent connected to it can change anything in SDRangel. Keep the address at 127.0.0.1 unless a token is set. |
||||
|
||||
To keep web pages from driving the server through a browser, requests carrying an `Origin` header are only accepted from an `http` or `https` localhost origin (the opaque `null` origin is rejected), and the request body must be declared as `application/json`. |
||||
|
||||
|
||||
@ -1,83 +1,83 @@
@@ -1,83 +1,83 @@
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
|
||||
// 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 <http://www.gnu.org/licenses/>. //
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
// Writes the MCP tool list to a file at build time, so that the Claude Desktop extension can
|
||||
// carry the real list rather than inventing one. A client that starts before SDRangel reads
|
||||
// the tool list once and does not ask again, so the bridge has to be able to answer with the
|
||||
// tools this very build of the server provides, before it has ever spoken to it.
|
||||
//
|
||||
// The registry is metadata and handler functions: building it touches neither the Web API nor
|
||||
// any device, so a null adapter is all it needs.
|
||||
|
||||
#include <cstdio> |
||||
#include <cstdlib> |
||||
|
||||
#ifdef _WIN32 |
||||
#include <windows.h> |
||||
#endif |
||||
|
||||
#include <QCoreApplication> |
||||
#include <QFile> |
||||
#include <QJsonDocument> |
||||
#include <QJsonObject> |
||||
|
||||
#include "mcptools.h" |
||||
|
||||
int main(int argc, char *argv[]) |
||||
{ |
||||
QCoreApplication application(argc, argv); |
||||
|
||||
if (argc < 2) |
||||
{ |
||||
std::fprintf(stderr, "usage: %s <output file>\n", argv[0]); |
||||
return 2; |
||||
} |
||||
|
||||
std::fprintf(stderr, "toolsdump: application up\n"); |
||||
MCPTools tools(nullptr); |
||||
std::fprintf(stderr, "toolsdump: registry built\n"); |
||||
|
||||
QJsonObject result; |
||||
result["tools"] = tools.listTools(); |
||||
std::fprintf(stderr, "toolsdump: listed\n"); |
||||
|
||||
QFile file(QString::fromLocal8Bit(argv[1])); |
||||
|
||||
if (!file.open(QIODevice::WriteOnly)) |
||||
{ |
||||
std::fprintf(stderr, "cannot write %s: %s\n", argv[1], qPrintable(file.errorString())); |
||||
return 1; |
||||
} |
||||
|
||||
file.write(QJsonDocument(result).toJson(QJsonDocument::Compact)); |
||||
file.close(); |
||||
std::fprintf(stderr, "toolsdump: written\n"); |
||||
|
||||
std::fprintf(stderr, "%s: %d tools\n", argv[1], result["tools"].toArray().size()); |
||||
|
||||
// The registry brings background threads up with it and they do not all stop when main
|
||||
// returns, which leaves the process, and so the build, hanging. Even _Exit does not get
|
||||
// out, since the runtime's own teardown waits on them, so end the process from the kernel
|
||||
// side. The file is written and flushed by this point
|
||||
std::fflush(nullptr); |
||||
|
||||
#ifdef _WIN32 |
||||
TerminateProcess(GetCurrentProcess(), 0); |
||||
#endif |
||||
std::_Exit(0); |
||||
} |
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
|
||||
// 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 <http://www.gnu.org/licenses/>. //
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
// Writes the MCP tool list to a file at build time, so that the Claude Desktop extension can
|
||||
// carry the real list rather than inventing one. A client that starts before SDRangel reads
|
||||
// the tool list once and does not ask again, so the bridge has to be able to answer with the
|
||||
// tools this very build of the server provides, before it has ever spoken to it.
|
||||
//
|
||||
// The registry is metadata and handler functions: building it touches neither the Web API nor
|
||||
// any device, so a null adapter is all it needs.
|
||||
|
||||
#include <cstdio> |
||||
#include <cstdlib> |
||||
|
||||
#ifdef _WIN32 |
||||
#include <windows.h> |
||||
#endif |
||||
|
||||
#include <QCoreApplication> |
||||
#include <QFile> |
||||
#include <QJsonDocument> |
||||
#include <QJsonObject> |
||||
|
||||
#include "mcptools.h" |
||||
|
||||
int main(int argc, char *argv[]) |
||||
{ |
||||
QCoreApplication application(argc, argv); |
||||
|
||||
if (argc < 2) |
||||
{ |
||||
std::fprintf(stderr, "usage: %s <output file>\n", argv[0]); |
||||
return 2; |
||||
} |
||||
|
||||
std::fprintf(stderr, "toolsdump: application up\n"); |
||||
MCPTools tools(nullptr); |
||||
std::fprintf(stderr, "toolsdump: registry built\n"); |
||||
|
||||
QJsonObject result; |
||||
result["tools"] = tools.listTools(); |
||||
std::fprintf(stderr, "toolsdump: listed\n"); |
||||
|
||||
QFile file(QString::fromLocal8Bit(argv[1])); |
||||
|
||||
if (!file.open(QIODevice::WriteOnly)) |
||||
{ |
||||
std::fprintf(stderr, "cannot write %s: %s\n", argv[1], qPrintable(file.errorString())); |
||||
return 1; |
||||
} |
||||
|
||||
file.write(QJsonDocument(result).toJson(QJsonDocument::Compact)); |
||||
file.close(); |
||||
std::fprintf(stderr, "toolsdump: written\n"); |
||||
|
||||
std::fprintf(stderr, "%s: %d tools\n", argv[1], result["tools"].toArray().size()); |
||||
|
||||
// The registry brings background threads up with it and they do not all stop when main
|
||||
// returns, which leaves the process, and so the build, hanging. Even _Exit does not get
|
||||
// out, since the runtime's own teardown waits on them, so end the process from the kernel
|
||||
// side. The file is written and flushed by this point
|
||||
std::fflush(nullptr); |
||||
|
||||
#ifdef _WIN32 |
||||
TerminateProcess(GetCurrentProcess(), 0); |
||||
#endif |
||||
std::_Exit(0); |
||||
} |
||||
|
||||
|
Before Width: | Height: | Size: 779 B After Width: | Height: | Size: 760 B |
|
Before Width: | Height: | Size: 1.2 KiB After Width: | Height: | Size: 1.2 KiB |
|
Before Width: | Height: | Size: 2.2 KiB After Width: | Height: | Size: 2.2 KiB |
|
Before Width: | Height: | Size: 3.2 KiB After Width: | Height: | Size: 3.1 KiB |
|
Before Width: | Height: | Size: 3.7 KiB After Width: | Height: | Size: 3.6 KiB |
|
Before Width: | Height: | Size: 3.6 KiB After Width: | Height: | Size: 3.6 KiB |
|
Before Width: | Height: | Size: 4.1 KiB After Width: | Height: | Size: 4.0 KiB |
@ -1,172 +1,172 @@
@@ -1,172 +1,172 @@
|
||||
#include "checklist.h" |
||||
|
||||
CheckList::CheckList(QWidget* parent) : |
||||
QComboBox(parent) |
||||
{ |
||||
m_model = new QStandardItemModel(); |
||||
setModel(m_model); |
||||
|
||||
setEditable(true); |
||||
lineEdit()->setReadOnly(true); |
||||
lineEdit()->installEventFilter(this); |
||||
setItemDelegate(new QCheckListStyledItemDelegate(this)); |
||||
|
||||
connect(lineEdit(), &QLineEdit::selectionChanged, lineEdit(), &QLineEdit::deselect); |
||||
connect((QListView*) view(), SIGNAL(pressed(QModelIndex)), this, SLOT(on_itemPressed(QModelIndex))); |
||||
connect(m_model, SIGNAL(dataChanged(QModelIndex, QModelIndex, QVector<int>)), this, SLOT(on_modelDataChanged())); |
||||
} |
||||
|
||||
CheckList::~CheckList() |
||||
{ |
||||
delete m_model; |
||||
} |
||||
|
||||
void CheckList::setText(const QString &text) |
||||
{ |
||||
m_text = text; |
||||
updateText(); |
||||
} |
||||
|
||||
void CheckList::setAllCheckedText(const QString &text) |
||||
{ |
||||
m_allCheckedText = text; |
||||
updateText(); |
||||
} |
||||
|
||||
void CheckList::setNoneCheckedText(const QString &text) |
||||
{ |
||||
m_noneCheckedText = text; |
||||
updateText(); |
||||
} |
||||
|
||||
void CheckList::setUnknownlyCheckedText(const QString &text) |
||||
{ |
||||
m_unknownlyCheckedText = text; |
||||
updateText(); |
||||
} |
||||
|
||||
void CheckList::setSortRole(int role) |
||||
{ |
||||
m_model->setSortRole(role); |
||||
} |
||||
|
||||
QStandardItem* CheckList::addCheckItem(const QString &label, const QVariant &data, const Qt::CheckState checkState) |
||||
{ |
||||
QStandardItem* item = new QStandardItem(label); |
||||
item->setCheckState(checkState); |
||||
item->setData(data); |
||||
item->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled); |
||||
|
||||
m_model->appendRow(item); |
||||
|
||||
updateText(); |
||||
|
||||
return item; |
||||
} |
||||
|
||||
int CheckList::globalCheckState() |
||||
{ |
||||
int nbRows = m_model->rowCount(), nbChecked = 0, nbUnchecked = 0; |
||||
|
||||
if (nbRows == 0) |
||||
{ |
||||
return StateUnknown; |
||||
} |
||||
|
||||
for (int i = 0; i < nbRows; i++) |
||||
{ |
||||
if (m_model->item(i)->checkState() == Qt::Checked) |
||||
{ |
||||
nbChecked++; |
||||
} |
||||
else if (m_model->item(i)->checkState() == Qt::Unchecked) |
||||
{ |
||||
nbUnchecked++; |
||||
} |
||||
else |
||||
{ |
||||
return StateUnknown; |
||||
} |
||||
} |
||||
|
||||
return nbChecked == nbRows ? Qt::Checked : nbUnchecked == nbRows ? Qt::Unchecked : Qt::PartiallyChecked; |
||||
} |
||||
|
||||
bool CheckList::eventFilter(QObject* _object, QEvent* _event) |
||||
{ |
||||
if (_object == lineEdit() && _event->type() == QEvent::MouseButtonPress) |
||||
{ |
||||
showPopup(); |
||||
return true; |
||||
} |
||||
|
||||
return false; |
||||
} |
||||
|
||||
void CheckList::updateText() |
||||
{ |
||||
QString text; |
||||
|
||||
if (m_text.isEmpty()) |
||||
{ |
||||
switch (globalCheckState()) |
||||
{ |
||||
case Qt::Checked: |
||||
text = m_allCheckedText; |
||||
break; |
||||
|
||||
case Qt::Unchecked: |
||||
text = m_noneCheckedText; |
||||
break; |
||||
|
||||
case Qt::PartiallyChecked: |
||||
for (int i = 0; i < m_model->rowCount(); i++) |
||||
{ |
||||
if (m_model->item(i)->checkState() == Qt::Checked) |
||||
{ |
||||
if (!text.isEmpty()) |
||||
{ |
||||
text+= ", "; |
||||
} |
||||
|
||||
text+= m_model->item(i)->text(); |
||||
} |
||||
} |
||||
break; |
||||
|
||||
default: |
||||
text = m_unknownlyCheckedText; |
||||
} |
||||
} |
||||
else |
||||
{ |
||||
text = m_text; |
||||
} |
||||
|
||||
lineEdit()->setText(text); |
||||
} |
||||
|
||||
void CheckList::on_modelDataChanged() |
||||
{ |
||||
updateText(); |
||||
emit globalCheckStateChanged(globalCheckState()); |
||||
} |
||||
|
||||
void CheckList::on_itemPressed(const QModelIndex &index) |
||||
{ |
||||
QStandardItem* item = m_model->itemFromIndex(index); |
||||
|
||||
if (item->checkState() == Qt::Checked) |
||||
{ |
||||
item->setCheckState(Qt::Unchecked); |
||||
} |
||||
else |
||||
{ |
||||
item->setCheckState(Qt::Checked); |
||||
} |
||||
} |
||||
|
||||
bool CheckList::isChecked(int index) const |
||||
{ |
||||
return m_model->item(index)->checkState() == Qt::Checked; |
||||
} |
||||
#include "checklist.h" |
||||
|
||||
CheckList::CheckList(QWidget* parent) : |
||||
QComboBox(parent) |
||||
{ |
||||
m_model = new QStandardItemModel(); |
||||
setModel(m_model); |
||||
|
||||
setEditable(true); |
||||
lineEdit()->setReadOnly(true); |
||||
lineEdit()->installEventFilter(this); |
||||
setItemDelegate(new QCheckListStyledItemDelegate(this)); |
||||
|
||||
connect(lineEdit(), &QLineEdit::selectionChanged, lineEdit(), &QLineEdit::deselect); |
||||
connect((QListView*) view(), SIGNAL(pressed(QModelIndex)), this, SLOT(on_itemPressed(QModelIndex))); |
||||
connect(m_model, SIGNAL(dataChanged(QModelIndex, QModelIndex, QVector<int>)), this, SLOT(on_modelDataChanged())); |
||||
} |
||||
|
||||
CheckList::~CheckList() |
||||
{ |
||||
delete m_model; |
||||
} |
||||
|
||||
void CheckList::setText(const QString &text) |
||||
{ |
||||
m_text = text; |
||||
updateText(); |
||||
} |
||||
|
||||
void CheckList::setAllCheckedText(const QString &text) |
||||
{ |
||||
m_allCheckedText = text; |
||||
updateText(); |
||||
} |
||||
|
||||
void CheckList::setNoneCheckedText(const QString &text) |
||||
{ |
||||
m_noneCheckedText = text; |
||||
updateText(); |
||||
} |
||||
|
||||
void CheckList::setUnknownlyCheckedText(const QString &text) |
||||
{ |
||||
m_unknownlyCheckedText = text; |
||||
updateText(); |
||||
} |
||||
|
||||
void CheckList::setSortRole(int role) |
||||
{ |
||||
m_model->setSortRole(role); |
||||
} |
||||
|
||||
QStandardItem* CheckList::addCheckItem(const QString &label, const QVariant &data, const Qt::CheckState checkState) |
||||
{ |
||||
QStandardItem* item = new QStandardItem(label); |
||||
item->setCheckState(checkState); |
||||
item->setData(data); |
||||
item->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled); |
||||
|
||||
m_model->appendRow(item); |
||||
|
||||
updateText(); |
||||
|
||||
return item; |
||||
} |
||||
|
||||
int CheckList::globalCheckState() |
||||
{ |
||||
int nbRows = m_model->rowCount(), nbChecked = 0, nbUnchecked = 0; |
||||
|
||||
if (nbRows == 0) |
||||
{ |
||||
return StateUnknown; |
||||
} |
||||
|
||||
for (int i = 0; i < nbRows; i++) |
||||
{ |
||||
if (m_model->item(i)->checkState() == Qt::Checked) |
||||
{ |
||||
nbChecked++; |
||||
} |
||||
else if (m_model->item(i)->checkState() == Qt::Unchecked) |
||||
{ |
||||
nbUnchecked++; |
||||
} |
||||
else |
||||
{ |
||||
return StateUnknown; |
||||
} |
||||
} |
||||
|
||||
return nbChecked == nbRows ? Qt::Checked : nbUnchecked == nbRows ? Qt::Unchecked : Qt::PartiallyChecked; |
||||
} |
||||
|
||||
bool CheckList::eventFilter(QObject* _object, QEvent* _event) |
||||
{ |
||||
if (_object == lineEdit() && _event->type() == QEvent::MouseButtonPress) |
||||
{ |
||||
showPopup(); |
||||
return true; |
||||
} |
||||
|
||||
return false; |
||||
} |
||||
|
||||
void CheckList::updateText() |
||||
{ |
||||
QString text; |
||||
|
||||
if (m_text.isEmpty()) |
||||
{ |
||||
switch (globalCheckState()) |
||||
{ |
||||
case Qt::Checked: |
||||
text = m_allCheckedText; |
||||
break; |
||||
|
||||
case Qt::Unchecked: |
||||
text = m_noneCheckedText; |
||||
break; |
||||
|
||||
case Qt::PartiallyChecked: |
||||
for (int i = 0; i < m_model->rowCount(); i++) |
||||
{ |
||||
if (m_model->item(i)->checkState() == Qt::Checked) |
||||
{ |
||||
if (!text.isEmpty()) |
||||
{ |
||||
text+= ", "; |
||||
} |
||||
|
||||
text+= m_model->item(i)->text(); |
||||
} |
||||
} |
||||
break; |
||||
|
||||
default: |
||||
text = m_unknownlyCheckedText; |
||||
} |
||||
} |
||||
else |
||||
{ |
||||
text = m_text; |
||||
} |
||||
|
||||
lineEdit()->setText(text); |
||||
} |
||||
|
||||
void CheckList::on_modelDataChanged() |
||||
{ |
||||
updateText(); |
||||
emit globalCheckStateChanged(globalCheckState()); |
||||
} |
||||
|
||||
void CheckList::on_itemPressed(const QModelIndex &index) |
||||
{ |
||||
QStandardItem* item = m_model->itemFromIndex(index); |
||||
|
||||
if (item->checkState() == Qt::Checked) |
||||
{ |
||||
item->setCheckState(Qt::Unchecked); |
||||
} |
||||
else |
||||
{ |
||||
item->setCheckState(Qt::Checked); |
||||
} |
||||
} |
||||
|
||||
bool CheckList::isChecked(int index) const |
||||
{ |
||||
return m_model->item(index)->checkState() == Qt::Checked; |
||||
} |
||||
|
||||
@ -1,105 +1,105 @@
@@ -1,105 +1,105 @@
|
||||
#ifndef CHECKLIST |
||||
#define CHECKLIST |
||||
|
||||
#include <QWidget> |
||||
#include <QComboBox> |
||||
#include <QStandardItemModel> |
||||
#include <QLineEdit> |
||||
#include <QEvent> |
||||
#include <QStyledItemDelegate> |
||||
#include <QListView> |
||||
|
||||
#include "export.h" |
||||
|
||||
/**
|
||||
* @brief QComboBox with support of checkboxes |
||||
* http://stackoverflow.com/questions/8422760/combobox-of-checkboxes
|
||||
*/ |
||||
class SDRGUI_API CheckList : public QComboBox |
||||
{ |
||||
Q_OBJECT |
||||
|
||||
public: |
||||
/**
|
||||
* @brief Additional value to Qt::CheckState when some checkboxes are Qt::PartiallyChecked |
||||
*/ |
||||
static const int StateUnknown = 3; |
||||
|
||||
private: |
||||
QStandardItemModel* m_model; |
||||
/**
|
||||
* @brief Text to display regardless of what is checked |
||||
*/ |
||||
QString m_text; |
||||
/**
|
||||
* @brief Text displayed when no item is checked |
||||
*/ |
||||
QString m_noneCheckedText; |
||||
/**
|
||||
* @brief Text displayed when all items are checked |
||||
*/ |
||||
QString m_allCheckedText; |
||||
/**
|
||||
* @brief Text displayed when some items are partially checked |
||||
*/ |
||||
QString m_unknownlyCheckedText; |
||||
|
||||
signals: |
||||
void globalCheckStateChanged(int); |
||||
|
||||
public: |
||||
CheckList(QWidget* parent = nullptr); |
||||
~CheckList(); |
||||
|
||||
void setText(const QString &text); |
||||
void setAllCheckedText(const QString &text); |
||||
void setNoneCheckedText(const QString &text); |
||||
void setUnknownlyCheckedText(const QString &text); |
||||
|
||||
bool isChecked(int index) const; |
||||
|
||||
void setSortRole(int role); |
||||
|
||||
/**
|
||||
* @brief Adds a item to the checklist |
||||
* @return the new QStandardItem |
||||
*/ |
||||
QStandardItem* addCheckItem(const QString &label, const QVariant &data, const Qt::CheckState checkState); |
||||
|
||||
/**
|
||||
* @brief Computes the global state of the checklist : |
||||
* - if there is no item: StateUnknown |
||||
* - if there is at least one item partially checked: StateUnknown |
||||
* - if all items are checked: Qt::Checked |
||||
* - if no item is checked: Qt::Unchecked |
||||
* - else: Qt::PartiallyChecked |
||||
*/ |
||||
int globalCheckState(); |
||||
|
||||
protected: |
||||
bool eventFilter(QObject* _object, QEvent* _event); |
||||
|
||||
private: |
||||
void updateText(); |
||||
|
||||
private slots: |
||||
void on_modelDataChanged(); |
||||
|
||||
void on_itemPressed(const QModelIndex &index); |
||||
|
||||
public: |
||||
class QCheckListStyledItemDelegate : public QStyledItemDelegate |
||||
{ |
||||
public: |
||||
QCheckListStyledItemDelegate(QObject* parent = 0) : QStyledItemDelegate(parent) {} |
||||
|
||||
void paint(QPainter * painter_, const QStyleOptionViewItem & option_, const QModelIndex & index_) const |
||||
{ |
||||
QStyleOptionViewItem & refToNonConstOption = const_cast<QStyleOptionViewItem &>(option_); |
||||
refToNonConstOption.showDecorationSelected = false; |
||||
QStyledItemDelegate::paint(painter_, refToNonConstOption, index_); |
||||
} |
||||
}; |
||||
}; |
||||
|
||||
#endif |
||||
#ifndef CHECKLIST |
||||
#define CHECKLIST |
||||
|
||||
#include <QWidget> |
||||
#include <QComboBox> |
||||
#include <QStandardItemModel> |
||||
#include <QLineEdit> |
||||
#include <QEvent> |
||||
#include <QStyledItemDelegate> |
||||
#include <QListView> |
||||
|
||||
#include "export.h" |
||||
|
||||
/**
|
||||
* @brief QComboBox with support of checkboxes |
||||
* http://stackoverflow.com/questions/8422760/combobox-of-checkboxes
|
||||
*/ |
||||
class SDRGUI_API CheckList : public QComboBox |
||||
{ |
||||
Q_OBJECT |
||||
|
||||
public: |
||||
/**
|
||||
* @brief Additional value to Qt::CheckState when some checkboxes are Qt::PartiallyChecked |
||||
*/ |
||||
static const int StateUnknown = 3; |
||||
|
||||
private: |
||||
QStandardItemModel* m_model; |
||||
/**
|
||||
* @brief Text to display regardless of what is checked |
||||
*/ |
||||
QString m_text; |
||||
/**
|
||||
* @brief Text displayed when no item is checked |
||||
*/ |
||||
QString m_noneCheckedText; |
||||
/**
|
||||
* @brief Text displayed when all items are checked |
||||
*/ |
||||
QString m_allCheckedText; |
||||
/**
|
||||
* @brief Text displayed when some items are partially checked |
||||
*/ |
||||
QString m_unknownlyCheckedText; |
||||
|
||||
signals: |
||||
void globalCheckStateChanged(int); |
||||
|
||||
public: |
||||
CheckList(QWidget* parent = nullptr); |
||||
~CheckList(); |
||||
|
||||
void setText(const QString &text); |
||||
void setAllCheckedText(const QString &text); |
||||
void setNoneCheckedText(const QString &text); |
||||
void setUnknownlyCheckedText(const QString &text); |
||||
|
||||
bool isChecked(int index) const; |
||||
|
||||
void setSortRole(int role); |
||||
|
||||
/**
|
||||
* @brief Adds a item to the checklist |
||||
* @return the new QStandardItem |
||||
*/ |
||||
QStandardItem* addCheckItem(const QString &label, const QVariant &data, const Qt::CheckState checkState); |
||||
|
||||
/**
|
||||
* @brief Computes the global state of the checklist : |
||||
* - if there is no item: StateUnknown |
||||
* - if there is at least one item partially checked: StateUnknown |
||||
* - if all items are checked: Qt::Checked |
||||
* - if no item is checked: Qt::Unchecked |
||||
* - else: Qt::PartiallyChecked |
||||
*/ |
||||
int globalCheckState(); |
||||
|
||||
protected: |
||||
bool eventFilter(QObject* _object, QEvent* _event); |
||||
|
||||
private: |
||||
void updateText(); |
||||
|
||||
private slots: |
||||
void on_modelDataChanged(); |
||||
|
||||
void on_itemPressed(const QModelIndex &index); |
||||
|
||||
public: |
||||
class QCheckListStyledItemDelegate : public QStyledItemDelegate |
||||
{ |
||||
public: |
||||
QCheckListStyledItemDelegate(QObject* parent = 0) : QStyledItemDelegate(parent) {} |
||||
|
||||
void paint(QPainter * painter_, const QStyleOptionViewItem & option_, const QModelIndex & index_) const |
||||
{ |
||||
QStyleOptionViewItem & refToNonConstOption = const_cast<QStyleOptionViewItem &>(option_); |
||||
refToNonConstOption.showDecorationSelected = false; |
||||
QStyledItemDelegate::paint(painter_, refToNonConstOption, index_); |
||||
} |
||||
}; |
||||
}; |
||||
|
||||
#endif |
||||
|
||||