Browse Source

Add message / ship chart.

Add images of ships from VesselFinder.
chirpmodem-v8.0.0
Jon Beniston 4 months ago
parent
commit
77e43defe6
  1. 2
      plugins/feature/ais/CMakeLists.txt
  2. 1
      plugins/feature/ais/ais.qrc
  3. 324
      plugins/feature/ais/aisgui.cpp
  4. 34
      plugins/feature/ais/aisgui.h
  5. 195
      plugins/feature/ais/aisgui.ui
  6. 9
      plugins/feature/ais/aissettings.cpp
  7. 1
      plugins/feature/ais/aissettings.h
  8. 6
      plugins/feature/ais/readme.md
  9. 2
      sdrbase/CMakeLists.txt
  10. 284
      sdrbase/util/vesselfinder.cpp
  11. 88
      sdrbase/util/vesselfinder.h

2
plugins/feature/ais/CMakeLists.txt

@ -31,7 +31,7 @@ if(NOT SERVER_MODE) @@ -31,7 +31,7 @@ if(NOT SERVER_MODE)
)
set(TARGET_NAME ${PLUGINS_PREFIX}featureais)
set(TARGET_LIB Qt::Widgets)
set(TARGET_LIB Qt::Widgets Qt::Charts)
set(TARGET_LIB_GUI "sdrgui")
set(INSTALL_FOLDER ${INSTALL_PLUGINS_DIR})
else()

1
plugins/feature/ais/ais.qrc

@ -1,5 +1,6 @@ @@ -1,5 +1,6 @@
<RCC>
<qresource prefix="/ais/">
<file alias="chart.png">../../channelrx/demodadsb/icons/chart.png</file>
<file>map/aircraft.png</file>
<file>map/helicopter.png</file>
<file>map/ship.png</file>

324
plugins/feature/ais/aisgui.cpp

@ -23,12 +23,14 @@ @@ -23,12 +23,14 @@
#include <QDesktopServices>
#include <QAction>
#include <QClipboard>
#include <QPainter>
#include "feature/featureuiset.h"
#include "feature/featurewebapiutils.h"
#include "gui/basicfeaturesettingsdialog.h"
#include "gui/tabletapandhold.h"
#include "gui/dialogpositioner.h"
#include "gui/crightclickenabler.h"
#include "util/mmsi.h"
#include "maincore.h"
@ -158,6 +160,7 @@ bool AISGUI::handleMessage(const Message& message) @@ -158,6 +160,7 @@ bool AISGUI::handleMessage(const Message& message)
if (ais)
{
updateVessels(ais, report.getDateTime());
m_messageCount++;
delete ais;
}
@ -196,7 +199,16 @@ AISGUI::AISGUI(PluginAPI* pluginAPI, FeatureUISet *featureUISet, Feature *featur @@ -196,7 +199,16 @@ AISGUI::AISGUI(PluginAPI* pluginAPI, FeatureUISet *featureUISet, Feature *featur
m_pluginAPI(pluginAPI),
m_featureUISet(featureUISet),
m_doApplySettings(true),
m_lastFeatureState(0)
m_lastFeatureState(0),
m_messageRateTime(QDateTime::currentDateTime()),
m_messageCount(0),
m_chartTickCount(0),
m_chart(nullptr),
m_messageSeries(nullptr),
m_shipSeries(nullptr),
m_chartXAxis(nullptr),
m_messageYAxis(nullptr),
m_shipYAxis(nullptr)
{
m_feature = feature;
setAttribute(Qt::WA_DeleteOnClose, true);
@ -216,6 +228,8 @@ AISGUI::AISGUI(PluginAPI* pluginAPI, FeatureUISet *featureUISet, Feature *featur @@ -216,6 +228,8 @@ AISGUI::AISGUI(PluginAPI* pluginAPI, FeatureUISet *featureUISet, Feature *featur
connect(&m_timer, SIGNAL(timeout()), this, SLOT(removeOldVessels()));
m_timer.start(60*1000);
connect(&m_chartTimer, &QTimer::timeout, this, &AISGUI::updateChart);
// Resize the table using dummy data
resizeTable();
// Allow user to reorder columns
@ -239,27 +253,326 @@ AISGUI::AISGUI(PluginAPI* pluginAPI, FeatureUISet *featureUISet, Feature *featur @@ -239,27 +253,326 @@ AISGUI::AISGUI(PluginAPI* pluginAPI, FeatureUISet *featureUISet, Feature *featur
connect(ui->vessels, SIGNAL(customContextMenuRequested(QPoint)), SLOT(vessels_customContextMenuRequested(QPoint)));
TableTapAndHold *tableTapAndHold = new TableTapAndHold(ui->vessels);
connect(tableTapAndHold, &TableTapAndHold::tapAndHold, this, &AISGUI::vessels_customContextMenuRequested);
connect(ui->vessels, &QTableWidget::currentCellChanged, this, &AISGUI::vesselSelectionChanged);
connect(&m_vesselFinder, &VesselFinder::shipPhoto, this, &AISGUI::shipPhoto);
connect(ui->hidePhoto, &QToolButton::clicked, this, &AISGUI::hideShipPhotoClicked);
CRightClickEnabler *displayChartClickEnabler = new CRightClickEnabler(ui->displayChart);
connect(displayChartClickEnabler, &CRightClickEnabler::rightClick, this, &AISGUI::clearChart);
ui->photoCredit->setOpenExternalLinks(true);
hideShipPhoto();
ui->chart->setRenderHint(QPainter::Antialiasing);
plotChart();
m_chartTimer.start(1000);
m_settings.setRollupState(&m_rollupState);
displaySettings();
applySettings(true);
makeUIConnections();
m_resizer.enableChildMouseTracking();
}
AISGUI::~AISGUI()
void AISGUI::makeUIConnections()
{
QObject::connect(
ui->vessels,
&QTableWidget::cellDoubleClicked,
this,
&AISGUI::on_vessels_cellDoubleClicked
);
QObject::connect(
ui->displayChart,
&ButtonSwitch::clicked,
this,
&AISGUI::on_displayChart_clicked
);
QObject::connect(
ui->deleteVessels,
&QToolButton::clicked,
this,
&AISGUI::on_deleteVessels_clicked
);
}
void AISGUI::hideShipPhoto()
{
ui->shipPhoto->clear();
ui->photoCredit->clear();
ui->photoPanel->setVisible(false);
}
void AISGUI::hideShipPhotoClicked()
{
// Prevent an outstanding download from showing the photo again.
m_selectedPhotoId.clear();
hideShipPhoto();
}
void AISGUI::on_displayChart_clicked(bool checked)
{
// Remove all ships from map
m_settings.m_displayChart = checked;
m_settingsKeys.append("displayChart");
applySettings();
ui->chart->setVisible(checked);
}
void AISGUI::on_deleteVessels_clicked()
{
deleteAllVessels();
}
void AISGUI::deleteAllVessels()
{
m_selectedPhotoId.clear();
hideShipPhoto();
for (int row = ui->vessels->rowCount() - 1; row >= 0; row--)
{
QString mmsi = ui->vessels->item(row, VESSEL_COL_MMSI)->text();
const QString mmsi = ui->vessels->item(row, VESSEL_COL_MMSI)->text();
sendToMap(mmsi, "",
"", "",
"", 0.0f, 0.0f,
0.0f, 0.0f, QDateTime(),
0.0f);
}
ui->vessels->setRowCount(0);
qDeleteAll(m_vessels);
m_vessels.clear();
}
int AISGUI::countShips() const
{
int ships = 0;
for (int row = 0; row < ui->vessels->rowCount(); row++)
{
const QTableWidgetItem *typeItem = ui->vessels->item(row, VESSEL_COL_TYPE);
if (typeItem && (typeItem->text() == "Vessel")) {
ships++;
}
}
return ships;
}
void AISGUI::clearChart(const QPoint& p)
{
(void) p;
m_messageSeries->clear();
m_shipSeries->clear();
m_messageCount = 0;
m_chartTickCount = 0;
m_averageTime = QDateTime();
m_messageRateTime = QDateTime::currentDateTime();
resetChartAxes();
}
void AISGUI::resetChartAxes()
{
const QDateTime now = QDateTime::currentDateTime();
m_chartXAxis->setMin(now.addSecs(-60));
m_chartXAxis->setMax(now);
m_messageYAxis->setRange(0.0, 10.0);
m_shipYAxis->setRange(0.0, 10.0);
}
void AISGUI::plotChart()
{
QChart *oldChart = m_chart;
m_chart = new QChart();
m_chart->layout()->setContentsMargins(0, 0, 0, 0);
m_chart->setMargins(QMargins(1, 1, 1, 1));
m_chart->setTheme(QChart::ChartThemeDark);
m_chart->legend()->setAlignment(Qt::AlignRight);
m_messageSeries = new QLineSeries();
m_messageSeries->setName("Messages");
m_shipSeries = new QLineSeries();
m_shipSeries->setName("Ships");
m_chartXAxis = new QDateTimeAxis();
m_chartXAxis->setFormat("hh:mm:ss");
m_messageYAxis = new QValueAxis();
m_messageYAxis->setTitleText("Messages/s");
m_shipYAxis = new QValueAxis();
m_shipYAxis->setTitleText("Ships");
m_chart->addAxis(m_chartXAxis, Qt::AlignBottom);
m_chart->addAxis(m_messageYAxis, Qt::AlignLeft);
m_chart->addAxis(m_shipYAxis, Qt::AlignRight);
m_chart->addSeries(m_messageSeries);
m_chart->addSeries(m_shipSeries);
m_messageSeries->attachAxis(m_chartXAxis);
m_messageSeries->attachAxis(m_messageYAxis);
m_shipSeries->attachAxis(m_chartXAxis);
m_shipSeries->attachAxis(m_shipYAxis);
resetChartAxes();
ui->chart->setChart(m_chart);
delete oldChart;
}
void AISGUI::updateChart()
{
const QDateTime now = QDateTime::currentDateTime();
const qint64 elapsedMS = m_messageRateTime.msecsTo(now);
if (elapsedMS <= 0) {
return;
}
const double messageRate = m_messageCount / (elapsedMS / 1000.0);
const int ships = countShips();
const bool xAtMax = (m_messageSeries->count() == 0)
|| (m_messageSeries->at(m_messageSeries->count() - 1).x() == m_chartXAxis->max().toMSecsSinceEpoch());
m_messageSeries->append(now.toMSecsSinceEpoch(), messageRate);
m_shipSeries->append(now.toMSecsSinceEpoch(), ships);
if (xAtMax) {
m_chartXAxis->setMax(now);
}
if (m_messageYAxis->max() < messageRate) {
m_messageYAxis->setMax(std::ceil(messageRate) + 1.0);
}
if (m_shipYAxis->max() < ships + 1) {
m_shipYAxis->setMax(ships + 1);
}
m_messageCount = 0;
m_messageRateTime = now;
m_chartTickCount++;
// Average one-second samples after ten minutes to limit long-running chart growth.
if ((m_chartTickCount % 60) == 0)
{
QDateTime startTime;
QDateTime endTime;
if (m_averageTime.isValid())
{
startTime = m_averageTime;
endTime = startTime.addSecs(60);
}
else
{
endTime = now.addSecs(-10 * 60);
startTime = endTime.addSecs(-60);
}
averageSeries(m_messageSeries, startTime, endTime);
averageSeries(m_shipSeries, startTime, endTime);
m_averageTime = endTime;
}
}
void AISGUI::averageSeries(QLineSeries *series, const QDateTime& startTime, const QDateTime& endTime)
{
int startIndex = 0;
int endIndex = -1;
for (int i = series->count() - 1; i >= 0; i--)
{
const QDateTime dateTime = QDateTime::fromMSecsSinceEpoch(series->at(i).x());
if ((endIndex == -1) && (dateTime <= endTime)) {
endIndex = i;
} else if (dateTime < startTime) {
startIndex = i + 1;
break;
}
}
const int count = endIndex - startIndex + 1;
if ((endIndex != -1) && (count > 1))
{
double sum = 0.0;
for (int i = startIndex; i <= endIndex; i++) {
sum += series->at(i).y();
}
const double average = sum / count;
const qint64 midpoint = startTime.toMSecsSinceEpoch()
+ (endTime.toMSecsSinceEpoch() - startTime.toMSecsSinceEpoch()) / 2;
series->removePoints(startIndex, count);
series->insert(startIndex, QPointF(midpoint, average));
}
}
void AISGUI::vesselSelectionChanged(int currentRow, int currentColumn, int previousRow, int previousColumn)
{
(void) currentColumn;
(void) previousRow;
(void) previousColumn;
m_selectedPhotoId.clear();
hideShipPhoto();
if ((currentRow < 0) || (currentRow >= ui->vessels->rowCount())) {
return;
}
const QTableWidgetItem *mmsiItem = ui->vessels->item(currentRow, VESSEL_COL_MMSI);
const QTableWidgetItem *imoItem = ui->vessels->item(currentRow, VESSEL_COL_IMO);
const QString mmsi = mmsiItem ? mmsiItem->text().trimmed() : QString();
const QString imo = imoItem ? imoItem->text().trimmed() : QString();
bool imoOk = false;
bool mmsiOk = false;
const qulonglong imoNumber = imo.toULongLong(&imoOk);
const qulonglong mmsiNumber = mmsi.toULongLong(&mmsiOk);
if (imoOk && (imoNumber != 0)) {
m_selectedPhotoId = QString("imo:%1").arg(imoNumber);
} else if (mmsiOk && (mmsiNumber != 0)) {
m_selectedPhotoId = QString("mmsi:%1").arg(mmsiNumber);
} else {
return;
}
m_vesselFinder.getShipPhoto(imo, mmsi);
}
void AISGUI::shipPhoto(const VesselFinderPhoto *photo)
{
// A request can complete after another row has been selected.
if (!photo || (photo->m_id != m_selectedPhotoId)) {
return;
}
if (photo->m_pixmap.isNull())
{
hideShipPhoto();
return;
}
ui->shipPhoto->setPixmap(photo->m_pixmap.scaled(
320,
320,
Qt::KeepAspectRatio,
Qt::SmoothTransformation
));
const QString link = photo->m_link.toHtmlEscaped();
const QString credit = photo->m_photographer.isEmpty()
? QString("View on VesselFinder")
: QString("Photo by %1").arg(photo->m_photographer.toHtmlEscaped());
ui->photoCredit->setText(QString("<a href=\"%1\">%2</a>").arg(link, credit));
ui->photoPanel->setVisible(true);
}
AISGUI::~AISGUI()
{
m_chartTimer.stop();
m_timer.stop();
disconnect(&m_vesselFinder, &VesselFinder::shipPhoto, this, &AISGUI::shipPhoto);
deleteAllVessels();
delete ui;
}
@ -281,6 +594,9 @@ void AISGUI::displaySettings() @@ -281,6 +594,9 @@ void AISGUI::displaySettings()
setTitle(m_settings.m_title);
blockApplySettings(true);
ui->displayChart->setChecked(m_settings.m_displayChart);
ui->chart->setVisible(m_settings.m_displayChart);
// Order and size columns
QHeaderView *header = ui->vessels->horizontalHeader();
for (int i = 0; i < AIS_VESSEL_COLUMNS; i++)

34
plugins/feature/ais/aisgui.h

@ -27,10 +27,12 @@ @@ -27,10 +27,12 @@
#include <QDateTime>
#include <QHash>
#include <QRandomGenerator>
#include <QtCharts>
#include "feature/featuregui.h"
#include "util/messagequeue.h"
#include "util/ais.h"
#include "util/vesselfinder.h"
#include "settings/rollupstate.h"
#include "aissettings.h"
@ -43,6 +45,10 @@ namespace Ui { @@ -43,6 +45,10 @@ namespace Ui {
class AISGUI;
}
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
using namespace QtCharts;
#endif
class AISGUI : public FeatureGUI {
Q_OBJECT
@ -77,10 +83,24 @@ private: @@ -77,10 +83,24 @@ private:
AIS* m_ais;
MessageQueue m_inputMessageQueue;
QTimer m_timer;
QTimer m_chartTimer;
int m_lastFeatureState;
QDateTime m_messageRateTime;
int m_messageCount;
int m_chartTickCount;
QDateTime m_averageTime;
QChart *m_chart;
QLineSeries *m_messageSeries;
QLineSeries *m_shipSeries;
QDateTimeAxis *m_chartXAxis;
QValueAxis *m_messageYAxis;
QValueAxis *m_shipYAxis;
QRandomGenerator m_random;
QHash<QString, Vessel *> m_vessels; // Hash of mmsi to vessels
VesselFinder m_vesselFinder;
QString m_selectedPhotoId;
static QStringList m_shipModels;
static QStringList m_sailboatModels;
static QHash<QString, float> m_labelOffset;
@ -95,6 +115,7 @@ private: @@ -95,6 +115,7 @@ private:
void applySettings(bool force = false);
void displaySettings();
bool handleMessage(const Message& message);
void makeUIConnections();
void sendToMap(const QString &name, const QString &label,
const QString &image, const QString &text,
@ -104,6 +125,13 @@ private: @@ -104,6 +125,13 @@ private:
);
void updateVessels(AISMessage *ais, QDateTime dateTime);
void getImageAndModel(const QString &type, const QString &shipType, int length, const QString &status, Vessel *vessel);
void hideShipPhoto();
void hideShipPhotoClicked();
void deleteAllVessels();
int countShips() const;
void plotChart();
void resetChartAxes();
void averageSeries(QLineSeries *series, const QDateTime& startTime, const QDateTime& endTime);
void resizeTable();
QAction *createCheckableItem(QString& text, int idx, bool checked, const char *slot);
@ -132,6 +160,12 @@ private slots: @@ -132,6 +160,12 @@ private slots:
void onMenuDialogCalled(const QPoint &p);
void onWidgetRolled(QWidget* widget, bool rollDown);
void handleInputMessages();
void on_displayChart_clicked(bool checked);
void on_deleteVessels_clicked();
void clearChart(const QPoint& p);
void updateChart();
void vesselSelectionChanged(int currentRow, int currentColumn, int previousRow, int previousColumn);
void shipPhoto(const VesselFinderPhoto *photo);
void on_vessels_cellDoubleClicked(int row, int column);
void vessels_customContextMenuRequested(QPoint pos);
void vessels_sectionMoved(int logicalIndex, int oldVisualIndex, int newVisualIndex);

195
plugins/feature/ais/aisgui.ui

@ -57,7 +57,7 @@ @@ -57,7 +57,7 @@
<property name="windowTitle">
<string>Vessels, Base stations and Aids-to-navigation</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<layout class="QVBoxLayout" name="mainLayout">
<property name="spacing">
<number>3</number>
</property>
@ -70,11 +70,78 @@ @@ -70,11 +70,78 @@
<property name="rightMargin">
<number>2</number>
</property>
<property name="bottomMargin">
<number>2</number>
</property>
<item>
<widget class="QTableWidget" name="vessels">
<property name="bottomMargin">
<number>2</number>
</property>
<item>
<layout class="QHBoxLayout" name="toolbarLayout">
<item>
<widget class="ButtonSwitch" name="displayChart">
<property name="toolTip">
<string>Display chart. Right click to reset data</string>
</property>
<property name="text">
<string/>
</property>
<property name="icon">
<iconset resource="ais.qrc">
<normaloff>:/ais/chart.png</normaloff>:/ais/chart.png</iconset>
</property>
<property name="checkable">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QToolButton" name="deleteVessels">
<property name="toolTip">
<string>Delete all vessels and table items</string>
</property>
<property name="text">
<string/>
</property>
<property name="icon">
<iconset resource="../../../sdrgui/resources/res.qrc">
<normaloff>:/bin.png</normaloff>:/bin.png</iconset>
</property>
</widget>
</item>
<item>
<spacer name="toolbarSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
<item>
<widget class="QSplitter" name="splitter">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<widget class="QWidget" name="vesselPanel" native="true">
<layout class="QHBoxLayout" name="vesselLayout">
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QTableWidget" name="vessels">
<property name="toolTip">
<string>Vessels</string>
</property>
@ -212,19 +279,133 @@ @@ -212,19 +279,133 @@
</column>
</widget>
</item>
</layout>
<item>
<widget class="QWidget" name="photoPanel" native="true">
<property name="maximumSize">
<size>
<width>330</width>
<height>16777215</height>
</size>
</property>
<layout class="QVBoxLayout" name="photoLayout">
<property name="leftMargin">
<number>3</number>
</property>
<property name="topMargin">
<number>3</number>
</property>
<property name="rightMargin">
<number>3</number>
</property>
<property name="bottomMargin">
<number>3</number>
</property>
<item alignment="Qt::AlignRight">
<widget class="QToolButton" name="hidePhoto">
<property name="toolTip">
<string>Hide ship photograph</string>
</property>
<property name="text">
<string>×</string>
</property>
<property name="autoRaise">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="shipPhoto">
<property name="minimumSize">
<size>
<width>180</width>
<height>120</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>320</width>
<height>320</height>
</size>
</property>
<property name="frameShape">
<enum>QFrame::StyledPanel</enum>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="photoCredit">
<property name="textFormat">
<enum>Qt::RichText</enum>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
<property name="openExternalLinks">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<spacer name="photoSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
</item>
</layout>
</widget>
<widget class="QChartView" name="chart">
<property name="minimumSize">
<size>
<width>300</width>
<height>160</height>
</size>
</property>
<property name="toolTip">
<string>AIS messages per second and ships over time</string>
</property>
</widget>
</widget>
</item>
</layout>
</widget>
</widget>
<customwidgets>
<customwidget>
<class>ButtonSwitch</class>
<extends>QToolButton</extends>
<header>gui/buttonswitch.h</header>
</customwidget>
<customwidget>
<class>RollupContents</class>
<extends>QWidget</extends>
<header>gui/rollupcontents.h</header>
<container>1</container>
</customwidget>
<customwidget>
<class>QChartView</class>
<extends>QGraphicsView</extends>
<header>QtCharts</header>
</customwidget>
</customwidgets>
<resources>
<include location="../../../sdrgui/resources/res.qrc"/>
<include location="ais.qrc"/>
</resources>
<connections/>
</ui>

9
plugins/feature/ais/aissettings.cpp

@ -50,6 +50,7 @@ void AISSettings::resetToDefaults() @@ -50,6 +50,7 @@ void AISSettings::resetToDefaults()
m_reverseAPIFeatureSetIndex = 0;
m_reverseAPIFeatureIndex = 0;
m_workspaceIndex = 0;
m_displayChart = false;
for (int i = 0; i < AIS_VESSEL_COLUMNS; i++)
{
@ -76,6 +77,7 @@ QByteArray AISSettings::serialize() const @@ -76,6 +77,7 @@ QByteArray AISSettings::serialize() const
s.writeS32(28, m_workspaceIndex);
s.writeBlob(29, m_geometryBytes);
s.writeBool(30, m_displayChart);
for (int i = 0; i < AIS_VESSEL_COLUMNS; i++) {
s.writeS32(300 + i, m_vesselColumnIndexes[i]);
@ -128,6 +130,7 @@ bool AISSettings::deserialize(const QByteArray& data) @@ -128,6 +130,7 @@ bool AISSettings::deserialize(const QByteArray& data)
d.readS32(28, &m_workspaceIndex, 0);
d.readBlob(29, &m_geometryBytes);
d.readBool(30, &m_displayChart, false);
for (int i = 0; i < AIS_VESSEL_COLUMNS; i++) {
d.readS32(300 + i, &m_vesselColumnIndexes[i], i);
@ -172,6 +175,9 @@ void AISSettings::applySettings(const QStringList& settingsKeys, const AISSettin @@ -172,6 +175,9 @@ void AISSettings::applySettings(const QStringList& settingsKeys, const AISSettin
if (settingsKeys.contains("workspaceIndex")) {
m_workspaceIndex = settings.m_workspaceIndex;
}
if (settingsKeys.contains("displayChart")) {
m_displayChart = settings.m_displayChart;
}
if (settingsKeys.contains("vesselColumnIndexes"))
{
@ -216,6 +222,9 @@ QString AISSettings::getDebugString(const QStringList& settingsKeys, bool force) @@ -216,6 +222,9 @@ QString AISSettings::getDebugString(const QStringList& settingsKeys, bool force)
if (settingsKeys.contains("workspaceIndex") || force) {
ostr << " m_workspaceIndex: " << m_workspaceIndex;
}
if (settingsKeys.contains("displayChart") || force) {
ostr << " m_displayChart: " << m_displayChart;
}
if (settingsKeys.contains("vesselColumnIndexes"))
{

1
plugins/feature/ais/aissettings.h

@ -41,6 +41,7 @@ struct AISSettings @@ -41,6 +41,7 @@ struct AISSettings
Serializable *m_rollupState;
int m_workspaceIndex;
QByteArray m_geometryBytes;
bool m_displayChart;
int m_vesselColumnIndexes[AIS_VESSEL_COLUMNS];
int m_vesselColumnSizes[AIS_VESSEL_COLUMNS];

6
plugins/feature/ais/readme.md

@ -34,6 +34,10 @@ The vessels table displays the current status for each vessel, base station or a @@ -34,6 +34,10 @@ The vessels table displays the current status for each vessel, base station or a
* Updated - Gives the date and time the last message was received.
* Messages - Displays the number of messages received.
* Selecting a vessel displays its first available VesselFinder gallery image to the right of the table. The photographer credit below the image links to the vessel's gallery.
The chart button displays the received AIS message rate and number of ships over time. Right click the chart button to reset the collected chart data. The delete button removes every table item and its corresponding object from the Map feature.
Right clicking on the table header allows you to select which columns to show. The columns can be reordered by left clicking and dragging the column header.
Right clicking on a table cell allows you to copy the cell contents, view the vessel on a variety of websites or find the vessel on the map.
@ -54,3 +58,5 @@ Selecting an AIS item on the map will display a text bubble containing informati @@ -54,3 +58,5 @@ Selecting an AIS item on the map will display a text bubble containing informati
Map icons are by Maarten van der Werf, DE Alvida Biersack, ID and jokokerto, MY, from the Noun Project https://thenounproject.com/
Map icons are from http://all-free-download.com.
Vessel photographs and photographer credits are provided by https://www.vesselfinder.com/

2
sdrbase/CMakeLists.txt

@ -261,6 +261,7 @@ set(sdrbase_SOURCES @@ -261,6 +261,7 @@ set(sdrbase_SOURCES
util/ourairportsdb.cpp
util/peakfinder.cpp
util/planespotters.cpp
util/vesselfinder.cpp
util/png.cpp
util/prettyprint.cpp
util/profiler.cpp
@ -530,6 +531,7 @@ set(sdrbase_HEADERS @@ -530,6 +531,7 @@ set(sdrbase_HEADERS
util/outairportsdb.h
util/peakfinder.h
util/planespotters.h
util/vesselfinder.h
util/png.h
util/prettyprint.h
util/profiler.h

284
sdrbase/util/vesselfinder.cpp

@ -0,0 +1,284 @@ @@ -0,0 +1,284 @@
///////////////////////////////////////////////////////////////////////////////////
// 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 "vesselfinder.h"
#include <QDebug>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QRegularExpression>
#include <QUrl>
#include <QUrlQuery>
const char *VesselFinder::m_userAgent =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) SDRangel/1.0";
VesselFinder::VesselFinder(QObject *parent) :
QObject(parent),
m_networkManager(new QNetworkAccessManager(this))
{
connect(
m_networkManager,
&QNetworkAccessManager::finished,
this,
&VesselFinder::handleReply
);
}
VesselFinder::~VesselFinder()
{
disconnect(
m_networkManager,
&QNetworkAccessManager::finished,
this,
&VesselFinder::handleReply
);
qDeleteAll(m_photos);
}
void VesselFinder::setCommonHeaders(QNetworkRequest& request)
{
request.setRawHeader("User-Agent", m_userAgent);
request.setRawHeader("Accept-Language", "en-US,en;q=0.8");
request.setAttribute(
QNetworkRequest::RedirectPolicyAttribute,
QNetworkRequest::NoLessSafeRedirectPolicy
);
}
QString VesselFinder::identifier(const QString& imo, const QString& mmsi)
{
bool imoOk = false;
bool mmsiOk = false;
const qulonglong imoNumber = imo.trimmed().toULongLong(&imoOk);
const qulonglong mmsiNumber = mmsi.trimmed().toULongLong(&mmsiOk);
if (imoOk && (imoNumber != 0)) {
return QString("imo:%1").arg(imoNumber);
}
if (mmsiOk && (mmsiNumber != 0)) {
return QString("mmsi:%1").arg(mmsiNumber);
}
return QString();
}
void VesselFinder::getShipPhoto(const QString& imo, const QString& mmsi)
{
const QString id = identifier(imo, mmsi);
if (id.isEmpty()) {
return;
}
if (m_photos.contains(id))
{
VesselFinderPhoto *photo = m_photos.value(id);
if (photo->m_complete) {
emit shipPhoto(photo);
}
return;
}
VesselFinderPhoto *photo = new VesselFinderPhoto();
photo->m_id = id;
photo->m_imo = imo.trimmed();
photo->m_mmsi = mmsi.trimmed();
m_photos.insert(id, photo);
requestGallery(photo, id.startsWith("imo:"));
}
void VesselFinder::requestGallery(VesselFinderPhoto *photo, bool useIMO)
{
QUrl url("https://www.vesselfinder.com/gallery");
QUrlQuery query;
query.addQueryItem(useIMO ? "imo" : "mmsi", useIMO ? photo->m_imo : photo->m_mmsi);
url.setQuery(query);
photo->m_queryUsesIMO = useIMO;
photo->m_link = url.toString(QUrl::FullyEncoded);
QNetworkRequest request(url);
setCommonHeaders(request);
request.setRawHeader("Accept", "text/html,application/xhtml+xml");
request.setAttribute(QNetworkRequest::User, GalleryRequest);
request.setOriginatingObject(photo);
m_networkManager->get(request);
}
void VesselFinder::handleReply(QNetworkReply *reply)
{
if (!reply) {
return;
}
VesselFinderPhoto *photo = qobject_cast<VesselFinderPhoto *>(
reply->request().originatingObject()
);
const RequestType requestType = static_cast<RequestType>(
reply->request().attribute(QNetworkRequest::User).toInt()
);
if (!photo)
{
qDebug() << "VesselFinder::handleReply: missing photo request context";
reply->deleteLater();
return;
}
if (reply->error() != QNetworkReply::NoError)
{
qDebug() << "VesselFinder::handleReply:" << reply->url() << reply->errorString();
if ((requestType != GalleryRequest) || !tryMMSIFallback(photo)) {
finish(photo);
}
reply->deleteLater();
return;
}
const QByteArray bytes = reply->readAll();
if (requestType == GalleryRequest)
{
if (!parseGallery(photo, bytes) && !tryMMSIFallback(photo)) {
finish(photo);
}
}
else
{
parseImage(photo, bytes);
}
reply->deleteLater();
}
bool VesselFinder::parseGallery(VesselFinderPhoto *photo, const QByteArray& bytes)
{
const QString html = QString::fromUtf8(bytes);
const QRegularExpression photoLinkExpression(
"<a\\b[^>]*href\\s*=\\s*[\\\"']/ship-photos/(\\d+)[\\\"'][^>]*>",
QRegularExpression::CaseInsensitiveOption
);
const QRegularExpressionMatch photoLinkMatch = photoLinkExpression.match(html);
if (!photoLinkMatch.hasMatch()) {
return false;
}
const int linkStart = photoLinkMatch.capturedStart();
const int linkEnd = html.indexOf("</a>", photoLinkMatch.capturedEnd(), Qt::CaseInsensitive);
if (linkEnd < 0) {
return false;
}
const QString photoAnchor = html.mid(linkStart, linkEnd - linkStart);
const QRegularExpression imageExpression(
"<img\\b[^>]*src\\s*=\\s*[\\\"']([^\\\"']+)[\\\"']",
QRegularExpression::CaseInsensitiveOption
);
const QRegularExpressionMatch imageMatch = imageExpression.match(photoAnchor);
if (!imageMatch.hasMatch()) {
return false;
}
photo->m_imageUrl = imageMatch.captured(1);
photo->m_imageUrl.replace("&amp;", "&");
const int nextPicture = html.indexOf("class=\"picture", linkEnd, Qt::CaseInsensitive);
const QString cardTail = html.mid(
linkEnd,
nextPicture < 0 ? -1 : nextPicture - linkEnd
);
const QRegularExpression photographerExpression(
"<a\\b[^>]*class\\s*=\\s*[\\\"'][^\\\"']*photographer[^\\\"']*[\\\"'][^>]*>(.*?)</a>",
QRegularExpression::CaseInsensitiveOption | QRegularExpression::DotMatchesEverythingOption
);
const QRegularExpressionMatch photographerMatch = photographerExpression.match(cardTail);
if (photographerMatch.hasMatch()) {
photo->m_photographer = htmlToPlainText(photographerMatch.captured(1));
}
QUrl imageUrl(photo->m_imageUrl);
if (imageUrl.isRelative()) {
imageUrl = QUrl(photo->m_link).resolved(imageUrl);
}
QNetworkRequest request(imageUrl);
setCommonHeaders(request);
request.setRawHeader("Accept", "image/avif,image/webp,image/png,image/jpeg,*/*;q=0.8");
request.setRawHeader("Referer", photo->m_link.toUtf8());
request.setAttribute(QNetworkRequest::User, ImageRequest);
request.setOriginatingObject(photo);
m_networkManager->get(request);
return true;
}
QString VesselFinder::htmlToPlainText(QString html)
{
html.remove(QRegularExpression("<[^>]*>"));
html.replace("&nbsp;", " ", Qt::CaseInsensitive);
html.replace("&#160;", " ", Qt::CaseInsensitive);
html.replace("&amp;", "&", Qt::CaseInsensitive);
html.replace("&quot;", "\"", Qt::CaseInsensitive);
html.replace("&#39;", "'", Qt::CaseInsensitive);
html.replace("&#x27;", "'", Qt::CaseInsensitive);
html.replace("&lt;", "<", Qt::CaseInsensitive);
html.replace("&gt;", ">", Qt::CaseInsensitive);
return html.simplified();
}
void VesselFinder::parseImage(VesselFinderPhoto *photo, const QByteArray& bytes)
{
if (!photo->m_pixmap.loadFromData(bytes)) {
qDebug() << "VesselFinder::parseImage: unable to decode" << bytes.size() << "bytes";
}
finish(photo);
}
bool VesselFinder::tryMMSIFallback(VesselFinderPhoto *photo)
{
bool mmsiOk = false;
const qulonglong mmsi = photo->m_mmsi.toULongLong(&mmsiOk);
if (photo->m_queryUsesIMO && mmsiOk && (mmsi != 0))
{
requestGallery(photo, false);
return true;
}
return false;
}
void VesselFinder::finish(VesselFinderPhoto *photo)
{
photo->m_complete = true;
emit shipPhoto(photo);
}

88
sdrbase/util/vesselfinder.h

@ -0,0 +1,88 @@ @@ -0,0 +1,88 @@
///////////////////////////////////////////////////////////////////////////////////
// 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_VESSELFINDER_H
#define INCLUDE_VESSELFINDER_H
#include <QHash>
#include <QObject>
#include <QPixmap>
#include <QString>
#include "export.h"
class QNetworkAccessManager;
class QNetworkReply;
class QNetworkRequest;
class SDRBASE_API VesselFinderPhoto : public QObject
{
Q_OBJECT
public:
QString m_id;
QString m_imo;
QString m_mmsi;
QString m_imageUrl;
QString m_link;
QString m_photographer;
QPixmap m_pixmap;
bool m_queryUsesIMO = false;
bool m_complete = false;
};
// VesselFinder gallery wrapper. Gallery results and images are cached in memory so
// selecting the same vessel repeatedly does not generate additional web requests.
class SDRBASE_API VesselFinder : public QObject
{
Q_OBJECT
public:
explicit VesselFinder(QObject *parent = nullptr);
~VesselFinder();
void getShipPhoto(const QString& imo, const QString& mmsi);
signals:
void shipPhoto(const VesselFinderPhoto *photo);
private slots:
void handleReply(QNetworkReply *reply);
private:
enum RequestType
{
GalleryRequest = 1,
ImageRequest
};
static const char *m_userAgent;
static void setCommonHeaders(QNetworkRequest& request);
static QString identifier(const QString& imo, const QString& mmsi);
static QString htmlToPlainText(QString html);
void requestGallery(VesselFinderPhoto *photo, bool useIMO);
bool parseGallery(VesselFinderPhoto *photo, const QByteArray& bytes);
void parseImage(VesselFinderPhoto *photo, const QByteArray& bytes);
bool tryMMSIFallback(VesselFinderPhoto *photo);
void finish(VesselFinderPhoto *photo);
QNetworkAccessManager *m_networkManager;
QHash<QString, VesselFinderPhoto *> m_photos;
};
#endif // INCLUDE_VESSELFINDER_H
Loading…
Cancel
Save