diff options
| author | Christoph Berg <myon@debian.org> | 2026-04-07 19:04:48 +0200 |
|---|---|---|
| committer | Christoph Berg <myon@debian.org> | 2026-04-07 19:04:48 +0200 |
| commit | 9b9d6a272fa4204d45956828da3f20b7be49f675 (patch) | |
| tree | b611f981259a12a2bfd4d7305843929447f1bb74 /Transceiver | |
| parent | 2f7ab3ab46786fa2a5931dae22a1b119b5cfdafa (diff) | |
| parent | f647d78463c1250ce9c99af664615fafccf5e959 (diff) | |
Update upstream source from tag 'upstream/3.0.0'
Update to upstream version '3.0.0'
with Debian dir 3b764e9a4be12ad8351230b538640dd98ddb9d05
Diffstat (limited to 'Transceiver')
20 files changed, 8045 insertions, 8045 deletions
diff --git a/Transceiver/DXLabSuiteCommanderTransceiver.cpp b/Transceiver/DXLabSuiteCommanderTransceiver.cpp index 365f433c..87fc27ba 100755..100644 --- a/Transceiver/DXLabSuiteCommanderTransceiver.cpp +++ b/Transceiver/DXLabSuiteCommanderTransceiver.cpp @@ -1,498 +1,498 @@ -#include "DXLabSuiteCommanderTransceiver.hpp"
-
-#include <QTcpSocket>
-#include <QRegularExpression>
-#include <QLocale>
-#include <QThread>
-#include <QDateTime>
-
-#include "qt_helpers.hpp"
-#include "Network/NetworkServerLookup.hpp"
-
-#include "moc_DXLabSuiteCommanderTransceiver.cpp"
-
-namespace
-{
- char const * const commander_transceiver_name {"DX Lab Suite Commander"};
-
- QString map_mode (Transceiver::MODE mode)
- {
- switch (mode)
- {
- case Transceiver::AM: return "AM";
- case Transceiver::CW: return "CW";
- case Transceiver::CW_R: return "CW-R";
- case Transceiver::USB: return "USB";
- case Transceiver::LSB: return "LSB";
- case Transceiver::FSK: return "RTTY";
- case Transceiver::FSK_R: return "RTTY-R";
- case Transceiver::DIG_L: return "DATA-L";
- case Transceiver::DIG_U: return "DATA-U";
- case Transceiver::FM:
- case Transceiver::DIG_FM:
- return "FM";
- default: break;
- }
- return "USB";
- }
-}
-
-void DXLabSuiteCommanderTransceiver::register_transceivers (logger_type * /*logger*/,
- TransceiverFactory::Transceivers * registry,
- unsigned id)
-{
- (*registry)[commander_transceiver_name] = TransceiverFactory::Capabilities {id, TransceiverFactory::Capabilities::network, true};
-}
-
-DXLabSuiteCommanderTransceiver::DXLabSuiteCommanderTransceiver (logger_type * logger,
- std::unique_ptr<TransceiverBase> wrapped,
- QString const& address, bool use_for_ptt,
- int poll_interval, QObject * parent)
- : PollingTransceiver {logger, poll_interval, parent}
- , wrapped_ {std::move (wrapped)}
- , use_for_ptt_ {use_for_ptt}
- , server_ {address}
- , commander_ {nullptr}
-{
-}
-
-int DXLabSuiteCommanderTransceiver::do_start ()
-{
- CAT_TRACE ("starting");
- if (wrapped_) wrapped_->start (0);
-
- auto server_details = network_server_lookup (server_, 52002u, QHostAddress::LocalHost, QAbstractSocket::IPv4Protocol);
-
- if (!commander_)
- {
- commander_ = new QTcpSocket {this}; // QObject takes ownership
- }
-
- commander_->connectToHost (std::get<0> (server_details), std::get<1> (server_details));
- if (!commander_->waitForConnected ())
- {
- CAT_ERROR ("failed to connect" << commander_->errorString ());
- throw error {tr ("Failed to connect to DX Lab Suite Commander\n") + commander_->errorString ()};
- }
-
- // sleeps here are to ensure Commander has actually queried the rig
- // rather than returning cached data which maybe stale or simply
- // read backs of not yet committed values, the 2s delays are
- // arbitrary but hopefully enough as the actual time required is rig
- // and Commander setting dependent
- int resolution {0};
- QThread::msleep (2000);
- auto reply = command_with_reply ("<command:10>CmdGetFreq<parameters:0>");
- if (0 == reply.indexOf ("<CmdFreq:"))
- {
- auto f = string_to_frequency (reply.mid (reply.indexOf ('>') + 1));
- if (f && !(f % 10))
- {
- auto test_frequency = f - f % 100 + 55;
- auto f_string = frequency_to_string (test_frequency);
- auto params = ("<xcvrfreq:%1>" + f_string).arg (f_string.size ());
- simple_command (("<command:10>CmdSetFreq<parameters:%1>" + params).arg (params.size ()));
- QThread::msleep (2000);
- reply = command_with_reply ("<command:10>CmdGetFreq<parameters:0>");
- if (0 == reply.indexOf ("<CmdFreq:"))
- {
- auto new_frequency = string_to_frequency (reply.mid (reply.indexOf ('>') + 1));
- switch (static_cast<Radio::FrequencyDelta> (new_frequency - test_frequency))
- {
- case -5: resolution = -1; break; // 10Hz truncated
- case 5: resolution = 1; break; // 10Hz rounded
- case -15: resolution = -2; break; // 20Hz truncated
- case -55: resolution = -2; break; // 100Hz truncated
- case 45: resolution = 2; break; // 100Hz rounded
- }
- if (1 == resolution) // may be 20Hz rounded
- {
- test_frequency = f - f % 100 + 51;
- f_string = frequency_to_string (test_frequency);
- params = ("<xcvrfreq:%1>" + f_string).arg (f_string.size ());
- simple_command (("<command:10>CmdSetFreq<parameters:%1>" + params).arg (params.size ()));
- QThread::msleep (2000);
- reply = command_with_reply ("<command:10>CmdGetFreq<parameters:0>");
- new_frequency = string_to_frequency (reply.mid (reply.indexOf ('>') + 1));
- if (9 == static_cast<Radio::FrequencyDelta> (new_frequency - test_frequency))
- {
- resolution = 2; // 20Hz rounded
- }
- }
- f_string = frequency_to_string (f);
- params = ("<xcvrfreq:%1>" + f_string).arg (f_string.size ());
- simple_command (("<command:10>CmdSetFreq<parameters:%1>" + params).arg (params.size ()));
- }
- }
- }
- else
- {
- CAT_ERROR ("get frequency unexpected response" << reply);
- throw error {tr ("DX Lab Suite Commander didn't respond correctly reading frequency: ") + reply};
- }
-
- do_poll ();
- return resolution;
-}
-
-void DXLabSuiteCommanderTransceiver::do_stop ()
-{
- if (commander_)
- {
- commander_->close ();
- delete commander_, commander_ = nullptr;
- }
-
- if (wrapped_) wrapped_->stop ();
- CAT_TRACE ("stopped");
-}
-
-void DXLabSuiteCommanderTransceiver::do_ptt (bool on)
-{
- CAT_TRACE (on << ' ' << state ());
- if (use_for_ptt_)
- {
- simple_command (on ? "<command:5>CmdTX<parameters:0>" : "<command:5>CmdRX<parameters:0>");
-
- bool tx {!on};
- auto start = QDateTime::currentMSecsSinceEpoch ();
- // we must now wait for Tx on the rig, we will wait a short while
- // before bailing out
- while (tx != on && QDateTime::currentMSecsSinceEpoch () - start < 1000)
- {
- auto reply = command_with_reply ("<command:9>CmdSendTx<parameters:0>");
- if (0 == reply.indexOf ("<CmdTX:"))
- {
- auto state = reply.mid (reply.indexOf ('>') + 1);
- if ("ON" == state)
- {
- tx = true;
- }
- else if ("OFF" == state)
- {
- tx = false;
- }
- else
- {
- CAT_ERROR ("unexpected TX state" << state);
- throw error {tr ("DX Lab Suite Commander sent an unrecognised TX state: ") + state};
- }
- }
- else
- {
- CAT_ERROR ("get TX unexpected response" << reply);
- throw error {tr ("DX Lab Suite Commander didn't respond correctly polling TX status: ") + reply};
- }
- if (tx != on) QThread::msleep (10); // don't thrash Commander
- }
- update_PTT (tx);
- if (tx != on)
- {
- CAT_ERROR ("rig failed to respond to PTT: " << on);
- throw error {tr ("Transceiver did not respond to PTT On/Off quickly enough; \n"
- "reduce DX Lab Suite Commander's 'Command Interval' setting \n"
- "or contact DXLab support at DXLab@groups.io.")};
- }
- }
- else
- {
- Q_ASSERT (wrapped_);
- TransceiverState new_state {wrapped_->state ()};
- new_state.ptt (on);
- wrapped_->set (new_state, 0);
- update_PTT (on);
- }
-}
-
-void DXLabSuiteCommanderTransceiver::do_frequency (Frequency f, MODE m, bool /*no_ignore*/)
-{
- CAT_TRACE (f << ' ' << state ());
- auto f_string = frequency_to_string (f);
- if (UNK != m && m != get_mode ())
- {
- auto m_string = map_mode (m);
- auto params = ("<xcvrfreq:%1>" + f_string + "<xcvrmode:%2>" + m_string + "<preservesplitanddual:1>Y").arg (f_string.size ()).arg (m_string.size ());
- simple_command (("<command:14>CmdSetFreqMode<parameters:%1>" + params).arg (params.size ()));
- update_mode (m);
- }
- else
- {
- auto params = ("<xcvrfreq:%1>" + f_string).arg (f_string.size ());
- simple_command (("<command:10>CmdSetFreq<parameters:%1>" + params).arg (params.size ()));
- }
- update_rx_frequency (f);
-}
-
-void DXLabSuiteCommanderTransceiver::do_tx_frequency (Frequency tx, MODE mode, bool /*no_ignore*/)
-{
- CAT_TRACE (tx << ' ' << state ());
- if (tx)
- {
- auto f_string = frequency_to_string (tx);
- auto params = ("<xcvrfreq:%1>" + f_string + "<SuppressDual:1>Y").arg (f_string.size ());
- if (UNK == mode)
- {
- params += "<SuppressModeChange:1>Y";
- }
- simple_command (("<command:11>CmdQSXSplit<parameters:%1>" + params).arg (params.size ()));
- }
- else
- {
- simple_command ("<command:8>CmdSplit<parameters:8><1:3>off");
- }
- update_split (tx);
- update_other_frequency (tx);
-}
-
-void DXLabSuiteCommanderTransceiver::do_mode (MODE m)
-{
- CAT_TRACE (m << ' ' << state ());
- auto m_string = map_mode (m);
- auto params = ("<1:%1>" + m_string).arg (m_string.size ());
- simple_command (("<command:10>CmdSetMode<parameters:%1>" + params).arg (params.size ()));
- update_mode (m);
-}
-
-void DXLabSuiteCommanderTransceiver::do_poll ()
-{
- auto reply = command_with_reply ("<command:10>CmdGetFreq<parameters:0>");
- if (0 == reply.indexOf ("<CmdFreq:"))
- {
- auto f = string_to_frequency (reply.mid (reply.indexOf ('>') + 1));
- if (f)
- {
- if (!state ().ptt ()) // Commander is not reliable on frequency
- // polls while transmitting
- {
- update_rx_frequency (f);
- }
- }
- }
- else
- {
- CAT_ERROR ("get frequency unexpected response" << reply);
- throw error {tr ("DX Lab Suite Commander didn't respond correctly polling frequency: ") + reply};
- }
-
- if (state ().split ())
- {
- reply = command_with_reply ("<command:12>CmdGetTXFreq<parameters:0>");
- if (0 == reply.indexOf ("<CmdTXFreq:"))
- {
- auto f = string_to_frequency (reply.mid (reply.indexOf ('>') + 1));
- if (f)
- {
- if (!state ().ptt ()) // Commander is not reliable on frequency
- // polls while transmitting
- {
- update_other_frequency (f);
- }
- }
- }
- else
- {
- CAT_ERROR ("get tx frequency unexpected response" << reply);
- throw error {tr ("DX Lab Suite Commander didn't respond correctly polling TX frequency: ") + reply};
- }
- }
-
- reply = command_with_reply ("<command:12>CmdSendSplit<parameters:0>");
- if (0 == reply.indexOf ("<CmdSplit:"))
- {
- auto split = reply.mid (reply.indexOf ('>') + 1);
- if ("ON" == split)
- {
- update_split (true);
- }
- else if ("OFF" == split)
- {
- update_split (false);
- }
- else
- {
- CAT_ERROR ("unexpected split state" << split);
- throw error {tr ("DX Lab Suite Commander sent an unrecognised split state: ") + split};
- }
- }
- else
- {
- CAT_ERROR ("get split mode unexpected response" << reply);
- throw error {tr ("DX Lab Suite Commander didn't respond correctly polling split status: ") + reply};
- }
-
- get_mode ();
-}
-
-auto DXLabSuiteCommanderTransceiver::get_mode () -> MODE
-{
- MODE m {UNK};
- auto reply = command_with_reply ("<command:11>CmdSendMode<parameters:0>");
- if (0 == reply.indexOf ("<CmdMode:"))
- {
- auto mode = reply.mid (reply.indexOf ('>') + 1);
- if ("AM" == mode)
- {
- m = AM;
- }
- else if ("CW" == mode)
- {
- m = CW;
- }
- else if ("CW-R" == mode)
- {
- m = CW_R;
- }
- else if ("FM" == mode || "WBFM" == mode)
- {
- m = FM;
- }
- else if ("LSB" == mode)
- {
- m = LSB;
- }
- else if ("USB" == mode)
- {
- m = USB;
- }
- else if ("RTTY" == mode)
- {
- m = FSK;
- }
- else if ("RTTY-R" == mode)
- {
- m = FSK_R;
- }
- else if ("PKT" == mode || "DATA-L" == mode || "Data-L" == mode || "DIGL" == mode)
- {
- m = DIG_L;
- }
- else if ("PKT-R" == mode || "DATA-U" == mode || "Data-U" == mode || "DIGU" == mode)
- {
- m = DIG_U;
- }
- else
- {
- CAT_ERROR ("unexpected mode name" << mode);
- throw error {tr ("DX Lab Suite Commander sent an unrecognised mode: \"") + mode + '"'};
- }
- update_mode (m);
- }
- else
- {
- CAT_ERROR ("unexpected response" << reply);
- throw error {tr ("DX Lab Suite Commander didn't respond correctly polling mode: ") + reply};
- }
- return m;
-}
-
-void DXLabSuiteCommanderTransceiver::simple_command (QString const& cmd)
-{
- if (!commander_) return;
-
- CAT_TRACE (cmd);
-
- if (!write_to_port (cmd))
- {
- CAT_ERROR ("failed:" << commander_->errorString ());
- throw error {tr ("DX Lab Suite Commander send command failed\n") + commander_->errorString ()};
- }
-}
-
-QString DXLabSuiteCommanderTransceiver::command_with_reply (QString const& cmd)
-{
- if (!commander_) return QString {};
-
- if (!write_to_port (cmd))
- {
- CAT_ERROR ("failed to send command:" << commander_->errorString ());
- throw error {
- tr ("DX Lab Suite Commander send command failed \"%1\": %2\n")
- .arg (cmd)
- .arg (commander_->errorString ())
- };
- }
-
- // waitForReadReady appears to be unreliable on Windows timing out
- // when data is waiting so retry a few times
- unsigned retries {5};
- bool replied {false};
- while (!replied && --retries)
- {
- replied = commander_->waitForReadyRead ();
- if (!replied && commander_->error () != commander_->SocketTimeoutError)
- {
- CAT_ERROR (cmd << "failed to read reply:" << commander_->errorString ());
- throw error {
- tr ("DX Lab Suite Commander send command \"%1\" read reply failed: %2\n")
- .arg (cmd)
- .arg (commander_->errorString ())
- };
- }
- }
-
- if (!replied)
- {
- CAT_ERROR (cmd << "retries exhausted");
- throw error {
- tr ("DX Lab Suite Commander retries exhausted sending command \"%1\"")
- .arg (cmd)
- };
- }
-
- QString result = commander_->readAll ();
-
- if (result != NULL)
- {
- CAT_TRACE (cmd << " -> " << QString {result});
- return result; // converting raw UTF-8 bytes to QString
- }
- return "";
-}
-
-bool DXLabSuiteCommanderTransceiver::write_to_port (QString const& s)
-{
- auto data = s.toLocal8Bit ();
- auto to_send = data.constData ();
- auto length = data.size ();
-
- qint64 total_bytes_sent {0};
- while (total_bytes_sent < length)
- {
- auto bytes_sent = commander_->write (to_send + total_bytes_sent, length - total_bytes_sent);
- if (bytes_sent < 0 || !commander_->waitForBytesWritten ())
- {
- return false;
- }
-
- total_bytes_sent += bytes_sent;
- }
- return true;
-}
-
-QString DXLabSuiteCommanderTransceiver::frequency_to_string (Frequency f) const
-{
- // number is localized and in kHz, avoid floating point translation
- // errors by adding a small number (0.1Hz)
- return QString {"%L1"}.arg (f / 1e3 + 1e-4, 10, 'f', 3);
-}
-
-auto DXLabSuiteCommanderTransceiver::string_to_frequency (QString s) const -> Frequency
-{
- // temporary hack because Commander is returning invalid UTF-8 bytes
- s.replace (QChar {QChar::ReplacementCharacter}, locale_.groupSeparator ());
-
- // remove DP - relies on n.nnn kHz format so we can do ulonglong
- // conversion to Hz
- bool ok;
-
- // auto f = locale_.toDouble (s, &ok); // use when CmdSendFreq and
- // CmdSendTxFreq reinstated
-
- auto f = QLocale::c ().toDouble (s, &ok); // temporary fix
-
- if (!ok)
- {
- throw error {tr ("DX Lab Suite Commander sent an unrecognized frequency")};
- }
- return (f + 1e-4) * 1e3;
-}
+#include "DXLabSuiteCommanderTransceiver.hpp" + +#include <QTcpSocket> +#include <QRegularExpression> +#include <QLocale> +#include <QThread> +#include <QDateTime> + +#include "qt_helpers.hpp" +#include "Network/NetworkServerLookup.hpp" + +#include "moc_DXLabSuiteCommanderTransceiver.cpp" + +namespace +{ + char const * const commander_transceiver_name {"DX Lab Suite Commander"}; + + QString map_mode (Transceiver::MODE mode) + { + switch (mode) + { + case Transceiver::AM: return "AM"; + case Transceiver::CW: return "CW"; + case Transceiver::CW_R: return "CW-R"; + case Transceiver::USB: return "USB"; + case Transceiver::LSB: return "LSB"; + case Transceiver::FSK: return "RTTY"; + case Transceiver::FSK_R: return "RTTY-R"; + case Transceiver::DIG_L: return "DATA-L"; + case Transceiver::DIG_U: return "DATA-U"; + case Transceiver::FM: + case Transceiver::DIG_FM: + return "FM"; + default: break; + } + return "USB"; + } +} + +void DXLabSuiteCommanderTransceiver::register_transceivers (logger_type * /*logger*/, + TransceiverFactory::Transceivers * registry, + unsigned id) +{ + (*registry)[commander_transceiver_name] = TransceiverFactory::Capabilities {id, TransceiverFactory::Capabilities::network, true}; +} + +DXLabSuiteCommanderTransceiver::DXLabSuiteCommanderTransceiver (logger_type * logger, + std::unique_ptr<TransceiverBase> wrapped, + QString const& address, bool use_for_ptt, + int poll_interval, QObject * parent) + : PollingTransceiver {logger, poll_interval, parent} + , wrapped_ {std::move (wrapped)} + , use_for_ptt_ {use_for_ptt} + , server_ {address} + , commander_ {nullptr} +{ +} + +int DXLabSuiteCommanderTransceiver::do_start () +{ + CAT_TRACE ("starting"); + if (wrapped_) wrapped_->start (0); + + auto server_details = network_server_lookup (server_, 52002u, QHostAddress::LocalHost, QAbstractSocket::IPv4Protocol); + + if (!commander_) + { + commander_ = new QTcpSocket {this}; // QObject takes ownership + } + + commander_->connectToHost (std::get<0> (server_details), std::get<1> (server_details)); + if (!commander_->waitForConnected ()) + { + CAT_ERROR ("failed to connect" << commander_->errorString ()); + throw error {tr ("Failed to connect to DX Lab Suite Commander\n") + commander_->errorString ()}; + } + + // sleeps here are to ensure Commander has actually queried the rig + // rather than returning cached data which maybe stale or simply + // read backs of not yet committed values, the 2s delays are + // arbitrary but hopefully enough as the actual time required is rig + // and Commander setting dependent + int resolution {0}; + QThread::msleep (2000); + auto reply = command_with_reply ("<command:10>CmdGetFreq<parameters:0>"); + if (0 == reply.indexOf ("<CmdFreq:")) + { + auto f = string_to_frequency (reply.mid (reply.indexOf ('>') + 1)); + if (f && !(f % 10)) + { + auto test_frequency = f - f % 100 + 55; + auto f_string = frequency_to_string (test_frequency); + auto params = ("<xcvrfreq:%1>" + f_string).arg (f_string.size ()); + simple_command (("<command:10>CmdSetFreq<parameters:%1>" + params).arg (params.size ())); + QThread::msleep (2000); + reply = command_with_reply ("<command:10>CmdGetFreq<parameters:0>"); + if (0 == reply.indexOf ("<CmdFreq:")) + { + auto new_frequency = string_to_frequency (reply.mid (reply.indexOf ('>') + 1)); + switch (static_cast<Radio::FrequencyDelta> (new_frequency - test_frequency)) + { + case -5: resolution = -1; break; // 10Hz truncated + case 5: resolution = 1; break; // 10Hz rounded + case -15: resolution = -2; break; // 20Hz truncated + case -55: resolution = -2; break; // 100Hz truncated + case 45: resolution = 2; break; // 100Hz rounded + } + if (1 == resolution) // may be 20Hz rounded + { + test_frequency = f - f % 100 + 51; + f_string = frequency_to_string (test_frequency); + params = ("<xcvrfreq:%1>" + f_string).arg (f_string.size ()); + simple_command (("<command:10>CmdSetFreq<parameters:%1>" + params).arg (params.size ())); + QThread::msleep (2000); + reply = command_with_reply ("<command:10>CmdGetFreq<parameters:0>"); + new_frequency = string_to_frequency (reply.mid (reply.indexOf ('>') + 1)); + if (9 == static_cast<Radio::FrequencyDelta> (new_frequency - test_frequency)) + { + resolution = 2; // 20Hz rounded + } + } + f_string = frequency_to_string (f); + params = ("<xcvrfreq:%1>" + f_string).arg (f_string.size ()); + simple_command (("<command:10>CmdSetFreq<parameters:%1>" + params).arg (params.size ())); + } + } + } + else + { + CAT_ERROR ("get frequency unexpected response" << reply); + throw error {tr ("DX Lab Suite Commander didn't respond correctly reading frequency: ") + reply}; + } + + do_poll (); + return resolution; +} + +void DXLabSuiteCommanderTransceiver::do_stop () +{ + if (commander_) + { + commander_->close (); + delete commander_, commander_ = nullptr; + } + + if (wrapped_) wrapped_->stop (); + CAT_TRACE ("stopped"); +} + +void DXLabSuiteCommanderTransceiver::do_ptt (bool on) +{ + CAT_TRACE (on << ' ' << state ()); + if (use_for_ptt_) + { + simple_command (on ? "<command:5>CmdTX<parameters:0>" : "<command:5>CmdRX<parameters:0>"); + + bool tx {!on}; + auto start = QDateTime::currentMSecsSinceEpoch (); + // we must now wait for Tx on the rig, we will wait a short while + // before bailing out + while (tx != on && QDateTime::currentMSecsSinceEpoch () - start < 1000) + { + auto reply = command_with_reply ("<command:9>CmdSendTx<parameters:0>"); + if (0 == reply.indexOf ("<CmdTX:")) + { + auto state = reply.mid (reply.indexOf ('>') + 1); + if ("ON" == state) + { + tx = true; + } + else if ("OFF" == state) + { + tx = false; + } + else + { + CAT_ERROR ("unexpected TX state" << state); + throw error {tr ("DX Lab Suite Commander sent an unrecognised TX state: ") + state}; + } + } + else + { + CAT_ERROR ("get TX unexpected response" << reply); + throw error {tr ("DX Lab Suite Commander didn't respond correctly polling TX status: ") + reply}; + } + if (tx != on) QThread::msleep (10); // don't thrash Commander + } + update_PTT (tx); + if (tx != on) + { + CAT_ERROR ("rig failed to respond to PTT: " << on); + throw error {tr ("Transceiver did not respond to PTT On/Off quickly enough; \n" + "reduce DX Lab Suite Commander's 'Command Interval' setting \n" + "or contact DXLab support at DXLab@groups.io.")}; + } + } + else + { + Q_ASSERT (wrapped_); + TransceiverState new_state {wrapped_->state ()}; + new_state.ptt (on); + wrapped_->set (new_state, 0); + update_PTT (on); + } +} + +void DXLabSuiteCommanderTransceiver::do_frequency (Frequency f, MODE m, bool /*no_ignore*/) +{ + CAT_TRACE (f << ' ' << state ()); + auto f_string = frequency_to_string (f); + if (UNK != m && m != get_mode ()) + { + auto m_string = map_mode (m); + auto params = ("<xcvrfreq:%1>" + f_string + "<xcvrmode:%2>" + m_string + "<preservesplitanddual:1>Y").arg (f_string.size ()).arg (m_string.size ()); + simple_command (("<command:14>CmdSetFreqMode<parameters:%1>" + params).arg (params.size ())); + update_mode (m); + } + else + { + auto params = ("<xcvrfreq:%1>" + f_string).arg (f_string.size ()); + simple_command (("<command:10>CmdSetFreq<parameters:%1>" + params).arg (params.size ())); + } + update_rx_frequency (f); +} + +void DXLabSuiteCommanderTransceiver::do_tx_frequency (Frequency tx, MODE mode, bool /*no_ignore*/) +{ + CAT_TRACE (tx << ' ' << state ()); + if (tx) + { + auto f_string = frequency_to_string (tx); + auto params = ("<xcvrfreq:%1>" + f_string + "<SuppressDual:1>Y").arg (f_string.size ()); + if (UNK == mode) + { + params += "<SuppressModeChange:1>Y"; + } + simple_command (("<command:11>CmdQSXSplit<parameters:%1>" + params).arg (params.size ())); + } + else + { + simple_command ("<command:8>CmdSplit<parameters:8><1:3>off"); + } + update_split (tx); + update_other_frequency (tx); +} + +void DXLabSuiteCommanderTransceiver::do_mode (MODE m) +{ + CAT_TRACE (m << ' ' << state ()); + auto m_string = map_mode (m); + auto params = ("<1:%1>" + m_string).arg (m_string.size ()); + simple_command (("<command:10>CmdSetMode<parameters:%1>" + params).arg (params.size ())); + update_mode (m); +} + +void DXLabSuiteCommanderTransceiver::do_poll () +{ + auto reply = command_with_reply ("<command:10>CmdGetFreq<parameters:0>"); + if (0 == reply.indexOf ("<CmdFreq:")) + { + auto f = string_to_frequency (reply.mid (reply.indexOf ('>') + 1)); + if (f) + { + if (!state ().ptt ()) // Commander is not reliable on frequency + // polls while transmitting + { + update_rx_frequency (f); + } + } + } + else + { + CAT_ERROR ("get frequency unexpected response" << reply); + throw error {tr ("DX Lab Suite Commander didn't respond correctly polling frequency: ") + reply}; + } + + if (state ().split ()) + { + reply = command_with_reply ("<command:12>CmdGetTXFreq<parameters:0>"); + if (0 == reply.indexOf ("<CmdTXFreq:")) + { + auto f = string_to_frequency (reply.mid (reply.indexOf ('>') + 1)); + if (f) + { + if (!state ().ptt ()) // Commander is not reliable on frequency + // polls while transmitting + { + update_other_frequency (f); + } + } + } + else + { + CAT_ERROR ("get tx frequency unexpected response" << reply); + throw error {tr ("DX Lab Suite Commander didn't respond correctly polling TX frequency: ") + reply}; + } + } + + reply = command_with_reply ("<command:12>CmdSendSplit<parameters:0>"); + if (0 == reply.indexOf ("<CmdSplit:")) + { + auto split = reply.mid (reply.indexOf ('>') + 1); + if ("ON" == split) + { + update_split (true); + } + else if ("OFF" == split) + { + update_split (false); + } + else + { + CAT_ERROR ("unexpected split state" << split); + throw error {tr ("DX Lab Suite Commander sent an unrecognised split state: ") + split}; + } + } + else + { + CAT_ERROR ("get split mode unexpected response" << reply); + throw error {tr ("DX Lab Suite Commander didn't respond correctly polling split status: ") + reply}; + } + + get_mode (); +} + +auto DXLabSuiteCommanderTransceiver::get_mode () -> MODE +{ + MODE m {UNK}; + auto reply = command_with_reply ("<command:11>CmdSendMode<parameters:0>"); + if (0 == reply.indexOf ("<CmdMode:")) + { + auto mode = reply.mid (reply.indexOf ('>') + 1); + if ("AM" == mode) + { + m = AM; + } + else if ("CW" == mode) + { + m = CW; + } + else if ("CW-R" == mode) + { + m = CW_R; + } + else if ("FM" == mode || "WBFM" == mode) + { + m = FM; + } + else if ("LSB" == mode) + { + m = LSB; + } + else if ("USB" == mode) + { + m = USB; + } + else if ("RTTY" == mode) + { + m = FSK; + } + else if ("RTTY-R" == mode) + { + m = FSK_R; + } + else if ("PKT" == mode || "DATA-L" == mode || "Data-L" == mode || "DIGL" == mode) + { + m = DIG_L; + } + else if ("PKT-R" == mode || "DATA-U" == mode || "Data-U" == mode || "DIGU" == mode) + { + m = DIG_U; + } + else + { + CAT_ERROR ("unexpected mode name" << mode); + throw error {tr ("DX Lab Suite Commander sent an unrecognised mode: \"") + mode + '"'}; + } + update_mode (m); + } + else + { + CAT_ERROR ("unexpected response" << reply); + throw error {tr ("DX Lab Suite Commander didn't respond correctly polling mode: ") + reply}; + } + return m; +} + +void DXLabSuiteCommanderTransceiver::simple_command (QString const& cmd) +{ + if (!commander_) return; + + CAT_TRACE (cmd); + + if (!write_to_port (cmd)) + { + CAT_ERROR ("failed:" << commander_->errorString ()); + throw error {tr ("DX Lab Suite Commander send command failed\n") + commander_->errorString ()}; + } +} + +QString DXLabSuiteCommanderTransceiver::command_with_reply (QString const& cmd) +{ + if (!commander_) return QString {}; + + if (!write_to_port (cmd)) + { + CAT_ERROR ("failed to send command:" << commander_->errorString ()); + throw error { + tr ("DX Lab Suite Commander send command failed \"%1\": %2\n") + .arg (cmd) + .arg (commander_->errorString ()) + }; + } + + // waitForReadReady appears to be unreliable on Windows timing out + // when data is waiting so retry a few times + unsigned retries {5}; + bool replied {false}; + while (!replied && --retries) + { + replied = commander_->waitForReadyRead (); + if (!replied && commander_->error () != commander_->SocketTimeoutError) + { + CAT_ERROR (cmd << "failed to read reply:" << commander_->errorString ()); + throw error { + tr ("DX Lab Suite Commander send command \"%1\" read reply failed: %2\n") + .arg (cmd) + .arg (commander_->errorString ()) + }; + } + } + + if (!replied) + { + CAT_ERROR (cmd << "retries exhausted"); + throw error { + tr ("DX Lab Suite Commander retries exhausted sending command \"%1\"") + .arg (cmd) + }; + } + + QString result = commander_->readAll (); + + if (result != NULL) + { + CAT_TRACE (cmd << " -> " << QString {result}); + return result; // converting raw UTF-8 bytes to QString + } + return ""; +} + +bool DXLabSuiteCommanderTransceiver::write_to_port (QString const& s) +{ + auto data = s.toLocal8Bit (); + auto to_send = data.constData (); + auto length = data.size (); + + qint64 total_bytes_sent {0}; + while (total_bytes_sent < length) + { + auto bytes_sent = commander_->write (to_send + total_bytes_sent, length - total_bytes_sent); + if (bytes_sent < 0 || !commander_->waitForBytesWritten ()) + { + return false; + } + + total_bytes_sent += bytes_sent; + } + return true; +} + +QString DXLabSuiteCommanderTransceiver::frequency_to_string (Frequency f) const +{ + // number is localized and in kHz, avoid floating point translation + // errors by adding a small number (0.1Hz) + return QString {"%L1"}.arg (f / 1e3 + 1e-4, 10, 'f', 3); +} + +auto DXLabSuiteCommanderTransceiver::string_to_frequency (QString s) const -> Frequency +{ + // temporary hack because Commander is returning invalid UTF-8 bytes + s.replace (QChar {QChar::ReplacementCharacter}, locale_.groupSeparator ()); + + // remove DP - relies on n.nnn kHz format so we can do ulonglong + // conversion to Hz + bool ok; + + // auto f = locale_.toDouble (s, &ok); // use when CmdSendFreq and + // CmdSendTxFreq reinstated + + auto f = QLocale::c ().toDouble (s, &ok); // temporary fix + + if (!ok) + { + throw error {tr ("DX Lab Suite Commander sent an unrecognized frequency")}; + } + return (f + 1e-4) * 1e3; +} diff --git a/Transceiver/DXLabSuiteCommanderTransceiver.hpp b/Transceiver/DXLabSuiteCommanderTransceiver.hpp index 03ed7942..fc060fb7 100755..100644 --- a/Transceiver/DXLabSuiteCommanderTransceiver.hpp +++ b/Transceiver/DXLabSuiteCommanderTransceiver.hpp @@ -1,59 +1,59 @@ -#ifndef DX_LAB_SUITE_COMMANDER_TRANSCEIVER_HPP__
-#define DX_LAB_SUITE_COMMANDER_TRANSCEIVER_HPP__
-
-#include <memory>
-
-#include "TransceiverFactory.hpp"
-#include "PollingTransceiver.hpp"
-
-class QTcpSocket;
-class QByteArray;
-class QString;
-
-//
-// DX Lab Suite Commander Interface
-//
-// Implemented as a Transceiver decorator because we may want the PTT
-// services of another Transceiver type such as the HamlibTransceiver
-// which can be enabled by wrapping a HamlibTransceiver instantiated
-// as a "Hamlib Dummy" transceiver in the Transceiver factory method.
-//
-class DXLabSuiteCommanderTransceiver final
- : public PollingTransceiver
-{
- Q_OBJECT; // for translation context
-
-public:
- static void register_transceivers (logger_type *, TransceiverFactory::Transceivers *, unsigned id);
-
- // takes ownership of wrapped Transceiver
- explicit DXLabSuiteCommanderTransceiver (logger_type *, std::unique_ptr<TransceiverBase> wrapped,
- QString const& address, bool use_for_ptt,
- int poll_interval, QObject * parent = nullptr);
-
-protected:
- int do_start () override;
- void do_stop () override;
- void do_frequency (Frequency, MODE, bool no_ignore) override;
- void do_tx_frequency (Frequency, MODE, bool no_ignore) override;
- void do_mode (MODE) override;
- void do_ptt (bool on) override;
-
- void do_poll () override;
-
-private:
- MODE get_mode ();
- void simple_command (QString const&);
- QString command_with_reply (QString const&);
- bool write_to_port (QString const&);
- QString frequency_to_string (Frequency) const;
- Frequency string_to_frequency (QString) const;
-
- std::unique_ptr<TransceiverBase> wrapped_; // may be null
- bool use_for_ptt_;
- QString server_;
- QTcpSocket * commander_;
- QLocale locale_;
-};
-
-#endif
+#ifndef DX_LAB_SUITE_COMMANDER_TRANSCEIVER_HPP__ +#define DX_LAB_SUITE_COMMANDER_TRANSCEIVER_HPP__ + +#include <memory> + +#include "TransceiverFactory.hpp" +#include "PollingTransceiver.hpp" + +class QTcpSocket; +class QByteArray; +class QString; + +// +// DX Lab Suite Commander Interface +// +// Implemented as a Transceiver decorator because we may want the PTT +// services of another Transceiver type such as the HamlibTransceiver +// which can be enabled by wrapping a HamlibTransceiver instantiated +// as a "Hamlib Dummy" transceiver in the Transceiver factory method. +// +class DXLabSuiteCommanderTransceiver final + : public PollingTransceiver +{ + Q_OBJECT; // for translation context + +public: + static void register_transceivers (logger_type *, TransceiverFactory::Transceivers *, unsigned id); + + // takes ownership of wrapped Transceiver + explicit DXLabSuiteCommanderTransceiver (logger_type *, std::unique_ptr<TransceiverBase> wrapped, + QString const& address, bool use_for_ptt, + int poll_interval, QObject * parent = nullptr); + +protected: + int do_start () override; + void do_stop () override; + void do_frequency (Frequency, MODE, bool no_ignore) override; + void do_tx_frequency (Frequency, MODE, bool no_ignore) override; + void do_mode (MODE) override; + void do_ptt (bool on) override; + + void do_poll () override; + +private: + MODE get_mode (); + void simple_command (QString const&); + QString command_with_reply (QString const&); + bool write_to_port (QString const&); + QString frequency_to_string (Frequency) const; + Frequency string_to_frequency (QString) const; + + std::unique_ptr<TransceiverBase> wrapped_; // may be null + bool use_for_ptt_; + QString server_; + QTcpSocket * commander_; + QLocale locale_; +}; + +#endif diff --git a/Transceiver/EmulateSplitTransceiver.cpp b/Transceiver/EmulateSplitTransceiver.cpp index 8cf19f72..3dfc4b5c 100755..100644 --- a/Transceiver/EmulateSplitTransceiver.cpp +++ b/Transceiver/EmulateSplitTransceiver.cpp @@ -1,71 +1,71 @@ -#include "EmulateSplitTransceiver.hpp"
-
-#include "moc_EmulateSplitTransceiver.cpp"
-
-EmulateSplitTransceiver::EmulateSplitTransceiver (logger_type * logger,
- std::unique_ptr<Transceiver> wrapped,
- QObject * parent)
- : Transceiver {logger, parent}
- , wrapped_ {std::move (wrapped)}
- , rx_frequency_ {0}
- , tx_frequency_ {0}
- , split_ {false}
-{
- // Connect update signal of wrapped Transceiver object instance to ours.
- connect (wrapped_.get (), &Transceiver::update, this, &EmulateSplitTransceiver::handle_update);
-
- // Connect other signals of wrapped Transceiver object to our
- // parent matching signals.
- connect (wrapped_.get (), &Transceiver::resolution, this, &Transceiver::resolution);
- connect (wrapped_.get (), &Transceiver::tciframeswritten, this, &Transceiver::tciframeswritten);
- connect (wrapped_.get (), &Transceiver::tci_mod_active, this, &Transceiver::tci_mod_active);
- connect (wrapped_.get (), &Transceiver::finished, this, &Transceiver::finished);
- connect (wrapped_.get (), &Transceiver::failure, this, &Transceiver::failure);
-}
-
-void EmulateSplitTransceiver::set (TransceiverState const& s, unsigned sequence_number) noexcept
-{
-#if WSJT_TRACE_CAT
- qDebug () << "EmulateSplitTransceiver::set: state:" << s << "#:" << sequence_number;
-#endif
- // save for use in updates
- rx_frequency_ = s.frequency ();
- tx_frequency_ = s.tx_frequency ();
- split_ = s.split ();
-
- TransceiverState emulated_state {s};
- if (s.ptt () && split_) emulated_state.frequency (s.tx_frequency ());
- emulated_state.split (false);
- emulated_state.tx_frequency (0);
- wrapped_->set (emulated_state, sequence_number);
-}
-
-void EmulateSplitTransceiver::handle_update (TransceiverState const& state,
- unsigned sequence_number)
-{
-#if WSJT_TRACE_CAT
- qDebug () << "EmulateSplitTransceiver::handle_update: from wrapped:" << state;
-#endif
-
- if (state.split ())
- {
- Q_EMIT failure (tr ("Emulated split mode requires rig to be in simplex mode"));
- }
- else
- {
- TransceiverState new_state {state};
- // Follow the rig if in RX mode.
- if (state.ptt ()) new_state.frequency (rx_frequency_);
-
- // These are always what was requested in prior set state operation
- new_state.tx_frequency (tx_frequency_);
- new_state.split (split_);
-
-#if WSJT_TRACE_CAT
- qDebug () << "EmulateSplitTransceiver::handle_update: signalling:" << state;
-#endif
-
- // signal emulated state
- Q_EMIT update (new_state, sequence_number);
- }
-}
+#include "EmulateSplitTransceiver.hpp" + +#include "moc_EmulateSplitTransceiver.cpp" + +EmulateSplitTransceiver::EmulateSplitTransceiver (logger_type * logger, + std::unique_ptr<Transceiver> wrapped, + QObject * parent) + : Transceiver {logger, parent} + , wrapped_ {std::move (wrapped)} + , rx_frequency_ {0} + , tx_frequency_ {0} + , split_ {false} +{ + // Connect update signal of wrapped Transceiver object instance to ours. + connect (wrapped_.get (), &Transceiver::update, this, &EmulateSplitTransceiver::handle_update); + + // Connect other signals of wrapped Transceiver object to our + // parent matching signals. + connect (wrapped_.get (), &Transceiver::resolution, this, &Transceiver::resolution); + connect (wrapped_.get (), &Transceiver::tciframeswritten, this, &Transceiver::tciframeswritten); + connect (wrapped_.get (), &Transceiver::tci_mod_active, this, &Transceiver::tci_mod_active); + connect (wrapped_.get (), &Transceiver::finished, this, &Transceiver::finished); + connect (wrapped_.get (), &Transceiver::failure, this, &Transceiver::failure); +} + +void EmulateSplitTransceiver::set (TransceiverState const& s, unsigned sequence_number) noexcept +{ +#if WSJT_TRACE_CAT + qDebug () << "EmulateSplitTransceiver::set: state:" << s << "#:" << sequence_number; +#endif + // save for use in updates + rx_frequency_ = s.frequency (); + tx_frequency_ = s.tx_frequency (); + split_ = s.split (); + + TransceiverState emulated_state {s}; + if (s.ptt () && split_) emulated_state.frequency (s.tx_frequency ()); + emulated_state.split (false); + emulated_state.tx_frequency (0); + wrapped_->set (emulated_state, sequence_number); +} + +void EmulateSplitTransceiver::handle_update (TransceiverState const& state, + unsigned sequence_number) +{ +#if WSJT_TRACE_CAT + qDebug () << "EmulateSplitTransceiver::handle_update: from wrapped:" << state; +#endif + + if (state.split ()) + { + Q_EMIT failure (tr ("Emulated split mode requires rig to be in simplex mode")); + } + else + { + TransceiverState new_state {state}; + // Follow the rig if in RX mode. + if (state.ptt ()) new_state.frequency (rx_frequency_); + + // These are always what was requested in prior set state operation + new_state.tx_frequency (tx_frequency_); + new_state.split (split_); + +#if WSJT_TRACE_CAT + qDebug () << "EmulateSplitTransceiver::handle_update: signalling:" << state; +#endif + + // signal emulated state + Q_EMIT update (new_state, sequence_number); + } +} diff --git a/Transceiver/EmulateSplitTransceiver.hpp b/Transceiver/EmulateSplitTransceiver.hpp index e6d85690..250305d1 100755..100644 --- a/Transceiver/EmulateSplitTransceiver.hpp +++ b/Transceiver/EmulateSplitTransceiver.hpp @@ -1,54 +1,54 @@ -#ifndef EMULATE_SPLIT_TRANSCEIVER_HPP__
-#define EMULATE_SPLIT_TRANSCEIVER_HPP__
-
-#include <memory>
-
-#include "Transceiver.hpp"
-
-//
-// Emulate Split Transceiver
-//
-// Helper decorator class that encapsulates the emulation of split TX
-// operation.
-//
-// Responsibilities
-//
-// Delegates all but setting of other (split) frequency to the
-// wrapped Transceiver instance. Also routes failure signals from the
-// wrapped Transceiver instance to this instances failure signal.
-//
-// Intercepts status updates from the wrapped Transceiver instance
-// and re-signals it with the emulated status.
-//
-// Generates a status update signal if the other (split) frequency is
-// changed, this is necessary since the wrapped transceiver instance
-// never receives other frequency changes.
-//
-class EmulateSplitTransceiver final
- : public Transceiver
-{
- Q_OBJECT
-
-public:
- // takes ownership of wrapped Transceiver
- explicit EmulateSplitTransceiver (logger_type *,
- std::unique_ptr<Transceiver> wrapped,
- QObject * parent = nullptr);
-
- void set (TransceiverState const&,
- unsigned sequence_number) noexcept override;
-
- // forward everything else to wrapped Transceiver
- void start (unsigned sequence_number) noexcept override {wrapped_->start (sequence_number);}
- void stop () noexcept override {wrapped_->stop ();}
-
-private:
- void handle_update (TransceiverState const&, unsigned seqeunce_number);
-
- std::unique_ptr<Transceiver> wrapped_;
- Frequency rx_frequency_; // requested Rx frequency
- Frequency tx_frequency_; // requested Tx frequency
- bool split_; // requested split state
-};
-
-#endif
+#ifndef EMULATE_SPLIT_TRANSCEIVER_HPP__ +#define EMULATE_SPLIT_TRANSCEIVER_HPP__ + +#include <memory> + +#include "Transceiver.hpp" + +// +// Emulate Split Transceiver +// +// Helper decorator class that encapsulates the emulation of split TX +// operation. +// +// Responsibilities +// +// Delegates all but setting of other (split) frequency to the +// wrapped Transceiver instance. Also routes failure signals from the +// wrapped Transceiver instance to this instances failure signal. +// +// Intercepts status updates from the wrapped Transceiver instance +// and re-signals it with the emulated status. +// +// Generates a status update signal if the other (split) frequency is +// changed, this is necessary since the wrapped transceiver instance +// never receives other frequency changes. +// +class EmulateSplitTransceiver final + : public Transceiver +{ + Q_OBJECT + +public: + // takes ownership of wrapped Transceiver + explicit EmulateSplitTransceiver (logger_type *, + std::unique_ptr<Transceiver> wrapped, + QObject * parent = nullptr); + + void set (TransceiverState const&, + unsigned sequence_number) noexcept override; + + // forward everything else to wrapped Transceiver + void start (unsigned sequence_number) noexcept override {wrapped_->start (sequence_number);} + void stop () noexcept override {wrapped_->stop ();} + +private: + void handle_update (TransceiverState const&, unsigned seqeunce_number); + + std::unique_ptr<Transceiver> wrapped_; + Frequency rx_frequency_; // requested Rx frequency + Frequency tx_frequency_; // requested Tx frequency + bool split_; // requested split state +}; + +#endif diff --git a/Transceiver/HRDTransceiver.cpp b/Transceiver/HRDTransceiver.cpp index f7ed97da..a0cef0ce 100755..100644 --- a/Transceiver/HRDTransceiver.cpp +++ b/Transceiver/HRDTransceiver.cpp @@ -1,1163 +1,1163 @@ -#include "HRDTransceiver.hpp"
-
-#include <algorithm>
-#include <QHostAddress>
-#include <QByteArray>
-#include <QRegExp>
-#include <QTcpSocket>
-#include <QThread>
-#include <QStandardPaths>
-#include <QDir>
-
-#include "Network/NetworkServerLookup.hpp"
-#include "qt_helpers.hpp"
-
-namespace
-{
- char const * const HRD_transceiver_name = "Ham Radio Deluxe";
-
- // some commands require a settling time, particularly "RX A" and
- // "RX B" on the Yaesu FTdx3000.
- int constexpr yaesu_delay {350};
-}
-
-#include "moc_HRDTransceiver.cpp"
-
-void HRDTransceiver::register_transceivers (logger_type *,
- TransceiverFactory::Transceivers * registry,
- unsigned id)
-{
- (*registry)[HRD_transceiver_name] = TransceiverFactory::Capabilities (id, TransceiverFactory::Capabilities::network, true, true /* maybe */);
-}
-
-struct HRDMessage
-{
- // Placement style new overload for outgoing messages that does the
- // construction too.
- static void * operator new (size_t size, QString const& payload)
- {
- size += sizeof (QChar) * (payload.size () + 1); // space for terminator too
- HRDMessage * storage (reinterpret_cast<HRDMessage *> (new char[size]));
- storage->size_ = size ;
- ushort const * pl (payload.utf16 ());
- std::copy (pl, pl + payload.size () + 1, storage->payload_); // copy terminator too
- storage->magic_1_ = magic_1_value_;
- storage->magic_2_ = magic_2_value_;
- storage->checksum_ = 0;
- return storage;
- }
-
- // Placement style new overload for incoming messages that does the
- // construction too.
- //
- // No memory allocation here.
- static void * operator new (size_t /* size */, QByteArray const& message)
- {
- // Nasty const_cast here to avoid copying the message buffer.
- return const_cast<HRDMessage *> (reinterpret_cast<HRDMessage const *> (message.data ()));
- }
-
- void operator delete (void * p, size_t)
- {
- delete [] reinterpret_cast<char *> (p); // Mirror allocation in operator new above.
- }
-
- quint32 size_;
- qint32 magic_1_;
- qint32 magic_2_;
- qint32 checksum_; // Apparently not used.
- QChar payload_[0]; // UTF-16 (which is wchar_t on Windows)
-
- static qint32 constexpr magic_1_value_ = 0x1234ABCD;
- static qint32 constexpr magic_2_value_ = 0xABCD1234;
-};
-
-HRDTransceiver::HRDTransceiver (logger_type * logger
- , std::unique_ptr<TransceiverBase> wrapped
- , QString const& server
- , bool use_for_ptt
- , TransceiverFactory::TXAudioSource audio_source
- , int poll_interval
- , QObject * parent)
- : PollingTransceiver {logger, poll_interval, parent}
- , wrapped_ {std::move (wrapped)}
- , use_for_ptt_ {use_for_ptt}
- , audio_source_ {audio_source}
- , server_ {server}
- , hrd_ {0}
- , protocol_ {none}
- , current_radio_ {0}
- , vfo_count_ {0}
- , vfo_A_button_ {-1}
- , vfo_B_button_ {-1}
- , vfo_toggle_button_ {-1}
- , mode_A_dropdown_ {-1}
- , mode_B_dropdown_ {-1}
- , data_mode_toggle_button_ {-1}
- , data_mode_on_button_ {-1}
- , data_mode_off_button_ {-1}
- , data_mode_dropdown_ {-1}
- , split_mode_button_ {-1}
- , split_mode_dropdown_ {-1}
- , split_mode_dropdown_write_only_ {false}
- , split_off_button_ {-1}
- , tx_A_button_ {-1}
- , tx_B_button_ {-1}
- , rx_A_button_ {-1}
- , rx_B_button_ {-1}
- , receiver_dropdown_ {-1}
- , ptt_button_ {-1}
- , alt_ptt_button_ {-1}
- , reversed_ {false}
-{
-}
-
-int HRDTransceiver::do_start ()
-{
- CAT_TRACE ("starting");
- if (wrapped_) wrapped_->start (0);
-
- auto server_details = network_server_lookup (server_, 7809u);
- if (!hrd_)
- {
- hrd_ = new QTcpSocket {this}; // QObject takes ownership
- }
- hrd_->connectToHost (std::get<0> (server_details), std::get<1> (server_details));
- if (!hrd_->waitForConnected ())
- {
- CAT_ERROR ("failed to connect:" << hrd_->errorString ());
- throw error {tr ("Failed to connect to Ham Radio Deluxe\n") + hrd_->errorString ()};
- }
-
- if (none == protocol_)
- {
- try
- {
- protocol_ = v5; // try this first (works for v6 too)
- send_command ("get context", false, false);
- }
- catch (error const&)
- {
- protocol_ = none;
- }
- }
-
- if (none == protocol_)
- {
- hrd_->close ();
-
- protocol_ = v4; // try again with older protocol
- hrd_->connectToHost (std::get<0> (server_details), std::get<1> (server_details));
- if (!hrd_->waitForConnected ())
- {
- CAT_ERROR ("failed to connect:" << hrd_->errorString ());
- throw error {tr ("Failed to connect to Ham Radio Deluxe\n") + hrd_->errorString ()};
- }
-
- send_command ("get context", false, false);
- }
-
- QFile HRD_info_file {QDir {QStandardPaths::writableLocation (QStandardPaths::DataLocation)}.absoluteFilePath ("HRD Interface Information.txt")};
- if (!HRD_info_file.open (QFile::WriteOnly | QFile::Text | QFile::Truncate))
- {
- throw error {tr ("Failed to open file \"%1\": %2.").arg (HRD_info_file.fileName ()).arg (HRD_info_file.errorString ())};
- }
- QTextStream HRD_info {&HRD_info_file};
-
- auto id = send_command ("get id", false, false);
- auto version = send_command ("get version", false, false);
-
- CAT_INFO ("Id: " << id << "Version: " << version);
- HRD_info << "Id: " << id << "\n";
- HRD_info << "Version: " << version << "\n";
-
- auto radios = send_command ("get radios", false, false).trimmed ().split (',', SkipEmptyParts);
- if (radios.isEmpty ())
- {
- CAT_ERROR ("no rig found");
- throw error {tr ("Ham Radio Deluxe: no rig found")};
- }
-
- HRD_info << "Radios:\n";
- Q_FOREACH (auto const& radio, radios)
- {
- HRD_info << "\t" << radio << "\n";
- auto entries = radio.trimmed ().split (':', SkipEmptyParts);
- radios_.push_back (std::forward_as_tuple (entries[0].toUInt (), entries[1]));
- }
-
- CAT_TRACE ("radios:-");
- Q_FOREACH (auto const& radio, radios_)
- {
- CAT_TRACE ("\t[" << std::get<0> (radio) << "] " << std::get<1> (radio));
- }
-
- auto current_radio_name = send_command ("get radio", false, false);
- HRD_info << "Current radio: " << current_radio_name << "\n";
- if (current_radio_name.isEmpty ())
- {
- CAT_ERROR ("no rig found");
- throw error {tr ("Ham Radio Deluxe: no rig found")};
- }
-
- vfo_count_ = send_command ("get vfo-count").toUInt ();
- HRD_info << "VFO count: " << vfo_count_ << "\n";
- CAT_TRACE ("vfo count:" << vfo_count_);
-
- buttons_ = send_command ("get buttons").trimmed ().split (',', SkipEmptyParts).replaceInStrings (" ", "~");
- CAT_TRACE ("HRD Buttons: " << buttons_.join (", "));
- HRD_info << "Buttons: {" << buttons_.join (", ") << "}\n";
-
- dropdown_names_ = send_command ("get dropdowns").trimmed ().split (',', SkipEmptyParts);
- CAT_TRACE ("Dropdowns:");
- HRD_info << "Dropdowns:\n";
- Q_FOREACH (auto const& dd, dropdown_names_)
- {
- auto selections = send_command ("get dropdown-list {" + dd + "}").trimmed ().split (',');
- CAT_TRACE ("\t" << dd << ": {" << selections.join (", ") << "}");
- HRD_info << "\t" << dd << ": {" << selections.join (", ") << "}\n";
- dropdowns_[dd] = selections;
- }
-
- slider_names_ = send_command ("get sliders").trimmed ().split (',', SkipEmptyParts).replaceInStrings (" ", "~");
- CAT_TRACE ("Sliders:-");
- HRD_info << "Sliders:\n";
- Q_FOREACH (auto const& s, slider_names_)
- {
- auto range = send_command ("get slider-range " + current_radio_name + " " + s).trimmed ().split (',', SkipEmptyParts);
- CAT_TRACE ("\t" << s << ": {" << range.join (", ") << "}");
- HRD_info << "\t" << s << ": {" << range.join (", ") << "}\n";
- sliders_[s] = range;
- }
-
- // set RX VFO
- rx_A_button_ = find_button (QRegExp ("^(RX~A)$"));
- rx_B_button_ = find_button (QRegExp ("^(RX~B)$"));
-
- // select VFO (sometime set as well)
- vfo_A_button_ = find_button (QRegExp ("^(VFO~A|Main)$"));
- vfo_B_button_ = find_button (QRegExp ("^(VFO~B|Sub)$"));
-
- vfo_toggle_button_ = find_button (QRegExp ("^(A~/~B|VFO~A/B)$"));
-
- split_mode_button_ = find_button (QRegExp ("^(Spl~On|Spl_On|Split|Split~On)$"));
- split_off_button_ = find_button (QRegExp ("^(Spl~Off|Spl_Off|Split~Off)$"));
-
- if ((split_mode_dropdown_ = find_dropdown (QRegExp ("^(Split)$"))) >= 0)
- {
- split_mode_dropdown_selection_on_ = find_dropdown_selection (split_mode_dropdown_, QRegExp ("^(On)$"));
- split_mode_dropdown_selection_off_ = find_dropdown_selection (split_mode_dropdown_, QRegExp ("^(Off)$"));
- }
- else if ((receiver_dropdown_ = find_dropdown (QRegExp ("^Receiver$"))) >= 0)
- {
- rx_A_selection_ = find_dropdown_selection (receiver_dropdown_, QRegExp ("^(RX / Off)$"));
- rx_B_selection_ = find_dropdown_selection (receiver_dropdown_, QRegExp ("^(Mute / RX)$"));
- }
-
- tx_A_button_ = find_button (QRegExp ("^(TX~main|TX~-~A|TX~A)$"));
- tx_B_button_ = find_button (QRegExp ("^(TX~sub|TX~-~B|TX~B)$"));
-
- if ((mode_A_dropdown_ = find_dropdown (QRegExp ("^(Main Mode|Mode|Mode A)$"))) >= 0)
- {
- map_modes (mode_A_dropdown_, &mode_A_map_);
- }
- else
- {
- Q_ASSERT (mode_A_dropdown_ <= 0);
- }
-
- if ((mode_B_dropdown_ = find_dropdown (QRegExp ("^(Sub Mode|Mode B)$"))) >= 0)
- {
- map_modes (mode_B_dropdown_, &mode_B_map_);
- }
-
- // Can't do this with ^Data$ as the button name because some Kenwood
- // rigs have a "Data" button which is for turning the DSP on and off
- // so we must filter by rig name as well
- if (current_radio_name.startsWith ("IC")) // works with Icom transceivers
- {
- data_mode_toggle_button_ = find_button (QRegExp ("^(Data)$"));
- }
-
- data_mode_on_button_ = find_button (QRegExp ("^(DATA-ON\\(mid\\))$"));
- data_mode_off_button_ = find_button (QRegExp ("^(DATA-OFF)$"));
-
- // Some newer Icoms have a Data drop down with (Off,On,D1,D2,D3)
- // Some newer Icoms have a Data drop down with (Off,D1,D2,D3)
- // Some newer Icoms (IC-7300) have a Data drop down with
- // (Off,,D1-FIL1,D1-FIL2,D1-FIL3) the missing value counts as an
- // index value - I think it is a drop down separator line - this
- // appears to be an HRD defect and we cannot work around it
- if ((data_mode_dropdown_ = find_dropdown (QRegExp ("^(Data)$"))) >= 0)
- {
- data_mode_dropdown_selection_on_ = find_dropdown_selection (data_mode_dropdown_, QRegExp ("^(On|Data1|D1|D1-FIL1)$"));
- data_mode_dropdown_selection_off_ = find_dropdown_selection (data_mode_dropdown_, QRegExp ("^(Off)$"));
- }
-
- ptt_button_ = find_button (QRegExp ("^(TX)$"));
- alt_ptt_button_ = find_button (QRegExp ("^(TX~Alt|TX~Data)$"));
-
- if (vfo_count_ == 1 && ((vfo_B_button_ >= 0 && vfo_A_button_ >= 0) || vfo_toggle_button_ >= 0))
- {
- // put the rig into a known state for tricky cases like Icoms
-
- auto f = send_command ("get frequency").toUInt ();
- auto m = get_data_mode (lookup_mode (get_dropdown (mode_A_dropdown_), mode_A_map_));
- set_button (vfo_B_button_ >= 0 ? vfo_B_button_ : vfo_toggle_button_);
- auto fo = send_command ("get frequency").toUInt ();
- update_other_frequency (fo);
- auto mo = get_data_mode (lookup_mode (get_dropdown (mode_A_dropdown_), mode_A_map_));
- set_button (vfo_A_button_ >= 0 ? vfo_A_button_ : vfo_toggle_button_);
- if (f != fo || m != mo)
- {
- // we must have started with A/MAIN
- update_rx_frequency (f);
- update_mode (m);
- }
- else
- {
- update_rx_frequency (send_command ("get frequency").toUInt ());
- update_mode (get_data_mode (lookup_mode (get_dropdown (mode_A_dropdown_), mode_A_map_)));
- }
- }
-
- int resolution {0};
- auto f = send_command ("get frequency").toUInt ();
- if (f && !(f % 10))
- {
- auto test_frequency = f - f % 100 + 55;
- send_simple_command ("set frequency-hz " + QString::number (test_frequency));
- auto new_frequency = send_command ("get frequency").toUInt ();
- switch (static_cast<Radio::FrequencyDelta> (new_frequency - test_frequency))
- {
- case -5: resolution = -1; break; // 10Hz truncated
- case 5: resolution = 1; break; // 10Hz rounded
- case -15: resolution = -2; break; // 20Hz truncated
- case -55: resolution = -2; break; // 100Hz truncated
- case 45: resolution = 2; break; // 100Hz rounded
- }
- if (1 == resolution) // may be 20Hz rounded
- {
- test_frequency = f - f % 100 + 51;
- send_simple_command ("set frequency-hz " + QString::number (test_frequency));
- new_frequency = send_command ("get frequency").toUInt ();
- if (9 == static_cast<Radio::FrequencyDelta> (new_frequency - test_frequency))
- {
- resolution = 2; // 20Hz rounded
- }
- }
- send_simple_command ("set frequency-hz " + QString::number (f));
- }
- return resolution;
-}
-
-void HRDTransceiver::do_stop ()
-{
- if (hrd_)
- {
- hrd_->close ();
- }
-
- if (wrapped_) wrapped_->stop ();
- CAT_TRACE ("stopped" << state () << "reversed" << reversed_);
-}
-
-int HRDTransceiver::find_button (QRegExp const& re) const
-{
- return buttons_.indexOf (re);
-}
-
-int HRDTransceiver::find_dropdown (QRegExp const& re) const
-{
- return dropdown_names_.indexOf (re);
-}
-
-std::vector<int> HRDTransceiver::find_dropdown_selection (int dropdown, QRegExp const& re) const
-{
- std::vector<int> indices; // this will always contain at least a
- // -1
- auto list = dropdowns_.value (dropdown_names_.value (dropdown));
- int index {0};
- while (-1 != (index = list.lastIndexOf (re, index - 1)))
- {
- // search backwards because more specialized modes tend to be
- // later in list
- indices.push_back (index);
- if (!index)
- {
- break;
- }
- }
- return indices;
-}
-
-void HRDTransceiver::map_modes (int dropdown, ModeMap *map)
-{
- // order matters here (both in the map and in the regexps)
- map->push_back (std::forward_as_tuple (CW, find_dropdown_selection (dropdown, QRegExp ("^(CW|CW\\(N\\)|CW-LSB|CWL)$"))));
- map->push_back (std::forward_as_tuple (CW_R, find_dropdown_selection (dropdown, QRegExp ("^(CW-R|CW-R\\(N\\)|CW|CW-USB|CWU)$"))));
- map->push_back (std::forward_as_tuple (LSB, find_dropdown_selection (dropdown, QRegExp ("^(LSB\\(N\\)|LSB)$"))));
- map->push_back (std::forward_as_tuple (USB, find_dropdown_selection (dropdown, QRegExp ("^(USB\\(N\\)|USB)$"))));
- map->push_back (std::forward_as_tuple (DIG_U, find_dropdown_selection (dropdown, QRegExp ("^(DIG|DIGU|DATA-U|PKT-U|DATA|AFSK|USER-U|USB)$"))));
- map->push_back (std::forward_as_tuple (DIG_L, find_dropdown_selection (dropdown, QRegExp ("^(DIG|DIGL|DATA-L|PKT-L|DATA-R|USER-L|LSB)$"))));
- map->push_back (std::forward_as_tuple (FSK, find_dropdown_selection (dropdown, QRegExp ("^(DIG|FSK|RTTY|RTTY-LSB)$"))));
- map->push_back (std::forward_as_tuple (FSK_R, find_dropdown_selection (dropdown, QRegExp ("^(DIG|FSK-R|RTTY-R|RTTY|RTTY-USB)$"))));
- map->push_back (std::forward_as_tuple (AM, find_dropdown_selection (dropdown, QRegExp ("^(AM|DSB|SAM|DRM)$"))));
- map->push_back (std::forward_as_tuple (FM, find_dropdown_selection (dropdown, QRegExp ("^(FM|FM\\(N\\)|FM-N|WFM)$"))));
- map->push_back (std::forward_as_tuple (DIG_FM, find_dropdown_selection (dropdown, QRegExp ("^(PKT-FM|PKT|DATA\\(FM\\)|FM)$"))));
-
- CAT_TRACE ("for dropdown" << dropdown_names_[dropdown]);
- std::for_each (map->begin (), map->end (), [this, dropdown] (ModeMap::value_type const& item)
- {
- auto const& rhs = std::get<1> (item);
- CAT_TRACE ('\t' << std::get<0> (item) << "<->" << (rhs.size () ? dropdowns_[dropdown_names_[dropdown]][rhs.front ()] : "None"));
- });
-}
-
-int HRDTransceiver::lookup_mode (MODE mode, ModeMap const& map) const
-{
- auto it = std::find_if (map.begin (), map.end (), [mode] (ModeMap::value_type const& item) {return std::get<0> (item) == mode;});
- if (map.end () == it)
- {
- throw error {tr ("Ham Radio Deluxe: rig doesn't support mode")};
- }
- return std::get<1> (*it).front ();
-}
-
-auto HRDTransceiver::lookup_mode (int mode, ModeMap const& map) const -> MODE
-{
- if (mode < 0)
- {
- return UNK; // no mode dropdown
- }
-
- auto it = std::find_if (map.begin (), map.end (), [mode] (ModeMap::value_type const& item)
- {
- auto const& indices = std::get<1> (item);
- return indices.cend () != std::find (indices.cbegin (), indices.cend (), mode);
- });
- if (map.end () == it)
- {
- throw error {tr ("Ham Radio Deluxe: sent an unrecognised mode")};
- }
- return std::get<0> (*it);
-}
-
-int HRDTransceiver::get_dropdown (int dd)
-{
- if (dd < 0)
- {
- return -1; // no dropdown to interrogate
- }
-
- auto dd_name = dropdown_names_.value (dd);
- auto reply = send_command ("get dropdown-text {" + dd_name + "}");
- auto colon_index = reply.indexOf (':');
-
- if (colon_index < 0)
- {
- return -1;
- }
-
- Q_ASSERT (reply.left (colon_index).trimmed () == dd_name);
- return dropdowns_.value (dropdown_names_.value (dd)).indexOf (reply.mid (colon_index + 1).trimmed ());
-}
-
-void HRDTransceiver::set_dropdown (int dd, int value)
-{
- auto dd_name = dropdown_names_.value (dd);
- if (value >= 0)
- {
- send_simple_command ("set dropdown " + dd_name.replace (' ', '~') + ' ' + dropdowns_.value (dd_name).value (value).replace (' ', '~') + ' ' + QString::number (value));
- }
- else
- {
- CAT_ERROR ("item" << value << "not found in" << dd_name);
- throw error {tr ("Ham Radio Deluxe: item not found in %1 dropdown list").arg (dd_name)};
- }
-}
-
-void HRDTransceiver::do_ptt (bool on)
-{
- CAT_TRACE (on);
- if (use_for_ptt_)
- {
- if (alt_ptt_button_ >= 0 && TransceiverFactory::TX_audio_source_rear == audio_source_)
- {
- set_button (alt_ptt_button_, on);
- }
- else if (ptt_button_ >= 0)
- {
- set_button (ptt_button_, on);
- }
- // else
- // allow for pathological HRD rig interfaces that don't do
- // PTT by simply not even trying
- }
- else
- {
- Q_ASSERT (wrapped_);
- TransceiverState new_state {wrapped_->state ()};
- new_state.ptt (on);
- wrapped_->set (new_state, 0);
- }
- update_PTT (on);
-}
-
-void HRDTransceiver::set_button (int button_index, bool checked)
-{
- if (button_index >= 0)
- {
- send_simple_command ("set button-select " + buttons_.value (button_index) + (checked ? " 1" : " 0"));
- if (button_index == rx_A_button_ || button_index == rx_B_button_)
- {
- QThread::msleep (yaesu_delay);
- }
- }
- else
- {
- CAT_ERROR ("invalid button");
- throw error {tr ("Ham Radio Deluxe: button not available")};
- }
-}
-
-void HRDTransceiver::set_data_mode (MODE m)
-{
- if (data_mode_toggle_button_ >= 0)
- {
- switch (m)
- {
- case DIG_U:
- case DIG_L:
- case DIG_FM:
- set_button (data_mode_toggle_button_, true);
- break;
- default:
- set_button (data_mode_toggle_button_, false);
- break;
- }
- }
- else if (data_mode_on_button_ >= 0 && data_mode_off_button_ >= 0)
- {
- switch (m)
- {
- case DIG_U:
- case DIG_L:
- case DIG_FM:
- set_button (data_mode_on_button_, true);
- break;
- default:
- set_button (data_mode_off_button_, true);
- break;
- }
- }
- else if (data_mode_dropdown_ >= 0
- && data_mode_dropdown_selection_off_.size ()
- && data_mode_dropdown_selection_on_.size ())
- {
- switch (m)
- {
- case DIG_U:
- case DIG_L:
- case DIG_FM:
- set_dropdown (data_mode_dropdown_, data_mode_dropdown_selection_on_.front ());
- break;
- default:
- set_dropdown (data_mode_dropdown_, data_mode_dropdown_selection_off_.front ());
- break;
- }
- }
-}
-
-auto HRDTransceiver::get_data_mode (MODE m) -> MODE
-{
- if (data_mode_dropdown_ >= 0
- && data_mode_dropdown_selection_off_.size ())
- {
- auto selection = get_dropdown (data_mode_dropdown_);
- // can't check for on here as there may be multiple on values so
- // we must rely on the initial parse finding valid on values
- if (selection >= 0 && selection != data_mode_dropdown_selection_off_.front ())
- {
- switch (m)
- {
- case USB: m = DIG_U; break;
- case LSB: m = DIG_L; break;
- case FM: m = DIG_FM; break;
- default: break;
- }
- }
- }
- return m;
-}
-
-void HRDTransceiver::do_frequency (Frequency f, MODE m, bool /*no_ignore*/)
-{
- CAT_TRACE (f << "reversed" << reversed_);
- if (UNK != m)
- {
- do_mode (m);
- }
- auto fo_string = QString::number (f);
- if (vfo_count_ > 1 && reversed_)
- {
- auto frequencies = send_command ("get frequencies").trimmed ().split ('-', SkipEmptyParts);
- send_simple_command ("set frequencies-hz " + QString::number (frequencies[0].toUInt ()) + ' ' + fo_string);
- }
- else
- {
- send_simple_command ("set frequency-hz " + QString::number (f));
- }
- update_rx_frequency (f);
-}
-
-void HRDTransceiver::do_tx_frequency (Frequency tx, MODE mode, bool /*no_ignore*/)
-{
- CAT_TRACE (tx << "reversed" << reversed_);
-
- // re-check if reversed VFOs
- bool rx_A {true};
- bool rx_B {false};
- if (receiver_dropdown_ >= 0 && rx_A_selection_.size ())
- {
- auto selection = get_dropdown (receiver_dropdown_);
- rx_A = selection == rx_A_selection_.front ();
- if (!rx_A && rx_B_selection_.size ())
- {
- rx_B = selection == rx_B_selection_.front ();
- }
- }
- else if (vfo_B_button_ >= 0 || rx_B_button_ >= 0)
- {
- rx_A = is_button_checked (rx_A_button_ >= 0 ? rx_A_button_ : vfo_A_button_);
- if (!rx_A)
- {
- rx_B = is_button_checked (rx_B_button_ >= 0 ? rx_B_button_ : vfo_B_button_);
- }
- }
- reversed_ = rx_B;
-
- bool split {tx != 0};
- if (split)
- {
- if (mode != UNK)
- {
- if (!reversed_ && mode_B_dropdown_ >= 0)
- {
- set_dropdown (mode_B_dropdown_, lookup_mode (mode, mode_B_map_));
- }
- else if (reversed_ && mode_B_dropdown_ >= 0)
- {
- set_dropdown (mode_A_dropdown_, lookup_mode (mode, mode_A_map_));
- }
- else
- {
- Q_ASSERT (mode_A_dropdown_ >= 0 && ((vfo_A_button_ >=0 && vfo_B_button_ >=0) || vfo_toggle_button_ >= 0));
-
- if (rx_B_button_ >= 0)
- {
- set_button (reversed_ ? rx_A_button_ : rx_B_button_);
- set_dropdown (mode_A_dropdown_, lookup_mode (mode, mode_A_map_));
- set_data_mode (mode);
- set_button (reversed_ ? rx_B_button_ : rx_A_button_);
- }
- else if (receiver_dropdown_ >= 0
- && rx_A_selection_.size () && rx_B_selection_.size ())
- {
- set_dropdown (receiver_dropdown_, (reversed_ ? rx_A_selection_ : rx_B_selection_).front ());
- set_dropdown (mode_A_dropdown_, lookup_mode (mode, mode_A_map_));
- set_data_mode (mode);
- set_dropdown (receiver_dropdown_, (reversed_ ? rx_B_selection_ : rx_A_selection_).front ());
- }
- else if (vfo_count_ > 1 && ((vfo_A_button_ >=0 && vfo_B_button_ >=0) || vfo_toggle_button_ >= 0))
- {
- set_button (vfo_A_button_ >= 0 ? (reversed_ ? vfo_A_button_ : vfo_B_button_) : vfo_toggle_button_);
- set_dropdown (mode_A_dropdown_, lookup_mode (mode, mode_A_map_));
- set_data_mode (mode);
- set_button (vfo_A_button_ >= 0 ? (reversed_ ? vfo_B_button_ : vfo_A_button_) : vfo_toggle_button_);
- }
- // else Tx VFO mode gets set with frequency below or we
- // don't have a way of setting it so we assume it is
- // always the same as the Rx VFO mode
- }
- }
-
- auto fo_string = QString::number (tx);
- if (reversed_)
- {
- Q_ASSERT (vfo_count_ > 1);
-
- auto frequencies = send_command ("get frequencies").trimmed ().split ('-', SkipEmptyParts);
- send_simple_command ("set frequencies-hz " + fo_string + ' ' + QString::number (frequencies[1].toUInt ()));
- }
- else
- {
- if (vfo_count_ > 1)
- {
- auto frequencies = send_command ("get frequencies").trimmed ().split ('-', SkipEmptyParts);
- send_simple_command ("set frequencies-hz " + QString::number (frequencies[0].toUInt ()) + ' ' + fo_string);
- }
- else if ((vfo_B_button_ >= 0 && vfo_A_button_ >= 0) || vfo_toggle_button_ >= 0)
- {
- // we rationalise the modes here as well as the frequencies
- set_button (vfo_B_button_ >= 0 ? vfo_B_button_ : vfo_toggle_button_);
- send_simple_command ("set frequency-hz " + fo_string);
- if (mode != UNK && mode_B_dropdown_ < 0)
- {
- // do this here rather than later so we only
- // toggle/switch VFOs once
- set_dropdown (mode_A_dropdown_, lookup_mode (mode, mode_A_map_));
- set_data_mode (mode);
- }
- set_button (vfo_A_button_ >= 0 ? vfo_A_button_ : vfo_toggle_button_);
- }
- }
- }
- update_other_frequency (tx);
-
- if (split_mode_button_ >= 0)
- {
- if (split_off_button_ >= 0 && !split)
- {
- set_button (split_off_button_);
- }
- else
- {
- set_button (split_mode_button_, split);
- }
- }
- else if (split_mode_dropdown_ >= 0
- && split_mode_dropdown_selection_off_.size ()
- && split_mode_dropdown_selection_on_.size ())
- {
- set_dropdown (split_mode_dropdown_, split ? split_mode_dropdown_selection_on_.front () : split_mode_dropdown_selection_off_.front ());
- }
- else if (vfo_A_button_ >= 0 && vfo_B_button_ >= 0 && tx_A_button_ >= 0 && tx_B_button_ >= 0)
- {
- if (split)
- {
- if (reversed_ != is_button_checked (tx_A_button_))
- {
- if (rx_A_button_ >= 0 && rx_B_button_ >= 0)
- {
- set_button (reversed_ ? rx_B_button_ : rx_A_button_);
- }
- else if (receiver_dropdown_ >= 0
- && rx_A_selection_.size () && rx_B_selection_.size ())
- {
- set_dropdown (receiver_dropdown_, (reversed_ ? rx_B_selection_ : rx_A_selection_).front ());
- }
- else
- {
- set_button (reversed_ ? vfo_B_button_ : vfo_A_button_);
- }
- set_button (reversed_ ? tx_A_button_ : tx_B_button_);
- }
- }
- else
- {
- if (reversed_ != is_button_checked (tx_B_button_))
- {
- if (rx_A_button_ >= 0 && rx_B_button_ >= 0)
- {
- set_button (reversed_ ? rx_B_button_ : rx_A_button_);
- }
- else if (receiver_dropdown_ >= 0
- && rx_A_selection_.size () && rx_B_selection_.size ())
- {
- set_dropdown (receiver_dropdown_, (reversed_ ? rx_B_selection_ : rx_A_selection_).front ());
- }
- else
- {
- set_button (reversed_ ? vfo_B_button_ : vfo_A_button_);
- }
- set_button (reversed_ ? tx_B_button_ : tx_A_button_);
- }
- }
- }
- update_split (split);
-}
-
-void HRDTransceiver::do_mode (MODE mode)
-{
- CAT_TRACE (mode);
- if (reversed_ && mode_B_dropdown_ >= 0)
- {
- set_dropdown (mode_B_dropdown_, lookup_mode (mode, mode_B_map_));
- }
- else
- {
- set_dropdown (mode_A_dropdown_, lookup_mode (mode, mode_A_map_));
- }
- if (mode != UNK && state ().split ()) // rationalise mode if split
- {
- if (reversed_)
- {
- if (mode_B_dropdown_ >= 0)
- {
- set_dropdown (mode_A_dropdown_, lookup_mode (mode, mode_A_map_));
- }
- else
- {
- Q_ASSERT ((vfo_B_button_ >= 0 && vfo_A_button_ >= 0) || vfo_toggle_button_ >= 0);
-
- if (rx_B_button_ >= 0)
- {
- set_button (rx_A_button_);
- set_dropdown (mode_A_dropdown_, lookup_mode (mode, mode_A_map_));
- set_button (rx_B_button_);
- }
- else if (receiver_dropdown_ >= 0
- && rx_A_selection_.size () && rx_B_selection_.size ())
- {
- set_dropdown (receiver_dropdown_, rx_A_selection_.front ());
- set_dropdown (mode_A_dropdown_, lookup_mode (mode, mode_A_map_));
- set_dropdown (receiver_dropdown_, rx_B_selection_.front ());
- }
- else if (vfo_count_ > 1 && ((vfo_A_button_ >=0 && vfo_B_button_ >=0) || vfo_toggle_button_ >= 0))
- {
- set_button (vfo_A_button_ >= 0 ? vfo_A_button_ : vfo_toggle_button_);
- set_dropdown (mode_A_dropdown_, lookup_mode (mode, mode_A_map_));
- set_button (vfo_B_button_ >= 0 ? vfo_B_button_ : vfo_toggle_button_);
- }
- // else Tx VFO mode gets set when Tx VFO frequency is
- // set
-
- if ( tx_A_button_ >= 0)
- {
- set_button (tx_A_button_);
- }
- }
- }
- else
- {
- if (mode_B_dropdown_ >= 0)
- {
- set_dropdown (mode_B_dropdown_, lookup_mode (mode, mode_B_map_));
- }
- else
- {
- Q_ASSERT ((vfo_B_button_ >= 0 && vfo_A_button_ >= 0) || vfo_toggle_button_ >= 0);
-
- if (rx_B_button_ >= 0)
- {
- set_button (rx_B_button_);
- set_dropdown (mode_A_dropdown_, lookup_mode (mode, mode_A_map_));
- set_button (rx_A_button_);
- }
- else if (receiver_dropdown_ >= 0
- && rx_A_selection_.size () && rx_B_selection_.size ())
- {
- set_dropdown (receiver_dropdown_, rx_B_selection_.front ());
- set_dropdown (mode_A_dropdown_, lookup_mode (mode, mode_A_map_));
- set_dropdown (receiver_dropdown_, rx_A_selection_.front ());
- }
- else if (vfo_count_ > 1 && ((vfo_A_button_ >=0 && vfo_B_button_ >=0) || vfo_toggle_button_ >= 0))
- {
- set_button (vfo_B_button_ >= 0 ? vfo_B_button_ : vfo_toggle_button_);
- set_dropdown (mode_A_dropdown_, lookup_mode (mode, mode_A_map_));
- set_button (vfo_A_button_ >= 0 ? vfo_A_button_ : vfo_toggle_button_);
- }
- // else Tx VFO mode gets set when Tx VFO frequency is
- // set
-
- if ( tx_B_button_ >= 0)
- {
- set_button (tx_B_button_);
- }
- }
- }
- }
- set_data_mode (mode);
- update_mode (mode);
-}
-
-bool HRDTransceiver::is_button_checked (int button_index)
-{
- if (button_index < 0)
- {
- return false;
- }
-
- auto reply = send_command ("get button-select " + buttons_.value (button_index));
- if ("1" != reply && "0" != reply)
- {
- CAT_ERROR ("bad response");
- throw error {tr ("Ham Radio Deluxe didn't respond as expected")};
- }
- return "1" == reply;
-}
-
-void HRDTransceiver::do_poll ()
-{
- CAT_TRACE ("+++++++ poll dump +++++++");
- CAT_TRACE ("reversed:" << reversed_);
- is_button_checked (vfo_A_button_);
- is_button_checked (vfo_B_button_);
- is_button_checked (vfo_toggle_button_);
- is_button_checked (split_mode_button_);
- is_button_checked (split_off_button_);
- is_button_checked (rx_A_button_);
- is_button_checked (rx_B_button_);
- get_dropdown (receiver_dropdown_);
- is_button_checked (tx_A_button_);
- is_button_checked (tx_B_button_);
- is_button_checked (ptt_button_);
- is_button_checked (alt_ptt_button_);
- get_dropdown (mode_A_dropdown_);
- get_dropdown (mode_B_dropdown_);
- is_button_checked (data_mode_toggle_button_);
- is_button_checked (data_mode_on_button_);
- is_button_checked (data_mode_off_button_);
- if (data_mode_dropdown_ >=0
- && data_mode_dropdown_selection_off_.size ()
- && data_mode_dropdown_selection_on_.size ())
- {
- get_dropdown (data_mode_dropdown_);
- }
- if (!split_mode_dropdown_write_only_)
- {
- get_dropdown (split_mode_dropdown_);
- }
- CAT_TRACE ("------- poll dump -------");
-
- if (split_off_button_ >= 0)
- {
- // we are probably dealing with an Icom and have to guess SPLIT mode :(
- }
- else if (split_mode_button_ >= 0 && !(tx_A_button_ >= 0 && tx_B_button_ >= 0))
- {
- update_split (is_button_checked (split_mode_button_));
- }
- else if (split_mode_dropdown_ >= 0)
- {
- if (!split_mode_dropdown_write_only_)
- {
- auto selection = get_dropdown (split_mode_dropdown_);
- if (selection >= 0
- && split_mode_dropdown_selection_off_.size ())
- {
- update_split (selection == split_mode_dropdown_selection_on_.front ());
- }
- else
- {
- // leave split alone as we can't query it - it should be
- // correct so long as rig or HRD haven't been changed
- split_mode_dropdown_write_only_ = true;
- }
- }
- }
- else if (vfo_A_button_ >= 0 && vfo_B_button_ >= 0 && tx_A_button_ >= 0 && tx_B_button_ >= 0)
- {
- bool rx_A {true}; // no Rx taken as not reversed
- bool rx_B {false};
-
- auto tx_A = is_button_checked (tx_A_button_);
-
- // some rigs have dual Rx, we take VFO A/MAIN receiving as
- // normal and only say reversed when only VFO B/SUB is active
- // i.e. VFO A/MAIN muted VFO B/SUB active
- if (receiver_dropdown_ >= 0 && rx_A_selection_.size ())
- {
- auto selection = get_dropdown (receiver_dropdown_);
- rx_A = selection == rx_A_selection_.front ();
- if (!rx_A && rx_B_selection_.size ())
- {
- rx_B = selection == rx_B_selection_.front ();
- }
- }
- else if (vfo_B_button_ >= 0 || rx_B_button_ >= 0)
- {
- rx_A = is_button_checked (rx_A_button_ >= 0 ? rx_A_button_ : vfo_A_button_);
- if (!rx_A)
- {
- rx_B = is_button_checked (rx_B_button_ >= 0 ? rx_B_button_ : vfo_B_button_);
- }
- }
-
- update_split (rx_B == tx_A);
- reversed_ = rx_B;
- }
-
- if (vfo_count_ > 1)
- {
- auto frequencies = send_command ("get frequencies").trimmed ().split ('-', SkipEmptyParts);
- update_rx_frequency (frequencies[reversed_ ? 1 : 0].toUInt ());
- update_other_frequency (frequencies[reversed_ ? 0 : 1].toUInt ());
- }
- else
- {
- // read frequency is unreliable on single VFO addressing rigs
- // while transmitting
- if (!state ().ptt ())
- {
- update_rx_frequency (send_command ("get frequency").toUInt ());
- }
- }
-
- // read mode is unreliable on single VFO addressing rigs while
- // transmitting
- if (vfo_count_ > 1 || !state ().ptt ())
- {
- update_mode (get_data_mode (lookup_mode (get_dropdown (mode_A_dropdown_), mode_A_map_)));
- }
-}
-
-QString HRDTransceiver::send_command (QString const& cmd, bool prepend_context, bool recurse)
-{
- if (!hrd_) return QString {};
-
- QString result;
-
- if (current_radio_ && prepend_context && vfo_count_ < 2)
- {
- // required on some radios because commands don't get executed
- // correctly otherwise (ICOM for example)
- QThread::msleep (50);
- }
-
- if (!recurse && prepend_context)
- {
- auto radio_name = send_command ("get radio", current_radio_, true);
- qDebug () << "HRDTransceiver::send_command: radio_name:" << radio_name;
- auto radio_iter = std::find_if (radios_.begin (), radios_.end (), [&radio_name] (RadioMap::value_type const& radio)
- {
- return std::get<1> (radio) == radio_name;
- });
- if (radio_iter == radios_.end ())
- {
- CAT_TRACE ("rig disappeared or changed");
- throw error {tr ("Ham Radio Deluxe: rig has disappeared or changed")};
- }
-
- if (0u == current_radio_ || std::get<0> (*radio_iter) != current_radio_)
- {
- current_radio_ = std::get<0> (*radio_iter);
- }
- }
-
- auto context = '[' + QString::number (current_radio_) + "] ";
-
- if (QTcpSocket::ConnectedState != hrd_->state ())
- {
- CAT_ERROR (cmd << "failed" << hrd_->errorString ());
- throw error {
- tr ("Ham Radio Deluxe send command \"%1\" failed %2\n")
- .arg (cmd)
- .arg (hrd_->errorString ())
- };
- }
-
- if (v4 == protocol_)
- {
- auto message = ((prepend_context ? context + cmd : cmd) + "\r").toLocal8Bit ();
- if (!write_to_port (message.constData (), message.size ()))
- {
- CAT_ERROR ("failed to write command" << cmd << "to HRD");
- throw error {
- tr ("Ham Radio Deluxe: failed to write command \"%1\"")
- .arg (cmd)
- };
- }
- }
- else
- {
- auto string = prepend_context ? context + cmd : cmd;
- QScopedPointer<HRDMessage> message {new (string) HRDMessage};
- if (!write_to_port (reinterpret_cast<char const *> (message.data ()), message->size_))
- {
- CAT_ERROR ("failed to write command" << cmd << "to HRD");
- throw error {
- tr ("Ham Radio Deluxe: failed to write command \"%1\"")
- .arg (cmd)
- };
- }
- }
- auto buffer = read_reply (cmd);
- if (v4 == protocol_)
- {
- result = QString {buffer}.trimmed ();
- }
- else
- {
- HRDMessage const * reply {new (buffer) HRDMessage};
- if (reply->magic_1_value_ != reply->magic_1_ && reply->magic_2_value_ != reply->magic_2_)
- {
- CAT_ERROR (cmd << "invalid reply");
- throw error {
- tr ("Ham Radio Deluxe sent an invalid reply to our command \"%1\"")
- .arg (cmd)
- };
- }
-
- // keep reading until expected size arrives
- while (buffer.size () - offsetof (HRDMessage, size_) < reply->size_)
- {
- CAT_TRACE (cmd << "reading more reply data");
- buffer += read_reply (cmd);
- reply = new (buffer) HRDMessage;
- }
-
- result = QString {reply->payload_}; // this is not a memory leak (honest!)
- }
- CAT_TRACE (cmd << " ->" << result);
- return result;
-}
-
-bool HRDTransceiver::write_to_port (char const * data, qint64 length)
-{
- qint64 total_bytes_sent {0};
- while (total_bytes_sent < length)
- {
- auto bytes_sent = hrd_->write (data + total_bytes_sent, length - total_bytes_sent);
- if (bytes_sent < 0 || !hrd_->waitForBytesWritten ())
- {
- return false;
- }
-
- total_bytes_sent += bytes_sent;
- }
- return true;
-}
-
-QByteArray HRDTransceiver::read_reply (QString const& cmd)
-{
- // waitForReadReady appears to be occasionally unreliable on Windows
- // timing out when data is waiting so retry a few times
- unsigned retries {30};
- bool replied {false};
- while (!replied && retries--)
- {
- replied = hrd_->waitForReadyRead ();
- if (!replied && hrd_->error () != hrd_->SocketTimeoutError)
- {
- CAT_ERROR (cmd << "failed to reply" << hrd_->errorString ());
- throw error {
- tr ("Ham Radio Deluxe failed to reply to command \"%1\" %2\n")
- .arg (cmd)
- .arg (hrd_->errorString ())
- };
- }
- }
- if (!replied)
- {
- CAT_ERROR (cmd << "retries exhausted");
- throw error {
- tr ("Ham Radio Deluxe retries exhausted sending command \"%1\"")
- .arg (cmd)
- };
- }
- return hrd_->readAll ();
-}
-
-void HRDTransceiver::send_simple_command (QString const& command)
-{
- if ("OK" != send_command (command))
- {
- CAT_ERROR (command << "unexpected response");
- throw error {
- tr ("Ham Radio Deluxe didn't respond to command \"%1\" as expected")
- .arg (command)
- };
- }
-}
+#include "HRDTransceiver.hpp" + +#include <algorithm> +#include <QHostAddress> +#include <QByteArray> +#include <QRegExp> +#include <QTcpSocket> +#include <QThread> +#include <QStandardPaths> +#include <QDir> + +#include "Network/NetworkServerLookup.hpp" +#include "qt_helpers.hpp" + +namespace +{ + char const * const HRD_transceiver_name = "Ham Radio Deluxe"; + + // some commands require a settling time, particularly "RX A" and + // "RX B" on the Yaesu FTdx3000. + int constexpr yaesu_delay {350}; +} + +#include "moc_HRDTransceiver.cpp" + +void HRDTransceiver::register_transceivers (logger_type *, + TransceiverFactory::Transceivers * registry, + unsigned id) +{ + (*registry)[HRD_transceiver_name] = TransceiverFactory::Capabilities (id, TransceiverFactory::Capabilities::network, true, true /* maybe */); +} + +struct HRDMessage +{ + // Placement style new overload for outgoing messages that does the + // construction too. + static void * operator new (size_t size, QString const& payload) + { + size += sizeof (QChar) * (payload.size () + 1); // space for terminator too + HRDMessage * storage (reinterpret_cast<HRDMessage *> (new char[size])); + storage->size_ = size ; + ushort const * pl (payload.utf16 ()); + std::copy (pl, pl + payload.size () + 1, storage->payload_); // copy terminator too + storage->magic_1_ = magic_1_value_; + storage->magic_2_ = magic_2_value_; + storage->checksum_ = 0; + return storage; + } + + // Placement style new overload for incoming messages that does the + // construction too. + // + // No memory allocation here. + static void * operator new (size_t /* size */, QByteArray const& message) + { + // Nasty const_cast here to avoid copying the message buffer. + return const_cast<HRDMessage *> (reinterpret_cast<HRDMessage const *> (message.data ())); + } + + void operator delete (void * p, size_t) + { + delete [] reinterpret_cast<char *> (p); // Mirror allocation in operator new above. + } + + quint32 size_; + qint32 magic_1_; + qint32 magic_2_; + qint32 checksum_; // Apparently not used. + QChar payload_[0]; // UTF-16 (which is wchar_t on Windows) + + static qint32 constexpr magic_1_value_ = 0x1234ABCD; + static qint32 constexpr magic_2_value_ = 0xABCD1234; +}; + +HRDTransceiver::HRDTransceiver (logger_type * logger + , std::unique_ptr<TransceiverBase> wrapped + , QString const& server + , bool use_for_ptt + , TransceiverFactory::TXAudioSource audio_source + , int poll_interval + , QObject * parent) + : PollingTransceiver {logger, poll_interval, parent} + , wrapped_ {std::move (wrapped)} + , use_for_ptt_ {use_for_ptt} + , audio_source_ {audio_source} + , server_ {server} + , hrd_ {0} + , protocol_ {none} + , current_radio_ {0} + , vfo_count_ {0} + , vfo_A_button_ {-1} + , vfo_B_button_ {-1} + , vfo_toggle_button_ {-1} + , mode_A_dropdown_ {-1} + , mode_B_dropdown_ {-1} + , data_mode_toggle_button_ {-1} + , data_mode_on_button_ {-1} + , data_mode_off_button_ {-1} + , data_mode_dropdown_ {-1} + , split_mode_button_ {-1} + , split_mode_dropdown_ {-1} + , split_mode_dropdown_write_only_ {false} + , split_off_button_ {-1} + , tx_A_button_ {-1} + , tx_B_button_ {-1} + , rx_A_button_ {-1} + , rx_B_button_ {-1} + , receiver_dropdown_ {-1} + , ptt_button_ {-1} + , alt_ptt_button_ {-1} + , reversed_ {false} +{ +} + +int HRDTransceiver::do_start () +{ + CAT_TRACE ("starting"); + if (wrapped_) wrapped_->start (0); + + auto server_details = network_server_lookup (server_, 7809u); + if (!hrd_) + { + hrd_ = new QTcpSocket {this}; // QObject takes ownership + } + hrd_->connectToHost (std::get<0> (server_details), std::get<1> (server_details)); + if (!hrd_->waitForConnected ()) + { + CAT_ERROR ("failed to connect:" << hrd_->errorString ()); + throw error {tr ("Failed to connect to Ham Radio Deluxe\n") + hrd_->errorString ()}; + } + + if (none == protocol_) + { + try + { + protocol_ = v5; // try this first (works for v6 too) + send_command ("get context", false, false); + } + catch (error const&) + { + protocol_ = none; + } + } + + if (none == protocol_) + { + hrd_->close (); + + protocol_ = v4; // try again with older protocol + hrd_->connectToHost (std::get<0> (server_details), std::get<1> (server_details)); + if (!hrd_->waitForConnected ()) + { + CAT_ERROR ("failed to connect:" << hrd_->errorString ()); + throw error {tr ("Failed to connect to Ham Radio Deluxe\n") + hrd_->errorString ()}; + } + + send_command ("get context", false, false); + } + + QFile HRD_info_file {QDir {QStandardPaths::writableLocation (QStandardPaths::DataLocation)}.absoluteFilePath ("HRD Interface Information.txt")}; + if (!HRD_info_file.open (QFile::WriteOnly | QFile::Text | QFile::Truncate)) + { + throw error {tr ("Failed to open file \"%1\": %2.").arg (HRD_info_file.fileName ()).arg (HRD_info_file.errorString ())}; + } + QTextStream HRD_info {&HRD_info_file}; + + auto id = send_command ("get id", false, false); + auto version = send_command ("get version", false, false); + + CAT_INFO ("Id: " << id << "Version: " << version); + HRD_info << "Id: " << id << "\n"; + HRD_info << "Version: " << version << "\n"; + + auto radios = send_command ("get radios", false, false).trimmed ().split (',', SkipEmptyParts); + if (radios.isEmpty ()) + { + CAT_ERROR ("no rig found"); + throw error {tr ("Ham Radio Deluxe: no rig found")}; + } + + HRD_info << "Radios:\n"; + Q_FOREACH (auto const& radio, radios) + { + HRD_info << "\t" << radio << "\n"; + auto entries = radio.trimmed ().split (':', SkipEmptyParts); + radios_.push_back (std::forward_as_tuple (entries[0].toUInt (), entries[1])); + } + + CAT_TRACE ("radios:-"); + Q_FOREACH (auto const& radio, radios_) + { + CAT_TRACE ("\t[" << std::get<0> (radio) << "] " << std::get<1> (radio)); + } + + auto current_radio_name = send_command ("get radio", false, false); + HRD_info << "Current radio: " << current_radio_name << "\n"; + if (current_radio_name.isEmpty ()) + { + CAT_ERROR ("no rig found"); + throw error {tr ("Ham Radio Deluxe: no rig found")}; + } + + vfo_count_ = send_command ("get vfo-count").toUInt (); + HRD_info << "VFO count: " << vfo_count_ << "\n"; + CAT_TRACE ("vfo count:" << vfo_count_); + + buttons_ = send_command ("get buttons").trimmed ().split (',', SkipEmptyParts).replaceInStrings (" ", "~"); + CAT_TRACE ("HRD Buttons: " << buttons_.join (", ")); + HRD_info << "Buttons: {" << buttons_.join (", ") << "}\n"; + + dropdown_names_ = send_command ("get dropdowns").trimmed ().split (',', SkipEmptyParts); + CAT_TRACE ("Dropdowns:"); + HRD_info << "Dropdowns:\n"; + Q_FOREACH (auto const& dd, dropdown_names_) + { + auto selections = send_command ("get dropdown-list {" + dd + "}").trimmed ().split (','); + CAT_TRACE ("\t" << dd << ": {" << selections.join (", ") << "}"); + HRD_info << "\t" << dd << ": {" << selections.join (", ") << "}\n"; + dropdowns_[dd] = selections; + } + + slider_names_ = send_command ("get sliders").trimmed ().split (',', SkipEmptyParts).replaceInStrings (" ", "~"); + CAT_TRACE ("Sliders:-"); + HRD_info << "Sliders:\n"; + Q_FOREACH (auto const& s, slider_names_) + { + auto range = send_command ("get slider-range " + current_radio_name + " " + s).trimmed ().split (',', SkipEmptyParts); + CAT_TRACE ("\t" << s << ": {" << range.join (", ") << "}"); + HRD_info << "\t" << s << ": {" << range.join (", ") << "}\n"; + sliders_[s] = range; + } + + // set RX VFO + rx_A_button_ = find_button (QRegExp ("^(RX~A)$")); + rx_B_button_ = find_button (QRegExp ("^(RX~B)$")); + + // select VFO (sometime set as well) + vfo_A_button_ = find_button (QRegExp ("^(VFO~A|Main)$")); + vfo_B_button_ = find_button (QRegExp ("^(VFO~B|Sub)$")); + + vfo_toggle_button_ = find_button (QRegExp ("^(A~/~B|VFO~A/B)$")); + + split_mode_button_ = find_button (QRegExp ("^(Spl~On|Spl_On|Split|Split~On)$")); + split_off_button_ = find_button (QRegExp ("^(Spl~Off|Spl_Off|Split~Off)$")); + + if ((split_mode_dropdown_ = find_dropdown (QRegExp ("^(Split)$"))) >= 0) + { + split_mode_dropdown_selection_on_ = find_dropdown_selection (split_mode_dropdown_, QRegExp ("^(On)$")); + split_mode_dropdown_selection_off_ = find_dropdown_selection (split_mode_dropdown_, QRegExp ("^(Off)$")); + } + else if ((receiver_dropdown_ = find_dropdown (QRegExp ("^Receiver$"))) >= 0) + { + rx_A_selection_ = find_dropdown_selection (receiver_dropdown_, QRegExp ("^(RX / Off)$")); + rx_B_selection_ = find_dropdown_selection (receiver_dropdown_, QRegExp ("^(Mute / RX)$")); + } + + tx_A_button_ = find_button (QRegExp ("^(TX~main|TX~-~A|TX~A)$")); + tx_B_button_ = find_button (QRegExp ("^(TX~sub|TX~-~B|TX~B)$")); + + if ((mode_A_dropdown_ = find_dropdown (QRegExp ("^(Main Mode|Mode|Mode A)$"))) >= 0) + { + map_modes (mode_A_dropdown_, &mode_A_map_); + } + else + { + Q_ASSERT (mode_A_dropdown_ <= 0); + } + + if ((mode_B_dropdown_ = find_dropdown (QRegExp ("^(Sub Mode|Mode B)$"))) >= 0) + { + map_modes (mode_B_dropdown_, &mode_B_map_); + } + + // Can't do this with ^Data$ as the button name because some Kenwood + // rigs have a "Data" button which is for turning the DSP on and off + // so we must filter by rig name as well + if (current_radio_name.startsWith ("IC")) // works with Icom transceivers + { + data_mode_toggle_button_ = find_button (QRegExp ("^(Data)$")); + } + + data_mode_on_button_ = find_button (QRegExp ("^(DATA-ON\\(mid\\))$")); + data_mode_off_button_ = find_button (QRegExp ("^(DATA-OFF)$")); + + // Some newer Icoms have a Data drop down with (Off,On,D1,D2,D3) + // Some newer Icoms have a Data drop down with (Off,D1,D2,D3) + // Some newer Icoms (IC-7300) have a Data drop down with + // (Off,,D1-FIL1,D1-FIL2,D1-FIL3) the missing value counts as an + // index value - I think it is a drop down separator line - this + // appears to be an HRD defect and we cannot work around it + if ((data_mode_dropdown_ = find_dropdown (QRegExp ("^(Data)$"))) >= 0) + { + data_mode_dropdown_selection_on_ = find_dropdown_selection (data_mode_dropdown_, QRegExp ("^(On|Data1|D1|D1-FIL1)$")); + data_mode_dropdown_selection_off_ = find_dropdown_selection (data_mode_dropdown_, QRegExp ("^(Off)$")); + } + + ptt_button_ = find_button (QRegExp ("^(TX)$")); + alt_ptt_button_ = find_button (QRegExp ("^(TX~Alt|TX~Data)$")); + + if (vfo_count_ == 1 && ((vfo_B_button_ >= 0 && vfo_A_button_ >= 0) || vfo_toggle_button_ >= 0)) + { + // put the rig into a known state for tricky cases like Icoms + + auto f = send_command ("get frequency").toUInt (); + auto m = get_data_mode (lookup_mode (get_dropdown (mode_A_dropdown_), mode_A_map_)); + set_button (vfo_B_button_ >= 0 ? vfo_B_button_ : vfo_toggle_button_); + auto fo = send_command ("get frequency").toUInt (); + update_other_frequency (fo); + auto mo = get_data_mode (lookup_mode (get_dropdown (mode_A_dropdown_), mode_A_map_)); + set_button (vfo_A_button_ >= 0 ? vfo_A_button_ : vfo_toggle_button_); + if (f != fo || m != mo) + { + // we must have started with A/MAIN + update_rx_frequency (f); + update_mode (m); + } + else + { + update_rx_frequency (send_command ("get frequency").toUInt ()); + update_mode (get_data_mode (lookup_mode (get_dropdown (mode_A_dropdown_), mode_A_map_))); + } + } + + int resolution {0}; + auto f = send_command ("get frequency").toUInt (); + if (f && !(f % 10)) + { + auto test_frequency = f - f % 100 + 55; + send_simple_command ("set frequency-hz " + QString::number (test_frequency)); + auto new_frequency = send_command ("get frequency").toUInt (); + switch (static_cast<Radio::FrequencyDelta> (new_frequency - test_frequency)) + { + case -5: resolution = -1; break; // 10Hz truncated + case 5: resolution = 1; break; // 10Hz rounded + case -15: resolution = -2; break; // 20Hz truncated + case -55: resolution = -2; break; // 100Hz truncated + case 45: resolution = 2; break; // 100Hz rounded + } + if (1 == resolution) // may be 20Hz rounded + { + test_frequency = f - f % 100 + 51; + send_simple_command ("set frequency-hz " + QString::number (test_frequency)); + new_frequency = send_command ("get frequency").toUInt (); + if (9 == static_cast<Radio::FrequencyDelta> (new_frequency - test_frequency)) + { + resolution = 2; // 20Hz rounded + } + } + send_simple_command ("set frequency-hz " + QString::number (f)); + } + return resolution; +} + +void HRDTransceiver::do_stop () +{ + if (hrd_) + { + hrd_->close (); + } + + if (wrapped_) wrapped_->stop (); + CAT_TRACE ("stopped" << state () << "reversed" << reversed_); +} + +int HRDTransceiver::find_button (QRegExp const& re) const +{ + return buttons_.indexOf (re); +} + +int HRDTransceiver::find_dropdown (QRegExp const& re) const +{ + return dropdown_names_.indexOf (re); +} + +std::vector<int> HRDTransceiver::find_dropdown_selection (int dropdown, QRegExp const& re) const +{ + std::vector<int> indices; // this will always contain at least a + // -1 + auto list = dropdowns_.value (dropdown_names_.value (dropdown)); + int index {0}; + while (-1 != (index = list.lastIndexOf (re, index - 1))) + { + // search backwards because more specialized modes tend to be + // later in list + indices.push_back (index); + if (!index) + { + break; + } + } + return indices; +} + +void HRDTransceiver::map_modes (int dropdown, ModeMap *map) +{ + // order matters here (both in the map and in the regexps) + map->push_back (std::forward_as_tuple (CW, find_dropdown_selection (dropdown, QRegExp ("^(CW|CW\\(N\\)|CW-LSB|CWL)$")))); + map->push_back (std::forward_as_tuple (CW_R, find_dropdown_selection (dropdown, QRegExp ("^(CW-R|CW-R\\(N\\)|CW|CW-USB|CWU)$")))); + map->push_back (std::forward_as_tuple (LSB, find_dropdown_selection (dropdown, QRegExp ("^(LSB\\(N\\)|LSB)$")))); + map->push_back (std::forward_as_tuple (USB, find_dropdown_selection (dropdown, QRegExp ("^(USB\\(N\\)|USB)$")))); + map->push_back (std::forward_as_tuple (DIG_U, find_dropdown_selection (dropdown, QRegExp ("^(DIG|DIGU|DATA-U|PKT-U|DATA|AFSK|USER-U|USB)$")))); + map->push_back (std::forward_as_tuple (DIG_L, find_dropdown_selection (dropdown, QRegExp ("^(DIG|DIGL|DATA-L|PKT-L|DATA-R|USER-L|LSB)$")))); + map->push_back (std::forward_as_tuple (FSK, find_dropdown_selection (dropdown, QRegExp ("^(DIG|FSK|RTTY|RTTY-LSB)$")))); + map->push_back (std::forward_as_tuple (FSK_R, find_dropdown_selection (dropdown, QRegExp ("^(DIG|FSK-R|RTTY-R|RTTY|RTTY-USB)$")))); + map->push_back (std::forward_as_tuple (AM, find_dropdown_selection (dropdown, QRegExp ("^(AM|DSB|SAM|DRM)$")))); + map->push_back (std::forward_as_tuple (FM, find_dropdown_selection (dropdown, QRegExp ("^(FM|FM\\(N\\)|FM-N|WFM)$")))); + map->push_back (std::forward_as_tuple (DIG_FM, find_dropdown_selection (dropdown, QRegExp ("^(PKT-FM|PKT|DATA\\(FM\\)|FM)$")))); + + CAT_TRACE ("for dropdown" << dropdown_names_[dropdown]); + std::for_each (map->begin (), map->end (), [this, dropdown] (ModeMap::value_type const& item) + { + auto const& rhs = std::get<1> (item); + CAT_TRACE ('\t' << std::get<0> (item) << "<->" << (rhs.size () ? dropdowns_[dropdown_names_[dropdown]][rhs.front ()] : "None")); + }); +} + +int HRDTransceiver::lookup_mode (MODE mode, ModeMap const& map) const +{ + auto it = std::find_if (map.begin (), map.end (), [mode] (ModeMap::value_type const& item) {return std::get<0> (item) == mode;}); + if (map.end () == it) + { + throw error {tr ("Ham Radio Deluxe: rig doesn't support mode")}; + } + return std::get<1> (*it).front (); +} + +auto HRDTransceiver::lookup_mode (int mode, ModeMap const& map) const -> MODE +{ + if (mode < 0) + { + return UNK; // no mode dropdown + } + + auto it = std::find_if (map.begin (), map.end (), [mode] (ModeMap::value_type const& item) + { + auto const& indices = std::get<1> (item); + return indices.cend () != std::find (indices.cbegin (), indices.cend (), mode); + }); + if (map.end () == it) + { + throw error {tr ("Ham Radio Deluxe: sent an unrecognised mode")}; + } + return std::get<0> (*it); +} + +int HRDTransceiver::get_dropdown (int dd) +{ + if (dd < 0) + { + return -1; // no dropdown to interrogate + } + + auto dd_name = dropdown_names_.value (dd); + auto reply = send_command ("get dropdown-text {" + dd_name + "}"); + auto colon_index = reply.indexOf (':'); + + if (colon_index < 0) + { + return -1; + } + + Q_ASSERT (reply.left (colon_index).trimmed () == dd_name); + return dropdowns_.value (dropdown_names_.value (dd)).indexOf (reply.mid (colon_index + 1).trimmed ()); +} + +void HRDTransceiver::set_dropdown (int dd, int value) +{ + auto dd_name = dropdown_names_.value (dd); + if (value >= 0) + { + send_simple_command ("set dropdown " + dd_name.replace (' ', '~') + ' ' + dropdowns_.value (dd_name).value (value).replace (' ', '~') + ' ' + QString::number (value)); + } + else + { + CAT_ERROR ("item" << value << "not found in" << dd_name); + throw error {tr ("Ham Radio Deluxe: item not found in %1 dropdown list").arg (dd_name)}; + } +} + +void HRDTransceiver::do_ptt (bool on) +{ + CAT_TRACE (on); + if (use_for_ptt_) + { + if (alt_ptt_button_ >= 0 && TransceiverFactory::TX_audio_source_rear == audio_source_) + { + set_button (alt_ptt_button_, on); + } + else if (ptt_button_ >= 0) + { + set_button (ptt_button_, on); + } + // else + // allow for pathological HRD rig interfaces that don't do + // PTT by simply not even trying + } + else + { + Q_ASSERT (wrapped_); + TransceiverState new_state {wrapped_->state ()}; + new_state.ptt (on); + wrapped_->set (new_state, 0); + } + update_PTT (on); +} + +void HRDTransceiver::set_button (int button_index, bool checked) +{ + if (button_index >= 0) + { + send_simple_command ("set button-select " + buttons_.value (button_index) + (checked ? " 1" : " 0")); + if (button_index == rx_A_button_ || button_index == rx_B_button_) + { + QThread::msleep (yaesu_delay); + } + } + else + { + CAT_ERROR ("invalid button"); + throw error {tr ("Ham Radio Deluxe: button not available")}; + } +} + +void HRDTransceiver::set_data_mode (MODE m) +{ + if (data_mode_toggle_button_ >= 0) + { + switch (m) + { + case DIG_U: + case DIG_L: + case DIG_FM: + set_button (data_mode_toggle_button_, true); + break; + default: + set_button (data_mode_toggle_button_, false); + break; + } + } + else if (data_mode_on_button_ >= 0 && data_mode_off_button_ >= 0) + { + switch (m) + { + case DIG_U: + case DIG_L: + case DIG_FM: + set_button (data_mode_on_button_, true); + break; + default: + set_button (data_mode_off_button_, true); + break; + } + } + else if (data_mode_dropdown_ >= 0 + && data_mode_dropdown_selection_off_.size () + && data_mode_dropdown_selection_on_.size ()) + { + switch (m) + { + case DIG_U: + case DIG_L: + case DIG_FM: + set_dropdown (data_mode_dropdown_, data_mode_dropdown_selection_on_.front ()); + break; + default: + set_dropdown (data_mode_dropdown_, data_mode_dropdown_selection_off_.front ()); + break; + } + } +} + +auto HRDTransceiver::get_data_mode (MODE m) -> MODE +{ + if (data_mode_dropdown_ >= 0 + && data_mode_dropdown_selection_off_.size ()) + { + auto selection = get_dropdown (data_mode_dropdown_); + // can't check for on here as there may be multiple on values so + // we must rely on the initial parse finding valid on values + if (selection >= 0 && selection != data_mode_dropdown_selection_off_.front ()) + { + switch (m) + { + case USB: m = DIG_U; break; + case LSB: m = DIG_L; break; + case FM: m = DIG_FM; break; + default: break; + } + } + } + return m; +} + +void HRDTransceiver::do_frequency (Frequency f, MODE m, bool /*no_ignore*/) +{ + CAT_TRACE (f << "reversed" << reversed_); + if (UNK != m) + { + do_mode (m); + } + auto fo_string = QString::number (f); + if (vfo_count_ > 1 && reversed_) + { + auto frequencies = send_command ("get frequencies").trimmed ().split ('-', SkipEmptyParts); + send_simple_command ("set frequencies-hz " + QString::number (frequencies[0].toUInt ()) + ' ' + fo_string); + } + else + { + send_simple_command ("set frequency-hz " + QString::number (f)); + } + update_rx_frequency (f); +} + +void HRDTransceiver::do_tx_frequency (Frequency tx, MODE mode, bool /*no_ignore*/) +{ + CAT_TRACE (tx << "reversed" << reversed_); + + // re-check if reversed VFOs + bool rx_A {true}; + bool rx_B {false}; + if (receiver_dropdown_ >= 0 && rx_A_selection_.size ()) + { + auto selection = get_dropdown (receiver_dropdown_); + rx_A = selection == rx_A_selection_.front (); + if (!rx_A && rx_B_selection_.size ()) + { + rx_B = selection == rx_B_selection_.front (); + } + } + else if (vfo_B_button_ >= 0 || rx_B_button_ >= 0) + { + rx_A = is_button_checked (rx_A_button_ >= 0 ? rx_A_button_ : vfo_A_button_); + if (!rx_A) + { + rx_B = is_button_checked (rx_B_button_ >= 0 ? rx_B_button_ : vfo_B_button_); + } + } + reversed_ = rx_B; + + bool split {tx != 0}; + if (split) + { + if (mode != UNK) + { + if (!reversed_ && mode_B_dropdown_ >= 0) + { + set_dropdown (mode_B_dropdown_, lookup_mode (mode, mode_B_map_)); + } + else if (reversed_ && mode_B_dropdown_ >= 0) + { + set_dropdown (mode_A_dropdown_, lookup_mode (mode, mode_A_map_)); + } + else + { + Q_ASSERT (mode_A_dropdown_ >= 0 && ((vfo_A_button_ >=0 && vfo_B_button_ >=0) || vfo_toggle_button_ >= 0)); + + if (rx_B_button_ >= 0) + { + set_button (reversed_ ? rx_A_button_ : rx_B_button_); + set_dropdown (mode_A_dropdown_, lookup_mode (mode, mode_A_map_)); + set_data_mode (mode); + set_button (reversed_ ? rx_B_button_ : rx_A_button_); + } + else if (receiver_dropdown_ >= 0 + && rx_A_selection_.size () && rx_B_selection_.size ()) + { + set_dropdown (receiver_dropdown_, (reversed_ ? rx_A_selection_ : rx_B_selection_).front ()); + set_dropdown (mode_A_dropdown_, lookup_mode (mode, mode_A_map_)); + set_data_mode (mode); + set_dropdown (receiver_dropdown_, (reversed_ ? rx_B_selection_ : rx_A_selection_).front ()); + } + else if (vfo_count_ > 1 && ((vfo_A_button_ >=0 && vfo_B_button_ >=0) || vfo_toggle_button_ >= 0)) + { + set_button (vfo_A_button_ >= 0 ? (reversed_ ? vfo_A_button_ : vfo_B_button_) : vfo_toggle_button_); + set_dropdown (mode_A_dropdown_, lookup_mode (mode, mode_A_map_)); + set_data_mode (mode); + set_button (vfo_A_button_ >= 0 ? (reversed_ ? vfo_B_button_ : vfo_A_button_) : vfo_toggle_button_); + } + // else Tx VFO mode gets set with frequency below or we + // don't have a way of setting it so we assume it is + // always the same as the Rx VFO mode + } + } + + auto fo_string = QString::number (tx); + if (reversed_) + { + Q_ASSERT (vfo_count_ > 1); + + auto frequencies = send_command ("get frequencies").trimmed ().split ('-', SkipEmptyParts); + send_simple_command ("set frequencies-hz " + fo_string + ' ' + QString::number (frequencies[1].toUInt ())); + } + else + { + if (vfo_count_ > 1) + { + auto frequencies = send_command ("get frequencies").trimmed ().split ('-', SkipEmptyParts); + send_simple_command ("set frequencies-hz " + QString::number (frequencies[0].toUInt ()) + ' ' + fo_string); + } + else if ((vfo_B_button_ >= 0 && vfo_A_button_ >= 0) || vfo_toggle_button_ >= 0) + { + // we rationalise the modes here as well as the frequencies + set_button (vfo_B_button_ >= 0 ? vfo_B_button_ : vfo_toggle_button_); + send_simple_command ("set frequency-hz " + fo_string); + if (mode != UNK && mode_B_dropdown_ < 0) + { + // do this here rather than later so we only + // toggle/switch VFOs once + set_dropdown (mode_A_dropdown_, lookup_mode (mode, mode_A_map_)); + set_data_mode (mode); + } + set_button (vfo_A_button_ >= 0 ? vfo_A_button_ : vfo_toggle_button_); + } + } + } + update_other_frequency (tx); + + if (split_mode_button_ >= 0) + { + if (split_off_button_ >= 0 && !split) + { + set_button (split_off_button_); + } + else + { + set_button (split_mode_button_, split); + } + } + else if (split_mode_dropdown_ >= 0 + && split_mode_dropdown_selection_off_.size () + && split_mode_dropdown_selection_on_.size ()) + { + set_dropdown (split_mode_dropdown_, split ? split_mode_dropdown_selection_on_.front () : split_mode_dropdown_selection_off_.front ()); + } + else if (vfo_A_button_ >= 0 && vfo_B_button_ >= 0 && tx_A_button_ >= 0 && tx_B_button_ >= 0) + { + if (split) + { + if (reversed_ != is_button_checked (tx_A_button_)) + { + if (rx_A_button_ >= 0 && rx_B_button_ >= 0) + { + set_button (reversed_ ? rx_B_button_ : rx_A_button_); + } + else if (receiver_dropdown_ >= 0 + && rx_A_selection_.size () && rx_B_selection_.size ()) + { + set_dropdown (receiver_dropdown_, (reversed_ ? rx_B_selection_ : rx_A_selection_).front ()); + } + else + { + set_button (reversed_ ? vfo_B_button_ : vfo_A_button_); + } + set_button (reversed_ ? tx_A_button_ : tx_B_button_); + } + } + else + { + if (reversed_ != is_button_checked (tx_B_button_)) + { + if (rx_A_button_ >= 0 && rx_B_button_ >= 0) + { + set_button (reversed_ ? rx_B_button_ : rx_A_button_); + } + else if (receiver_dropdown_ >= 0 + && rx_A_selection_.size () && rx_B_selection_.size ()) + { + set_dropdown (receiver_dropdown_, (reversed_ ? rx_B_selection_ : rx_A_selection_).front ()); + } + else + { + set_button (reversed_ ? vfo_B_button_ : vfo_A_button_); + } + set_button (reversed_ ? tx_B_button_ : tx_A_button_); + } + } + } + update_split (split); +} + +void HRDTransceiver::do_mode (MODE mode) +{ + CAT_TRACE (mode); + if (reversed_ && mode_B_dropdown_ >= 0) + { + set_dropdown (mode_B_dropdown_, lookup_mode (mode, mode_B_map_)); + } + else + { + set_dropdown (mode_A_dropdown_, lookup_mode (mode, mode_A_map_)); + } + if (mode != UNK && state ().split ()) // rationalise mode if split + { + if (reversed_) + { + if (mode_B_dropdown_ >= 0) + { + set_dropdown (mode_A_dropdown_, lookup_mode (mode, mode_A_map_)); + } + else + { + Q_ASSERT ((vfo_B_button_ >= 0 && vfo_A_button_ >= 0) || vfo_toggle_button_ >= 0); + + if (rx_B_button_ >= 0) + { + set_button (rx_A_button_); + set_dropdown (mode_A_dropdown_, lookup_mode (mode, mode_A_map_)); + set_button (rx_B_button_); + } + else if (receiver_dropdown_ >= 0 + && rx_A_selection_.size () && rx_B_selection_.size ()) + { + set_dropdown (receiver_dropdown_, rx_A_selection_.front ()); + set_dropdown (mode_A_dropdown_, lookup_mode (mode, mode_A_map_)); + set_dropdown (receiver_dropdown_, rx_B_selection_.front ()); + } + else if (vfo_count_ > 1 && ((vfo_A_button_ >=0 && vfo_B_button_ >=0) || vfo_toggle_button_ >= 0)) + { + set_button (vfo_A_button_ >= 0 ? vfo_A_button_ : vfo_toggle_button_); + set_dropdown (mode_A_dropdown_, lookup_mode (mode, mode_A_map_)); + set_button (vfo_B_button_ >= 0 ? vfo_B_button_ : vfo_toggle_button_); + } + // else Tx VFO mode gets set when Tx VFO frequency is + // set + + if ( tx_A_button_ >= 0) + { + set_button (tx_A_button_); + } + } + } + else + { + if (mode_B_dropdown_ >= 0) + { + set_dropdown (mode_B_dropdown_, lookup_mode (mode, mode_B_map_)); + } + else + { + Q_ASSERT ((vfo_B_button_ >= 0 && vfo_A_button_ >= 0) || vfo_toggle_button_ >= 0); + + if (rx_B_button_ >= 0) + { + set_button (rx_B_button_); + set_dropdown (mode_A_dropdown_, lookup_mode (mode, mode_A_map_)); + set_button (rx_A_button_); + } + else if (receiver_dropdown_ >= 0 + && rx_A_selection_.size () && rx_B_selection_.size ()) + { + set_dropdown (receiver_dropdown_, rx_B_selection_.front ()); + set_dropdown (mode_A_dropdown_, lookup_mode (mode, mode_A_map_)); + set_dropdown (receiver_dropdown_, rx_A_selection_.front ()); + } + else if (vfo_count_ > 1 && ((vfo_A_button_ >=0 && vfo_B_button_ >=0) || vfo_toggle_button_ >= 0)) + { + set_button (vfo_B_button_ >= 0 ? vfo_B_button_ : vfo_toggle_button_); + set_dropdown (mode_A_dropdown_, lookup_mode (mode, mode_A_map_)); + set_button (vfo_A_button_ >= 0 ? vfo_A_button_ : vfo_toggle_button_); + } + // else Tx VFO mode gets set when Tx VFO frequency is + // set + + if ( tx_B_button_ >= 0) + { + set_button (tx_B_button_); + } + } + } + } + set_data_mode (mode); + update_mode (mode); +} + +bool HRDTransceiver::is_button_checked (int button_index) +{ + if (button_index < 0) + { + return false; + } + + auto reply = send_command ("get button-select " + buttons_.value (button_index)); + if ("1" != reply && "0" != reply) + { + CAT_ERROR ("bad response"); + throw error {tr ("Ham Radio Deluxe didn't respond as expected")}; + } + return "1" == reply; +} + +void HRDTransceiver::do_poll () +{ + CAT_TRACE ("+++++++ poll dump +++++++"); + CAT_TRACE ("reversed:" << reversed_); + is_button_checked (vfo_A_button_); + is_button_checked (vfo_B_button_); + is_button_checked (vfo_toggle_button_); + is_button_checked (split_mode_button_); + is_button_checked (split_off_button_); + is_button_checked (rx_A_button_); + is_button_checked (rx_B_button_); + get_dropdown (receiver_dropdown_); + is_button_checked (tx_A_button_); + is_button_checked (tx_B_button_); + is_button_checked (ptt_button_); + is_button_checked (alt_ptt_button_); + get_dropdown (mode_A_dropdown_); + get_dropdown (mode_B_dropdown_); + is_button_checked (data_mode_toggle_button_); + is_button_checked (data_mode_on_button_); + is_button_checked (data_mode_off_button_); + if (data_mode_dropdown_ >=0 + && data_mode_dropdown_selection_off_.size () + && data_mode_dropdown_selection_on_.size ()) + { + get_dropdown (data_mode_dropdown_); + } + if (!split_mode_dropdown_write_only_) + { + get_dropdown (split_mode_dropdown_); + } + CAT_TRACE ("------- poll dump -------"); + + if (split_off_button_ >= 0) + { + // we are probably dealing with an Icom and have to guess SPLIT mode :( + } + else if (split_mode_button_ >= 0 && !(tx_A_button_ >= 0 && tx_B_button_ >= 0)) + { + update_split (is_button_checked (split_mode_button_)); + } + else if (split_mode_dropdown_ >= 0) + { + if (!split_mode_dropdown_write_only_) + { + auto selection = get_dropdown (split_mode_dropdown_); + if (selection >= 0 + && split_mode_dropdown_selection_off_.size ()) + { + update_split (selection == split_mode_dropdown_selection_on_.front ()); + } + else + { + // leave split alone as we can't query it - it should be + // correct so long as rig or HRD haven't been changed + split_mode_dropdown_write_only_ = true; + } + } + } + else if (vfo_A_button_ >= 0 && vfo_B_button_ >= 0 && tx_A_button_ >= 0 && tx_B_button_ >= 0) + { + bool rx_A {true}; // no Rx taken as not reversed + bool rx_B {false}; + + auto tx_A = is_button_checked (tx_A_button_); + + // some rigs have dual Rx, we take VFO A/MAIN receiving as + // normal and only say reversed when only VFO B/SUB is active + // i.e. VFO A/MAIN muted VFO B/SUB active + if (receiver_dropdown_ >= 0 && rx_A_selection_.size ()) + { + auto selection = get_dropdown (receiver_dropdown_); + rx_A = selection == rx_A_selection_.front (); + if (!rx_A && rx_B_selection_.size ()) + { + rx_B = selection == rx_B_selection_.front (); + } + } + else if (vfo_B_button_ >= 0 || rx_B_button_ >= 0) + { + rx_A = is_button_checked (rx_A_button_ >= 0 ? rx_A_button_ : vfo_A_button_); + if (!rx_A) + { + rx_B = is_button_checked (rx_B_button_ >= 0 ? rx_B_button_ : vfo_B_button_); + } + } + + update_split (rx_B == tx_A); + reversed_ = rx_B; + } + + if (vfo_count_ > 1) + { + auto frequencies = send_command ("get frequencies").trimmed ().split ('-', SkipEmptyParts); + update_rx_frequency (frequencies[reversed_ ? 1 : 0].toUInt ()); + update_other_frequency (frequencies[reversed_ ? 0 : 1].toUInt ()); + } + else + { + // read frequency is unreliable on single VFO addressing rigs + // while transmitting + if (!state ().ptt ()) + { + update_rx_frequency (send_command ("get frequency").toUInt ()); + } + } + + // read mode is unreliable on single VFO addressing rigs while + // transmitting + if (vfo_count_ > 1 || !state ().ptt ()) + { + update_mode (get_data_mode (lookup_mode (get_dropdown (mode_A_dropdown_), mode_A_map_))); + } +} + +QString HRDTransceiver::send_command (QString const& cmd, bool prepend_context, bool recurse) +{ + if (!hrd_) return QString {}; + + QString result; + + if (current_radio_ && prepend_context && vfo_count_ < 2) + { + // required on some radios because commands don't get executed + // correctly otherwise (ICOM for example) + QThread::msleep (50); + } + + if (!recurse && prepend_context) + { + auto radio_name = send_command ("get radio", current_radio_, true); + qDebug () << "HRDTransceiver::send_command: radio_name:" << radio_name; + auto radio_iter = std::find_if (radios_.begin (), radios_.end (), [&radio_name] (RadioMap::value_type const& radio) + { + return std::get<1> (radio) == radio_name; + }); + if (radio_iter == radios_.end ()) + { + CAT_TRACE ("rig disappeared or changed"); + throw error {tr ("Ham Radio Deluxe: rig has disappeared or changed")}; + } + + if (0u == current_radio_ || std::get<0> (*radio_iter) != current_radio_) + { + current_radio_ = std::get<0> (*radio_iter); + } + } + + auto context = '[' + QString::number (current_radio_) + "] "; + + if (QTcpSocket::ConnectedState != hrd_->state ()) + { + CAT_ERROR (cmd << "failed" << hrd_->errorString ()); + throw error { + tr ("Ham Radio Deluxe send command \"%1\" failed %2\n") + .arg (cmd) + .arg (hrd_->errorString ()) + }; + } + + if (v4 == protocol_) + { + auto message = ((prepend_context ? context + cmd : cmd) + "\r").toLocal8Bit (); + if (!write_to_port (message.constData (), message.size ())) + { + CAT_ERROR ("failed to write command" << cmd << "to HRD"); + throw error { + tr ("Ham Radio Deluxe: failed to write command \"%1\"") + .arg (cmd) + }; + } + } + else + { + auto string = prepend_context ? context + cmd : cmd; + QScopedPointer<HRDMessage> message {new (string) HRDMessage}; + if (!write_to_port (reinterpret_cast<char const *> (message.data ()), message->size_)) + { + CAT_ERROR ("failed to write command" << cmd << "to HRD"); + throw error { + tr ("Ham Radio Deluxe: failed to write command \"%1\"") + .arg (cmd) + }; + } + } + auto buffer = read_reply (cmd); + if (v4 == protocol_) + { + result = QString {buffer}.trimmed (); + } + else + { + HRDMessage const * reply {new (buffer) HRDMessage}; + if (reply->magic_1_value_ != reply->magic_1_ && reply->magic_2_value_ != reply->magic_2_) + { + CAT_ERROR (cmd << "invalid reply"); + throw error { + tr ("Ham Radio Deluxe sent an invalid reply to our command \"%1\"") + .arg (cmd) + }; + } + + // keep reading until expected size arrives + while (buffer.size () - offsetof (HRDMessage, size_) < reply->size_) + { + CAT_TRACE (cmd << "reading more reply data"); + buffer += read_reply (cmd); + reply = new (buffer) HRDMessage; + } + + result = QString {reply->payload_}; // this is not a memory leak (honest!) + } + CAT_TRACE (cmd << " ->" << result); + return result; +} + +bool HRDTransceiver::write_to_port (char const * data, qint64 length) +{ + qint64 total_bytes_sent {0}; + while (total_bytes_sent < length) + { + auto bytes_sent = hrd_->write (data + total_bytes_sent, length - total_bytes_sent); + if (bytes_sent < 0 || !hrd_->waitForBytesWritten ()) + { + return false; + } + + total_bytes_sent += bytes_sent; + } + return true; +} + +QByteArray HRDTransceiver::read_reply (QString const& cmd) +{ + // waitForReadReady appears to be occasionally unreliable on Windows + // timing out when data is waiting so retry a few times + unsigned retries {30}; + bool replied {false}; + while (!replied && retries--) + { + replied = hrd_->waitForReadyRead (); + if (!replied && hrd_->error () != hrd_->SocketTimeoutError) + { + CAT_ERROR (cmd << "failed to reply" << hrd_->errorString ()); + throw error { + tr ("Ham Radio Deluxe failed to reply to command \"%1\" %2\n") + .arg (cmd) + .arg (hrd_->errorString ()) + }; + } + } + if (!replied) + { + CAT_ERROR (cmd << "retries exhausted"); + throw error { + tr ("Ham Radio Deluxe retries exhausted sending command \"%1\"") + .arg (cmd) + }; + } + return hrd_->readAll (); +} + +void HRDTransceiver::send_simple_command (QString const& command) +{ + if ("OK" != send_command (command)) + { + CAT_ERROR (command << "unexpected response"); + throw error { + tr ("Ham Radio Deluxe didn't respond to command \"%1\" as expected") + .arg (command) + }; + } +} diff --git a/Transceiver/HRDTransceiver.hpp b/Transceiver/HRDTransceiver.hpp index 75560220..f3db8bce 100755..100644 --- a/Transceiver/HRDTransceiver.hpp +++ b/Transceiver/HRDTransceiver.hpp @@ -1,200 +1,200 @@ -#ifndef HRD_TRANSCEIVER_HPP__
-#define HRD_TRANSCEIVER_HPP__
-
-#include <vector>
-#include <tuple>
-#include <memory>
-
-#include <QScopedPointer>
-#include <QString>
-#include <QStringList>
-
-#include "TransceiverFactory.hpp"
-#include "PollingTransceiver.hpp"
-
-class QRegExp;
-class QTcpSocket;
-class QByteArray;
-
-//
-// Ham Radio Deluxe Transceiver Interface
-//
-// Implemented as a Transceiver decorator because we may want the PTT
-// services of another Transceiver type such as the HamlibTransceiver
-// which can be enabled by wrapping a HamlibTransceiver instantiated
-// as a "Hamlib Dummy" transceiver in the Transceiver factory method.
-//
-class HRDTransceiver final
- : public PollingTransceiver
-{
- Q_OBJECT
-
-public:
- static void register_transceivers (logger_type *, TransceiverFactory::Transceivers *, unsigned id);
-
- // takes ownership of wrapped Transceiver
- explicit HRDTransceiver (logger_type *
- , std::unique_ptr<TransceiverBase> wrapped
- , QString const& server
- , bool use_for_ptt
- , TransceiverFactory::TXAudioSource
- , int poll_interval
- , QObject * parent = nullptr);
-
-protected:
- // Implement the TransceiverBase interface.
- int do_start () override;
- void do_stop () override;
- void do_frequency (Frequency, MODE, bool no_ignore) override;
- void do_tx_frequency (Frequency, MODE, bool no_ignore) override;
- void do_mode (MODE) override;
- void do_ptt (bool on) override;
-
- // Implement the PollingTransceiver interface.
- void do_poll () override;
-
-private:
- QString send_command (QString const&, bool prepend_context = true, bool recurse = false);
- QByteArray read_reply (QString const& command);
- void send_simple_command (QString const&);
- bool write_to_port (char const *, qint64 length);
- int find_button (QRegExp const&) const;
- int find_dropdown (QRegExp const&) const;
- std::vector<int> find_dropdown_selection (int dropdown, QRegExp const&) const;
- int get_dropdown (int);
- void set_dropdown (int, int);
- void set_button (int button_index, bool checked = true);
- bool is_button_checked (int button_index);
-
- // This dictionary type maps Transceiver::MODE to a list of mode
- // drop down selection indexes that equate to that mode. It is used
- // to map internal MODE values to HRD drop down selections and vice
- // versa.
- using ModeMap = std::vector<std::tuple<MODE, std::vector<int> > >;
-
- void map_modes (int dropdown, ModeMap *);
- int lookup_mode (MODE, ModeMap const&) const;
- MODE lookup_mode (int, ModeMap const&) const;
- void set_data_mode (MODE);
- MODE get_data_mode (MODE);
-
- // An alternate TransceiverBase instance that can be used to drive
- // PTT if required.
- std::unique_ptr<TransceiverBase> wrapped_; // may be null
-
- bool use_for_ptt_; // Use HRD for PTT.
- TransceiverFactory::TXAudioSource audio_source_; // Select rear/data
- // audio if available
-
- QString server_; // The TCP/IP addrress and port for
- // the HRD server.
-
- QTcpSocket * hrd_; // The TCP/IP client that links to the
- // HRD server.
-
- enum {none, v4, v5} protocol_; // The HRD protocol that has been
- // detected.
-
- using RadioMap = std::vector<std::tuple<unsigned, QString> >;
-
- RadioMap radios_; // Dictionary of available radios.
-
- unsigned current_radio_; // The current addressed radio.
-
- unsigned vfo_count_; // How many VFOs are supported.
-
- QStringList buttons_; // The buttons available to click.
-
- QStringList dropdown_names_; // The names of drop down selectors
- // available.
-
- QMap<QString, QStringList> dropdowns_; // Dictionary of available
- // drop down selections.
-
- QStringList slider_names_; // The name of available sliders.
-
- QMap<QString, QStringList> sliders_; // Dictionary of available
- // slider ranges.
-
- int vfo_A_button_; // The button we use to select VFO
- // A. May be -1 if none available.
-
- int vfo_B_button_; // Index of button we use to select
- // VFO B. May be -1 if none available.
-
- int vfo_toggle_button_; // Index of button we use to toggle
- // the VFOs. Use this if VFO A and VFO
- // B selection are not available.
-
- int mode_A_dropdown_; // Index of the mode drop down for VFO
- // A.
-
- ModeMap mode_A_map_; // The map of modes available for VFO
- // A.
-
- int mode_B_dropdown_; // The drop down index for VFO B mode
- // setting. May be -1 if independent
- // VFO mode setting not available.
-
- ModeMap mode_B_map_; // The map of modes for VFO B.
-
- int data_mode_toggle_button_; // Button to toggle DATA mode
- int data_mode_on_button_; // Button to enable DATA mode
- int data_mode_off_button_; // Button to disable DATA mode
- int data_mode_dropdown_; // Index of data mode drop down, may
- // be -1 if no such drop down exists
- std::vector<int> data_mode_dropdown_selection_on_; // The drop down
- // selection to turn on data mode.
-
- std::vector<int> data_mode_dropdown_selection_off_; // The drop
- // down selection to disable data mode.
-
- int split_mode_button_; // Button to use to select split
- // operation. May be -1 if no button
- // is available.
-
- int split_mode_dropdown_; // The drop down index that allows
- // split mode to be turned on and
- // off. May be -1 if no such drop down
- // exists.
-
- bool split_mode_dropdown_write_only_; // Some rigs cannot report
- // split status.
-
- std::vector<int> split_mode_dropdown_selection_on_; // The drop down
- // selection to
- // turn on
- // split.
-
- std::vector<int> split_mode_dropdown_selection_off_; // The drop
- // down
- // selection to
- // disable
- // split.
-
- int split_off_button_; // The button to turn off split mode.
-
- int tx_A_button_; // The button to transmit on VFO A.
-
- int tx_B_button_; // The button to transmit on VFO B.
-
- int rx_A_button_; // The button to receive on VFO A
- // A. May be -1 if none available.
-
- int rx_B_button_; // The button to receive on VFO B
- // May be -1 if none available.
-
- int receiver_dropdown_; // Select receiver
-
- std::vector<int> rx_A_selection_;
-
- std::vector<int> rx_B_selection_;
-
- int ptt_button_; // The button to toggle PTT.
- int alt_ptt_button_; // The alternative button to toggle
- // PTT - used to select rear audio.
-
- bool reversed_; // True if VFOs are reversed.
-};
-
-#endif
+#ifndef HRD_TRANSCEIVER_HPP__ +#define HRD_TRANSCEIVER_HPP__ + +#include <vector> +#include <tuple> +#include <memory> + +#include <QScopedPointer> +#include <QString> +#include <QStringList> + +#include "TransceiverFactory.hpp" +#include "PollingTransceiver.hpp" + +class QRegExp; +class QTcpSocket; +class QByteArray; + +// +// Ham Radio Deluxe Transceiver Interface +// +// Implemented as a Transceiver decorator because we may want the PTT +// services of another Transceiver type such as the HamlibTransceiver +// which can be enabled by wrapping a HamlibTransceiver instantiated +// as a "Hamlib Dummy" transceiver in the Transceiver factory method. +// +class HRDTransceiver final + : public PollingTransceiver +{ + Q_OBJECT + +public: + static void register_transceivers (logger_type *, TransceiverFactory::Transceivers *, unsigned id); + + // takes ownership of wrapped Transceiver + explicit HRDTransceiver (logger_type * + , std::unique_ptr<TransceiverBase> wrapped + , QString const& server + , bool use_for_ptt + , TransceiverFactory::TXAudioSource + , int poll_interval + , QObject * parent = nullptr); + +protected: + // Implement the TransceiverBase interface. + int do_start () override; + void do_stop () override; + void do_frequency (Frequency, MODE, bool no_ignore) override; + void do_tx_frequency (Frequency, MODE, bool no_ignore) override; + void do_mode (MODE) override; + void do_ptt (bool on) override; + + // Implement the PollingTransceiver interface. + void do_poll () override; + +private: + QString send_command (QString const&, bool prepend_context = true, bool recurse = false); + QByteArray read_reply (QString const& command); + void send_simple_command (QString const&); + bool write_to_port (char const *, qint64 length); + int find_button (QRegExp const&) const; + int find_dropdown (QRegExp const&) const; + std::vector<int> find_dropdown_selection (int dropdown, QRegExp const&) const; + int get_dropdown (int); + void set_dropdown (int, int); + void set_button (int button_index, bool checked = true); + bool is_button_checked (int button_index); + + // This dictionary type maps Transceiver::MODE to a list of mode + // drop down selection indexes that equate to that mode. It is used + // to map internal MODE values to HRD drop down selections and vice + // versa. + using ModeMap = std::vector<std::tuple<MODE, std::vector<int> > >; + + void map_modes (int dropdown, ModeMap *); + int lookup_mode (MODE, ModeMap const&) const; + MODE lookup_mode (int, ModeMap const&) const; + void set_data_mode (MODE); + MODE get_data_mode (MODE); + + // An alternate TransceiverBase instance that can be used to drive + // PTT if required. + std::unique_ptr<TransceiverBase> wrapped_; // may be null + + bool use_for_ptt_; // Use HRD for PTT. + TransceiverFactory::TXAudioSource audio_source_; // Select rear/data + // audio if available + + QString server_; // The TCP/IP addrress and port for + // the HRD server. + + QTcpSocket * hrd_; // The TCP/IP client that links to the + // HRD server. + + enum {none, v4, v5} protocol_; // The HRD protocol that has been + // detected. + + using RadioMap = std::vector<std::tuple<unsigned, QString> >; + + RadioMap radios_; // Dictionary of available radios. + + unsigned current_radio_; // The current addressed radio. + + unsigned vfo_count_; // How many VFOs are supported. + + QStringList buttons_; // The buttons available to click. + + QStringList dropdown_names_; // The names of drop down selectors + // available. + + QMap<QString, QStringList> dropdowns_; // Dictionary of available + // drop down selections. + + QStringList slider_names_; // The name of available sliders. + + QMap<QString, QStringList> sliders_; // Dictionary of available + // slider ranges. + + int vfo_A_button_; // The button we use to select VFO + // A. May be -1 if none available. + + int vfo_B_button_; // Index of button we use to select + // VFO B. May be -1 if none available. + + int vfo_toggle_button_; // Index of button we use to toggle + // the VFOs. Use this if VFO A and VFO + // B selection are not available. + + int mode_A_dropdown_; // Index of the mode drop down for VFO + // A. + + ModeMap mode_A_map_; // The map of modes available for VFO + // A. + + int mode_B_dropdown_; // The drop down index for VFO B mode + // setting. May be -1 if independent + // VFO mode setting not available. + + ModeMap mode_B_map_; // The map of modes for VFO B. + + int data_mode_toggle_button_; // Button to toggle DATA mode + int data_mode_on_button_; // Button to enable DATA mode + int data_mode_off_button_; // Button to disable DATA mode + int data_mode_dropdown_; // Index of data mode drop down, may + // be -1 if no such drop down exists + std::vector<int> data_mode_dropdown_selection_on_; // The drop down + // selection to turn on data mode. + + std::vector<int> data_mode_dropdown_selection_off_; // The drop + // down selection to disable data mode. + + int split_mode_button_; // Button to use to select split + // operation. May be -1 if no button + // is available. + + int split_mode_dropdown_; // The drop down index that allows + // split mode to be turned on and + // off. May be -1 if no such drop down + // exists. + + bool split_mode_dropdown_write_only_; // Some rigs cannot report + // split status. + + std::vector<int> split_mode_dropdown_selection_on_; // The drop down + // selection to + // turn on + // split. + + std::vector<int> split_mode_dropdown_selection_off_; // The drop + // down + // selection to + // disable + // split. + + int split_off_button_; // The button to turn off split mode. + + int tx_A_button_; // The button to transmit on VFO A. + + int tx_B_button_; // The button to transmit on VFO B. + + int rx_A_button_; // The button to receive on VFO A + // A. May be -1 if none available. + + int rx_B_button_; // The button to receive on VFO B + // May be -1 if none available. + + int receiver_dropdown_; // Select receiver + + std::vector<int> rx_A_selection_; + + std::vector<int> rx_B_selection_; + + int ptt_button_; // The button to toggle PTT. + int alt_ptt_button_; // The alternative button to toggle + // PTT - used to select rear audio. + + bool reversed_; // True if VFOs are reversed. +}; + +#endif diff --git a/Transceiver/HamlibTransceiver.cpp b/Transceiver/HamlibTransceiver.cpp index 4d2795a8..99b31f5c 100755..100644 --- a/Transceiver/HamlibTransceiver.cpp +++ b/Transceiver/HamlibTransceiver.cpp @@ -1,1336 +1,1336 @@ -#include "HamlibTransceiver.hpp"
-
-#include <cstring>
-#include <cmath>
-#include <tuple>
-#include <QByteArray>
-#include <QString>
-#include <QStandardPaths>
-#include <QFile>
-#include <QTimer>
-#include <QJsonDocument>
-#include <QJsonObject>
-#include <QJsonValue>
-#include <QDebug>
-#include <hamlib/rig.h>
-#include "pimpl_impl.hpp"
-#include "moc_HamlibTransceiver.cpp"
-
-#if HAVE_HAMLIB_OLD_CACHING
-#define HAMLIB_CACHE_ALL CACHE_ALL
-#endif
-
-namespace
-{
- // Unfortunately bandwidth is conflated with mode, this is probably
- // because Icom do the same. So we have to care about bandwidth if
- // we want to set mode otherwise we will end up setting unwanted
- // bandwidths every time we change mode. The best we can do via the
- // Hamlib API is to request the normal option for the mode and hope
- // that an appropriate filter is selected. Also ensure that mode is
- // only set is absolutely necessary. On Icoms (and probably others)
- // the filter is selected by number without checking the actual BW
- // so unless the "normal" defaults are set on the rig we won't get
- // desirable results.
- //
- // As an ultimate workaround make sure the user always has the
- // option to skip mode setting altogether.
-
- // callback function that receives transceiver capabilities from the
- // hamlib libraries
- int register_callback (rig_model_t rig_model, void * callback_data)
- {
- TransceiverFactory::Transceivers * rigs = reinterpret_cast<TransceiverFactory::Transceivers *> (callback_data);
- // We can't use this one because it is only for testing Hamlib and
- // would confuse users, possibly causing operating on the wrong
- // frequency!
-#ifdef RIG_MODEL_DUMMY_NOVFO
- if (RIG_MODEL_DUMMY_NOVFO == rig_model)
- {
- return 1;
- }
-#endif
-
- QString key;
- if (RIG_MODEL_DUMMY == rig_model)
- {
- key = TransceiverFactory::basic_transceiver_name_;
- }
- else
- {
- key = QString::fromLatin1 (rig_get_caps_cptr (rig_model, RIG_CAPS_MFG_NAME_CPTR)).trimmed ()
- + ' '+ QString::fromLatin1 (rig_get_caps_cptr (rig_model, RIG_CAPS_MODEL_NAME_CPTR)).trimmed ()
- // + ' '+ QString::fromLatin1 (rig_get_caps_cptr (rig_model, RIG_CAPS_VERSION)).trimmed ()
- // + " (" + QString::fromLatin1 (rig_get_caps_cptr (rig_model, RIG_CAPS_STATUS)).trimmed () + ')'
- ;
- }
-
- auto port_type = TransceiverFactory::Capabilities::none;
- switch(rig_get_caps_int (rig_model, RIG_CAPS_PORT_TYPE))
- {
- case RIG_PORT_SERIAL:
- port_type = TransceiverFactory::Capabilities::serial;
- break;
-
- case RIG_PORT_NETWORK:
- port_type = TransceiverFactory::Capabilities::network;
- break;
-
- case RIG_PORT_USB:
- port_type = TransceiverFactory::Capabilities::usb;
- break;
-
- default: break;
- }
- auto ptt_type = rig_get_caps_int (rig_model, RIG_CAPS_PTT_TYPE);
- (*rigs)[key] = TransceiverFactory::Capabilities (rig_model
- , port_type
- , RIG_MODEL_DUMMY != rig_model
- && (RIG_PTT_RIG == ptt_type
- || RIG_PTT_RIG_MICDATA == ptt_type)
- , RIG_PTT_RIG_MICDATA == ptt_type);
-
- return 1; // keep them coming
- }
-
- int unregister_callback (rig_model_t rig_model, void *)
- {
- rig_unregister (rig_get_caps_int (rig_model, RIG_CAPS_RIG_MODEL));
- return 1; // keep them coming
- }
-
- // int frequency_change_callback (RIG * /* rig */, vfo_t vfo, freq_t f, rig_ptr_t arg)
- // {
- // (void)vfo; // unused in release build
-
- // Q_ASSERT (vfo == RIG_VFO_CURR); // G4WJS: at the time of writing only current VFO is signalled by hamlib
-
- // HamlibTransceiver * transceiver (reinterpret_cast<HamlibTransceiver *> (arg));
- // Q_EMIT transceiver->frequency_change (f, Transceiver::A);
- // return RIG_OK;
- // }
-
- class hamlib_tx_vfo_fixup final
- {
- public:
- hamlib_tx_vfo_fixup (RIG * rig, vfo_t tx_vfo)
- : rig_ {rig}
- {
- original_vfo_ = rig_->state.tx_vfo;
- rig_->state.tx_vfo = tx_vfo;
- }
-
- ~hamlib_tx_vfo_fixup ()
- {
- rig_->state.tx_vfo = original_vfo_;
- }
-
- private:
- RIG * rig_;
- vfo_t original_vfo_;
- };
-}
-
-class HamlibTransceiver::impl final
-{
-public:
- impl (HamlibTransceiver::logger_type * logger)
- : logger_ {logger}
- , model_ {RIG_MODEL_DUMMY}
- , rig_ {rig_init (model_)}
- , ptt_only_ {true}
- , back_ptt_port_ {false}
- , one_VFO_ {false}
- , is_dummy_ {true}
- , reversed_ {false}
- , freq_query_works_ {true}
- , mode_query_works_ {true}
- , split_query_works_ {true}
- , tickle_hamlib_ {false}
- , get_vfo_works_ {true}
- , set_vfo_works_ {true}
- , do_snr_ {false}
- , do_pwr_ {false}
- , do_pwr2_ {false}
- , do_swr_ {false}
- {
- }
-
- impl (HamlibTransceiver::logger_type * logger, unsigned model_number
- , TransceiverFactory::ParameterPack const& params)
- : logger_ {logger}
- , model_ {model_number}
- , rig_ {rig_init (model_)}
- , ptt_only_ {false}
- , back_ptt_port_ {TransceiverFactory::TX_audio_source_rear == params.audio_source}
- , one_VFO_ {false}
- , is_dummy_ {RIG_MODEL_DUMMY == model_}
- , reversed_ {false}
- , freq_query_works_ {rig_ && rig_get_function_ptr (model_, RIG_FUNCTION_GET_FREQ)}
- , mode_query_works_ {rig_ && rig_get_function_ptr (model_, RIG_FUNCTION_GET_MODE)}
- , split_query_works_ {rig_ && rig_get_function_ptr (model_, RIG_FUNCTION_GET_SPLIT_VFO)}
- , tickle_hamlib_ {false}
- , get_vfo_works_ {true}
- , set_vfo_works_ {true}
- , do_snr_ {false}
- , do_pwr_ {false}
- , do_pwr2_ {false}
- , do_swr_ {false}
- {
- }
-
- HamlibTransceiver::logger_type& logger () const
- {
- return *logger_;
- }
-
- void error_check (int ret_code, QString const& doing) const;
- void set_conf (char const * item, char const * value);
- QByteArray get_conf (char const * item);
- Transceiver::MODE map_mode (rmode_t) const;
- rmode_t map_mode (Transceiver::MODE mode) const;
- std::tuple<vfo_t, vfo_t> get_vfos (bool for_split) const;
-
- HamlibTransceiver::logger_type mutable * logger_;
- unsigned model_;
- struct RIGDeleter {static void cleanup (RIG *);};
- QScopedPointer<RIG, RIGDeleter> rig_;
-
- bool ptt_only_; // we can use a dummy device for PTT
- bool back_ptt_port_;
- bool one_VFO_;
- bool is_dummy_;
-
- // these are saved on destruction so we can start new instances
- // where the last one left off
- static freq_t dummy_frequency_;
- static rmode_t dummy_mode_;
-
- bool mutable reversed_;
-
- bool freq_query_works_;
- bool mode_query_works_;
- bool split_query_works_;
- bool tickle_hamlib_; // Hamlib requires a
- // rig_set_split_vfo() call to
- // establish the Tx VFO
- bool get_vfo_works_; // Net rigctl promises what it can't deliver
- bool set_vfo_works_; // More rigctl promises which it can't deliver
- bool do_snr_;
- bool do_pwr_;
- bool do_pwr2_;
- bool do_swr_;
-
- static int debug_callback (enum rig_debug_level_e level, rig_ptr_t arg, char const * format, va_list ap);
-};
-
-freq_t HamlibTransceiver::impl::dummy_frequency_;
-rmode_t HamlibTransceiver::impl::dummy_mode_ {RIG_MODE_NONE};
-
- // reroute Hamlib diagnostic messages to Qt
-int HamlibTransceiver::impl::debug_callback (enum rig_debug_level_e level, rig_ptr_t arg, char const * format, va_list ap)
-{
- auto logger = reinterpret_cast<logger_type *> (arg);
- auto message = QString::vasprintf (format, ap);
- va_end (ap);
- auto severity = boost::log::trivial::trace;
- switch (level)
- {
- case RIG_DEBUG_BUG: severity = boost::log::trivial::fatal; break;
- case RIG_DEBUG_ERR: severity = boost::log::trivial::error; break;
- case RIG_DEBUG_WARN: severity = boost::log::trivial::warning; break;
- case RIG_DEBUG_VERBOSE: severity = boost::log::trivial::debug; break;
- case RIG_DEBUG_TRACE: severity = boost::log::trivial::trace; break;
- default: break;
- };
- if (level != RIG_DEBUG_NONE) // no idea what level NONE means so
- // ignore it
- {
- BOOST_LOG_SEV (*logger, severity) << message.trimmed ().toStdString ();
- }
- return 0;
-}
-
-void HamlibTransceiver::register_transceivers (logger_type * logger,
- TransceiverFactory::Transceivers * registry)
-{
- rig_set_debug_callback (impl::debug_callback, logger);
- rig_set_debug (RIG_DEBUG_TRACE);
- BOOST_LOG_SEV (*logger, boost::log::trivial::info) << "Hamlib version: " << rig_version ();
- rig_load_all_backends ();
- rig_list_foreach_model (register_callback, registry);
-}
-
-void HamlibTransceiver::unregister_transceivers ()
-{
- rig_list_foreach_model (unregister_callback, nullptr);
-}
-
-void HamlibTransceiver::impl::RIGDeleter::cleanup (RIG * rig)
-{
- if (rig)
- {
- rig_cleanup (rig);
- }
-}
-
-void HamlibTransceiver::impl::error_check (int ret_code, QString const& doing) const
-{
- if (RIG_OK != ret_code)
- {
- CAT_ERROR ("error: " << rigerror (ret_code));
- throw error {tr ("Hamlib error: %1 while %2").arg (rigerror (ret_code)).arg (doing)};
- }
-}
-
-std::tuple<vfo_t, vfo_t> HamlibTransceiver::impl::get_vfos (bool for_split) const
-{
- if (get_vfo_works_ && rig_get_function_ptr (model_, RIG_FUNCTION_GET_VFO))
- {
- vfo_t v;
- error_check (rig_get_vfo (rig_.data (), &v), tr ("getting current VFO")); // has side effect of establishing current VFO inside hamlib
- CAT_TRACE ("rig_get_vfo VFO=" << rig_strvfo (v));
-
- reversed_ = RIG_VFO_B == v;
- }
- else if (!for_split && set_vfo_works_ && rig_get_function_ptr (model_, RIG_FUNCTION_SET_VFO) && rig_get_function_ptr (model_, RIG_FUNCTION_SET_SPLIT_VFO))
- {
- // use VFO A/MAIN for main frequency and B/SUB for Tx
- // frequency if split since these type of radios can only
- // support this way around
-
- CAT_TRACE ("rig_set_vfo VFO=A/MAIN");
- error_check (rig_set_vfo (rig_.data (), rig_->state.vfo_list & RIG_VFO_A ? RIG_VFO_A : RIG_VFO_MAIN), tr ("setting current VFO"));
- }
- // else only toggle available but VFOs should be substitutable
-
- auto rx_vfo = rig_->state.vfo_list & RIG_VFO_A ? RIG_VFO_A : RIG_VFO_MAIN;
- auto tx_vfo = (WSJT_RIG_NONE_CAN_SPLIT || !is_dummy_) && for_split
- ? (rig_->state.vfo_list & RIG_VFO_B ? RIG_VFO_B : RIG_VFO_SUB)
- : rx_vfo;
- if (reversed_)
- {
- CAT_TRACE ("reversing VFOs");
- std::swap (rx_vfo, tx_vfo);
- }
-
- CAT_TRACE ("RX VFO=" << rig_strvfo (rx_vfo) << " TX VFO=" << rig_strvfo (tx_vfo));
- return std::make_tuple (rx_vfo, tx_vfo);
-}
-
-void HamlibTransceiver::impl::set_conf (char const * item, char const * value)
-{
- token_t token = rig_token_lookup (rig_.data (), item);
- if (RIG_CONF_END != token) // only set if valid for rig model
- {
- error_check (rig_set_conf (rig_.data (), token, value), tr ("setting a configuration item"));
- }
-}
-
-QByteArray HamlibTransceiver::impl::get_conf (char const * item)
-{
- token_t token = rig_token_lookup (rig_.data (), item);
- QByteArray value {128, '\0'};
- if (RIG_CONF_END != token) // only get if valid for rig model
- {
- error_check (rig_get_conf2 (rig_.data (), token, value.data (),value.length()), tr ("getting a configuration item")); //changed to conf2, added parameter for buffer length
- }
- return value;
-}
-
-auto HamlibTransceiver::impl::map_mode (rmode_t m) const -> MODE
-{
- switch (m)
- {
- case RIG_MODE_AM:
- case RIG_MODE_SAM:
- case RIG_MODE_AMS:
- case RIG_MODE_DSB:
- return AM;
-
- case RIG_MODE_CW:
- return CW;
-
- case RIG_MODE_CWR:
- return CW_R;
-
- case RIG_MODE_USB:
- case RIG_MODE_ECSSUSB:
- case RIG_MODE_SAH:
- case RIG_MODE_FAX:
- return USB;
-
- case RIG_MODE_LSB:
- case RIG_MODE_ECSSLSB:
- case RIG_MODE_SAL:
- return LSB;
-
- case RIG_MODE_RTTY:
- return FSK;
-
- case RIG_MODE_RTTYR:
- return FSK_R;
-
- case RIG_MODE_PKTLSB:
- return DIG_L;
-
- case RIG_MODE_PKTUSB:
- return DIG_U;
-
- case RIG_MODE_FM:
- case RIG_MODE_WFM:
- return FM;
-
- case RIG_MODE_PKTFM:
- return DIG_FM;
-
- default:
- return UNK;
- }
-}
-
-rmode_t HamlibTransceiver::impl::map_mode (MODE mode) const
-{
- switch (mode)
- {
- case AM: return RIG_MODE_AM;
- case CW: return RIG_MODE_CW;
- case CW_R: return RIG_MODE_CWR;
- case USB: return RIG_MODE_USB;
- case LSB: return RIG_MODE_LSB;
- case FSK: return RIG_MODE_RTTY;
- case FSK_R: return RIG_MODE_RTTYR;
- case DIG_L: return RIG_MODE_PKTLSB;
- case DIG_U: return RIG_MODE_PKTUSB;
- case FM: return RIG_MODE_FM;
- case DIG_FM: return RIG_MODE_PKTFM;
- default: break;
- }
- return RIG_MODE_USB; // quieten compiler grumble
-}
-
-HamlibTransceiver::HamlibTransceiver (logger_type * logger,
- TransceiverFactory::PTTMethod ptt_type, QString const& ptt_port,
- QObject * parent)
- : PollingTransceiver {logger, 0, parent}
- , m_ {logger}
-{
- if (!m_->rig_)
- {
- throw error {tr ("Hamlib initialisation error")};
- }
- switch (ptt_type)
- {
- case TransceiverFactory::PTT_method_VOX:
- m_->set_conf ("ptt_type", "None");
- break;
-
- case TransceiverFactory::PTT_method_CAT:
- // Use the default PTT_TYPE for the rig (defined in the Hamlib
- // rig back-end capabilities).
- break;
-
- case TransceiverFactory::PTT_method_DTR:
- case TransceiverFactory::PTT_method_RTS:
- if (!ptt_port.isEmpty ())
- {
-#if defined (WIN32)
- m_->set_conf ("ptt_pathname", ("\\\\.\\" + ptt_port).toLatin1 ().data ());
-#else
- m_->set_conf ("ptt_pathname", ptt_port.toLatin1 ().data ());
-#endif
- }
-
- if (TransceiverFactory::PTT_method_DTR == ptt_type)
- {
- m_->set_conf ("ptt_type", "DTR");
- }
- else
- {
- m_->set_conf ("ptt_type", "RTS");
- }
- m_->set_conf ("ptt_share", "1");
- }
-
- // do this late to allow any configuration option to be overriden
- load_user_settings ();
-}
-
-HamlibTransceiver::HamlibTransceiver (logger_type * logger,
- unsigned model_number,
- TransceiverFactory::ParameterPack const& params,
- QObject * parent)
- : PollingTransceiver {logger, params.poll_interval, parent}
- , m_ {logger, model_number, params}
-{
- if (!m_->rig_)
- {
- throw error {tr ("Hamlib initialisation error")};
- }
-
- // m_->rig_->state.obj = this;
-
- if (!m_->is_dummy_)
- {
- // printf("Hamlib open params: power_on=%d power_off=%d ptt_share=%d\n",(params.poll_interval & rig__power) == rig__power,(params.poll_interval & rig__power_off) == rig__power_off,(params.poll_interval & ptt__share) == ptt__share);
- if (params.poll_interval & do__pwr) { do_pwr_ = true; do_pwr2_ = true; do_swr_ = true;}
-
- switch (rig_get_caps_int (m_->model_, RIG_CAPS_PORT_TYPE))
- {
- case RIG_PORT_SERIAL:
- if (!params.serial_port.isEmpty ())
- {
- m_->set_conf ("rig_pathname", params.serial_port.toLatin1 ().data ());
- }
- m_->set_conf ("serial_speed", QByteArray::number (params.baud).data ());
- if (params.data_bits != TransceiverFactory::default_data_bits)
- {
- m_->set_conf ("data_bits", TransceiverFactory::seven_data_bits == params.data_bits ? "7" : "8");
- }
- if (params.stop_bits != TransceiverFactory::default_stop_bits)
- {
- m_->set_conf ("stop_bits", TransceiverFactory::one_stop_bit == params.stop_bits ? "1" : "2");
- }
-
- switch (params.handshake)
- {
- case TransceiverFactory::handshake_none: m_->set_conf ("serial_handshake", "None"); break;
- case TransceiverFactory::handshake_XonXoff: m_->set_conf ("serial_handshake", "XONXOFF"); break;
- case TransceiverFactory::handshake_hardware: m_->set_conf ("serial_handshake", "Hardware"); break;
- default: break;
- }
-
- if (params.force_dtr)
- {
- m_->set_conf ("dtr_state", params.dtr_high ? "ON" : "OFF");
- }
- if (params.force_rts)
- {
- if (TransceiverFactory::handshake_hardware != params.handshake)
- {
- m_->set_conf ("rts_state", params.rts_high ? "ON" : "OFF");
- }
- }
- break;
-
- case RIG_PORT_NETWORK:
- if (!params.network_port.isEmpty ())
- {
- m_->set_conf ("rig_pathname", params.network_port.toLatin1 ().data ());
- }
- break;
-
- case RIG_PORT_USB:
- if (!params.usb_port.isEmpty ())
- {
- m_->set_conf ("rig_pathname", params.usb_port.toLatin1 ().data ());
- }
- break;
-
- default:
- throw error {tr ("Unsupported CAT type")};
- break;
- }
- }
-
- switch (params.ptt_type)
- {
- case TransceiverFactory::PTT_method_VOX:
- m_->set_conf ("ptt_type", "None");
- break;
-
- case TransceiverFactory::PTT_method_CAT:
- // Use the default PTT_TYPE for the rig (defined in the Hamlib
- // rig back-end capabilities).
- break;
-
- case TransceiverFactory::PTT_method_DTR:
- case TransceiverFactory::PTT_method_RTS:
- if (params.ptt_port.size ()
- && params.ptt_port != "None"
- && (m_->is_dummy_
- || RIG_PORT_SERIAL != rig_get_caps_int (m_->model_, RIG_CAPS_PORT_TYPE)
- || params.ptt_port != params.serial_port))
- {
-#if defined (WIN32)
- m_->set_conf ("ptt_pathname", ("\\\\.\\" + params.ptt_port).toLatin1 ().data ());
-#else
- m_->set_conf ("ptt_pathname", params.ptt_port.toLatin1 ().data ());
-#endif
- }
-
- if (TransceiverFactory::PTT_method_DTR == params.ptt_type)
- {
- m_->set_conf ("ptt_type", "DTR");
- }
- else
- {
- m_->set_conf ("ptt_type", "RTS");
- }
- m_->set_conf ("ptt_share", "1");
- }
-
- // Make Icom CAT split commands less glitchy
- m_->set_conf ("no_xchg", "1");
-
- // do this late to allow any configuration option to be overriden
- load_user_settings ();
-
- // would be nice to get events but not supported on Windows and also not on a lot of rigs
- // rig_set_freq_callback (m_->rig_.data (), &frequency_change_callback, this);
-}
-
-HamlibTransceiver::~HamlibTransceiver () = default;
-
-void HamlibTransceiver::load_user_settings ()
-{
- //
- // user defined Hamlib settings
- //
- auto settings_file_name = QStandardPaths::locate (QStandardPaths::AppConfigLocation
- , "hamlib_settings.json");
- if (!settings_file_name.isEmpty ())
- {
- QFile settings_file {settings_file_name};
- qDebug () << "Using Hamlib settings file:" << settings_file_name;
- if (settings_file.open (QFile::ReadOnly))
- {
- QJsonParseError status;
- auto settings_doc = QJsonDocument::fromJson (settings_file.readAll (), &status);
- if (status.error)
- {
- throw error {tr ("Hamlib settings file error: %1 at character offset %2")
- .arg (status.errorString ()).arg (status.offset)};
- }
- qDebug () << "Hamlib settings JSON:" << settings_doc.toJson ();
- if (!settings_doc.isObject ())
- {
- throw error {tr ("Hamlib settings file error: top level must be a JSON object")};
- }
- auto const& settings = settings_doc.object ();
-
- //
- // configuration settings
- //
- auto const& config = settings["config"];
- if (!config.isUndefined ())
- {
- if (!config.isObject ())
- {
- throw error {tr ("Hamlib settings file error: config must be a JSON object")};
- }
- auto const& config_list = config.toObject ();
- for (auto item = config_list.constBegin (); item != config_list.constEnd (); ++item)
- {
- m_->set_conf (item.key ().toLocal8Bit ().constData ()
- , (*item).toVariant ().toString ().toLocal8Bit ().constData ());
- }
- }
- }
- }
-}
-
-int HamlibTransceiver::do_start ()
-{
- CAT_TRACE ("starting: " << rig_get_caps_cptr (m_->model_, RIG_CAPS_MFG_NAME_CPTR)
- << ": " << rig_get_caps_cptr (m_->model_, RIG_CAPS_MODEL_NAME_CPTR));
-
- token_t token = rig_token_lookup (m_->rig_.data (), "client");
- if (RIG_CONF_END != token) // only set if valid for rig model
- {
- rig_set_conf (m_->rig_.data (), token, "WSJTX");
- }
-
- m_->error_check (rig_open (m_->rig_.data ()), tr ("opening connection to rig"));
-
- // reset dynamic state
- m_->one_VFO_ = false;
- m_->reversed_ = false;
- m_->freq_query_works_ = rig_get_function_ptr (m_->model_, RIG_FUNCTION_GET_FREQ);
- m_->mode_query_works_ = rig_get_function_ptr (m_->model_, RIG_FUNCTION_GET_MODE);
- m_->split_query_works_ = rig_get_function_ptr (m_->model_, RIG_FUNCTION_GET_SPLIT_VFO);
- m_->tickle_hamlib_ = false;
- m_->get_vfo_works_ = true;
- m_->set_vfo_works_ = true;
- do_pwr_ &= (!m_->is_dummy_ && rig_get_function_ptr (m_->model_, RIG_FUNCTION_GET_LEVEL) && (rig_get_caps_int (m_->model_, RIG_CAPS_HAS_GET_LEVEL) & RIG_LEVEL_RFPOWER_METER_WATTS) == RIG_LEVEL_RFPOWER_METER_WATTS);
- do_pwr2_ &= (!m_->is_dummy_ && rig_get_function_ptr (m_->model_, RIG_FUNCTION_GET_LEVEL) && (rig_get_caps_int (m_->model_, RIG_CAPS_HAS_GET_LEVEL) & RIG_LEVEL_RFPOWER) == RIG_LEVEL_RFPOWER);
- do_swr_ &= (!m_->is_dummy_ && rig_get_function_ptr (m_->model_, RIG_FUNCTION_GET_LEVEL) && (rig_get_caps_int (m_->model_, RIG_CAPS_HAS_GET_LEVEL) & RIG_LEVEL_SWR) == RIG_LEVEL_SWR);
-
- // the Net rigctl back end promises all functions work but we must
- // test get_vfo as it determines our strategy for Icom rigs
- vfo_t vfo;
- int rc = rig_get_vfo (m_->rig_.data (), &vfo);
- if (-RIG_ENAVAIL == rc || -RIG_ENIMPL == rc)
- {
- m_->get_vfo_works_ = false;
- // determine if the rig uses single VFO addressing i.e. A/B and
- // no get_vfo function
- if (m_->rig_->state.vfo_list & RIG_VFO_B)
- {
- m_->one_VFO_ = true;
- }
- }
- else
- {
- m_->error_check (rc, "testing getting current VFO");
- }
-
- if ((WSJT_RIG_NONE_CAN_SPLIT || !m_->is_dummy_)
- && rig_get_function_ptr (m_->model_, RIG_FUNCTION_SET_SPLIT_VFO)) // if split is possible do some extra setup
- {
- freq_t f1;
- freq_t f2;
- rmode_t m {RIG_MODE_USB};
- rmode_t mb;
- pbwidth_t w {RIG_PASSBAND_NORMAL};
- pbwidth_t wb;
- if (m_->freq_query_works_ && m_->mode_query_works_
- && (!m_->get_vfo_works_ || !rig_get_function_ptr (m_->model_, RIG_FUNCTION_GET_VFO)))
- {
- // Icom have deficient CAT protocol with no way of reading which
- // VFO is selected or if SPLIT is selected so we have to simply
- // assume it is as when we started by setting at open time right
- // here. We also gather/set other initial state.
- m_->error_check (rig_get_freq (m_->rig_.data (), RIG_VFO_CURR, &f1), tr ("getting current frequency"));
- f1 = std::round (f1);
- CAT_TRACE ("current frequency=" << f1);
-
- m_->error_check (rig_get_mode (m_->rig_.data (), RIG_VFO_CURR, &m, &w), tr ("getting current mode"));
- CAT_TRACE ("current mode=" << rig_strrmode (m) << " bw=" << w);
-
- if (!rig_get_function_ptr (m_->model_, RIG_FUNCTION_SET_VFO))
- {
- CAT_TRACE ("rig_vfo_op TOGGLE");
- rc = rig_vfo_op (m_->rig_.data (), RIG_VFO_CURR, RIG_OP_TOGGLE);
- }
- else
- {
- CAT_TRACE ("rig_set_vfo to other VFO");
- rc = rig_set_vfo (m_->rig_.data (), m_->rig_->state.vfo_list & RIG_VFO_B ? RIG_VFO_B : RIG_VFO_SUB);
- if (-RIG_ENAVAIL == rc || -RIG_ENIMPL == rc)
- {
- // if we are talking to netrigctl then toggle VFO op
- // may still work
- CAT_TRACE ("rig_vfo_op TOGGLE");
- rc = rig_vfo_op (m_->rig_.data (), RIG_VFO_CURR, RIG_OP_TOGGLE);
- }
- }
- if (-RIG_ENAVAIL == rc || -RIG_ENIMPL == rc)
- {
- // we are probably dealing with rigctld so we do not
- // have completely accurate rig capabilities
- m_->set_vfo_works_ = false;
- m_->one_VFO_ = false; // we do not need single VFO addressing
- }
- else
- {
- m_->error_check (rc, tr ("exchanging VFOs"));
- }
-
- if (m_->set_vfo_works_)
- {
- // without the above we cannot proceed but we know we
- // are on VFO A and that will not change so there's no
- // need to execute this block
- m_->error_check (rig_get_freq (m_->rig_.data (), RIG_VFO_CURR, &f2), tr ("getting other VFO frequency"));
- f2 = std::round (f2);
- CAT_TRACE ("rig_get_freq other frequency=" << f2);
-
- m_->error_check (rig_get_mode (m_->rig_.data (), RIG_VFO_CURR, &mb, &wb), tr ("getting other VFO mode"));
- CAT_TRACE ("rig_get_mode other mode=" << rig_strrmode (mb) << " bw=" << wb);
-
- update_other_frequency (f2);
-
- if (!rig_get_function_ptr (m_->model_, RIG_FUNCTION_SET_VFO))
- {
- CAT_TRACE ("rig_vfo_op TOGGLE");
- m_->error_check (rig_vfo_op (m_->rig_.data (), RIG_VFO_CURR, RIG_OP_TOGGLE), tr ("exchanging VFOs"));
- }
- else
- {
- CAT_TRACE ("rig_set_vfo A/MAIN");
- m_->error_check (rig_set_vfo (m_->rig_.data (), m_->rig_->state.vfo_list & RIG_VFO_A ? RIG_VFO_A : RIG_VFO_MAIN), tr ("setting current VFO"));
- }
-
- if (f1 != f2 || m != mb || w != wb) // we must have started with MAIN/A
- {
- update_rx_frequency (f1);
- }
- else
- {
- m_->error_check (rig_get_freq (m_->rig_.data (), RIG_VFO_CURR, &f1), tr ("getting frequency"));
- f1 = std::round (f1);
- CAT_TRACE ("rig_get_freq frequency=" << f1);
-
- m_->error_check (rig_get_mode (m_->rig_.data (), RIG_VFO_CURR, &m, &w), tr ("getting mode"));
- CAT_TRACE ("rig_get_mode mode=" << rig_strrmode (m) << " bw=" << w);
-
- update_rx_frequency (f1);
- }
- }
-
- // TRACE_CAT ("rig_set_split_vfo split off");
- // m_->error_check (rig_set_split_vfo (m_->rig_.data (), RIG_VFO_CURR, RIG_SPLIT_OFF, RIG_VFO_CURR), tr ("setting split off"));
- // update_split (false);
- }
- else
- {
- vfo_t v {RIG_VFO_A}; // assume RX always on VFO A/MAIN
-
- if (m_->get_vfo_works_ && rig_get_function_ptr (m_->model_, RIG_FUNCTION_GET_VFO))
- {
- m_->error_check (rig_get_vfo (m_->rig_.data (), &v), tr ("getting current VFO")); // has side effect of establishing current VFO inside hamlib
- CAT_TRACE ("rig_get_vfo current VFO=" << rig_strvfo (v));
- }
-
- m_->reversed_ = RIG_VFO_B == v;
-
- if (m_->mode_query_works_ && !(rig_get_caps_int (m_->model_, RIG_CAPS_TARGETABLE_VFO) & RIG_TARGETABLE_MODE))
- {
- if (RIG_OK == rig_get_mode (m_->rig_.data (), RIG_VFO_CURR, &m, &w))
- {
- CAT_TRACE ("rig_get_mode current mode=" << rig_strrmode (m) << " bw=" << w);
- }
- else
- {
- m_->mode_query_works_ = false;
- // Some rigs (HDSDR) don't have a working way of
- // reporting MODE so we give up on mode queries -
- // sets will still cause an error
- CAT_TRACE ("rig_get_mode can't do on this rig");
- }
- }
- }
- update_mode (m_->map_mode (m));
- }
-
- m_->tickle_hamlib_ = true;
-
- if (m_->is_dummy_ && !m_->ptt_only_ && impl::dummy_frequency_)
- {
- // return to where last dummy instance was
- // TODO: this is going to break down if multiple dummy rigs are used
- rig_set_freq (m_->rig_.data (), RIG_VFO_CURR, impl::dummy_frequency_);
- update_rx_frequency (impl::dummy_frequency_);
- if (RIG_MODE_NONE != impl::dummy_mode_)
- {
- rig_set_mode (m_->rig_.data (), RIG_VFO_CURR, impl::dummy_mode_, RIG_PASSBAND_NOCHANGE);
- update_mode (m_->map_mode (impl::dummy_mode_));
- }
- }
-
-#if HAVE_HAMLIB_CACHING || HAVE_HAMLIB_OLD_CACHING
- // we must disable Hamlib caching because it lies about frequency
- // for less than 1 Hz resolution rigs
- auto orig_cache_timeout = rig_get_cache_timeout_ms (m_->rig_.data (), HAMLIB_CACHE_ALL);
- rig_set_cache_timeout_ms (m_->rig_.data (), HAMLIB_CACHE_ALL, 0);
-#endif
-
- int resolution {0};
- if (m_->freq_query_works_)
- {
- freq_t current_frequency;
- m_->error_check (rig_get_freq (m_->rig_.data (), RIG_VFO_CURR, ¤t_frequency), tr ("getting current VFO frequency"));
- current_frequency = std::round (current_frequency);
- Frequency f = current_frequency;
- if (f && !(f % 10))
- {
- auto test_frequency = f - f % 100 + 55;
- m_->error_check (rig_set_freq (m_->rig_.data (), RIG_VFO_CURR, test_frequency), tr ("setting frequency"));
- freq_t new_frequency;
- m_->error_check (rig_get_freq (m_->rig_.data (), RIG_VFO_CURR, &new_frequency), tr ("getting current VFO frequency"));
- new_frequency = std::round (new_frequency);
- switch (static_cast<Radio::FrequencyDelta> (new_frequency - test_frequency))
- {
- case -5: resolution = -1; break; // 10Hz truncated
- case 5: resolution = 1; break; // 10Hz rounded
- case -15: resolution = -2; break; // 20Hz truncated
- case -55: resolution = -3; break; // 100Hz truncated
- case 45: resolution = 3; break; // 100Hz rounded
- }
- if (1 == resolution) // may be 20Hz rounded
- {
- test_frequency = f - f % 100 + 51;
- m_->error_check (rig_set_freq (m_->rig_.data (), RIG_VFO_CURR, test_frequency), tr ("setting frequency"));
- m_->error_check (rig_get_freq (m_->rig_.data (), RIG_VFO_CURR, &new_frequency), tr ("getting current VFO frequency"));
- if (9 == static_cast<Radio::FrequencyDelta> (new_frequency - test_frequency))
- {
- resolution = 2; // 20Hz rounded
- }
- }
- m_->error_check (rig_set_freq (m_->rig_.data (), RIG_VFO_CURR, current_frequency), tr ("setting frequency"));
- }
- }
- else
- {
- resolution = -1; // best guess
- }
-
-#if HAVE_HAMLIB_CACHING || HAVE_HAMLIB_OLD_CACHING
- // revert Hamlib cache timeout
- rig_set_cache_timeout_ms (m_->rig_.data (), HAMLIB_CACHE_ALL, orig_cache_timeout);
-#endif
-
- do_poll ();
-
- CAT_TRACE ("finished start " << state () << " reversed=" << m_->reversed_ << " resolution=" << resolution);
- return resolution;
-}
-
-void HamlibTransceiver::do_stop ()
-{
- if (m_->is_dummy_ && !m_->ptt_only_)
- {
- rig_get_freq (m_->rig_.data (), RIG_VFO_CURR, &impl::dummy_frequency_);
- impl::dummy_frequency_ = std::round (impl::dummy_frequency_);
- if (m_->mode_query_works_)
- {
- pbwidth_t width;
- rig_get_mode (m_->rig_.data (), RIG_VFO_CURR, &impl::dummy_mode_, &width);
- }
- }
- if (m_->rig_)
- {
- rig_close (m_->rig_.data ());
- }
-
- CAT_TRACE ("state: " << state () << " reversed=" << m_->reversed_);
-}
-
-void HamlibTransceiver::do_frequency (Frequency f, MODE m, bool no_ignore)
-{
- CAT_TRACE ("f: " << f << " mode: " << m << " reversed: " << m_->reversed_);
-
- // only change when receiving or simplex or direct VFO addressing
- // unavailable or forced
- if (!state ().ptt () || !state ().split () || !m_->one_VFO_ || no_ignore)
- {
- // for the 1st time as a band change may cause a recalled mode to be
- // set
- vfo_t target_vfo = RIG_VFO_CURR;
- if (!(m_->rig_->state.vfo_list & RIG_VFO_B))
- {
- target_vfo = RIG_VFO_MAIN; // no VFO A/B so force to Rx on MAIN
- }
- m_->error_check (rig_set_freq (m_->rig_.data (), target_vfo, f), tr ("setting frequency"));
- update_rx_frequency (f);
-
- if (m_->mode_query_works_ && UNK != m)
- {
- rmode_t current_mode;
- pbwidth_t current_width;
- auto new_mode = m_->map_mode (m);
- m_->error_check (rig_get_mode (m_->rig_.data (), target_vfo, ¤t_mode, ¤t_width), tr ("getting current VFO mode"));
- CAT_TRACE ("rig_get_mode mode=" << rig_strrmode (current_mode) << " bw=" << current_width);
-
- if (new_mode != current_mode)
- {
- CAT_TRACE ("rig_set_mode mode=" << rig_strrmode (new_mode));
- m_->error_check (rig_set_mode (m_->rig_.data (), target_vfo, new_mode, RIG_PASSBAND_NOCHANGE), tr ("setting current VFO mode"));
-
- // for the 2nd time because a mode change may have caused a
- // frequency change
- m_->error_check (rig_set_freq (m_->rig_.data (), RIG_VFO_CURR, f), tr ("setting frequency"));
-
- // for the second time because some rigs change mode according
- // to frequency such as the TS-2000 auto mode setting
- CAT_TRACE ("rig_set_mode mode=" << rig_strrmode (new_mode));
- m_->error_check (rig_set_mode (m_->rig_.data (), target_vfo, new_mode, RIG_PASSBAND_NOCHANGE), tr ("setting current VFO mode"));
- }
- // set mode on VFOB too if we are in split
- if (state ().split()) rig_set_mode (m_->rig_.data (), RIG_VFO_B, new_mode, RIG_PASSBAND_NOCHANGE), tr ("setting VFOB mode");
- update_mode (m);
- }
- }
-}
-
-void HamlibTransceiver::do_tx_frequency (Frequency tx, MODE mode, bool no_ignore)
-{
- CAT_TRACE ("txf: " << tx << " reversed: " << m_->reversed_);
-
- if (WSJT_RIG_NONE_CAN_SPLIT || !m_->is_dummy_) // split is meaningless if you can't see it
- {
- auto split = tx ? RIG_SPLIT_ON : RIG_SPLIT_OFF;
- auto vfos = m_->get_vfos (tx);
- // auto rx_vfo = std::get<0> (vfos); // or use RIG_VFO_CURR
- auto tx_vfo = std::get<1> (vfos);
-
- if (tx)
- {
- // Doing set split for the 1st of two times, this one
- // ensures that the internal Hamlib state is correct
- // otherwise rig_set_split_freq() will target the wrong VFO
- // on some rigs
-
- if (m_->tickle_hamlib_)
- {
- // This potentially causes issues with the Elecraft K3
- // which will block setting split mode when it deems
- // cross mode split operation not possible. There's not
- // much we can do since the Hamlib Library needs this
- // call at least once to establish the Tx VFO. Best we
- // can do is only do this once per session.
- CAT_TRACE ("rig_set_split_vfo split=" << split);
- auto rc = rig_set_split_vfo (m_->rig_.data (), RIG_VFO_CURR, split, tx_vfo);
- if (tx || (-RIG_ENAVAIL != rc && -RIG_ENIMPL != rc))
- {
- // On rigs that can't have split controlled only throw an
- // exception when an error other than command not accepted
- // is returned when trying to leave split mode. This allows
- // fake split mode and non-split mode to work without error
- // on such rigs without having to know anything about the
- // specific rig.
- m_->error_check (rc, tr ("setting/unsetting split mode"));
- }
- m_->tickle_hamlib_ = false;
- update_split (tx);
- }
-
- // just change current when transmitting with single VFO
- // addressing
- if (state ().ptt () && m_->one_VFO_)
- {
- CAT_TRACE ("rig_set_split_vfo split=" << split);
- m_->error_check (rig_set_split_vfo (m_->rig_.data (), RIG_VFO_CURR, split, tx_vfo), tr ("setting split mode"));
-
- m_->error_check (rig_set_freq (m_->rig_.data (), RIG_VFO_CURR, tx), tr ("setting frequency"));
-
- if (UNK != mode && m_->mode_query_works_)
- {
- rmode_t current_mode;
- pbwidth_t current_width;
- auto new_mode = m_->map_mode (mode);
- m_->error_check (rig_get_mode (m_->rig_.data (), RIG_VFO_CURR, ¤t_mode, ¤t_width), tr ("getting current VFO mode"));
- CAT_TRACE ("rig_get_mode mode=" << rig_strrmode (current_mode) << " bw=" << current_width);
-
- if (new_mode != current_mode)
- {
- CAT_TRACE ("rig_set_mode mode=" << rig_strrmode (new_mode));
- m_->error_check (rig_set_mode (m_->rig_.data (), RIG_VFO_CURR, new_mode, RIG_PASSBAND_NOCHANGE), tr ("setting current VFO mode"));
- }
- }
- update_other_frequency (tx);
- }
- else if (!m_->one_VFO_ || no_ignore) // if not single VFO addressing and not forced
- {
- hamlib_tx_vfo_fixup fixup (m_->rig_.data (), tx_vfo);
- if (UNK != mode)
- {
- auto new_mode = m_->map_mode (mode);
- CAT_TRACE ("rig_set_split_freq_mode freq=" << tx
- << " mode = " << rig_strrmode (new_mode));
- m_->error_check (rig_set_split_freq_mode (m_->rig_.data (), RIG_VFO_CURR, tx, new_mode, RIG_PASSBAND_NOCHANGE), tr ("setting split TX frequency and mode"));
- }
- else
- {
- CAT_TRACE ("rig_set_split_freq freq=" << tx);
- m_->error_check (rig_set_split_freq (m_->rig_.data (), RIG_VFO_CURR, tx), tr ("setting split TX frequency"));
- }
- // Enable split last since some rigs (Kenwood for one) come out
- // of split when you switch RX VFO (to set split mode above for
- // example). Also the Elecraft K3 will refuse to go to split
- // with certain VFO A/B mode combinations.
- CAT_TRACE ("rig_set_split_vfo split=" << split);
- m_->error_check (rig_set_split_vfo (m_->rig_.data (), RIG_VFO_CURR, split, tx_vfo), tr ("setting split mode"));
- update_other_frequency (tx);
- update_split (tx);
- }
- }
- else
- {
- // Disable split
- CAT_TRACE ("rig_set_split_vfo split=" << split);
- auto rc = rig_set_split_vfo (m_->rig_.data (), RIG_VFO_CURR, split, tx_vfo);
- if (tx || (-RIG_ENAVAIL != rc && -RIG_ENIMPL != rc))
- {
- // On rigs that can't have split controlled only throw an
- // exception when an error other than command not accepted
- // is returned when trying to leave split mode. This allows
- // fake split mode and non-split mode to work without error
- // on such rigs without having to know anything about the
- // specific rig.
- m_->error_check (rc, tr ("setting/unsetting split mode"));
- }
- update_other_frequency (tx);
- update_split (tx);
- }
- }
-}
-
-void HamlibTransceiver::do_mode (MODE mode)
-{
- CAT_TRACE (mode);
-
- auto vfos = m_->get_vfos (state ().split ());
- // auto rx_vfo = std::get<0> (vfos);
- auto tx_vfo = std::get<1> (vfos);
-
- rmode_t current_mode;
- pbwidth_t current_width;
- auto new_mode = m_->map_mode (mode);
-
- vfo_t target_vfo = RIG_VFO_CURR;
- if (!(m_->rig_->state.vfo_list & RIG_VFO_B))
- {
- target_vfo = RIG_VFO_MAIN; // no VFO A/B so force to Rx on MAIN
- }
-
- // only change when receiving or simplex if direct VFO addressing unavailable
- if (!(state ().ptt () && state ().split () && m_->one_VFO_))
- {
- m_->error_check (rig_get_mode (m_->rig_.data (), target_vfo, ¤t_mode, ¤t_width), tr ("getting current VFO mode"));
- CAT_TRACE ("rig_get_mode mode=" << rig_strrmode (current_mode) << " bw=" << current_width);
-
- if (new_mode != current_mode)
- {
- CAT_TRACE ("rig_set_mode mode=" << rig_strrmode (new_mode));
- m_->error_check (rig_set_mode (m_->rig_.data (), target_vfo, new_mode, RIG_PASSBAND_NOCHANGE), tr ("setting current VFO mode"));
- }
- }
-
- // just change current when transmitting split with one VFO mode
- if (state ().ptt () && state ().split () && m_->one_VFO_)
- {
- m_->error_check (rig_get_mode (m_->rig_.data (), RIG_VFO_CURR, ¤t_mode, ¤t_width), tr ("getting current VFO mode"));
- CAT_TRACE ("rig_get_mode mode=" << rig_strrmode (current_mode) << " bw=" << current_width);
-
- if (new_mode != current_mode)
- {
- CAT_TRACE ("rig_set_mode mode=" << rig_strrmode (new_mode));
- m_->error_check (rig_set_mode (m_->rig_.data (), RIG_VFO_CURR, new_mode, RIG_PASSBAND_NOCHANGE), tr ("setting current VFO mode"));
- }
- }
- else if (state ().split () && !m_->one_VFO_)
- {
- m_->error_check (rig_get_split_mode (m_->rig_.data (), RIG_VFO_CURR, ¤t_mode, ¤t_width), tr ("getting split TX VFO mode"));
- CAT_TRACE ("rig_get_split_mode mode=" << rig_strrmode (current_mode) << " bw=" << current_width);
-
- if (new_mode != current_mode)
- {
- CAT_TRACE ("rig_set_split_mode mode=" << rig_strrmode (new_mode));
- hamlib_tx_vfo_fixup fixup (m_->rig_.data (), tx_vfo);
- m_->error_check (rig_set_split_mode (m_->rig_.data (), RIG_VFO_CURR, new_mode, RIG_PASSBAND_NOCHANGE), tr ("setting split TX VFO mode"));
- }
- }
- update_mode (mode);
-}
-
-void HamlibTransceiver::do_poll ()
-{
- freq_t f;
- rmode_t m;
- pbwidth_t w;
- split_t s;
-
- if (m_->get_vfo_works_ && rig_get_function_ptr (m_->model_, RIG_FUNCTION_GET_VFO))
- {
- vfo_t v;
- m_->error_check (rig_get_vfo (m_->rig_.data (), &v), tr ("getting current VFO")); // has side effect of establishing current VFO inside hamlib
- CAT_TRACE ("VFO=" << rig_strvfo (v));
- m_->reversed_ = RIG_VFO_B == v;
- }
-
- if ((WSJT_RIG_NONE_CAN_SPLIT || !m_->is_dummy_)
- && rig_get_function_ptr (m_->model_, RIG_FUNCTION_GET_SPLIT_VFO) && m_->split_query_works_)
- {
- vfo_t v {RIG_VFO_NONE}; // so we can tell if it doesn't get updated :(
- auto rc = rig_get_split_vfo (m_->rig_.data (), RIG_VFO_CURR, &s, &v);
- if (-RIG_OK == rc && RIG_SPLIT_ON == s)
- {
- CAT_TRACE ("rig_get_split_vfo split=" << s << " VFO=" << rig_strvfo (v));
- update_split (true);
- // if (RIG_VFO_A == v)
- // {
- // m_->reversed_ = true; // not sure if this helps us here
- // }
- }
- else if (-RIG_OK == rc) // not split
- {
- CAT_TRACE ("rig_get_split_vfo split=" << s << " VFO=" << rig_strvfo (v));
- update_split (false);
- }
- else
- {
- // Some rigs (Icom) don't have a way of reporting SPLIT
- // mode
- CAT_TRACE ("rig_get_split_vfo can't do on this rig");
- // just report how we see it based on prior commands
- m_->split_query_works_ = false;
- }
- }
-
- if (m_->freq_query_works_)
- {
- // only read if possible and when receiving or simplex
- if (!state ().ptt () || !state ().split ())
- {
- m_->error_check (rig_get_freq (m_->rig_.data (), RIG_VFO_CURR, &f), tr ("getting current VFO frequency"));
- f = std::round (f);
- CAT_TRACE ("rig_get_freq frequency=" << Radio::frequency (f));
- update_rx_frequency (f);
- }
-
- if ((WSJT_RIG_NONE_CAN_SPLIT || !m_->is_dummy_)
- && state ().split ()
- && (rig_get_caps_int (m_->model_, RIG_CAPS_TARGETABLE_VFO) & RIG_TARGETABLE_FREQ)
- && !m_->one_VFO_)
- {
- // only read "other" VFO if in split, this allows rigs like
- // FlexRadio to work in Kenwood TS-2000 mode despite them
- // not having a FB; command
-
- // we can only probe current VFO unless rig supports reading
- // the other one directly because we can't glitch the Rx
- m_->error_check (rig_get_freq (m_->rig_.data ()
- , m_->reversed_
- ? (m_->rig_->state.vfo_list & RIG_VFO_A ? RIG_VFO_A : RIG_VFO_MAIN)
- : (m_->rig_->state.vfo_list & RIG_VFO_B ? RIG_VFO_B : RIG_VFO_SUB)
- , &f), tr ("getting other VFO frequency"));
- f = std::round (f);
- CAT_TRACE ("rig_get_freq other VFO=" << f);
- update_other_frequency (f);
- }
- }
-
- // only read when receiving or simplex if direct VFO addressing unavailable
- if ((!state ().ptt () || !state ().split ())
- && m_->mode_query_works_)
- {
- // We have to ignore errors here because Yaesu FTdx... rigs can
- // report the wrong mode when transmitting split with different
- // modes per VFO. This is unfortunate because that is exactly
- // what you need to do to get 4kHz Rx b.w and modulation into
- // the rig through the data socket or USB. I.e. USB for Rx and
- // DATA-USB for Tx.
- auto rc = rig_get_mode (m_->rig_.data (), RIG_VFO_CURR, &m, &w);
- if (RIG_OK == rc)
- {
- CAT_TRACE ("rig_get_mode mode=" << rig_strrmode (m) << " bw=" << w);
- update_mode (m_->map_mode (m));
- }
- else
- {
- CAT_TRACE ("rig_get_mode mode failed with rc: " << rc << " ignoring");
- }
- }
-
- if (RIG_PTT_NONE != m_->rig_->state.pttport.type.ptt && rig_get_function_ptr (m_->model_, RIG_FUNCTION_GET_PTT))
- {
- ptt_t p;
- auto rc = rig_get_ptt (m_->rig_.data (), RIG_VFO_CURR, &p);
- if (-RIG_ENAVAIL != rc && -RIG_ENIMPL != rc) // may fail if
- // Net rig ctl and target doesn't
- // support command
- {
- m_->error_check (rc, tr ("getting PTT state"));
- CAT_TRACE ("rig_get_ptt PTT=" << p);
- update_PTT (!(RIG_PTT_OFF == p));
- }
- }
-
- if (ptt_on_) {
- // update PWR and SWR
- value_t strength;
- int rc;
- if (do_swr_) {
- rc = rig_get_level (m_->rig_.data (), RIG_VFO_CURR, RIG_LEVEL_SWR, &strength);
- if (RIG_OK == rc && ptt_on_) {
- // printf ("SWR %.3f\n",strength.f);
- if (strength.f >= 1.000)
- {
- update_swr (strength.f*100);
- }
- else
- {
- update_swr (0);
- }
- } else {
- CAT_TRACE ("rig_get_level RIG_LEVEL_SWR failed with rc:" << rc << "ignoring");
- update_swr (0);
- }
- }
- if (do_pwr_) {
- rc = rig_get_level (m_->rig_.data (), RIG_VFO_CURR, RIG_LEVEL_RFPOWER_METER_WATTS, &strength);
- if (RIG_OK == rc) {
- update_power (strength.f*1000);
- } else {
- CAT_TRACE ("rig_get_level RFPOWER_METER_WATTS failed with rc:" << rc << "ignoring");
- update_power (0);
- }
- } else if (do_pwr2_) {
- rc = rig_get_level (m_->rig_.data (), RIG_VFO_CURR, RIG_LEVEL_RFPOWER, &strength);
- if (RIG_OK == rc) {
- unsigned int mwpower;
- rc = rig_power2mW(m_->rig_.data (),&mwpower,strength.f,f,m);
- if (RIG_OK != rc) {
- CAT_TRACE ("rig_power2mW failed with rc:" << rc << "ignoring");
- mwpower=0;
- }
- update_power (mwpower);
- // printf ("POWER %.3f %.1f\n",strength.f,mwpower / 1000.);
- } else {
- CAT_TRACE ("rig_get_level RFPOWER failed with rc:" << rc << "ignoring");
- update_power (0);
- }
- } else update_power (0);
- } else {
- update_power (0);
- update_swr (0);
- }
-}
-
-void HamlibTransceiver::do_ptt (bool on)
-{
- CAT_TRACE ("PTT: " << on << " " << state () << " reversed=" << m_->reversed_);
- if (on)
- {
- if (RIG_PTT_NONE != m_->rig_->state.pttport.type.ptt)
- {
- ptt_on_ = true;
- CAT_TRACE ("rig_set_ptt PTT=true");
- auto ptt_type = rig_get_caps_int (m_->model_, RIG_CAPS_PTT_TYPE);
- m_->error_check (rig_set_ptt (m_->rig_.data (), RIG_VFO_CURR
- , RIG_PTT_RIG_MICDATA == ptt_type && m_->back_ptt_port_
- ? RIG_PTT_ON_DATA : RIG_PTT_ON), tr ("setting PTT on"));
- }
- }
- else
- {
- if (RIG_PTT_NONE != m_->rig_->state.pttport.type.ptt)
- {
- ptt_on_ = false;
- CAT_TRACE ("rig_set_ptt PTT=false");
- m_->error_check (rig_set_ptt (m_->rig_.data (), RIG_VFO_CURR, RIG_PTT_OFF), tr ("setting PTT off"));
- }
- }
-
- update_PTT (on);
-}
-
-// pass in false if any post_action is needed for a rig -- don't know of any as of 2024-04-14
-void HamlibTransceiver::do_tune (bool on)
-{
- CAT_TRACE ("Tune: " << on << " " << state ());
- if (on)
- {
- if (RIG_PTT_NONE != m_->rig_->state.pttport.type.ptt)
- {
- update_PTT (true); // we'll change the PTT button while we do this
- CAT_TRACE ("rig_vfo_opt RIG_VFO_OP_TUNE=" << on);
- // ptt button will stay lit if error message is displaye
- m_->error_check(rig_vfo_op (m_->rig_.data (), RIG_VFO_CURR, RIG_OP_TUNE), "turning TUNE on");
- update_PTT (false);
- }
- }
-#if 0
- else // do we need to be able to turn PTT off on anybody?
- {
- if (RIG_PTT_NONE != m_->rig_->state.pttport.type.ptt)
- {
- ptt_on_ = false;
- CAT_TRACE ("rig_set_ptt PTT=false");
- m_->error_check (rig_set_ptt (m_->rig_.data (), RIG_VFO_CURR, RIG_PTT_OFF), tr ("setting PTT off"));
- }
- }
-#endif
-}
+#include "HamlibTransceiver.hpp" + +#include <cstring> +#include <cmath> +#include <tuple> +#include <QByteArray> +#include <QString> +#include <QStandardPaths> +#include <QFile> +#include <QTimer> +#include <QJsonDocument> +#include <QJsonObject> +#include <QJsonValue> +#include <QDebug> +#include <hamlib/rig.h> +#include "pimpl_impl.hpp" +#include "moc_HamlibTransceiver.cpp" + +#if HAVE_HAMLIB_OLD_CACHING +#define HAMLIB_CACHE_ALL CACHE_ALL +#endif + +namespace +{ + // Unfortunately bandwidth is conflated with mode, this is probably + // because Icom do the same. So we have to care about bandwidth if + // we want to set mode otherwise we will end up setting unwanted + // bandwidths every time we change mode. The best we can do via the + // Hamlib API is to request the normal option for the mode and hope + // that an appropriate filter is selected. Also ensure that mode is + // only set is absolutely necessary. On Icoms (and probably others) + // the filter is selected by number without checking the actual BW + // so unless the "normal" defaults are set on the rig we won't get + // desirable results. + // + // As an ultimate workaround make sure the user always has the + // option to skip mode setting altogether. + + // callback function that receives transceiver capabilities from the + // hamlib libraries + int register_callback (rig_model_t rig_model, void * callback_data) + { + TransceiverFactory::Transceivers * rigs = reinterpret_cast<TransceiverFactory::Transceivers *> (callback_data); + // We can't use this one because it is only for testing Hamlib and + // would confuse users, possibly causing operating on the wrong + // frequency! +#ifdef RIG_MODEL_DUMMY_NOVFO + if (RIG_MODEL_DUMMY_NOVFO == rig_model) + { + return 1; + } +#endif + + QString key; + if (RIG_MODEL_DUMMY == rig_model) + { + key = TransceiverFactory::basic_transceiver_name_; + } + else + { + key = QString::fromLatin1 (rig_get_caps_cptr (rig_model, RIG_CAPS_MFG_NAME_CPTR)).trimmed () + + ' '+ QString::fromLatin1 (rig_get_caps_cptr (rig_model, RIG_CAPS_MODEL_NAME_CPTR)).trimmed () + // + ' '+ QString::fromLatin1 (rig_get_caps_cptr (rig_model, RIG_CAPS_VERSION)).trimmed () + // + " (" + QString::fromLatin1 (rig_get_caps_cptr (rig_model, RIG_CAPS_STATUS)).trimmed () + ')' + ; + } + + auto port_type = TransceiverFactory::Capabilities::none; + switch(rig_get_caps_int (rig_model, RIG_CAPS_PORT_TYPE)) + { + case RIG_PORT_SERIAL: + port_type = TransceiverFactory::Capabilities::serial; + break; + + case RIG_PORT_NETWORK: + port_type = TransceiverFactory::Capabilities::network; + break; + + case RIG_PORT_USB: + port_type = TransceiverFactory::Capabilities::usb; + break; + + default: break; + } + auto ptt_type = rig_get_caps_int (rig_model, RIG_CAPS_PTT_TYPE); + (*rigs)[key] = TransceiverFactory::Capabilities (rig_model + , port_type + , RIG_MODEL_DUMMY != rig_model + && (RIG_PTT_RIG == ptt_type + || RIG_PTT_RIG_MICDATA == ptt_type) + , RIG_PTT_RIG_MICDATA == ptt_type); + + return 1; // keep them coming + } + + int unregister_callback (rig_model_t rig_model, void *) + { + rig_unregister (rig_get_caps_int (rig_model, RIG_CAPS_RIG_MODEL)); + return 1; // keep them coming + } + + // int frequency_change_callback (RIG * /* rig */, vfo_t vfo, freq_t f, rig_ptr_t arg) + // { + // (void)vfo; // unused in release build + + // Q_ASSERT (vfo == RIG_VFO_CURR); // G4WJS: at the time of writing only current VFO is signalled by hamlib + + // HamlibTransceiver * transceiver (reinterpret_cast<HamlibTransceiver *> (arg)); + // Q_EMIT transceiver->frequency_change (f, Transceiver::A); + // return RIG_OK; + // } + + class hamlib_tx_vfo_fixup final + { + public: + hamlib_tx_vfo_fixup (RIG * rig, vfo_t tx_vfo) + : rig_ {rig} + { + original_vfo_ = rig_->state.tx_vfo; + rig_->state.tx_vfo = tx_vfo; + } + + ~hamlib_tx_vfo_fixup () + { + rig_->state.tx_vfo = original_vfo_; + } + + private: + RIG * rig_; + vfo_t original_vfo_; + }; +} + +class HamlibTransceiver::impl final +{ +public: + impl (HamlibTransceiver::logger_type * logger) + : logger_ {logger} + , model_ {RIG_MODEL_DUMMY} + , rig_ {rig_init (model_)} + , ptt_only_ {true} + , back_ptt_port_ {false} + , one_VFO_ {false} + , is_dummy_ {true} + , reversed_ {false} + , freq_query_works_ {true} + , mode_query_works_ {true} + , split_query_works_ {true} + , tickle_hamlib_ {false} + , get_vfo_works_ {true} + , set_vfo_works_ {true} + , do_snr_ {false} + , do_pwr_ {false} + , do_pwr2_ {false} + , do_swr_ {false} + { + } + + impl (HamlibTransceiver::logger_type * logger, unsigned model_number + , TransceiverFactory::ParameterPack const& params) + : logger_ {logger} + , model_ {model_number} + , rig_ {rig_init (model_)} + , ptt_only_ {false} + , back_ptt_port_ {TransceiverFactory::TX_audio_source_rear == params.audio_source} + , one_VFO_ {false} + , is_dummy_ {RIG_MODEL_DUMMY == model_} + , reversed_ {false} + , freq_query_works_ {rig_ && rig_get_function_ptr (model_, RIG_FUNCTION_GET_FREQ)} + , mode_query_works_ {rig_ && rig_get_function_ptr (model_, RIG_FUNCTION_GET_MODE)} + , split_query_works_ {rig_ && rig_get_function_ptr (model_, RIG_FUNCTION_GET_SPLIT_VFO)} + , tickle_hamlib_ {false} + , get_vfo_works_ {true} + , set_vfo_works_ {true} + , do_snr_ {false} + , do_pwr_ {false} + , do_pwr2_ {false} + , do_swr_ {false} + { + } + + HamlibTransceiver::logger_type& logger () const + { + return *logger_; + } + + void error_check (int ret_code, QString const& doing) const; + void set_conf (char const * item, char const * value); + QByteArray get_conf (char const * item); + Transceiver::MODE map_mode (rmode_t) const; + rmode_t map_mode (Transceiver::MODE mode) const; + std::tuple<vfo_t, vfo_t> get_vfos (bool for_split) const; + + HamlibTransceiver::logger_type mutable * logger_; + unsigned model_; + struct RIGDeleter {static void cleanup (RIG *);}; + QScopedPointer<RIG, RIGDeleter> rig_; + + bool ptt_only_; // we can use a dummy device for PTT + bool back_ptt_port_; + bool one_VFO_; + bool is_dummy_; + + // these are saved on destruction so we can start new instances + // where the last one left off + static freq_t dummy_frequency_; + static rmode_t dummy_mode_; + + bool mutable reversed_; + + bool freq_query_works_; + bool mode_query_works_; + bool split_query_works_; + bool tickle_hamlib_; // Hamlib requires a + // rig_set_split_vfo() call to + // establish the Tx VFO + bool get_vfo_works_; // Net rigctl promises what it can't deliver + bool set_vfo_works_; // More rigctl promises which it can't deliver + bool do_snr_; + bool do_pwr_; + bool do_pwr2_; + bool do_swr_; + + static int debug_callback (enum rig_debug_level_e level, rig_ptr_t arg, char const * format, va_list ap); +}; + +freq_t HamlibTransceiver::impl::dummy_frequency_; +rmode_t HamlibTransceiver::impl::dummy_mode_ {RIG_MODE_NONE}; + + // reroute Hamlib diagnostic messages to Qt +int HamlibTransceiver::impl::debug_callback (enum rig_debug_level_e level, rig_ptr_t arg, char const * format, va_list ap) +{ + auto logger = reinterpret_cast<logger_type *> (arg); + auto message = QString::vasprintf (format, ap); + va_end (ap); + auto severity = boost::log::trivial::trace; + switch (level) + { + case RIG_DEBUG_BUG: severity = boost::log::trivial::fatal; break; + case RIG_DEBUG_ERR: severity = boost::log::trivial::error; break; + case RIG_DEBUG_WARN: severity = boost::log::trivial::warning; break; + case RIG_DEBUG_VERBOSE: severity = boost::log::trivial::debug; break; + case RIG_DEBUG_TRACE: severity = boost::log::trivial::trace; break; + default: break; + }; + if (level != RIG_DEBUG_NONE) // no idea what level NONE means so + // ignore it + { + BOOST_LOG_SEV (*logger, severity) << message.trimmed ().toStdString (); + } + return 0; +} + +void HamlibTransceiver::register_transceivers (logger_type * logger, + TransceiverFactory::Transceivers * registry) +{ + rig_set_debug_callback (impl::debug_callback, logger); + rig_set_debug (RIG_DEBUG_TRACE); + BOOST_LOG_SEV (*logger, boost::log::trivial::info) << "Hamlib version: " << rig_version (); + rig_load_all_backends (); + rig_list_foreach_model (register_callback, registry); +} + +void HamlibTransceiver::unregister_transceivers () +{ + rig_list_foreach_model (unregister_callback, nullptr); +} + +void HamlibTransceiver::impl::RIGDeleter::cleanup (RIG * rig) +{ + if (rig) + { + rig_cleanup (rig); + } +} + +void HamlibTransceiver::impl::error_check (int ret_code, QString const& doing) const +{ + if (RIG_OK != ret_code) + { + CAT_ERROR ("error: " << rigerror (ret_code)); + throw error {tr ("Hamlib error: %1 while %2").arg (rigerror (ret_code)).arg (doing)}; + } +} + +std::tuple<vfo_t, vfo_t> HamlibTransceiver::impl::get_vfos (bool for_split) const +{ + if (get_vfo_works_ && rig_get_function_ptr (model_, RIG_FUNCTION_GET_VFO)) + { + vfo_t v; + error_check (rig_get_vfo (rig_.data (), &v), tr ("getting current VFO")); // has side effect of establishing current VFO inside hamlib + CAT_TRACE ("rig_get_vfo VFO=" << rig_strvfo (v)); + + reversed_ = RIG_VFO_B == v; + } + else if (!for_split && set_vfo_works_ && rig_get_function_ptr (model_, RIG_FUNCTION_SET_VFO) && rig_get_function_ptr (model_, RIG_FUNCTION_SET_SPLIT_VFO)) + { + // use VFO A/MAIN for main frequency and B/SUB for Tx + // frequency if split since these type of radios can only + // support this way around + + CAT_TRACE ("rig_set_vfo VFO=A/MAIN"); + error_check (rig_set_vfo (rig_.data (), rig_->state.vfo_list & RIG_VFO_A ? RIG_VFO_A : RIG_VFO_MAIN), tr ("setting current VFO")); + } + // else only toggle available but VFOs should be substitutable + + auto rx_vfo = rig_->state.vfo_list & RIG_VFO_A ? RIG_VFO_A : RIG_VFO_MAIN; + auto tx_vfo = (WSJT_RIG_NONE_CAN_SPLIT || !is_dummy_) && for_split + ? (rig_->state.vfo_list & RIG_VFO_B ? RIG_VFO_B : RIG_VFO_SUB) + : rx_vfo; + if (reversed_) + { + CAT_TRACE ("reversing VFOs"); + std::swap (rx_vfo, tx_vfo); + } + + CAT_TRACE ("RX VFO=" << rig_strvfo (rx_vfo) << " TX VFO=" << rig_strvfo (tx_vfo)); + return std::make_tuple (rx_vfo, tx_vfo); +} + +void HamlibTransceiver::impl::set_conf (char const * item, char const * value) +{ + token_t token = rig_token_lookup (rig_.data (), item); + if (RIG_CONF_END != token) // only set if valid for rig model + { + error_check (rig_set_conf (rig_.data (), token, value), tr ("setting a configuration item")); + } +} + +QByteArray HamlibTransceiver::impl::get_conf (char const * item) +{ + token_t token = rig_token_lookup (rig_.data (), item); + QByteArray value {128, '\0'}; + if (RIG_CONF_END != token) // only get if valid for rig model + { + error_check (rig_get_conf2 (rig_.data (), token, value.data (),value.length()), tr ("getting a configuration item")); //changed to conf2, added parameter for buffer length + } + return value; +} + +auto HamlibTransceiver::impl::map_mode (rmode_t m) const -> MODE +{ + switch (m) + { + case RIG_MODE_AM: + case RIG_MODE_SAM: + case RIG_MODE_AMS: + case RIG_MODE_DSB: + return AM; + + case RIG_MODE_CW: + return CW; + + case RIG_MODE_CWR: + return CW_R; + + case RIG_MODE_USB: + case RIG_MODE_ECSSUSB: + case RIG_MODE_SAH: + case RIG_MODE_FAX: + return USB; + + case RIG_MODE_LSB: + case RIG_MODE_ECSSLSB: + case RIG_MODE_SAL: + return LSB; + + case RIG_MODE_RTTY: + return FSK; + + case RIG_MODE_RTTYR: + return FSK_R; + + case RIG_MODE_PKTLSB: + return DIG_L; + + case RIG_MODE_PKTUSB: + return DIG_U; + + case RIG_MODE_FM: + case RIG_MODE_WFM: + return FM; + + case RIG_MODE_PKTFM: + return DIG_FM; + + default: + return UNK; + } +} + +rmode_t HamlibTransceiver::impl::map_mode (MODE mode) const +{ + switch (mode) + { + case AM: return RIG_MODE_AM; + case CW: return RIG_MODE_CW; + case CW_R: return RIG_MODE_CWR; + case USB: return RIG_MODE_USB; + case LSB: return RIG_MODE_LSB; + case FSK: return RIG_MODE_RTTY; + case FSK_R: return RIG_MODE_RTTYR; + case DIG_L: return RIG_MODE_PKTLSB; + case DIG_U: return RIG_MODE_PKTUSB; + case FM: return RIG_MODE_FM; + case DIG_FM: return RIG_MODE_PKTFM; + default: break; + } + return RIG_MODE_USB; // quieten compiler grumble +} + +HamlibTransceiver::HamlibTransceiver (logger_type * logger, + TransceiverFactory::PTTMethod ptt_type, QString const& ptt_port, + QObject * parent) + : PollingTransceiver {logger, 0, parent} + , m_ {logger} +{ + if (!m_->rig_) + { + throw error {tr ("Hamlib initialisation error")}; + } + switch (ptt_type) + { + case TransceiverFactory::PTT_method_VOX: + m_->set_conf ("ptt_type", "None"); + break; + + case TransceiverFactory::PTT_method_CAT: + // Use the default PTT_TYPE for the rig (defined in the Hamlib + // rig back-end capabilities). + break; + + case TransceiverFactory::PTT_method_DTR: + case TransceiverFactory::PTT_method_RTS: + if (!ptt_port.isEmpty ()) + { +#if defined (WIN32) + m_->set_conf ("ptt_pathname", ("\\\\.\\" + ptt_port).toLatin1 ().data ()); +#else + m_->set_conf ("ptt_pathname", ptt_port.toLatin1 ().data ()); +#endif + } + + if (TransceiverFactory::PTT_method_DTR == ptt_type) + { + m_->set_conf ("ptt_type", "DTR"); + } + else + { + m_->set_conf ("ptt_type", "RTS"); + } + m_->set_conf ("ptt_share", "1"); + } + + // do this late to allow any configuration option to be overriden + load_user_settings (); +} + +HamlibTransceiver::HamlibTransceiver (logger_type * logger, + unsigned model_number, + TransceiverFactory::ParameterPack const& params, + QObject * parent) + : PollingTransceiver {logger, params.poll_interval, parent} + , m_ {logger, model_number, params} +{ + if (!m_->rig_) + { + throw error {tr ("Hamlib initialisation error")}; + } + + // m_->rig_->state.obj = this; + + if (!m_->is_dummy_) + { + // printf("Hamlib open params: power_on=%d power_off=%d ptt_share=%d\n",(params.poll_interval & rig__power) == rig__power,(params.poll_interval & rig__power_off) == rig__power_off,(params.poll_interval & ptt__share) == ptt__share); + if (params.poll_interval & do__pwr) { do_pwr_ = true; do_pwr2_ = true; do_swr_ = true;} + + switch (rig_get_caps_int (m_->model_, RIG_CAPS_PORT_TYPE)) + { + case RIG_PORT_SERIAL: + if (!params.serial_port.isEmpty ()) + { + m_->set_conf ("rig_pathname", params.serial_port.toLatin1 ().data ()); + } + m_->set_conf ("serial_speed", QByteArray::number (params.baud).data ()); + if (params.data_bits != TransceiverFactory::default_data_bits) + { + m_->set_conf ("data_bits", TransceiverFactory::seven_data_bits == params.data_bits ? "7" : "8"); + } + if (params.stop_bits != TransceiverFactory::default_stop_bits) + { + m_->set_conf ("stop_bits", TransceiverFactory::one_stop_bit == params.stop_bits ? "1" : "2"); + } + + switch (params.handshake) + { + case TransceiverFactory::handshake_none: m_->set_conf ("serial_handshake", "None"); break; + case TransceiverFactory::handshake_XonXoff: m_->set_conf ("serial_handshake", "XONXOFF"); break; + case TransceiverFactory::handshake_hardware: m_->set_conf ("serial_handshake", "Hardware"); break; + default: break; + } + + if (params.force_dtr) + { + m_->set_conf ("dtr_state", params.dtr_high ? "ON" : "OFF"); + } + if (params.force_rts) + { + if (TransceiverFactory::handshake_hardware != params.handshake) + { + m_->set_conf ("rts_state", params.rts_high ? "ON" : "OFF"); + } + } + break; + + case RIG_PORT_NETWORK: + if (!params.network_port.isEmpty ()) + { + m_->set_conf ("rig_pathname", params.network_port.toLatin1 ().data ()); + } + break; + + case RIG_PORT_USB: + if (!params.usb_port.isEmpty ()) + { + m_->set_conf ("rig_pathname", params.usb_port.toLatin1 ().data ()); + } + break; + + default: + throw error {tr ("Unsupported CAT type")}; + break; + } + } + + switch (params.ptt_type) + { + case TransceiverFactory::PTT_method_VOX: + m_->set_conf ("ptt_type", "None"); + break; + + case TransceiverFactory::PTT_method_CAT: + // Use the default PTT_TYPE for the rig (defined in the Hamlib + // rig back-end capabilities). + break; + + case TransceiverFactory::PTT_method_DTR: + case TransceiverFactory::PTT_method_RTS: + if (params.ptt_port.size () + && params.ptt_port != "None" + && (m_->is_dummy_ + || RIG_PORT_SERIAL != rig_get_caps_int (m_->model_, RIG_CAPS_PORT_TYPE) + || params.ptt_port != params.serial_port)) + { +#if defined (WIN32) + m_->set_conf ("ptt_pathname", ("\\\\.\\" + params.ptt_port).toLatin1 ().data ()); +#else + m_->set_conf ("ptt_pathname", params.ptt_port.toLatin1 ().data ()); +#endif + } + + if (TransceiverFactory::PTT_method_DTR == params.ptt_type) + { + m_->set_conf ("ptt_type", "DTR"); + } + else + { + m_->set_conf ("ptt_type", "RTS"); + } + m_->set_conf ("ptt_share", "1"); + } + + // Make Icom CAT split commands less glitchy + m_->set_conf ("no_xchg", "1"); + + // do this late to allow any configuration option to be overriden + load_user_settings (); + + // would be nice to get events but not supported on Windows and also not on a lot of rigs + // rig_set_freq_callback (m_->rig_.data (), &frequency_change_callback, this); +} + +HamlibTransceiver::~HamlibTransceiver () = default; + +void HamlibTransceiver::load_user_settings () +{ + // + // user defined Hamlib settings + // + auto settings_file_name = QStandardPaths::locate (QStandardPaths::AppConfigLocation + , "hamlib_settings.json"); + if (!settings_file_name.isEmpty ()) + { + QFile settings_file {settings_file_name}; + qDebug () << "Using Hamlib settings file:" << settings_file_name; + if (settings_file.open (QFile::ReadOnly)) + { + QJsonParseError status; + auto settings_doc = QJsonDocument::fromJson (settings_file.readAll (), &status); + if (status.error) + { + throw error {tr ("Hamlib settings file error: %1 at character offset %2") + .arg (status.errorString ()).arg (status.offset)}; + } + qDebug () << "Hamlib settings JSON:" << settings_doc.toJson (); + if (!settings_doc.isObject ()) + { + throw error {tr ("Hamlib settings file error: top level must be a JSON object")}; + } + auto const& settings = settings_doc.object (); + + // + // configuration settings + // + auto const& config = settings["config"]; + if (!config.isUndefined ()) + { + if (!config.isObject ()) + { + throw error {tr ("Hamlib settings file error: config must be a JSON object")}; + } + auto const& config_list = config.toObject (); + for (auto item = config_list.constBegin (); item != config_list.constEnd (); ++item) + { + m_->set_conf (item.key ().toLocal8Bit ().constData () + , (*item).toVariant ().toString ().toLocal8Bit ().constData ()); + } + } + } + } +} + +int HamlibTransceiver::do_start () +{ + CAT_TRACE ("starting: " << rig_get_caps_cptr (m_->model_, RIG_CAPS_MFG_NAME_CPTR) + << ": " << rig_get_caps_cptr (m_->model_, RIG_CAPS_MODEL_NAME_CPTR)); + + token_t token = rig_token_lookup (m_->rig_.data (), "client"); + if (RIG_CONF_END != token) // only set if valid for rig model + { + rig_set_conf (m_->rig_.data (), token, "WSJTX"); + } + + m_->error_check (rig_open (m_->rig_.data ()), tr ("opening connection to rig")); + + // reset dynamic state + m_->one_VFO_ = false; + m_->reversed_ = false; + m_->freq_query_works_ = rig_get_function_ptr (m_->model_, RIG_FUNCTION_GET_FREQ); + m_->mode_query_works_ = rig_get_function_ptr (m_->model_, RIG_FUNCTION_GET_MODE); + m_->split_query_works_ = rig_get_function_ptr (m_->model_, RIG_FUNCTION_GET_SPLIT_VFO); + m_->tickle_hamlib_ = false; + m_->get_vfo_works_ = true; + m_->set_vfo_works_ = true; + do_pwr_ &= (!m_->is_dummy_ && rig_get_function_ptr (m_->model_, RIG_FUNCTION_GET_LEVEL) && (rig_get_caps_int (m_->model_, RIG_CAPS_HAS_GET_LEVEL) & RIG_LEVEL_RFPOWER_METER_WATTS) == RIG_LEVEL_RFPOWER_METER_WATTS); + do_pwr2_ &= (!m_->is_dummy_ && rig_get_function_ptr (m_->model_, RIG_FUNCTION_GET_LEVEL) && (rig_get_caps_int (m_->model_, RIG_CAPS_HAS_GET_LEVEL) & RIG_LEVEL_RFPOWER) == RIG_LEVEL_RFPOWER); + do_swr_ &= (!m_->is_dummy_ && rig_get_function_ptr (m_->model_, RIG_FUNCTION_GET_LEVEL) && (rig_get_caps_int (m_->model_, RIG_CAPS_HAS_GET_LEVEL) & RIG_LEVEL_SWR) == RIG_LEVEL_SWR); + + // the Net rigctl back end promises all functions work but we must + // test get_vfo as it determines our strategy for Icom rigs + vfo_t vfo; + int rc = rig_get_vfo (m_->rig_.data (), &vfo); + if (-RIG_ENAVAIL == rc || -RIG_ENIMPL == rc) + { + m_->get_vfo_works_ = false; + // determine if the rig uses single VFO addressing i.e. A/B and + // no get_vfo function + if (m_->rig_->state.vfo_list & RIG_VFO_B) + { + m_->one_VFO_ = true; + } + } + else + { + m_->error_check (rc, "testing getting current VFO"); + } + + if ((WSJT_RIG_NONE_CAN_SPLIT || !m_->is_dummy_) + && rig_get_function_ptr (m_->model_, RIG_FUNCTION_SET_SPLIT_VFO)) // if split is possible do some extra setup + { + freq_t f1; + freq_t f2; + rmode_t m {RIG_MODE_USB}; + rmode_t mb; + pbwidth_t w {RIG_PASSBAND_NORMAL}; + pbwidth_t wb; + if (m_->freq_query_works_ && m_->mode_query_works_ + && (!m_->get_vfo_works_ || !rig_get_function_ptr (m_->model_, RIG_FUNCTION_GET_VFO))) + { + // Icom have deficient CAT protocol with no way of reading which + // VFO is selected or if SPLIT is selected so we have to simply + // assume it is as when we started by setting at open time right + // here. We also gather/set other initial state. + m_->error_check (rig_get_freq (m_->rig_.data (), RIG_VFO_CURR, &f1), tr ("getting current frequency")); + f1 = std::round (f1); + CAT_TRACE ("current frequency=" << f1); + + m_->error_check (rig_get_mode (m_->rig_.data (), RIG_VFO_CURR, &m, &w), tr ("getting current mode")); + CAT_TRACE ("current mode=" << rig_strrmode (m) << " bw=" << w); + + if (!rig_get_function_ptr (m_->model_, RIG_FUNCTION_SET_VFO)) + { + CAT_TRACE ("rig_vfo_op TOGGLE"); + rc = rig_vfo_op (m_->rig_.data (), RIG_VFO_CURR, RIG_OP_TOGGLE); + } + else + { + CAT_TRACE ("rig_set_vfo to other VFO"); + rc = rig_set_vfo (m_->rig_.data (), m_->rig_->state.vfo_list & RIG_VFO_B ? RIG_VFO_B : RIG_VFO_SUB); + if (-RIG_ENAVAIL == rc || -RIG_ENIMPL == rc) + { + // if we are talking to netrigctl then toggle VFO op + // may still work + CAT_TRACE ("rig_vfo_op TOGGLE"); + rc = rig_vfo_op (m_->rig_.data (), RIG_VFO_CURR, RIG_OP_TOGGLE); + } + } + if (-RIG_ENAVAIL == rc || -RIG_ENIMPL == rc) + { + // we are probably dealing with rigctld so we do not + // have completely accurate rig capabilities + m_->set_vfo_works_ = false; + m_->one_VFO_ = false; // we do not need single VFO addressing + } + else + { + m_->error_check (rc, tr ("exchanging VFOs")); + } + + if (m_->set_vfo_works_) + { + // without the above we cannot proceed but we know we + // are on VFO A and that will not change so there's no + // need to execute this block + m_->error_check (rig_get_freq (m_->rig_.data (), RIG_VFO_CURR, &f2), tr ("getting other VFO frequency")); + f2 = std::round (f2); + CAT_TRACE ("rig_get_freq other frequency=" << f2); + + m_->error_check (rig_get_mode (m_->rig_.data (), RIG_VFO_CURR, &mb, &wb), tr ("getting other VFO mode")); + CAT_TRACE ("rig_get_mode other mode=" << rig_strrmode (mb) << " bw=" << wb); + + update_other_frequency (f2); + + if (!rig_get_function_ptr (m_->model_, RIG_FUNCTION_SET_VFO)) + { + CAT_TRACE ("rig_vfo_op TOGGLE"); + m_->error_check (rig_vfo_op (m_->rig_.data (), RIG_VFO_CURR, RIG_OP_TOGGLE), tr ("exchanging VFOs")); + } + else + { + CAT_TRACE ("rig_set_vfo A/MAIN"); + m_->error_check (rig_set_vfo (m_->rig_.data (), m_->rig_->state.vfo_list & RIG_VFO_A ? RIG_VFO_A : RIG_VFO_MAIN), tr ("setting current VFO")); + } + + if (f1 != f2 || m != mb || w != wb) // we must have started with MAIN/A + { + update_rx_frequency (f1); + } + else + { + m_->error_check (rig_get_freq (m_->rig_.data (), RIG_VFO_CURR, &f1), tr ("getting frequency")); + f1 = std::round (f1); + CAT_TRACE ("rig_get_freq frequency=" << f1); + + m_->error_check (rig_get_mode (m_->rig_.data (), RIG_VFO_CURR, &m, &w), tr ("getting mode")); + CAT_TRACE ("rig_get_mode mode=" << rig_strrmode (m) << " bw=" << w); + + update_rx_frequency (f1); + } + } + + // TRACE_CAT ("rig_set_split_vfo split off"); + // m_->error_check (rig_set_split_vfo (m_->rig_.data (), RIG_VFO_CURR, RIG_SPLIT_OFF, RIG_VFO_CURR), tr ("setting split off")); + // update_split (false); + } + else + { + vfo_t v {RIG_VFO_A}; // assume RX always on VFO A/MAIN + + if (m_->get_vfo_works_ && rig_get_function_ptr (m_->model_, RIG_FUNCTION_GET_VFO)) + { + m_->error_check (rig_get_vfo (m_->rig_.data (), &v), tr ("getting current VFO")); // has side effect of establishing current VFO inside hamlib + CAT_TRACE ("rig_get_vfo current VFO=" << rig_strvfo (v)); + } + + m_->reversed_ = RIG_VFO_B == v; + + if (m_->mode_query_works_ && !(rig_get_caps_int (m_->model_, RIG_CAPS_TARGETABLE_VFO) & RIG_TARGETABLE_MODE)) + { + if (RIG_OK == rig_get_mode (m_->rig_.data (), RIG_VFO_CURR, &m, &w)) + { + CAT_TRACE ("rig_get_mode current mode=" << rig_strrmode (m) << " bw=" << w); + } + else + { + m_->mode_query_works_ = false; + // Some rigs (HDSDR) don't have a working way of + // reporting MODE so we give up on mode queries - + // sets will still cause an error + CAT_TRACE ("rig_get_mode can't do on this rig"); + } + } + } + update_mode (m_->map_mode (m)); + } + + m_->tickle_hamlib_ = true; + + if (m_->is_dummy_ && !m_->ptt_only_ && impl::dummy_frequency_) + { + // return to where last dummy instance was + // TODO: this is going to break down if multiple dummy rigs are used + rig_set_freq (m_->rig_.data (), RIG_VFO_CURR, impl::dummy_frequency_); + update_rx_frequency (impl::dummy_frequency_); + if (RIG_MODE_NONE != impl::dummy_mode_) + { + rig_set_mode (m_->rig_.data (), RIG_VFO_CURR, impl::dummy_mode_, RIG_PASSBAND_NOCHANGE); + update_mode (m_->map_mode (impl::dummy_mode_)); + } + } + +#if HAVE_HAMLIB_CACHING || HAVE_HAMLIB_OLD_CACHING + // we must disable Hamlib caching because it lies about frequency + // for less than 1 Hz resolution rigs + auto orig_cache_timeout = rig_get_cache_timeout_ms (m_->rig_.data (), HAMLIB_CACHE_ALL); + rig_set_cache_timeout_ms (m_->rig_.data (), HAMLIB_CACHE_ALL, 0); +#endif + + int resolution {0}; + if (m_->freq_query_works_) + { + freq_t current_frequency; + m_->error_check (rig_get_freq (m_->rig_.data (), RIG_VFO_CURR, ¤t_frequency), tr ("getting current VFO frequency")); + current_frequency = std::round (current_frequency); + Frequency f = current_frequency; + if (f && !(f % 10)) + { + auto test_frequency = f - f % 100 + 55; + m_->error_check (rig_set_freq (m_->rig_.data (), RIG_VFO_CURR, test_frequency), tr ("setting frequency")); + freq_t new_frequency; + m_->error_check (rig_get_freq (m_->rig_.data (), RIG_VFO_CURR, &new_frequency), tr ("getting current VFO frequency")); + new_frequency = std::round (new_frequency); + switch (static_cast<Radio::FrequencyDelta> (new_frequency - test_frequency)) + { + case -5: resolution = -1; break; // 10Hz truncated + case 5: resolution = 1; break; // 10Hz rounded + case -15: resolution = -2; break; // 20Hz truncated + case -55: resolution = -3; break; // 100Hz truncated + case 45: resolution = 3; break; // 100Hz rounded + } + if (1 == resolution) // may be 20Hz rounded + { + test_frequency = f - f % 100 + 51; + m_->error_check (rig_set_freq (m_->rig_.data (), RIG_VFO_CURR, test_frequency), tr ("setting frequency")); + m_->error_check (rig_get_freq (m_->rig_.data (), RIG_VFO_CURR, &new_frequency), tr ("getting current VFO frequency")); + if (9 == static_cast<Radio::FrequencyDelta> (new_frequency - test_frequency)) + { + resolution = 2; // 20Hz rounded + } + } + m_->error_check (rig_set_freq (m_->rig_.data (), RIG_VFO_CURR, current_frequency), tr ("setting frequency")); + } + } + else + { + resolution = -1; // best guess + } + +#if HAVE_HAMLIB_CACHING || HAVE_HAMLIB_OLD_CACHING + // revert Hamlib cache timeout + rig_set_cache_timeout_ms (m_->rig_.data (), HAMLIB_CACHE_ALL, orig_cache_timeout); +#endif + + do_poll (); + + CAT_TRACE ("finished start " << state () << " reversed=" << m_->reversed_ << " resolution=" << resolution); + return resolution; +} + +void HamlibTransceiver::do_stop () +{ + if (m_->is_dummy_ && !m_->ptt_only_) + { + rig_get_freq (m_->rig_.data (), RIG_VFO_CURR, &impl::dummy_frequency_); + impl::dummy_frequency_ = std::round (impl::dummy_frequency_); + if (m_->mode_query_works_) + { + pbwidth_t width; + rig_get_mode (m_->rig_.data (), RIG_VFO_CURR, &impl::dummy_mode_, &width); + } + } + if (m_->rig_) + { + rig_close (m_->rig_.data ()); + } + + CAT_TRACE ("state: " << state () << " reversed=" << m_->reversed_); +} + +void HamlibTransceiver::do_frequency (Frequency f, MODE m, bool no_ignore) +{ + CAT_TRACE ("f: " << f << " mode: " << m << " reversed: " << m_->reversed_); + + // only change when receiving or simplex or direct VFO addressing + // unavailable or forced + if (!state ().ptt () || !state ().split () || !m_->one_VFO_ || no_ignore) + { + // for the 1st time as a band change may cause a recalled mode to be + // set + vfo_t target_vfo = RIG_VFO_CURR; + if (!(m_->rig_->state.vfo_list & RIG_VFO_B)) + { + target_vfo = RIG_VFO_MAIN; // no VFO A/B so force to Rx on MAIN + } + m_->error_check (rig_set_freq (m_->rig_.data (), target_vfo, f), tr ("setting frequency")); + update_rx_frequency (f); + + if (m_->mode_query_works_ && UNK != m) + { + rmode_t current_mode; + pbwidth_t current_width; + auto new_mode = m_->map_mode (m); + m_->error_check (rig_get_mode (m_->rig_.data (), target_vfo, ¤t_mode, ¤t_width), tr ("getting current VFO mode")); + CAT_TRACE ("rig_get_mode mode=" << rig_strrmode (current_mode) << " bw=" << current_width); + + if (new_mode != current_mode) + { + CAT_TRACE ("rig_set_mode mode=" << rig_strrmode (new_mode)); + m_->error_check (rig_set_mode (m_->rig_.data (), target_vfo, new_mode, RIG_PASSBAND_NOCHANGE), tr ("setting current VFO mode")); + + // for the 2nd time because a mode change may have caused a + // frequency change + m_->error_check (rig_set_freq (m_->rig_.data (), RIG_VFO_CURR, f), tr ("setting frequency")); + + // for the second time because some rigs change mode according + // to frequency such as the TS-2000 auto mode setting + CAT_TRACE ("rig_set_mode mode=" << rig_strrmode (new_mode)); + m_->error_check (rig_set_mode (m_->rig_.data (), target_vfo, new_mode, RIG_PASSBAND_NOCHANGE), tr ("setting current VFO mode")); + } + // set mode on VFOB too if we are in split + if (state ().split()) rig_set_mode (m_->rig_.data (), RIG_VFO_B, new_mode, RIG_PASSBAND_NOCHANGE), tr ("setting VFOB mode"); + update_mode (m); + } + } +} + +void HamlibTransceiver::do_tx_frequency (Frequency tx, MODE mode, bool no_ignore) +{ + CAT_TRACE ("txf: " << tx << " reversed: " << m_->reversed_); + + if (WSJT_RIG_NONE_CAN_SPLIT || !m_->is_dummy_) // split is meaningless if you can't see it + { + auto split = tx ? RIG_SPLIT_ON : RIG_SPLIT_OFF; + auto vfos = m_->get_vfos (tx); + // auto rx_vfo = std::get<0> (vfos); // or use RIG_VFO_CURR + auto tx_vfo = std::get<1> (vfos); + + if (tx) + { + // Doing set split for the 1st of two times, this one + // ensures that the internal Hamlib state is correct + // otherwise rig_set_split_freq() will target the wrong VFO + // on some rigs + + if (m_->tickle_hamlib_) + { + // This potentially causes issues with the Elecraft K3 + // which will block setting split mode when it deems + // cross mode split operation not possible. There's not + // much we can do since the Hamlib Library needs this + // call at least once to establish the Tx VFO. Best we + // can do is only do this once per session. + CAT_TRACE ("rig_set_split_vfo split=" << split); + auto rc = rig_set_split_vfo (m_->rig_.data (), RIG_VFO_CURR, split, tx_vfo); + if (tx || (-RIG_ENAVAIL != rc && -RIG_ENIMPL != rc)) + { + // On rigs that can't have split controlled only throw an + // exception when an error other than command not accepted + // is returned when trying to leave split mode. This allows + // fake split mode and non-split mode to work without error + // on such rigs without having to know anything about the + // specific rig. + m_->error_check (rc, tr ("setting/unsetting split mode")); + } + m_->tickle_hamlib_ = false; + update_split (tx); + } + + // just change current when transmitting with single VFO + // addressing + if (state ().ptt () && m_->one_VFO_) + { + CAT_TRACE ("rig_set_split_vfo split=" << split); + m_->error_check (rig_set_split_vfo (m_->rig_.data (), RIG_VFO_CURR, split, tx_vfo), tr ("setting split mode")); + + m_->error_check (rig_set_freq (m_->rig_.data (), RIG_VFO_CURR, tx), tr ("setting frequency")); + + if (UNK != mode && m_->mode_query_works_) + { + rmode_t current_mode; + pbwidth_t current_width; + auto new_mode = m_->map_mode (mode); + m_->error_check (rig_get_mode (m_->rig_.data (), RIG_VFO_CURR, ¤t_mode, ¤t_width), tr ("getting current VFO mode")); + CAT_TRACE ("rig_get_mode mode=" << rig_strrmode (current_mode) << " bw=" << current_width); + + if (new_mode != current_mode) + { + CAT_TRACE ("rig_set_mode mode=" << rig_strrmode (new_mode)); + m_->error_check (rig_set_mode (m_->rig_.data (), RIG_VFO_CURR, new_mode, RIG_PASSBAND_NOCHANGE), tr ("setting current VFO mode")); + } + } + update_other_frequency (tx); + } + else if (!m_->one_VFO_ || no_ignore) // if not single VFO addressing and not forced + { + hamlib_tx_vfo_fixup fixup (m_->rig_.data (), tx_vfo); + if (UNK != mode) + { + auto new_mode = m_->map_mode (mode); + CAT_TRACE ("rig_set_split_freq_mode freq=" << tx + << " mode = " << rig_strrmode (new_mode)); + m_->error_check (rig_set_split_freq_mode (m_->rig_.data (), RIG_VFO_CURR, tx, new_mode, RIG_PASSBAND_NOCHANGE), tr ("setting split TX frequency and mode")); + } + else + { + CAT_TRACE ("rig_set_split_freq freq=" << tx); + m_->error_check (rig_set_split_freq (m_->rig_.data (), RIG_VFO_CURR, tx), tr ("setting split TX frequency")); + } + // Enable split last since some rigs (Kenwood for one) come out + // of split when you switch RX VFO (to set split mode above for + // example). Also the Elecraft K3 will refuse to go to split + // with certain VFO A/B mode combinations. + CAT_TRACE ("rig_set_split_vfo split=" << split); + m_->error_check (rig_set_split_vfo (m_->rig_.data (), RIG_VFO_CURR, split, tx_vfo), tr ("setting split mode")); + update_other_frequency (tx); + update_split (tx); + } + } + else + { + // Disable split + CAT_TRACE ("rig_set_split_vfo split=" << split); + auto rc = rig_set_split_vfo (m_->rig_.data (), RIG_VFO_CURR, split, tx_vfo); + if (tx || (-RIG_ENAVAIL != rc && -RIG_ENIMPL != rc)) + { + // On rigs that can't have split controlled only throw an + // exception when an error other than command not accepted + // is returned when trying to leave split mode. This allows + // fake split mode and non-split mode to work without error + // on such rigs without having to know anything about the + // specific rig. + m_->error_check (rc, tr ("setting/unsetting split mode")); + } + update_other_frequency (tx); + update_split (tx); + } + } +} + +void HamlibTransceiver::do_mode (MODE mode) +{ + CAT_TRACE (mode); + + auto vfos = m_->get_vfos (state ().split ()); + // auto rx_vfo = std::get<0> (vfos); + auto tx_vfo = std::get<1> (vfos); + + rmode_t current_mode; + pbwidth_t current_width; + auto new_mode = m_->map_mode (mode); + + vfo_t target_vfo = RIG_VFO_CURR; + if (!(m_->rig_->state.vfo_list & RIG_VFO_B)) + { + target_vfo = RIG_VFO_MAIN; // no VFO A/B so force to Rx on MAIN + } + + // only change when receiving or simplex if direct VFO addressing unavailable + if (!(state ().ptt () && state ().split () && m_->one_VFO_)) + { + m_->error_check (rig_get_mode (m_->rig_.data (), target_vfo, ¤t_mode, ¤t_width), tr ("getting current VFO mode")); + CAT_TRACE ("rig_get_mode mode=" << rig_strrmode (current_mode) << " bw=" << current_width); + + if (new_mode != current_mode) + { + CAT_TRACE ("rig_set_mode mode=" << rig_strrmode (new_mode)); + m_->error_check (rig_set_mode (m_->rig_.data (), target_vfo, new_mode, RIG_PASSBAND_NOCHANGE), tr ("setting current VFO mode")); + } + } + + // just change current when transmitting split with one VFO mode + if (state ().ptt () && state ().split () && m_->one_VFO_) + { + m_->error_check (rig_get_mode (m_->rig_.data (), RIG_VFO_CURR, ¤t_mode, ¤t_width), tr ("getting current VFO mode")); + CAT_TRACE ("rig_get_mode mode=" << rig_strrmode (current_mode) << " bw=" << current_width); + + if (new_mode != current_mode) + { + CAT_TRACE ("rig_set_mode mode=" << rig_strrmode (new_mode)); + m_->error_check (rig_set_mode (m_->rig_.data (), RIG_VFO_CURR, new_mode, RIG_PASSBAND_NOCHANGE), tr ("setting current VFO mode")); + } + } + else if (state ().split () && !m_->one_VFO_) + { + m_->error_check (rig_get_split_mode (m_->rig_.data (), RIG_VFO_CURR, ¤t_mode, ¤t_width), tr ("getting split TX VFO mode")); + CAT_TRACE ("rig_get_split_mode mode=" << rig_strrmode (current_mode) << " bw=" << current_width); + + if (new_mode != current_mode) + { + CAT_TRACE ("rig_set_split_mode mode=" << rig_strrmode (new_mode)); + hamlib_tx_vfo_fixup fixup (m_->rig_.data (), tx_vfo); + m_->error_check (rig_set_split_mode (m_->rig_.data (), RIG_VFO_CURR, new_mode, RIG_PASSBAND_NOCHANGE), tr ("setting split TX VFO mode")); + } + } + update_mode (mode); +} + +void HamlibTransceiver::do_poll () +{ + freq_t f; + rmode_t m; + pbwidth_t w; + split_t s; + + if (m_->get_vfo_works_ && rig_get_function_ptr (m_->model_, RIG_FUNCTION_GET_VFO)) + { + vfo_t v; + m_->error_check (rig_get_vfo (m_->rig_.data (), &v), tr ("getting current VFO")); // has side effect of establishing current VFO inside hamlib + CAT_TRACE ("VFO=" << rig_strvfo (v)); + m_->reversed_ = RIG_VFO_B == v; + } + + if ((WSJT_RIG_NONE_CAN_SPLIT || !m_->is_dummy_) + && rig_get_function_ptr (m_->model_, RIG_FUNCTION_GET_SPLIT_VFO) && m_->split_query_works_) + { + vfo_t v {RIG_VFO_NONE}; // so we can tell if it doesn't get updated :( + auto rc = rig_get_split_vfo (m_->rig_.data (), RIG_VFO_CURR, &s, &v); + if (-RIG_OK == rc && RIG_SPLIT_ON == s) + { + CAT_TRACE ("rig_get_split_vfo split=" << s << " VFO=" << rig_strvfo (v)); + update_split (true); + // if (RIG_VFO_A == v) + // { + // m_->reversed_ = true; // not sure if this helps us here + // } + } + else if (-RIG_OK == rc) // not split + { + CAT_TRACE ("rig_get_split_vfo split=" << s << " VFO=" << rig_strvfo (v)); + update_split (false); + } + else + { + // Some rigs (Icom) don't have a way of reporting SPLIT + // mode + CAT_TRACE ("rig_get_split_vfo can't do on this rig"); + // just report how we see it based on prior commands + m_->split_query_works_ = false; + } + } + + if (m_->freq_query_works_) + { + // only read if possible and when receiving or simplex + if (!state ().ptt () || !state ().split ()) + { + m_->error_check (rig_get_freq (m_->rig_.data (), RIG_VFO_CURR, &f), tr ("getting current VFO frequency")); + f = std::round (f); + CAT_TRACE ("rig_get_freq frequency=" << Radio::frequency (f)); + update_rx_frequency (f); + } + + if ((WSJT_RIG_NONE_CAN_SPLIT || !m_->is_dummy_) + && state ().split () + && (rig_get_caps_int (m_->model_, RIG_CAPS_TARGETABLE_VFO) & RIG_TARGETABLE_FREQ) + && !m_->one_VFO_) + { + // only read "other" VFO if in split, this allows rigs like + // FlexRadio to work in Kenwood TS-2000 mode despite them + // not having a FB; command + + // we can only probe current VFO unless rig supports reading + // the other one directly because we can't glitch the Rx + m_->error_check (rig_get_freq (m_->rig_.data () + , m_->reversed_ + ? (m_->rig_->state.vfo_list & RIG_VFO_A ? RIG_VFO_A : RIG_VFO_MAIN) + : (m_->rig_->state.vfo_list & RIG_VFO_B ? RIG_VFO_B : RIG_VFO_SUB) + , &f), tr ("getting other VFO frequency")); + f = std::round (f); + CAT_TRACE ("rig_get_freq other VFO=" << f); + update_other_frequency (f); + } + } + + // only read when receiving or simplex if direct VFO addressing unavailable + if ((!state ().ptt () || !state ().split ()) + && m_->mode_query_works_) + { + // We have to ignore errors here because Yaesu FTdx... rigs can + // report the wrong mode when transmitting split with different + // modes per VFO. This is unfortunate because that is exactly + // what you need to do to get 4kHz Rx b.w and modulation into + // the rig through the data socket or USB. I.e. USB for Rx and + // DATA-USB for Tx. + auto rc = rig_get_mode (m_->rig_.data (), RIG_VFO_CURR, &m, &w); + if (RIG_OK == rc) + { + CAT_TRACE ("rig_get_mode mode=" << rig_strrmode (m) << " bw=" << w); + update_mode (m_->map_mode (m)); + } + else + { + CAT_TRACE ("rig_get_mode mode failed with rc: " << rc << " ignoring"); + } + } + + if (RIG_PTT_NONE != m_->rig_->state.pttport.type.ptt && rig_get_function_ptr (m_->model_, RIG_FUNCTION_GET_PTT)) + { + ptt_t p; + auto rc = rig_get_ptt (m_->rig_.data (), RIG_VFO_CURR, &p); + if (-RIG_ENAVAIL != rc && -RIG_ENIMPL != rc) // may fail if + // Net rig ctl and target doesn't + // support command + { + m_->error_check (rc, tr ("getting PTT state")); + CAT_TRACE ("rig_get_ptt PTT=" << p); + update_PTT (!(RIG_PTT_OFF == p)); + } + } + + if (ptt_on_) { + // update PWR and SWR + value_t strength; + int rc; + if (do_swr_) { + rc = rig_get_level (m_->rig_.data (), RIG_VFO_CURR, RIG_LEVEL_SWR, &strength); + if (RIG_OK == rc && ptt_on_) { + // printf ("SWR %.3f\n",strength.f); + if (strength.f >= 1.000) + { + update_swr (strength.f*100); + } + else + { + update_swr (0); + } + } else { + CAT_TRACE ("rig_get_level RIG_LEVEL_SWR failed with rc:" << rc << "ignoring"); + update_swr (0); + } + } + if (do_pwr_) { + rc = rig_get_level (m_->rig_.data (), RIG_VFO_CURR, RIG_LEVEL_RFPOWER_METER_WATTS, &strength); + if (RIG_OK == rc) { + update_power (strength.f*1000); + } else { + CAT_TRACE ("rig_get_level RFPOWER_METER_WATTS failed with rc:" << rc << "ignoring"); + update_power (0); + } + } else if (do_pwr2_) { + rc = rig_get_level (m_->rig_.data (), RIG_VFO_CURR, RIG_LEVEL_RFPOWER, &strength); + if (RIG_OK == rc) { + unsigned int mwpower; + rc = rig_power2mW(m_->rig_.data (),&mwpower,strength.f,f,m); + if (RIG_OK != rc) { + CAT_TRACE ("rig_power2mW failed with rc:" << rc << "ignoring"); + mwpower=0; + } + update_power (mwpower); + // printf ("POWER %.3f %.1f\n",strength.f,mwpower / 1000.); + } else { + CAT_TRACE ("rig_get_level RFPOWER failed with rc:" << rc << "ignoring"); + update_power (0); + } + } else update_power (0); + } else { + update_power (0); + update_swr (0); + } +} + +void HamlibTransceiver::do_ptt (bool on) +{ + CAT_TRACE ("PTT: " << on << " " << state () << " reversed=" << m_->reversed_); + if (on) + { + if (RIG_PTT_NONE != m_->rig_->state.pttport.type.ptt) + { + ptt_on_ = true; + CAT_TRACE ("rig_set_ptt PTT=true"); + auto ptt_type = rig_get_caps_int (m_->model_, RIG_CAPS_PTT_TYPE); + m_->error_check (rig_set_ptt (m_->rig_.data (), RIG_VFO_CURR + , RIG_PTT_RIG_MICDATA == ptt_type && m_->back_ptt_port_ + ? RIG_PTT_ON_DATA : RIG_PTT_ON), tr ("setting PTT on")); + } + } + else + { + if (RIG_PTT_NONE != m_->rig_->state.pttport.type.ptt) + { + ptt_on_ = false; + CAT_TRACE ("rig_set_ptt PTT=false"); + m_->error_check (rig_set_ptt (m_->rig_.data (), RIG_VFO_CURR, RIG_PTT_OFF), tr ("setting PTT off")); + } + } + + update_PTT (on); +} + +// pass in false if any post_action is needed for a rig -- don't know of any as of 2024-04-14 +void HamlibTransceiver::do_tune (bool on) +{ + CAT_TRACE ("Tune: " << on << " " << state ()); + if (on) + { + if (RIG_PTT_NONE != m_->rig_->state.pttport.type.ptt) + { + update_PTT (true); // we'll change the PTT button while we do this + CAT_TRACE ("rig_vfo_opt RIG_VFO_OP_TUNE=" << on); + // ptt button will stay lit if error message is displaye + m_->error_check(rig_vfo_op (m_->rig_.data (), RIG_VFO_CURR, RIG_OP_TUNE), "turning TUNE on"); + update_PTT (false); + } + } +#if 0 + else // do we need to be able to turn PTT off on anybody? + { + if (RIG_PTT_NONE != m_->rig_->state.pttport.type.ptt) + { + ptt_on_ = false; + CAT_TRACE ("rig_set_ptt PTT=false"); + m_->error_check (rig_set_ptt (m_->rig_.data (), RIG_VFO_CURR, RIG_PTT_OFF), tr ("setting PTT off")); + } + } +#endif +} diff --git a/Transceiver/HamlibTransceiver.hpp b/Transceiver/HamlibTransceiver.hpp index b3e699d0..101cbb9d 100755..100644 --- a/Transceiver/HamlibTransceiver.hpp +++ b/Transceiver/HamlibTransceiver.hpp @@ -1,47 +1,47 @@ -#ifndef HAMLIB_TRANSCEIVER_HPP_
-#define HAMLIB_TRANSCEIVER_HPP_
-
-#include <QString>
-
-#include "TransceiverFactory.hpp"
-#include "PollingTransceiver.hpp"
-#include "pimpl_h.hpp"
-
-// hamlib transceiver and PTT mostly delegated directly to hamlib Rig class
-class HamlibTransceiver final
- : public PollingTransceiver
-{
- Q_OBJECT // for translation context
-
-public:
- static void register_transceivers (logger_type *, TransceiverFactory::Transceivers *);
- static void unregister_transceivers ();
-
- explicit HamlibTransceiver (logger_type *, unsigned model_number, TransceiverFactory::ParameterPack const&,
- QObject * parent = nullptr);
- explicit HamlibTransceiver (logger_type *, TransceiverFactory::PTTMethod ptt_type, QString const& ptt_port,
- QObject * parent = nullptr);
- ~HamlibTransceiver ();
-
-private:
- void load_user_settings ();
- int do_start () override;
- void do_stop () override;
- void do_frequency (Frequency, MODE, bool no_ignore) override;
- void do_tx_frequency (Frequency, MODE, bool no_ignore) override;
- void do_mode (MODE) override;
- void do_ptt (bool) override;
- void do_tune (bool) override;
-
- void do_poll () override;
-
- bool ptt_on_ = false;
- bool do_pwr_;
- bool do_pwr2_;
- bool do_swr_;
-
- class impl;
- pimpl<impl> m_;
-};
-
-#endif
+#ifndef HAMLIB_TRANSCEIVER_HPP_ +#define HAMLIB_TRANSCEIVER_HPP_ + +#include <QString> + +#include "TransceiverFactory.hpp" +#include "PollingTransceiver.hpp" +#include "pimpl_h.hpp" + +// hamlib transceiver and PTT mostly delegated directly to hamlib Rig class +class HamlibTransceiver final + : public PollingTransceiver +{ + Q_OBJECT // for translation context + +public: + static void register_transceivers (logger_type *, TransceiverFactory::Transceivers *); + static void unregister_transceivers (); + + explicit HamlibTransceiver (logger_type *, unsigned model_number, TransceiverFactory::ParameterPack const&, + QObject * parent = nullptr); + explicit HamlibTransceiver (logger_type *, TransceiverFactory::PTTMethod ptt_type, QString const& ptt_port, + QObject * parent = nullptr); + ~HamlibTransceiver (); + +private: + void load_user_settings (); + int do_start () override; + void do_stop () override; + void do_frequency (Frequency, MODE, bool no_ignore) override; + void do_tx_frequency (Frequency, MODE, bool no_ignore) override; + void do_mode (MODE) override; + void do_ptt (bool) override; + void do_tune (bool) override; + + void do_poll () override; + + bool ptt_on_ = false; + bool do_pwr_; + bool do_pwr2_; + bool do_swr_; + + class impl; + pimpl<impl> m_; +}; + +#endif diff --git a/Transceiver/OmniRigTransceiver.cpp b/Transceiver/OmniRigTransceiver.cpp index 0c1f0d96..67f4b178 100755..100644 --- a/Transceiver/OmniRigTransceiver.cpp +++ b/Transceiver/OmniRigTransceiver.cpp @@ -1,817 +1,817 @@ -#include "OmniRigTransceiver.hpp"
-
-#include <QDebug>
-#include <objbase.h>
-#include <QThread>
-#include <QEventLoop>
-
-#include "qt_helpers.hpp"
-
-#include "moc_OmniRigTransceiver.cpp"
-
-namespace
-{
- auto constexpr OmniRig_transceiver_one_name = "OmniRig Rig 1";
- auto constexpr OmniRig_transceiver_two_name = "OmniRig Rig 2";
-}
-
-auto OmniRigTransceiver::map_mode (OmniRig::RigParamX param) -> MODE
-{
- if (param & OmniRig::PM_CW_U)
- {
- return CW_R;
- }
- else if (param & OmniRig::PM_CW_L)
- {
- return CW;
- }
- else if (param & OmniRig::PM_SSB_U)
- {
- return USB;
- }
- else if (param & OmniRig::PM_SSB_L)
- {
- return LSB;
- }
- else if (param & OmniRig::PM_DIG_U)
- {
- return DIG_U;
- }
- else if (param & OmniRig::PM_DIG_L)
- {
- return DIG_L;
- }
- else if (param & OmniRig::PM_AM)
- {
- return AM;
- }
- else if (param & OmniRig::PM_FM)
- {
- return FM;
- }
- CAT_ERROR ("unrecognized mode");
- throw_qstring (tr ("OmniRig: unrecognized mode"));
- return UNK;
-}
-
-OmniRig::RigParamX OmniRigTransceiver::map_mode (MODE mode)
-{
- switch (mode)
- {
- case AM: return OmniRig::PM_AM;
- case CW: return OmniRig::PM_CW_L;
- case CW_R: return OmniRig::PM_CW_U;
- case USB: return OmniRig::PM_SSB_U;
- case LSB: return OmniRig::PM_SSB_L;
- case FSK: return OmniRig::PM_DIG_L;
- case FSK_R: return OmniRig::PM_DIG_U;
- case DIG_L: return OmniRig::PM_DIG_L;
- case DIG_U: return OmniRig::PM_DIG_U;
- case FM: return OmniRig::PM_FM;
- case DIG_FM: return OmniRig::PM_FM;
- default: break;
- }
- return OmniRig::PM_SSB_U; // quieten compiler grumble
-}
-
-void OmniRigTransceiver::register_transceivers (logger_type *,
- TransceiverFactory::Transceivers * registry,
- unsigned id1, unsigned id2)
-{
- (*registry)[OmniRig_transceiver_one_name] = TransceiverFactory::Capabilities {
- id1
- , TransceiverFactory::Capabilities::none // COM isn't serial or network
- , true // does PTT
- , false // doesn't select mic/data (use OmniRig config file)
- , true // can remote control RTS nd DTR
- , true // asynchronous interface
- };
- (*registry)[OmniRig_transceiver_two_name] = TransceiverFactory::Capabilities {
- id2
- , TransceiverFactory::Capabilities::none // COM isn't serial or network
- , true // does PTT
- , false // doesn't select mic/data (use OmniRig config file)
- , true // can remote control RTS nd DTR
- , true // asynchronous interface
- };
-}
-
-OmniRigTransceiver::OmniRigTransceiver (logger_type * the_logger,
- std::unique_ptr<TransceiverBase> wrapped,
- RigNumber n, TransceiverFactory::PTTMethod ptt_type,
- QString const& ptt_port, QObject * parent)
- : TransceiverBase {the_logger, parent}
- , wrapped_ {std::move (wrapped)}
- , use_for_ptt_ {TransceiverFactory::PTT_method_CAT == ptt_type || ("CAT" == ptt_port && (TransceiverFactory::PTT_method_RTS == ptt_type || TransceiverFactory::PTT_method_DTR == ptt_type))}
- , ptt_type_ {ptt_type}
- , rig_number_ {n}
- , readable_params_ {0}
- , writable_params_ {0}
- , send_update_signal_ {false}
- , reversed_ {false}
-{
- CoInitializeEx (nullptr, 0 /*COINIT_APARTMENTTHREADED*/); // required because Qt only does this for GUI thread
- CAT_TRACE ("constructed");
-}
-
-OmniRigTransceiver::~OmniRigTransceiver ()
-{
- CAT_TRACE ("destroying");
- CoUninitialize ();
-}
-
-int OmniRigTransceiver::do_start ()
-{
- CAT_TRACE ("starting");
- try
- {
- if (wrapped_) wrapped_->start (0);
-
- omni_rig_.reset (new OmniRig::OmniRigX {this});
- if (omni_rig_->isNull ())
- {
- CAT_ERROR ("failed to start COM server");
- throw_qstring (tr ("Failed to start OmniRig COM server"));
- }
-
- // COM/OLE exceptions get signaled
- connect (&*omni_rig_, SIGNAL (exception (int, QString, QString, QString)), this, SLOT (handle_COM_exception (int, QString, QString, QString)));
-
- // IOmniRigXEvent interface signals
- connect (&*omni_rig_, SIGNAL (VisibleChange ()), this, SLOT (handle_visible_change ()));
- connect (&*omni_rig_, SIGNAL (RigTypeChange (int)), this, SLOT (handle_rig_type_change (int)));
- connect (&*omni_rig_, SIGNAL (StatusChange (int)), this, SLOT (handle_status_change (int)));
- connect (&*omni_rig_, SIGNAL (ParamsChange (int, int)), this, SLOT (handle_params_change (int, int)));
- connect (&*omni_rig_
- , SIGNAL (CustomReply (int, QVariant const&, QVariant const&))
- , this, SLOT (handle_custom_reply (int, QVariant const&, QVariant const&)));
-
- CAT_INFO ("OmniRig s/w version: " << static_cast<quint16> (omni_rig_->SoftwareVersion () >> 16)
- << '.' << static_cast<quint16> (omni_rig_->SoftwareVersion () & 0xffff)
- << " i/f version: " << static_cast<int> (omni_rig_->InterfaceVersion () >> 8 & 0xff)
- << '.' << static_cast<int> (omni_rig_->InterfaceVersion () && 0xff));
-
- // fetch the interface of the RigX CoClass and instantiate a proxy object
- switch (rig_number_)
- {
- case One: rig_.reset (new OmniRig::RigX (omni_rig_->Rig1 ())); break;
- case Two: rig_.reset (new OmniRig::RigX (omni_rig_->Rig2 ())); break;
- }
-
- Q_ASSERT (rig_);
- Q_ASSERT (!rig_->isNull ());
-
- // COM/OLE exceptions get signaled
- connect (&*rig_, SIGNAL (exception (int, QString, QString, QString)), this, SLOT (handle_COM_exception (int, QString, QString, QString)));
-
- offline_timer_.reset (new QTimer); // instantiate here as constructor runs in wrong thread
- offline_timer_->setSingleShot (true);
- connect (offline_timer_.data (), &QTimer::timeout, [this] () {offline ("Rig went offline");});
-
- for (int i = 0; i < 5; ++i)
- {
- // leave some time for Omni-Rig to do its first poll
- QThread::msleep (300);
- if (OmniRig::ST_ONLINE == rig_->Status ())
- {
- break;
- }
- }
-
- if (OmniRig::ST_ONLINE != rig_->Status ())
- {
- CAT_ERROR ("rig not online");
- throw_qstring ("OmniRig: " + rig_->StatusStr ());
- }
-
- if (use_for_ptt_ && (TransceiverFactory::PTT_method_DTR == ptt_type_ || TransceiverFactory::PTT_method_RTS == ptt_type_))
- {
- // fetch the interface for the serial port if we need it for PTT
- port_.reset (new OmniRig::PortBits (rig_->PortBits ()));
-
- Q_ASSERT (port_);
- Q_ASSERT (!port_->isNull ());
-
- // COM/OLE exceptions get signaled
- connect (&*port_, SIGNAL (exception (int, QString, QString, QString)), this, SLOT (handle_COM_exception (int, QString, QString, QString)));
-
- CAT_TRACE ("OmniRig RTS state: " << port_->Rts ());
-
- // remove locking because it doesn't seem to work properly
- // if (!port_->Lock ()) // try to take exclusive use of the OmniRig serial port for PTT
- // {
- // CAT_WARNING ("Failed to get exclusive use of serial port for PTT from OmniRig");
- // }
-
- // start off so we don't accidentally key the radio
- if (TransceiverFactory::PTT_method_DTR == ptt_type_)
- {
- port_->SetDtr (false);
- }
- else // RTS
- {
- port_->SetRts (false);
- }
- }
-
- rig_type_ = rig_->RigType ();
- readable_params_ = rig_->ReadableParams ();
- writable_params_ = rig_->WriteableParams ();
-
- CAT_INFO (QString {"OmniRig initial rig type: %1 readable params=0x%2 writable params=0x%3 for rig %4"}
- .arg (rig_type_)
- .arg (readable_params_, 8, 16, QChar ('0'))
- .arg (writable_params_, 8, 16, QChar ('0'))
- .arg (rig_number_));
- update_rx_frequency (rig_->GetRxFrequency ());
- int resolution {0};
- if (OmniRig::PM_UNKNOWN == rig_->Vfo ()
- && (writable_params_ & (OmniRig::PM_VFOA | OmniRig::PM_VFOB))
- == (OmniRig::PM_VFOA | OmniRig::PM_VFOB))
- {
- // start with VFO A (probably MAIN) on rigs that we
- // can't query VFO but can set explicitly
- rig_->SetVfo (OmniRig::PM_VFOA);
- }
- auto f = state ().frequency ();
-
- /* Deactivate frequency resolution test for now as it does not work with OmniRig 1.20
- if (f % 10) return resolution; // 1Hz resolution
- auto test_frequency = f - f % 100 + 55;
- if (OmniRig::PM_FREQ & writable_params_)
- {
- rig_->SetFreq (test_frequency);
- }
- else if (reversed_ && (OmniRig::PM_FREQB & writable_params_))
- {
- rig_->SetFreqB (test_frequency);
- }
- else if (!reversed_ && (OmniRig::PM_FREQA & writable_params_))
- {
- rig_->SetFreqA (test_frequency);
- }
- else
- {
- throw_qstring (tr ("OmniRig: don't know how to set rig frequency"));
- }
- switch (rig_->GetRxFrequency () - test_frequency)
- {
- case -5: resolution = -1; break; // 10Hz truncated
- case 5: resolution = 1; break; // 10Hz rounded
- case -15: resolution = -2; break; // 20Hz truncated
- case -55: resolution = -2; break; // 100Hz truncated
- case 45: resolution = 2; break; // 100Hz rounded
- }
- if (1 == resolution) // may be 20Hz rounded
- {
- test_frequency = f - f % 100 + 51;
- if (OmniRig::PM_FREQ & writable_params_)
- {
- rig_->SetFreq (test_frequency);
- }
- else if (reversed_ && (OmniRig::PM_FREQB & writable_params_))
- {
- rig_->SetFreqB (test_frequency);
- }
- else if (!reversed_ && (OmniRig::PM_FREQA & writable_params_))
- {
- rig_->SetFreqA (test_frequency);
- }
- if (9 == rig_->GetRxFrequency () - test_frequency)
- {
- resolution = 2; // 20Hz rounded
- }
- }
-*/
- // For OmniRig v1.19 or later we need a delay between GetRxFrequency () and SetFreq (f),
- // otherwise rig QRG stays at f+55 Hz. 200 ms should do job for all modern transceivers.
- // However, with very slow rigs, QRG may still stay at f+55 Hz. Such rigs should use v1.18.
- // Due to the asynchronous nature of Omnirig commands, a better solution would be to implement
- // an event handler for OmniRig's OnParamChange event and read the frequency inside that handler.
-
- if (OmniRig::PM_FREQ & writable_params_)
- {
- rig_->SetFreq (f);
- }
- else if (reversed_ && (OmniRig::PM_FREQB & writable_params_))
- {
- rig_->SetFreqB (f);
- }
- else if (!reversed_ && (OmniRig::PM_FREQA & writable_params_))
- {
- rig_->SetFreqA (f);
- }
- update_rx_frequency (f);
- CAT_TRACE ("started");
-
- resolution = 1; // instead set resolutiion manually
- return resolution;
- }
- catch (...)
- {
- CAT_TRACE ("start threw exception");
- throw;
- }
-}
-
-void OmniRigTransceiver::do_stop ()
-{
- CAT_TRACE ("stopping");
- QThread::msleep (200); // leave some time for pending
- // commands at the server end
-
- offline_timer_.reset (); // destroy here rather than in
- // destructor as destructor runs in
- // wrong thread
-
- if (port_ && !port_->isNull ())
- {
- // port_->Unlock (); // release serial port
- port_->clear ();
- port_.reset ();
- }
- if (omni_rig_ && !omni_rig_->isNull ())
- {
- if (rig_ && !rig_->isNull ())
- {
- rig_->clear ();
- rig_.reset ();
- CAT_TRACE ("rig_ reset");
- }
- omni_rig_->clear ();
- omni_rig_.reset ();
- }
-
- if (wrapped_) wrapped_->stop ();
-
- CAT_TRACE ("stopped");
-}
-
-void OmniRigTransceiver::handle_COM_exception (int code, QString source, QString desc, QString help)
-{
- CAT_ERROR ((QString::number (code) + " at " + source + ": " + desc + " (" + help + ')'));
- throw_qstring (tr ("OmniRig COM/OLE error: %1 at %2: %3 (%4)").arg (QString::number (code)).arg (source). arg (desc). arg (help));
-}
-
-void OmniRigTransceiver::handle_visible_change ()
-{
- if (!omni_rig_ || omni_rig_->isNull ()) return;
- CAT_TRACE ("visibility change: visibility =" << omni_rig_->DialogVisible ());
-}
-
-void OmniRigTransceiver::handle_rig_type_change (int rig_number)
-{
- CAT_TRACE ("rig type change: rig =" << rig_number);
- if (rig_number_ == rig_number)
- {
- if (!rig_ || rig_->isNull ()) return;
- readable_params_ = rig_->ReadableParams ();
- writable_params_ = rig_->WriteableParams ();
- CAT_INFO (QString {"rig type change to: %1 readable params = 0x%2 writable params = 0x%3 for rig %4"}
- .arg (rig_->RigType ())
- .arg (readable_params_, 8, 16, QChar ('0'))
- .arg (writable_params_, 8, 16, QChar ('0'))
- .arg (rig_number));
- }
-}
-
-void OmniRigTransceiver::handle_status_change (int rig_number)
-{
- CAT_TRACE (QString {"status change for rig %1"}.arg (rig_number));
- if (rig_number_ == rig_number)
- {
- if (!rig_ || rig_->isNull ()) return;
- auto const& status = rig_->StatusStr ();
- CAT_TRACE ("OmniRig status change: new status = " << status);
- if (OmniRig::ST_ONLINE != rig_->Status ())
- {
- if (!offline_timer_->isActive ())
- {
- // Omni-Rig is prone to reporting the rig offline and
- // then recovering autonomously, so we will give it a
- // few seconds to make its mind up
- offline_timer_->start (10000);
- }
- }
- else
- {
- offline_timer_->stop (); // good to go again
- }
- // else
- // {
- // update_rx_frequency (rig_->GetRxFrequency ());
- // update_complete ();
- // CAT_TRACE ("frequency:" << state ().frequency ());
- // }
- }
-}
-
-void OmniRigTransceiver::handle_params_change (int rig_number, int params)
-{
- CAT_TRACE (QString {"params change: params=0x%1 for rig %2"}
- .arg (params, 8, 16, QChar ('0'))
- .arg (rig_number)
- << "state before:" << state ());
- if (rig_number_ == rig_number)
- {
- if (!rig_ || rig_->isNull ()) return;
- // starting_ = false;
- TransceiverState old_state {state ()};
- auto need_frequency = false;
-
- if (params & OmniRig::PM_VFOAA)
- {
- CAT_TRACE ("VFOAA");
- update_split (false);
- reversed_ = false;
- update_rx_frequency (rig_->FreqA ());
- update_other_frequency (rig_->FreqB ());
- }
- if (params & OmniRig::PM_VFOAB)
- {
- CAT_TRACE ("VFOAB");
- update_split (true);
- reversed_ = false;
- update_rx_frequency (rig_->FreqA ());
- update_other_frequency (rig_->FreqB ());
- }
- if (params & OmniRig::PM_VFOBA)
- {
- CAT_TRACE ("VFOBA");
- update_split (true);
- reversed_ = true;
- update_other_frequency (rig_->FreqA ());
- update_rx_frequency (rig_->FreqB ());
- }
- if (params & OmniRig::PM_VFOBB)
- {
- CAT_TRACE ("VFOBB");
- update_split (false);
- reversed_ = true;
- update_other_frequency (rig_->FreqA ());
- update_rx_frequency (rig_->FreqB ());
- }
- if (params & OmniRig::PM_VFOA)
- {
- CAT_TRACE ("VFOA");
- reversed_ = false;
- need_frequency = true;
- }
- if (params & OmniRig::PM_VFOB)
- {
- CAT_TRACE ("VFOB");
- reversed_ = true;
- need_frequency = true;
- }
-
- if (params & OmniRig::PM_FREQ)
- {
- need_frequency = true;
- }
- if (params & OmniRig::PM_FREQA)
- {
- auto f = rig_->FreqA ();
- CAT_TRACE ("FREQA = " << f);
- if (reversed_)
- {
- update_other_frequency (f);
- }
- else
- {
- update_rx_frequency (f);
- }
- }
- if (params & OmniRig::PM_FREQB)
- {
- auto f = rig_->FreqB ();
- CAT_TRACE ("FREQB = " << f);
- if (reversed_)
- {
- update_rx_frequency (f);
- }
- else
- {
- update_other_frequency (f);
- }
- }
- if (need_frequency)
- {
- if (readable_params_ & OmniRig::PM_FREQA)
- {
- auto f = rig_->FreqA ();
- if (f)
- {
- CAT_TRACE ("FREQA = " << f);
- if (reversed_)
- {
- update_other_frequency (f);
- }
- else
- {
- update_rx_frequency (f);
- }
- }
- }
- if (readable_params_ & OmniRig::PM_FREQB)
- {
- auto f = rig_->FreqB ();
- if (f)
- {
- CAT_TRACE ("FREQB = " << f);
- if (reversed_)
- {
- update_rx_frequency (f);
- }
- else
- {
- update_other_frequency (f);
- }
- }
- }
- if (readable_params_ & OmniRig::PM_FREQ && !state ().ptt ())
- {
- auto f = rig_->Freq ();
- if (f)
- {
- CAT_TRACE ("FREQ = " << f);
- update_rx_frequency (f);
- }
- }
- }
- if (params & OmniRig::PM_PITCH)
- {
- CAT_TRACE ("PITCH");
- }
- if (params & OmniRig::PM_RITOFFSET)
- {
- CAT_TRACE ("RITOFFSET");
- }
- if (params & OmniRig::PM_RIT0)
- {
- CAT_TRACE ("RIT0");
- }
- if (params & OmniRig::PM_VFOEQUAL)
- {
- auto f = readable_params_ & OmniRig::PM_FREQA ? rig_->FreqA () : rig_->Freq ();
- auto m = map_mode (rig_->Mode ());
- CAT_TRACE (QString {"VFOEQUAL f=%1 m=%2"}.arg (f).arg (m));
- update_rx_frequency (f);
- update_other_frequency (f);
- update_mode (m);
- }
- if (params & OmniRig::PM_VFOSWAP)
- {
- CAT_TRACE ("VFOSWAP");
- auto f = state ().tx_frequency ();
- update_other_frequency (state ().frequency ());
- update_rx_frequency (f);
- update_mode (map_mode (rig_->Mode ()));
- }
- if (params & OmniRig::PM_SPLITON)
- {
- CAT_TRACE ("SPLITON");
- update_split (true);
- }
- if (params & OmniRig::PM_SPLITOFF)
- {
- CAT_TRACE ("SPLITOFF");
- update_split (false);
- }
- if (params & OmniRig::PM_RITON)
- {
- CAT_TRACE ("RITON");
- }
- if (params & OmniRig::PM_RITOFF)
- {
- CAT_TRACE ("RITOFF");
- }
- if (params & OmniRig::PM_XITON)
- {
- CAT_TRACE ("XITON");
- }
- if (params & OmniRig::PM_XITOFF)
- {
- CAT_TRACE ("XITOFF");
- }
- if (params & OmniRig::PM_RX)
- {
- CAT_TRACE ("RX");
- update_PTT (false);
- }
- if (params & OmniRig::PM_TX)
- {
- CAT_TRACE ("TX");
- update_PTT ();
- }
- if (params & OmniRig::PM_CW_U)
- {
- CAT_TRACE ("CW-R");
- update_mode (CW_R);
- }
- if (params & OmniRig::PM_CW_L)
- {
- CAT_TRACE ("CW");
- update_mode (CW);
- }
- if (params & OmniRig::PM_SSB_U)
- {
- CAT_TRACE ("USB");
- update_mode (USB);
- }
- if (params & OmniRig::PM_SSB_L)
- {
- CAT_TRACE ("LSB");
- update_mode (LSB);
- }
- if (params & OmniRig::PM_DIG_U)
- {
- CAT_TRACE ("DATA-U");
- update_mode (DIG_U);
- }
- if (params & OmniRig::PM_DIG_L)
- {
- CAT_TRACE ("DATA-L");
- update_mode (DIG_L);
- }
- if (params & OmniRig::PM_AM)
- {
- CAT_TRACE ("AM");
- update_mode (AM);
- }
- if (params & OmniRig::PM_FM)
- {
- CAT_TRACE ("FM");
- update_mode (FM);
- }
-
- if (old_state != state () || send_update_signal_)
- {
- update_complete ();
- send_update_signal_ = false;
- }
- CAT_TRACE ("OmniRig params change: state after:" << state ());
- }
-}
-
-void OmniRigTransceiver::handle_custom_reply (int rig_number, QVariant const& command, QVariant const& reply)
-{
- (void)command;
- (void)reply;
-
- if (rig_number_ == rig_number)
- {
- if (!rig_ || rig_->isNull ()) return;
- CAT_TRACE ("custom command" << command.toString ()
- << "with reply" << reply.toString ()
- << QString ("for rig %1").arg (rig_number));
- CAT_TRACE ("rig number:" << rig_number_ << ':' << state ());
- }
-}
-
-void OmniRigTransceiver::do_ptt (bool on)
-{
- CAT_TRACE (on << state ());
- if (use_for_ptt_ && TransceiverFactory::PTT_method_CAT == ptt_type_)
- {
- CAT_TRACE ("set PTT");
- if (rig_ && !rig_->isNull ())
- {
- rig_->SetTx (on ? OmniRig::PM_TX : OmniRig::PM_RX);
- }
- }
- else
- {
- if (port_ && !port_->isNull ())
- {
- if (TransceiverFactory::PTT_method_RTS == ptt_type_)
- {
- CAT_TRACE ("set RTS");
- port_->SetRts (on);
- }
- else // "DTR"
- {
- CAT_TRACE ("set DTR");
- port_->SetDtr (on);
- }
- }
- else if (wrapped_)
- {
- CAT_TRACE ("set PTT using basic transceiver");
- TransceiverState new_state {wrapped_->state ()};
- new_state.ptt (on);
- wrapped_->set (new_state, 0);
- }
- }
- update_PTT (on);
-}
-
-void OmniRigTransceiver::do_frequency (Frequency f, MODE m, bool /*no_ignore*/)
-{
- CAT_TRACE (f << ' ' << state ());
- if (!rig_ || rig_->isNull ()) return;
- if (UNK != m)
- {
- do_mode (m);
- }
- if (OmniRig::PM_FREQ & writable_params_)
- {
- rig_->SetFreq (f);
- update_rx_frequency (f);
- }
- else if (reversed_ && (OmniRig::PM_FREQB & writable_params_))
- {
- rig_->SetFreqB (f);
- update_rx_frequency (f);
- }
- else if (!reversed_ && (OmniRig::PM_FREQA & writable_params_))
- {
- rig_->SetFreqA (f);
- update_rx_frequency (f);
- }
- else
- {
- throw_qstring (tr ("OmniRig: don't know how to set rig frequency"));
- }
-}
-
-void OmniRigTransceiver::do_tx_frequency (Frequency tx, MODE m, bool /*no_ignore*/)
-{
- CAT_TRACE (tx << ' ' << state ());
- if (!rig_ || rig_->isNull ()) return;
- bool split {tx != 0};
- if (split)
- {
- if (UNK != m)
- {
- do_mode (m);
- if (OmniRig::PM_UNKNOWN == rig_->Vfo ())
- {
- if (writable_params_ & OmniRig::PM_VFOEQUAL)
- {
- // nothing to do here because OmniRig will use VFO
- // equalize to set the mode of the Tx VFO for us
- }
- else if ((writable_params_ & (OmniRig::PM_VFOA | OmniRig::PM_VFOB))
- == (OmniRig::PM_VFOA | OmniRig::PM_VFOB))
- {
- rig_->SetVfo (OmniRig::PM_VFOB);
- do_mode (m);
- rig_->SetVfo (OmniRig::PM_VFOA);
- }
- else if (writable_params_ & OmniRig::PM_VFOSWAP)
- {
- rig_->SetVfo (OmniRig::PM_VFOSWAP);
- do_mode (m);
- rig_->SetVfo (OmniRig::PM_VFOSWAP);
- }
- }
- }
- CAT_TRACE ("set SPLIT mode on");
- rig_->SetSplitMode (state ().frequency (), tx);
- update_other_frequency (tx);
- update_split (true);
- }
- else
- {
- CAT_TRACE ("set SPLIT mode off");
- rig_->SetSimplexMode (state ().frequency ());
- update_split (false);
- }
- bool notify {false};
- if (readable_params_ & OmniRig::PM_FREQ || !(readable_params_ & (OmniRig::PM_FREQA | OmniRig::PM_FREQB)))
- {
- update_other_frequency (tx); // async updates won't return this
- // so just store it and hope
- // operator doesn't change the
- // "back" VFO on rig
- notify = true;
- }
- if (!((OmniRig::PM_VFOAB | OmniRig::PM_VFOBA | OmniRig::PM_SPLITON) & readable_params_))
- {
- CAT_TRACE ("setting SPLIT manually");
- update_split (split); // we can't read it so just set and
- // hope op doesn't change it
- notify = true;
- }
- if (notify)
- {
- update_complete ();
- }
-}
-
-void OmniRigTransceiver::do_mode (MODE mode)
-{
- CAT_TRACE (mode << ' ' << state ());
- if (!rig_ || rig_->isNull ()) return;
- // TODO: G4WJS OmniRig doesn't seem to have any capability of tracking/setting VFO B mode
- auto mapped = map_mode (mode);
- if (mapped & writable_params_)
- {
- rig_->SetMode (mapped);
- update_mode (mode);
- }
- else
- {
- offline ("OmniRig invalid mode");
- }
-}
+#include "OmniRigTransceiver.hpp" + +#include <QDebug> +#include <objbase.h> +#include <QThread> +#include <QEventLoop> + +#include "qt_helpers.hpp" + +#include "moc_OmniRigTransceiver.cpp" + +namespace +{ + auto constexpr OmniRig_transceiver_one_name = "OmniRig Rig 1"; + auto constexpr OmniRig_transceiver_two_name = "OmniRig Rig 2"; +} + +auto OmniRigTransceiver::map_mode (OmniRig::RigParamX param) -> MODE +{ + if (param & OmniRig::PM_CW_U) + { + return CW_R; + } + else if (param & OmniRig::PM_CW_L) + { + return CW; + } + else if (param & OmniRig::PM_SSB_U) + { + return USB; + } + else if (param & OmniRig::PM_SSB_L) + { + return LSB; + } + else if (param & OmniRig::PM_DIG_U) + { + return DIG_U; + } + else if (param & OmniRig::PM_DIG_L) + { + return DIG_L; + } + else if (param & OmniRig::PM_AM) + { + return AM; + } + else if (param & OmniRig::PM_FM) + { + return FM; + } + CAT_ERROR ("unrecognized mode"); + throw_qstring (tr ("OmniRig: unrecognized mode")); + return UNK; +} + +OmniRig::RigParamX OmniRigTransceiver::map_mode (MODE mode) +{ + switch (mode) + { + case AM: return OmniRig::PM_AM; + case CW: return OmniRig::PM_CW_L; + case CW_R: return OmniRig::PM_CW_U; + case USB: return OmniRig::PM_SSB_U; + case LSB: return OmniRig::PM_SSB_L; + case FSK: return OmniRig::PM_DIG_L; + case FSK_R: return OmniRig::PM_DIG_U; + case DIG_L: return OmniRig::PM_DIG_L; + case DIG_U: return OmniRig::PM_DIG_U; + case FM: return OmniRig::PM_FM; + case DIG_FM: return OmniRig::PM_FM; + default: break; + } + return OmniRig::PM_SSB_U; // quieten compiler grumble +} + +void OmniRigTransceiver::register_transceivers (logger_type *, + TransceiverFactory::Transceivers * registry, + unsigned id1, unsigned id2) +{ + (*registry)[OmniRig_transceiver_one_name] = TransceiverFactory::Capabilities { + id1 + , TransceiverFactory::Capabilities::none // COM isn't serial or network + , true // does PTT + , false // doesn't select mic/data (use OmniRig config file) + , true // can remote control RTS nd DTR + , true // asynchronous interface + }; + (*registry)[OmniRig_transceiver_two_name] = TransceiverFactory::Capabilities { + id2 + , TransceiverFactory::Capabilities::none // COM isn't serial or network + , true // does PTT + , false // doesn't select mic/data (use OmniRig config file) + , true // can remote control RTS nd DTR + , true // asynchronous interface + }; +} + +OmniRigTransceiver::OmniRigTransceiver (logger_type * the_logger, + std::unique_ptr<TransceiverBase> wrapped, + RigNumber n, TransceiverFactory::PTTMethod ptt_type, + QString const& ptt_port, QObject * parent) + : TransceiverBase {the_logger, parent} + , wrapped_ {std::move (wrapped)} + , use_for_ptt_ {TransceiverFactory::PTT_method_CAT == ptt_type || ("CAT" == ptt_port && (TransceiverFactory::PTT_method_RTS == ptt_type || TransceiverFactory::PTT_method_DTR == ptt_type))} + , ptt_type_ {ptt_type} + , rig_number_ {n} + , readable_params_ {0} + , writable_params_ {0} + , send_update_signal_ {false} + , reversed_ {false} +{ + CoInitializeEx (nullptr, 0 /*COINIT_APARTMENTTHREADED*/); // required because Qt only does this for GUI thread + CAT_TRACE ("constructed"); +} + +OmniRigTransceiver::~OmniRigTransceiver () +{ + CAT_TRACE ("destroying"); + CoUninitialize (); +} + +int OmniRigTransceiver::do_start () +{ + CAT_TRACE ("starting"); + try + { + if (wrapped_) wrapped_->start (0); + + omni_rig_.reset (new OmniRig::OmniRigX {this}); + if (omni_rig_->isNull ()) + { + CAT_ERROR ("failed to start COM server"); + throw_qstring (tr ("Failed to start OmniRig COM server")); + } + + // COM/OLE exceptions get signaled + connect (&*omni_rig_, SIGNAL (exception (int, QString, QString, QString)), this, SLOT (handle_COM_exception (int, QString, QString, QString))); + + // IOmniRigXEvent interface signals + connect (&*omni_rig_, SIGNAL (VisibleChange ()), this, SLOT (handle_visible_change ())); + connect (&*omni_rig_, SIGNAL (RigTypeChange (int)), this, SLOT (handle_rig_type_change (int))); + connect (&*omni_rig_, SIGNAL (StatusChange (int)), this, SLOT (handle_status_change (int))); + connect (&*omni_rig_, SIGNAL (ParamsChange (int, int)), this, SLOT (handle_params_change (int, int))); + connect (&*omni_rig_ + , SIGNAL (CustomReply (int, QVariant const&, QVariant const&)) + , this, SLOT (handle_custom_reply (int, QVariant const&, QVariant const&))); + + CAT_INFO ("OmniRig s/w version: " << static_cast<quint16> (omni_rig_->SoftwareVersion () >> 16) + << '.' << static_cast<quint16> (omni_rig_->SoftwareVersion () & 0xffff) + << " i/f version: " << static_cast<int> (omni_rig_->InterfaceVersion () >> 8 & 0xff) + << '.' << static_cast<int> (omni_rig_->InterfaceVersion () && 0xff)); + + // fetch the interface of the RigX CoClass and instantiate a proxy object + switch (rig_number_) + { + case One: rig_.reset (new OmniRig::RigX (omni_rig_->Rig1 ())); break; + case Two: rig_.reset (new OmniRig::RigX (omni_rig_->Rig2 ())); break; + } + + Q_ASSERT (rig_); + Q_ASSERT (!rig_->isNull ()); + + // COM/OLE exceptions get signaled + connect (&*rig_, SIGNAL (exception (int, QString, QString, QString)), this, SLOT (handle_COM_exception (int, QString, QString, QString))); + + offline_timer_.reset (new QTimer); // instantiate here as constructor runs in wrong thread + offline_timer_->setSingleShot (true); + connect (offline_timer_.data (), &QTimer::timeout, [this] () {offline ("Rig went offline");}); + + for (int i = 0; i < 5; ++i) + { + // leave some time for Omni-Rig to do its first poll + QThread::msleep (300); + if (OmniRig::ST_ONLINE == rig_->Status ()) + { + break; + } + } + + if (OmniRig::ST_ONLINE != rig_->Status ()) + { + CAT_ERROR ("rig not online"); + throw_qstring ("OmniRig: " + rig_->StatusStr ()); + } + + if (use_for_ptt_ && (TransceiverFactory::PTT_method_DTR == ptt_type_ || TransceiverFactory::PTT_method_RTS == ptt_type_)) + { + // fetch the interface for the serial port if we need it for PTT + port_.reset (new OmniRig::PortBits (rig_->PortBits ())); + + Q_ASSERT (port_); + Q_ASSERT (!port_->isNull ()); + + // COM/OLE exceptions get signaled + connect (&*port_, SIGNAL (exception (int, QString, QString, QString)), this, SLOT (handle_COM_exception (int, QString, QString, QString))); + + CAT_TRACE ("OmniRig RTS state: " << port_->Rts ()); + + // remove locking because it doesn't seem to work properly + // if (!port_->Lock ()) // try to take exclusive use of the OmniRig serial port for PTT + // { + // CAT_WARNING ("Failed to get exclusive use of serial port for PTT from OmniRig"); + // } + + // start off so we don't accidentally key the radio + if (TransceiverFactory::PTT_method_DTR == ptt_type_) + { + port_->SetDtr (false); + } + else // RTS + { + port_->SetRts (false); + } + } + + rig_type_ = rig_->RigType (); + readable_params_ = rig_->ReadableParams (); + writable_params_ = rig_->WriteableParams (); + + CAT_INFO (QString {"OmniRig initial rig type: %1 readable params=0x%2 writable params=0x%3 for rig %4"} + .arg (rig_type_) + .arg (readable_params_, 8, 16, QChar ('0')) + .arg (writable_params_, 8, 16, QChar ('0')) + .arg (rig_number_)); + update_rx_frequency (rig_->GetRxFrequency ()); + int resolution {0}; + if (OmniRig::PM_UNKNOWN == rig_->Vfo () + && (writable_params_ & (OmniRig::PM_VFOA | OmniRig::PM_VFOB)) + == (OmniRig::PM_VFOA | OmniRig::PM_VFOB)) + { + // start with VFO A (probably MAIN) on rigs that we + // can't query VFO but can set explicitly + rig_->SetVfo (OmniRig::PM_VFOA); + } + auto f = state ().frequency (); + + /* Deactivate frequency resolution test for now as it does not work with OmniRig 1.20 + if (f % 10) return resolution; // 1Hz resolution + auto test_frequency = f - f % 100 + 55; + if (OmniRig::PM_FREQ & writable_params_) + { + rig_->SetFreq (test_frequency); + } + else if (reversed_ && (OmniRig::PM_FREQB & writable_params_)) + { + rig_->SetFreqB (test_frequency); + } + else if (!reversed_ && (OmniRig::PM_FREQA & writable_params_)) + { + rig_->SetFreqA (test_frequency); + } + else + { + throw_qstring (tr ("OmniRig: don't know how to set rig frequency")); + } + switch (rig_->GetRxFrequency () - test_frequency) + { + case -5: resolution = -1; break; // 10Hz truncated + case 5: resolution = 1; break; // 10Hz rounded + case -15: resolution = -2; break; // 20Hz truncated + case -55: resolution = -2; break; // 100Hz truncated + case 45: resolution = 2; break; // 100Hz rounded + } + if (1 == resolution) // may be 20Hz rounded + { + test_frequency = f - f % 100 + 51; + if (OmniRig::PM_FREQ & writable_params_) + { + rig_->SetFreq (test_frequency); + } + else if (reversed_ && (OmniRig::PM_FREQB & writable_params_)) + { + rig_->SetFreqB (test_frequency); + } + else if (!reversed_ && (OmniRig::PM_FREQA & writable_params_)) + { + rig_->SetFreqA (test_frequency); + } + if (9 == rig_->GetRxFrequency () - test_frequency) + { + resolution = 2; // 20Hz rounded + } + } +*/ + // For OmniRig v1.19 or later we need a delay between GetRxFrequency () and SetFreq (f), + // otherwise rig QRG stays at f+55 Hz. 200 ms should do job for all modern transceivers. + // However, with very slow rigs, QRG may still stay at f+55 Hz. Such rigs should use v1.18. + // Due to the asynchronous nature of Omnirig commands, a better solution would be to implement + // an event handler for OmniRig's OnParamChange event and read the frequency inside that handler. + + if (OmniRig::PM_FREQ & writable_params_) + { + rig_->SetFreq (f); + } + else if (reversed_ && (OmniRig::PM_FREQB & writable_params_)) + { + rig_->SetFreqB (f); + } + else if (!reversed_ && (OmniRig::PM_FREQA & writable_params_)) + { + rig_->SetFreqA (f); + } + update_rx_frequency (f); + CAT_TRACE ("started"); + + resolution = 1; // instead set resolutiion manually + return resolution; + } + catch (...) + { + CAT_TRACE ("start threw exception"); + throw; + } +} + +void OmniRigTransceiver::do_stop () +{ + CAT_TRACE ("stopping"); + QThread::msleep (200); // leave some time for pending + // commands at the server end + + offline_timer_.reset (); // destroy here rather than in + // destructor as destructor runs in + // wrong thread + + if (port_ && !port_->isNull ()) + { + // port_->Unlock (); // release serial port + port_->clear (); + port_.reset (); + } + if (omni_rig_ && !omni_rig_->isNull ()) + { + if (rig_ && !rig_->isNull ()) + { + rig_->clear (); + rig_.reset (); + CAT_TRACE ("rig_ reset"); + } + omni_rig_->clear (); + omni_rig_.reset (); + } + + if (wrapped_) wrapped_->stop (); + + CAT_TRACE ("stopped"); +} + +void OmniRigTransceiver::handle_COM_exception (int code, QString source, QString desc, QString help) +{ + CAT_ERROR ((QString::number (code) + " at " + source + ": " + desc + " (" + help + ')')); + throw_qstring (tr ("OmniRig COM/OLE error: %1 at %2: %3 (%4)").arg (QString::number (code)).arg (source). arg (desc). arg (help)); +} + +void OmniRigTransceiver::handle_visible_change () +{ + if (!omni_rig_ || omni_rig_->isNull ()) return; + CAT_TRACE ("visibility change: visibility =" << omni_rig_->DialogVisible ()); +} + +void OmniRigTransceiver::handle_rig_type_change (int rig_number) +{ + CAT_TRACE ("rig type change: rig =" << rig_number); + if (rig_number_ == rig_number) + { + if (!rig_ || rig_->isNull ()) return; + readable_params_ = rig_->ReadableParams (); + writable_params_ = rig_->WriteableParams (); + CAT_INFO (QString {"rig type change to: %1 readable params = 0x%2 writable params = 0x%3 for rig %4"} + .arg (rig_->RigType ()) + .arg (readable_params_, 8, 16, QChar ('0')) + .arg (writable_params_, 8, 16, QChar ('0')) + .arg (rig_number)); + } +} + +void OmniRigTransceiver::handle_status_change (int rig_number) +{ + CAT_TRACE (QString {"status change for rig %1"}.arg (rig_number)); + if (rig_number_ == rig_number) + { + if (!rig_ || rig_->isNull ()) return; + auto const& status = rig_->StatusStr (); + CAT_TRACE ("OmniRig status change: new status = " << status); + if (OmniRig::ST_ONLINE != rig_->Status ()) + { + if (!offline_timer_->isActive ()) + { + // Omni-Rig is prone to reporting the rig offline and + // then recovering autonomously, so we will give it a + // few seconds to make its mind up + offline_timer_->start (10000); + } + } + else + { + offline_timer_->stop (); // good to go again + } + // else + // { + // update_rx_frequency (rig_->GetRxFrequency ()); + // update_complete (); + // CAT_TRACE ("frequency:" << state ().frequency ()); + // } + } +} + +void OmniRigTransceiver::handle_params_change (int rig_number, int params) +{ + CAT_TRACE (QString {"params change: params=0x%1 for rig %2"} + .arg (params, 8, 16, QChar ('0')) + .arg (rig_number) + << "state before:" << state ()); + if (rig_number_ == rig_number) + { + if (!rig_ || rig_->isNull ()) return; + // starting_ = false; + TransceiverState old_state {state ()}; + auto need_frequency = false; + + if (params & OmniRig::PM_VFOAA) + { + CAT_TRACE ("VFOAA"); + update_split (false); + reversed_ = false; + update_rx_frequency (rig_->FreqA ()); + update_other_frequency (rig_->FreqB ()); + } + if (params & OmniRig::PM_VFOAB) + { + CAT_TRACE ("VFOAB"); + update_split (true); + reversed_ = false; + update_rx_frequency (rig_->FreqA ()); + update_other_frequency (rig_->FreqB ()); + } + if (params & OmniRig::PM_VFOBA) + { + CAT_TRACE ("VFOBA"); + update_split (true); + reversed_ = true; + update_other_frequency (rig_->FreqA ()); + update_rx_frequency (rig_->FreqB ()); + } + if (params & OmniRig::PM_VFOBB) + { + CAT_TRACE ("VFOBB"); + update_split (false); + reversed_ = true; + update_other_frequency (rig_->FreqA ()); + update_rx_frequency (rig_->FreqB ()); + } + if (params & OmniRig::PM_VFOA) + { + CAT_TRACE ("VFOA"); + reversed_ = false; + need_frequency = true; + } + if (params & OmniRig::PM_VFOB) + { + CAT_TRACE ("VFOB"); + reversed_ = true; + need_frequency = true; + } + + if (params & OmniRig::PM_FREQ) + { + need_frequency = true; + } + if (params & OmniRig::PM_FREQA) + { + auto f = rig_->FreqA (); + CAT_TRACE ("FREQA = " << f); + if (reversed_) + { + update_other_frequency (f); + } + else + { + update_rx_frequency (f); + } + } + if (params & OmniRig::PM_FREQB) + { + auto f = rig_->FreqB (); + CAT_TRACE ("FREQB = " << f); + if (reversed_) + { + update_rx_frequency (f); + } + else + { + update_other_frequency (f); + } + } + if (need_frequency) + { + if (readable_params_ & OmniRig::PM_FREQA) + { + auto f = rig_->FreqA (); + if (f) + { + CAT_TRACE ("FREQA = " << f); + if (reversed_) + { + update_other_frequency (f); + } + else + { + update_rx_frequency (f); + } + } + } + if (readable_params_ & OmniRig::PM_FREQB) + { + auto f = rig_->FreqB (); + if (f) + { + CAT_TRACE ("FREQB = " << f); + if (reversed_) + { + update_rx_frequency (f); + } + else + { + update_other_frequency (f); + } + } + } + if (readable_params_ & OmniRig::PM_FREQ && !state ().ptt ()) + { + auto f = rig_->Freq (); + if (f) + { + CAT_TRACE ("FREQ = " << f); + update_rx_frequency (f); + } + } + } + if (params & OmniRig::PM_PITCH) + { + CAT_TRACE ("PITCH"); + } + if (params & OmniRig::PM_RITOFFSET) + { + CAT_TRACE ("RITOFFSET"); + } + if (params & OmniRig::PM_RIT0) + { + CAT_TRACE ("RIT0"); + } + if (params & OmniRig::PM_VFOEQUAL) + { + auto f = readable_params_ & OmniRig::PM_FREQA ? rig_->FreqA () : rig_->Freq (); + auto m = map_mode (rig_->Mode ()); + CAT_TRACE (QString {"VFOEQUAL f=%1 m=%2"}.arg (f).arg (m)); + update_rx_frequency (f); + update_other_frequency (f); + update_mode (m); + } + if (params & OmniRig::PM_VFOSWAP) + { + CAT_TRACE ("VFOSWAP"); + auto f = state ().tx_frequency (); + update_other_frequency (state ().frequency ()); + update_rx_frequency (f); + update_mode (map_mode (rig_->Mode ())); + } + if (params & OmniRig::PM_SPLITON) + { + CAT_TRACE ("SPLITON"); + update_split (true); + } + if (params & OmniRig::PM_SPLITOFF) + { + CAT_TRACE ("SPLITOFF"); + update_split (false); + } + if (params & OmniRig::PM_RITON) + { + CAT_TRACE ("RITON"); + } + if (params & OmniRig::PM_RITOFF) + { + CAT_TRACE ("RITOFF"); + } + if (params & OmniRig::PM_XITON) + { + CAT_TRACE ("XITON"); + } + if (params & OmniRig::PM_XITOFF) + { + CAT_TRACE ("XITOFF"); + } + if (params & OmniRig::PM_RX) + { + CAT_TRACE ("RX"); + update_PTT (false); + } + if (params & OmniRig::PM_TX) + { + CAT_TRACE ("TX"); + update_PTT (); + } + if (params & OmniRig::PM_CW_U) + { + CAT_TRACE ("CW-R"); + update_mode (CW_R); + } + if (params & OmniRig::PM_CW_L) + { + CAT_TRACE ("CW"); + update_mode (CW); + } + if (params & OmniRig::PM_SSB_U) + { + CAT_TRACE ("USB"); + update_mode (USB); + } + if (params & OmniRig::PM_SSB_L) + { + CAT_TRACE ("LSB"); + update_mode (LSB); + } + if (params & OmniRig::PM_DIG_U) + { + CAT_TRACE ("DATA-U"); + update_mode (DIG_U); + } + if (params & OmniRig::PM_DIG_L) + { + CAT_TRACE ("DATA-L"); + update_mode (DIG_L); + } + if (params & OmniRig::PM_AM) + { + CAT_TRACE ("AM"); + update_mode (AM); + } + if (params & OmniRig::PM_FM) + { + CAT_TRACE ("FM"); + update_mode (FM); + } + + if (old_state != state () || send_update_signal_) + { + update_complete (); + send_update_signal_ = false; + } + CAT_TRACE ("OmniRig params change: state after:" << state ()); + } +} + +void OmniRigTransceiver::handle_custom_reply (int rig_number, QVariant const& command, QVariant const& reply) +{ + (void)command; + (void)reply; + + if (rig_number_ == rig_number) + { + if (!rig_ || rig_->isNull ()) return; + CAT_TRACE ("custom command" << command.toString () + << "with reply" << reply.toString () + << QString ("for rig %1").arg (rig_number)); + CAT_TRACE ("rig number:" << rig_number_ << ':' << state ()); + } +} + +void OmniRigTransceiver::do_ptt (bool on) +{ + CAT_TRACE (on << state ()); + if (use_for_ptt_ && TransceiverFactory::PTT_method_CAT == ptt_type_) + { + CAT_TRACE ("set PTT"); + if (rig_ && !rig_->isNull ()) + { + rig_->SetTx (on ? OmniRig::PM_TX : OmniRig::PM_RX); + } + } + else + { + if (port_ && !port_->isNull ()) + { + if (TransceiverFactory::PTT_method_RTS == ptt_type_) + { + CAT_TRACE ("set RTS"); + port_->SetRts (on); + } + else // "DTR" + { + CAT_TRACE ("set DTR"); + port_->SetDtr (on); + } + } + else if (wrapped_) + { + CAT_TRACE ("set PTT using basic transceiver"); + TransceiverState new_state {wrapped_->state ()}; + new_state.ptt (on); + wrapped_->set (new_state, 0); + } + } + update_PTT (on); +} + +void OmniRigTransceiver::do_frequency (Frequency f, MODE m, bool /*no_ignore*/) +{ + CAT_TRACE (f << ' ' << state ()); + if (!rig_ || rig_->isNull ()) return; + if (UNK != m) + { + do_mode (m); + } + if (OmniRig::PM_FREQ & writable_params_) + { + rig_->SetFreq (f); + update_rx_frequency (f); + } + else if (reversed_ && (OmniRig::PM_FREQB & writable_params_)) + { + rig_->SetFreqB (f); + update_rx_frequency (f); + } + else if (!reversed_ && (OmniRig::PM_FREQA & writable_params_)) + { + rig_->SetFreqA (f); + update_rx_frequency (f); + } + else + { + throw_qstring (tr ("OmniRig: don't know how to set rig frequency")); + } +} + +void OmniRigTransceiver::do_tx_frequency (Frequency tx, MODE m, bool /*no_ignore*/) +{ + CAT_TRACE (tx << ' ' << state ()); + if (!rig_ || rig_->isNull ()) return; + bool split {tx != 0}; + if (split) + { + if (UNK != m) + { + do_mode (m); + if (OmniRig::PM_UNKNOWN == rig_->Vfo ()) + { + if (writable_params_ & OmniRig::PM_VFOEQUAL) + { + // nothing to do here because OmniRig will use VFO + // equalize to set the mode of the Tx VFO for us + } + else if ((writable_params_ & (OmniRig::PM_VFOA | OmniRig::PM_VFOB)) + == (OmniRig::PM_VFOA | OmniRig::PM_VFOB)) + { + rig_->SetVfo (OmniRig::PM_VFOB); + do_mode (m); + rig_->SetVfo (OmniRig::PM_VFOA); + } + else if (writable_params_ & OmniRig::PM_VFOSWAP) + { + rig_->SetVfo (OmniRig::PM_VFOSWAP); + do_mode (m); + rig_->SetVfo (OmniRig::PM_VFOSWAP); + } + } + } + CAT_TRACE ("set SPLIT mode on"); + rig_->SetSplitMode (state ().frequency (), tx); + update_other_frequency (tx); + update_split (true); + } + else + { + CAT_TRACE ("set SPLIT mode off"); + rig_->SetSimplexMode (state ().frequency ()); + update_split (false); + } + bool notify {false}; + if (readable_params_ & OmniRig::PM_FREQ || !(readable_params_ & (OmniRig::PM_FREQA | OmniRig::PM_FREQB))) + { + update_other_frequency (tx); // async updates won't return this + // so just store it and hope + // operator doesn't change the + // "back" VFO on rig + notify = true; + } + if (!((OmniRig::PM_VFOAB | OmniRig::PM_VFOBA | OmniRig::PM_SPLITON) & readable_params_)) + { + CAT_TRACE ("setting SPLIT manually"); + update_split (split); // we can't read it so just set and + // hope op doesn't change it + notify = true; + } + if (notify) + { + update_complete (); + } +} + +void OmniRigTransceiver::do_mode (MODE mode) +{ + CAT_TRACE (mode << ' ' << state ()); + if (!rig_ || rig_->isNull ()) return; + // TODO: G4WJS OmniRig doesn't seem to have any capability of tracking/setting VFO B mode + auto mapped = map_mode (mode); + if (mapped & writable_params_) + { + rig_->SetMode (mapped); + update_mode (mode); + } + else + { + offline ("OmniRig invalid mode"); + } +} diff --git a/Transceiver/OmniRigTransceiver.hpp b/Transceiver/OmniRigTransceiver.hpp index 41e09c5e..d2edca15 100755..100644 --- a/Transceiver/OmniRigTransceiver.hpp +++ b/Transceiver/OmniRigTransceiver.hpp @@ -1,72 +1,72 @@ -#ifndef OMNI_RIG_TRANSCEIVER_HPP__
-#define OMNI_RIG_TRANSCEIVER_HPP__
-
-#include <memory>
-
-#include <QScopedPointer>
-#include <QString>
-#include <QTimer>
-
-#include "TransceiverFactory.hpp"
-#include "TransceiverBase.hpp"
-
-#include "OmniRig.h"
-
-//
-// OmniRig Transceiver Interface
-//
-// Implemented as a Transceiver decorator because we may want the PTT
-// services of another Transceiver type such as the HamlibTransceiver
-// which can be enabled by wrapping a HamlibTransceiver instantiated
-// as a "Hamlib Dummy" transceiver in the Transceiver factory method.
-//
-class OmniRigTransceiver final
- : public TransceiverBase
-{
- Q_OBJECT;
-
-public:
- static void register_transceivers (logger_type *, TransceiverFactory::Transceivers *, unsigned id1, unsigned id2);
-
- enum RigNumber {One = 1, Two};
-
- // takes ownership of wrapped Transceiver
- explicit OmniRigTransceiver (logger_type *, std::unique_ptr<TransceiverBase> wrapped,
- RigNumber, TransceiverFactory::PTTMethod ptt_type,
- QString const& ptt_port, QObject * parent = nullptr);
- ~OmniRigTransceiver ();
-
- int do_start () override;
- void do_stop () override;
- void do_frequency (Frequency, MODE, bool no_ignore) override;
- void do_tx_frequency (Frequency, MODE, bool no_ignore) override;
- void do_mode (MODE) override;
- void do_ptt (bool on) override;
-
-private:
- Q_SLOT void handle_COM_exception (int, QString, QString, QString);
- Q_SLOT void handle_visible_change ();
- Q_SLOT void handle_rig_type_change (int rig_number);
- Q_SLOT void handle_status_change (int rig_number);
- Q_SLOT void handle_params_change (int rig_number, int params);
- Q_SLOT void handle_custom_reply (int, QVariant const& command, QVariant const& reply);
-
- MODE map_mode (OmniRig::RigParamX param);
- OmniRig::RigParamX map_mode (MODE mode);
-
- std::unique_ptr<TransceiverBase> wrapped_; // may be null
- bool use_for_ptt_;
- TransceiverFactory::PTTMethod ptt_type_;
- QScopedPointer<OmniRig::OmniRigX> omni_rig_;
- RigNumber rig_number_;
- QScopedPointer<OmniRig::RigX> rig_;
- QScopedPointer<OmniRig::PortBits> port_;
- QString rig_type_;
- int readable_params_;
- int writable_params_;
- QScopedPointer<QTimer> offline_timer_;
- bool send_update_signal_;
- bool reversed_; // some rigs can reverse VFOs
-};
-
-#endif
+#ifndef OMNI_RIG_TRANSCEIVER_HPP__ +#define OMNI_RIG_TRANSCEIVER_HPP__ + +#include <memory> + +#include <QScopedPointer> +#include <QString> +#include <QTimer> + +#include "TransceiverFactory.hpp" +#include "TransceiverBase.hpp" + +#include "OmniRig.h" + +// +// OmniRig Transceiver Interface +// +// Implemented as a Transceiver decorator because we may want the PTT +// services of another Transceiver type such as the HamlibTransceiver +// which can be enabled by wrapping a HamlibTransceiver instantiated +// as a "Hamlib Dummy" transceiver in the Transceiver factory method. +// +class OmniRigTransceiver final + : public TransceiverBase +{ + Q_OBJECT; + +public: + static void register_transceivers (logger_type *, TransceiverFactory::Transceivers *, unsigned id1, unsigned id2); + + enum RigNumber {One = 1, Two}; + + // takes ownership of wrapped Transceiver + explicit OmniRigTransceiver (logger_type *, std::unique_ptr<TransceiverBase> wrapped, + RigNumber, TransceiverFactory::PTTMethod ptt_type, + QString const& ptt_port, QObject * parent = nullptr); + ~OmniRigTransceiver (); + + int do_start () override; + void do_stop () override; + void do_frequency (Frequency, MODE, bool no_ignore) override; + void do_tx_frequency (Frequency, MODE, bool no_ignore) override; + void do_mode (MODE) override; + void do_ptt (bool on) override; + +private: + Q_SLOT void handle_COM_exception (int, QString, QString, QString); + Q_SLOT void handle_visible_change (); + Q_SLOT void handle_rig_type_change (int rig_number); + Q_SLOT void handle_status_change (int rig_number); + Q_SLOT void handle_params_change (int rig_number, int params); + Q_SLOT void handle_custom_reply (int, QVariant const& command, QVariant const& reply); + + MODE map_mode (OmniRig::RigParamX param); + OmniRig::RigParamX map_mode (MODE mode); + + std::unique_ptr<TransceiverBase> wrapped_; // may be null + bool use_for_ptt_; + TransceiverFactory::PTTMethod ptt_type_; + QScopedPointer<OmniRig::OmniRigX> omni_rig_; + RigNumber rig_number_; + QScopedPointer<OmniRig::RigX> rig_; + QScopedPointer<OmniRig::PortBits> port_; + QString rig_type_; + int readable_params_; + int writable_params_; + QScopedPointer<QTimer> offline_timer_; + bool send_update_signal_; + bool reversed_; // some rigs can reverse VFOs +}; + +#endif diff --git a/Transceiver/PollingTransceiver.cpp b/Transceiver/PollingTransceiver.cpp index 8904c39f..eee4e185 100755..100644 --- a/Transceiver/PollingTransceiver.cpp +++ b/Transceiver/PollingTransceiver.cpp @@ -1,192 +1,192 @@ -#include "PollingTransceiver.hpp"
-
-#include <exception>
-
-#include <QObject>
-#include <QString>
-#include <QTimer>
-#include <QThread>
-#include <QDir>
-#include <QStandardPaths>
-#include "moc_PollingTransceiver.cpp"
-
-namespace
-{
- unsigned const polls_to_stabilize {3};
-}
-
-PollingTransceiver::PollingTransceiver (logger_type * logger, int poll_interval, QObject * parent)
- : TransceiverBase {logger, parent}
- , interval_ {poll_interval * 1000}
- , poll_timer_ {nullptr}
- , retries_ {0}
-{
-}
-
-void PollingTransceiver::start_timer ()
-{
- if (interval_)
- {
- if (!poll_timer_)
- {
- poll_timer_ = new QTimer {this}; // pass ownership to
- // QObject which handles
- // destruction for us
-
- connect (poll_timer_, &QTimer::timeout, this,
- &PollingTransceiver::handle_timeout);
- }
- poll_timer_->start (interval_);
- }
- else
- {
- stop_timer ();
- }
-}
-
-void PollingTransceiver::stop_timer ()
-{
- if (poll_timer_)
- {
- poll_timer_->stop ();
- }
-}
-
-void PollingTransceiver::do_post_start ()
-{
- interval_ = 500; // needed for displaying PWR and SWR
- start_timer ();
- if (!next_state_.online ())
- {
- // remember that we are expecting to go online
- next_state_.online (true);
- retries_ = polls_to_stabilize;
- }
-}
-
-void PollingTransceiver::do_post_stop ()
-{
- // not much point waiting for rig to go offline since we are ceasing
- // polls
- stop_timer ();
-}
-
-void PollingTransceiver::do_post_frequency (Frequency f, MODE m)
-{
- // take care not to set the expected next mode to unknown since some
- // callers use mode == unknown to signify that they do not know the
- // mode and don't care
- if (next_state_.frequency () != f || (m != UNK && next_state_.mode () != m))
- {
- // update expected state with new frequency and set poll count
- next_state_.frequency (f);
- if (m != UNK)
- {
- next_state_.mode (m);
- }
- retries_ = polls_to_stabilize;
- }
-}
-
-void PollingTransceiver::do_post_tx_frequency (Frequency f, MODE)
-{
- if (next_state_.tx_frequency () != f)
- {
- // update expected state with new TX frequency and set poll
- // count
- next_state_.tx_frequency (f);
- next_state_.split (f); // setting non-zero TX frequency means split
- retries_ = polls_to_stabilize;
- }
-}
-
-void PollingTransceiver::do_post_mode (MODE m)
-{
- // we don't ever expect mode to goto to unknown
- if (m != UNK && next_state_.mode () != m)
- {
- // update expected state with new mode and set poll count
- next_state_.mode (m);
- retries_ = polls_to_stabilize;
- }
-}
-
-void PollingTransceiver::do_post_ptt (bool p)
-{
- if (next_state_.ptt () != p)
- {
- // update expected state with new PTT and set poll count
- next_state_.ptt (p);
- retries_ = polls_to_stabilize;
- //retries_ = 0; // fast feedback on PTT
- }
- else
- {
- next_state_.ptt(p); // ensure this is initialized
- }
-}
-
-bool PollingTransceiver::do_pre_update ()
-{
- // if we are holding off a change then withhold the signal
- if (retries_ && state () != next_state_)
- {
- return false;
- }
- return true;
-}
-
-void PollingTransceiver::handle_timeout ()
-{
- QString message;
- bool force_signal {false};
-
- // we must catch all exceptions here since we are called by Qt and
- // inform our parent of the failure via the offline() message
- try
- {
- do_poll (); // tell sub-classes to update our state
-
- // Signal new state if it what we expected or, hasn't become
- // what we expected after polls_to_stabilize polls. Unsolicited
- // changes will be signalled immediately unless they intervene
- // in a expected sequence where they will be delayed.
- if (retries_)
- {
- --retries_;
- if (state () == next_state_ || !retries_)
- {
- // the expected state has arrived or there are no more
- // retries
- force_signal = true;
- }
- }
- else if (state () != last_signalled_state_)
- {
- // here is the normal passive polling path where state has
- // changed asynchronously
- force_signal = true;
- }
-
- if (force_signal)
- {
- // reset everything, record and signal the current state
- retries_ = 0;
- next_state_ = state ();
- last_signalled_state_ = state ();
- update_complete (true);
- }
- }
- catch (std::exception const& e)
- {
- message = e.what ();
- }
- catch (...)
- {
- message = tr ("Unexpected rig error");
- }
- if (!message.isEmpty ())
- {
- offline (message);
- }
-}
+#include "PollingTransceiver.hpp" + +#include <exception> + +#include <QObject> +#include <QString> +#include <QTimer> +#include <QThread> +#include <QDir> +#include <QStandardPaths> +#include "moc_PollingTransceiver.cpp" + +namespace +{ + unsigned const polls_to_stabilize {3}; +} + +PollingTransceiver::PollingTransceiver (logger_type * logger, int poll_interval, QObject * parent) + : TransceiverBase {logger, parent} + , interval_ {poll_interval * 1000} + , poll_timer_ {nullptr} + , retries_ {0} +{ +} + +void PollingTransceiver::start_timer () +{ + if (interval_) + { + if (!poll_timer_) + { + poll_timer_ = new QTimer {this}; // pass ownership to + // QObject which handles + // destruction for us + + connect (poll_timer_, &QTimer::timeout, this, + &PollingTransceiver::handle_timeout); + } + poll_timer_->start (interval_); + } + else + { + stop_timer (); + } +} + +void PollingTransceiver::stop_timer () +{ + if (poll_timer_) + { + poll_timer_->stop (); + } +} + +void PollingTransceiver::do_post_start () +{ + interval_ = 500; // needed for displaying PWR and SWR + start_timer (); + if (!next_state_.online ()) + { + // remember that we are expecting to go online + next_state_.online (true); + retries_ = polls_to_stabilize; + } +} + +void PollingTransceiver::do_post_stop () +{ + // not much point waiting for rig to go offline since we are ceasing + // polls + stop_timer (); +} + +void PollingTransceiver::do_post_frequency (Frequency f, MODE m) +{ + // take care not to set the expected next mode to unknown since some + // callers use mode == unknown to signify that they do not know the + // mode and don't care + if (next_state_.frequency () != f || (m != UNK && next_state_.mode () != m)) + { + // update expected state with new frequency and set poll count + next_state_.frequency (f); + if (m != UNK) + { + next_state_.mode (m); + } + retries_ = polls_to_stabilize; + } +} + +void PollingTransceiver::do_post_tx_frequency (Frequency f, MODE) +{ + if (next_state_.tx_frequency () != f) + { + // update expected state with new TX frequency and set poll + // count + next_state_.tx_frequency (f); + next_state_.split (f); // setting non-zero TX frequency means split + retries_ = polls_to_stabilize; + } +} + +void PollingTransceiver::do_post_mode (MODE m) +{ + // we don't ever expect mode to goto to unknown + if (m != UNK && next_state_.mode () != m) + { + // update expected state with new mode and set poll count + next_state_.mode (m); + retries_ = polls_to_stabilize; + } +} + +void PollingTransceiver::do_post_ptt (bool p) +{ + if (next_state_.ptt () != p) + { + // update expected state with new PTT and set poll count + next_state_.ptt (p); + retries_ = polls_to_stabilize; + //retries_ = 0; // fast feedback on PTT + } + else + { + next_state_.ptt(p); // ensure this is initialized + } +} + +bool PollingTransceiver::do_pre_update () +{ + // if we are holding off a change then withhold the signal + if (retries_ && state () != next_state_) + { + return false; + } + return true; +} + +void PollingTransceiver::handle_timeout () +{ + QString message; + bool force_signal {false}; + + // we must catch all exceptions here since we are called by Qt and + // inform our parent of the failure via the offline() message + try + { + do_poll (); // tell sub-classes to update our state + + // Signal new state if it what we expected or, hasn't become + // what we expected after polls_to_stabilize polls. Unsolicited + // changes will be signalled immediately unless they intervene + // in a expected sequence where they will be delayed. + if (retries_) + { + --retries_; + if (state () == next_state_ || !retries_) + { + // the expected state has arrived or there are no more + // retries + force_signal = true; + } + } + else if (state () != last_signalled_state_) + { + // here is the normal passive polling path where state has + // changed asynchronously + force_signal = true; + } + + if (force_signal) + { + // reset everything, record and signal the current state + retries_ = 0; + next_state_ = state (); + last_signalled_state_ = state (); + update_complete (true); + } + } + catch (std::exception const& e) + { + message = e.what (); + } + catch (...) + { + message = tr ("Unexpected rig error"); + } + if (!message.isEmpty ()) + { + offline (message); + } +} diff --git a/Transceiver/PollingTransceiver.hpp b/Transceiver/PollingTransceiver.hpp index a633c5a1..4fb0a5cb 100755..100644 --- a/Transceiver/PollingTransceiver.hpp +++ b/Transceiver/PollingTransceiver.hpp @@ -1,74 +1,74 @@ -#ifndef POLLING_TRANSCEIVER_HPP__
-#define POLLING_TRANSCEIVER_HPP__
-
-#include <QObject>
-
-#include "Transceiver/TransceiverBase.hpp"
-
-class QTimer;
-
-//
-// Polling Transceiver
-//
-// Helper base class that encapsulates the emulation of continuous
-// update and caching of a transceiver state.
-//
-// Collaborations
-//
-// Implements the TransceiverBase post action interface and provides
-// the abstract poll() operation for sub-classes to implement. The
-// poll operation is invoked every poll_interval seconds.
-//
-// Responsibilities
-//
-// Because some rig interfaces don't immediately update after a state
-// change request; this class allows a rig a few polls to stabilise
-// to the requested state before signalling the change. This means
-// that clients don't see intermediate states that are sometimes
-// inaccurate, e.g. changing the split TX frequency on Icom rigs
-// requires a VFO switch and polls while switched will return the
-// wrong current frequency.
-//
-class PollingTransceiver
- : public TransceiverBase
-{
- Q_OBJECT; // for translation context
-
-protected:
- explicit PollingTransceiver (logger_type *, int poll_interval, // in seconds
- QObject * parent);
-
-protected:
- // Sub-classes implement this and fetch what they can from the rig
- // in a non-intrusive manner.
- virtual void do_poll () = 0;
-
- void do_post_start () override final;
- void do_post_stop () override final;
- void do_post_frequency (Frequency, MODE) override final;
- void do_post_tx_frequency (Frequency, MODE) override final;
- void do_post_mode (MODE) override final;
- void do_post_ptt (bool = true) override final;
- bool do_pre_update () override final;
-
-private:
- void start_timer ();
- void stop_timer ();
-
- Q_SLOT void handle_timeout ();
-
- int interval_; // polling interval in milliseconds
- QTimer * poll_timer_;
-
- // keep a record of the last state signalled so we can elide
- // duplicate updates
- Transceiver::TransceiverState last_signalled_state_;
-
- // keep a record of expected state so we can compare with actual
- // updates to determine when state changes have bubbled through
- Transceiver::TransceiverState next_state_;
-
- unsigned retries_;
-};
-
-#endif
+#ifndef POLLING_TRANSCEIVER_HPP__ +#define POLLING_TRANSCEIVER_HPP__ + +#include <QObject> + +#include "Transceiver/TransceiverBase.hpp" + +class QTimer; + +// +// Polling Transceiver +// +// Helper base class that encapsulates the emulation of continuous +// update and caching of a transceiver state. +// +// Collaborations +// +// Implements the TransceiverBase post action interface and provides +// the abstract poll() operation for sub-classes to implement. The +// poll operation is invoked every poll_interval seconds. +// +// Responsibilities +// +// Because some rig interfaces don't immediately update after a state +// change request; this class allows a rig a few polls to stabilise +// to the requested state before signalling the change. This means +// that clients don't see intermediate states that are sometimes +// inaccurate, e.g. changing the split TX frequency on Icom rigs +// requires a VFO switch and polls while switched will return the +// wrong current frequency. +// +class PollingTransceiver + : public TransceiverBase +{ + Q_OBJECT; // for translation context + +protected: + explicit PollingTransceiver (logger_type *, int poll_interval, // in seconds + QObject * parent); + +protected: + // Sub-classes implement this and fetch what they can from the rig + // in a non-intrusive manner. + virtual void do_poll () = 0; + + void do_post_start () override final; + void do_post_stop () override final; + void do_post_frequency (Frequency, MODE) override final; + void do_post_tx_frequency (Frequency, MODE) override final; + void do_post_mode (MODE) override final; + void do_post_ptt (bool = true) override final; + bool do_pre_update () override final; + +private: + void start_timer (); + void stop_timer (); + + Q_SLOT void handle_timeout (); + + int interval_; // polling interval in milliseconds + QTimer * poll_timer_; + + // keep a record of the last state signalled so we can elide + // duplicate updates + Transceiver::TransceiverState last_signalled_state_; + + // keep a record of expected state so we can compare with actual + // updates to determine when state changes have bubbled through + Transceiver::TransceiverState next_state_; + + unsigned retries_; +}; + +#endif diff --git a/Transceiver/TCITransceiver.cpp b/Transceiver/TCITransceiver.cpp index ab3476cd..f3a8001b 100755..100644 --- a/Transceiver/TCITransceiver.cpp +++ b/Transceiver/TCITransceiver.cpp @@ -1,1723 +1,1723 @@ -#include "Transceiver/TCITransceiver.hpp"
-
-#include <QRegularExpression>
-#include <QLocale>
-#include <QThread>
-#include <qmath.h>
-
-#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
-#include <QRandomGenerator>
-#endif
-
-#include <QString>
-#include "widgets/itoneAndicw.h"
-#include "Network/NetworkServerLookup.hpp"
-#include "moc_TCITransceiver.cpp"
-
-#include <QStandardPaths>
-#include <QDir>
-#include <QDebug>
-#include <QDateTime>
-#include <QTimer>
-
-namespace
-{
- char const * const TCI_transceiver_1_name {"TCI Client RX1"};
- char const * const TCI_transceiver_2_name {"TCI Client RX2"};
-
- QString map_mode (Transceiver::MODE mode)
- {
- switch (mode)
- {
- case Transceiver::AM: return "am";
- case Transceiver::CW: return "cw";
-// case Transceiver::CW_R: return "CW-R";
- case Transceiver::USB: return "usb";
- case Transceiver::LSB: return "lsb";
-// case Transceiver::FSK: return "RTTY";
-// case Transceiver::FSK_R: return "RTTY-R";
- case Transceiver::DIG_L: return "digl";
- case Transceiver::DIG_U: return "digu";
- case Transceiver::FM: return "wfm";
- case Transceiver::DIG_FM:
- return "nfm";
- default: break;
- }
- return "";
- }
- static const QString SmTZ(";");
- static const QString SmDP(":");
- static const QString SmCM(",");
- static const QString SmTrue("true");
- static const QString SmFalse("false");
-
- // Command maps
- static const QString CmdDevice("device");
- static const QString CmdReceiveOnly("receive_only");
- static const QString CmdTrxCount("trx_count");
- static const QString CmdChannelCount("channels_count");
- static const QString CmdVfoLimits("vfo_limits");
- static const QString CmdIfLimits("if_limits");
- static const QString CmdModeList("modulations_list");
- static const QString CmdMode("modulation");
- static const QString CmdReady("ready");
- static const QString CmdStop("stop");
- static const QString CmdStart("start");
- static const QString CmdPreamp("preamp");
- static const QString CmdDds("dds");
- static const QString CmdIf("if");
- static const QString CmdTrx("trx");
- static const QString CmdRxEnable("rx_enable");
- static const QString CmdTxEnable("tx_enable");
- static const QString CmdRxChannelEnable("rx_channel_enable");
- static const QString CmdRitEnable("rit_enable");
- static const QString CmdRitOffset("rit_offset");
- static const QString CmdXitEnable("xit_enable");
- static const QString CmdXitOffset("xit_offset");
- static const QString CmdSplitEnable("split_enable");
- static const QString CmdIqSR("iq_samplerate");
- static const QString CmdIqStart("iq_start");
- static const QString CmdIqStop("iq_stop");
- static const QString CmdCWSpeed("cw_macros_speed");
- static const QString CmdCWDelay("cw_macros_delay");
- static const QString CmdSpot("spot");
- static const QString CmdSpotDelete("spot_delete");
- static const QString CmdFilterBand("rx_filter_band");
- static const QString CmdVFO("vfo");
- static const QString CmdVersion("protocol"); //protocol:esdr,1.2;
- static const QString CmdTune("tune");
- static const QString CmdRxMute("rx_mute");
- static const QString CmdSmeter("rx_smeter");
- static const QString CmdPower("tx_power");
- static const QString CmdSWR("tx_swr");
- static const QString CmdECoderRX("ecoder_switch_rx");
- static const QString CmdECoderVFO("ecoder_switch_channel");
- static const QString CmdAudioSR("audio_samplerate");
- static const QString CmdAudioStart("audio_start");
- static const QString CmdAudioStop("audio_stop");
- static const QString CmdAppFocus("app_focus");
- static const QString CmdVolume("volume");
- static const QString CmdSqlEnable("sql_enable");
- static const QString CmdSqlLevel("sql_level");
- static const QString CmdDrive("drive");
- static const QString CmdTuneDrive("tune_drive");
- static const QString CmdMute("mute");
- static const QString CmdRxSensorsEnable("rx_sensors_enable");
- static const QString CmdTxSensorsEnable("tx_sensors_enable");
- static const QString CmdRxSensors("rx_sensors");
- static const QString CmdTxSensors("tx_sensors");
- static const QString CmdAgcMode("agc_mode");
- static const QString CmdAgcGain("agc_gain");
- static const QString CmdLock("lock");
-}
-
-extern "C" {
- void fil4_(qint16*, qint32*, qint16*, qint32*, short int*);
-}
-extern dec_data dec_data;
-
-extern float gran(); // Noise generator (for tests only)
-
-#define RAMP_INCREMENT 64 // MUST be an integral factor of 2^16
-
-#if defined (WSJT_SOFT_KEYING)
-# define SOFT_KEYING WSJT_SOFT_KEYING
-#else
-# define SOFT_KEYING 1
-#endif
-
-double constexpr TCITransceiver::m_twoPi;
-
-void TCITransceiver::register_transceivers (logger_type *, TransceiverFactory::Transceivers * registry, unsigned id1, unsigned id2)
-{
- (*registry)[TCI_transceiver_1_name] = TransceiverFactory::Capabilities {id1, TransceiverFactory::Capabilities::tci, true};
- (*registry)[TCI_transceiver_2_name] = TransceiverFactory::Capabilities {id2, TransceiverFactory::Capabilities::tci, true};
-}
-
-static constexpr quint32 AudioHeaderSize = 16u*sizeof(quint32);
-
-TCITransceiver::TCITransceiver (logger_type * logger, std::unique_ptr<TransceiverBase> wrapped,QString const& rignr,
- QString const& address, bool use_for_ptt,
- int poll_interval, QObject * parent)
- : PollingTransceiver {logger, poll_interval, parent}
- , wrapped_ {std::move (wrapped)}
- , rx_ {rignr}
- , server_ {address}
- , use_for_ptt_ {use_for_ptt}
- , errortable {tr("ConnectionRefused"),
- tr("RemoteHostClosed"),
- tr("HostNotFound"),
- tr("SocketAccess"),
- tr("SocketResource"),
- tr("SocketTimeout"),
- tr("DatagramTooLarge"),
- tr("Network"),
- tr("AddressInUse"),
- tr("SocketAddressNotAvailable"),
- tr("UnsupportedSocketOperation"),
- tr("UnfinishedSocketOperation"),
- tr("ProxyAuthenticationRequired"),
- tr("SslHandshakeFailed"),
- tr("ProxyConnectionRefused"),
- tr("ProxyConnectionClosed"),
- tr("ProxyConnectionTimeout"),
- tr("ProxyNotFound"),
- tr("ProxyProtocol"),
- tr("Operation"),
- tr("SslInternal"),
- tr("SslInvalidUserData"),
- tr("Temporary"),
- tr("UnknownSocket") }
- , error_ {""}
- , do_snr_ {(poll_interval & do__snr) == do__snr}
- , do_pwr_ {(poll_interval & do__pwr) == do__pwr}
- , rig_power_ {(poll_interval & rig__power) == rig__power}
- , rig_power_off_ {(poll_interval & rig__power_off) == rig__power_off}
- , tci_audio_ {(poll_interval & tci__audio) == tci__audio}
- , commander_ {nullptr}
- , tci_timer1_ {nullptr}
- , tci_loop1_ {nullptr}
- , tci_timer2_ {nullptr}
- , tci_loop2_ {nullptr}
- , tci_timer3_ {nullptr}
- , tci_loop3_ {nullptr}
- , tci_timer4_ {nullptr}
- , tci_loop4_ {nullptr}
- , tci_timer5_ {nullptr}
- , tci_loop5_ {nullptr}
- , tci_timer6_ {nullptr}
- , tci_loop6_ {nullptr}
- , tci_timer7_ {nullptr}
- , tci_loop7_ {nullptr}
- , tci_timer8_ {nullptr}
- , tci_loop8_ {nullptr}
- , wavptr_ {nullptr}
- , m_downSampleFactor {4}
- , m_buffer ((m_downSampleFactor > 1) ?
- new short [max_buffer_size * m_downSampleFactor] : nullptr)
- , m_quickClose {false}
- , m_phi {0.0}
- , m_toneSpacing {0.0}
- , m_fSpread {0.0}
- , m_state {Idle}
- , m_tuning {false}
- , m_cwLevel {false}
- , m_j0 {-1}
- , m_toneFrequency0 {1500.0}
- , wav_file_ {QDir(QStandardPaths::writableLocation (QStandardPaths::DataLocation)).absoluteFilePath ("tx.wav").toStdString()}
-{
- m_samplesPerFFT = 6912 / 2;
- tci_Ready = false;
- trxA = 0;
- trxB = 0;
- cntIQ = 0;
- bIQ = false;
- inConnected = false;
- audioSampleRate = 48000u;
- mapCmd_[CmdDevice] = Cmd_Device;
- mapCmd_[CmdReceiveOnly] = Cmd_ReceiveOnly;
- mapCmd_[CmdTrxCount] = Cmd_TrxCount;
- mapCmd_[CmdChannelCount] = Cmd_ChannelCount;
- mapCmd_[CmdVfoLimits] = Cmd_VfoLimits;
- mapCmd_[CmdIfLimits] = Cmd_IfLimits;
- mapCmd_[CmdModeList] = Cmd_ModeList;
- mapCmd_[CmdMode] = Cmd_Mode;
- mapCmd_[CmdReady] = Cmd_Ready;
- mapCmd_[CmdStop] = Cmd_Stop;
- mapCmd_[CmdStart] = Cmd_Start;
- mapCmd_[CmdPreamp] = Cmd_Preamp;
- mapCmd_[CmdDds] = Cmd_Dds;
- mapCmd_[CmdIf] = Cmd_If;
- mapCmd_[CmdTrx] = Cmd_Trx;
- mapCmd_[CmdRxEnable] = Cmd_RxEnable;
- mapCmd_[CmdTxEnable] = Cmd_TxEnable;
- mapCmd_[CmdRxChannelEnable] = Cmd_RxChannelEnable;
- mapCmd_[CmdRitEnable] = Cmd_RitEnable;
- mapCmd_[CmdRitOffset] = Cmd_RitOffset;
- mapCmd_[CmdXitEnable] = Cmd_XitEnable;
- mapCmd_[CmdXitOffset] = Cmd_XitOffset;
- mapCmd_[CmdSplitEnable] = Cmd_SplitEnable;
- mapCmd_[CmdIqSR] = Cmd_IqSR;
- mapCmd_[CmdIqStart] = Cmd_IqStart;
- mapCmd_[CmdIqStop] = Cmd_IqStop;
- mapCmd_[CmdCWSpeed] = Cmd_CWSpeed;
- mapCmd_[CmdCWDelay] = Cmd_CWDelay;
- mapCmd_[CmdFilterBand] = Cmd_FilterBand;
- mapCmd_[CmdVFO] = Cmd_VFO;
- mapCmd_[CmdVersion] = Cmd_Version;
- mapCmd_[CmdTune] = Cmd_Tune;
- mapCmd_[CmdRxMute] = Cmd_RxMute;
- mapCmd_[CmdSmeter] = Cmd_Smeter;
- mapCmd_[CmdPower] = Cmd_Power;
- mapCmd_[CmdSWR] = Cmd_SWR;
- mapCmd_[CmdECoderRX] = Cmd_ECoderRX;
- mapCmd_[CmdECoderVFO] = Cmd_ECoderVFO;
- mapCmd_[CmdAudioSR] = Cmd_AudioSR;
- mapCmd_[CmdAudioStart] = Cmd_AudioStart;
- mapCmd_[CmdAudioStop] = Cmd_AudioStop;
- mapCmd_[CmdAppFocus] = Cmd_AppFocus;
- mapCmd_[CmdVolume] = Cmd_Volume;
- mapCmd_[CmdSqlEnable] = Cmd_SqlEnable;
- mapCmd_[CmdSqlLevel] = Cmd_SqlLevel;
- mapCmd_[CmdDrive] = Cmd_Drive;
- mapCmd_[CmdTuneDrive] = Cmd_TuneDrive;
- mapCmd_[CmdMute] = Cmd_Mute;
- mapCmd_[CmdRxSensorsEnable] = Cmd_RxSensorsEnable;
- mapCmd_[CmdTxSensorsEnable] = Cmd_TxSensorsEnable;
- mapCmd_[CmdRxSensors] = Cmd_RxSensors;
- mapCmd_[CmdTxSensors] = Cmd_TxSensors;
- mapCmd_[CmdAgcMode] = Cmd_AgcMode;
- mapCmd_[CmdAgcGain] = Cmd_AgcGain;
- mapCmd_[CmdLock] = Cmd_Lock;
-}
-
-void TCITransceiver::onConnected()
-{
- inConnected = true;
- CAT_TRACE ("TCITransceiver entered TCI onConnected and inConnected==true\n");
-}
-
-void TCITransceiver::onDisconnected()
-{
- inConnected = false;
- CAT_TRACE ("TCITransceiver entered TCI onDisonnected and inConnected==false\n");
-}
-
-
-void TCITransceiver::onError(QAbstractSocket::SocketError err)
-{
- qDebug() << "WebInThread::onError";
- CAT_TRACE ("TCITransceiver entered TCI onError and ErrorNumber is " + QString::number(err) + '\n');
- error_ = tr ("TCI websocket error: %1").arg (errortable.at (err));
-}
-
-int TCITransceiver::do_start ()
-{
- if (tci_audio_) QThread::currentThread()->setPriority(QThread::HighPriority);
- CAT_TRACE ("TCITransceiver entered TCI do_start and tci_Ready is " + QString::number(tci_Ready) + '\n');
- qDebug () << "qDebug says do_start tci_Ready is: " << tci_Ready;
- if (wrapped_) wrapped_->start (0);
- url_.setUrl("ws://" + server_); //server_
- if (url_.host() == "") url_.setHost("localhost");
- if (url_.port() == -1) url_.setPort(40001);
-
- if (!commander_) {
- commander_ = new QWebSocket {}; // QObject takes ownership
- CAT_TRACE ("TCITransceiver entered TCI do_start and commander created\n");
- //printf ("commander created\n");
- connect(commander_,SIGNAL(connected()),this,SLOT(onConnected()));
- connect(commander_,SIGNAL(disconnected()),this,SLOT(onDisconnected()));
- connect(commander_,SIGNAL(binaryMessageReceived(QByteArray)),this,SLOT(onBinaryReceived(QByteArray)));
- connect(commander_,SIGNAL(textMessageReceived(QString)),this,SLOT(onMessageReceived(QString)));
- connect(commander_,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(onError(QAbstractSocket::SocketError)));
- }
- if (!tci_loop1_) {
- tci_loop1_ = new QEventLoop {this};
- }
- if (!tci_timer1_) {
- tci_timer1_ = new QTimer {this};
- tci_timer1_ -> setSingleShot(true);
- connect( tci_timer1_, &QTimer::timeout, tci_loop1_, &QEventLoop::quit);
- connect( this, &TCITransceiver::tci_done1, tci_loop1_, &QEventLoop::quit);
- }
- if (!tci_loop2_) {
- tci_loop2_ = new QEventLoop {this};
- }
- if (!tci_timer2_) {
- tci_timer2_ = new QTimer {this};
- tci_timer2_ -> setSingleShot(true);
- connect( tci_timer2_, &QTimer::timeout, tci_loop2_, &QEventLoop::quit);
- connect( this, &TCITransceiver::tci_done2, tci_loop2_, &QEventLoop::quit);
- }
- if (!tci_loop3_) {
- tci_loop3_ = new QEventLoop {this};
- }
- if (!tci_timer3_) {
- tci_timer3_ = new QTimer {this};
- tci_timer3_ -> setSingleShot(true);
- connect( tci_timer3_, &QTimer::timeout, tci_loop3_, &QEventLoop::quit);
- connect( this, &TCITransceiver::tci_done3, tci_loop3_, &QEventLoop::quit);
- }
- if (!tci_loop4_) {
- tci_loop4_ = new QEventLoop {this};
- }
- if (!tci_timer4_) {
- tci_timer4_ = new QTimer {this};
- tci_timer4_ -> setSingleShot(true);
- connect( tci_timer4_, &QTimer::timeout, tci_loop4_, &QEventLoop::quit);
- connect( this, &TCITransceiver::tci_done4, tci_loop4_, &QEventLoop::quit);
- }
- if (!tci_loop5_) {
- tci_loop5_ = new QEventLoop {this};
- }
- if (!tci_timer5_) {
- tci_timer5_ = new QTimer {this};
- tci_timer5_ -> setSingleShot(true);
- connect( tci_timer5_, &QTimer::timeout, tci_loop5_, &QEventLoop::quit);
- connect( this, &TCITransceiver::tci_done5, tci_loop5_, &QEventLoop::quit);
- }
- if (!tci_loop6_) {
- tci_loop6_ = new QEventLoop {this};
- }
- if (!tci_timer6_) {
- tci_timer6_ = new QTimer {this};
- tci_timer6_ -> setSingleShot(true);
- connect( tci_timer6_, &QTimer::timeout, tci_loop6_, &QEventLoop::quit);
- connect( this, &TCITransceiver::tci_done6, tci_loop6_, &QEventLoop::quit);
- }
- if (!tci_loop7_) {
- tci_loop7_ = new QEventLoop {this};
- }
- if (!tci_timer7_) {
- tci_timer7_ = new QTimer {this};
- tci_timer7_ -> setSingleShot(true);
- connect( tci_timer7_, &QTimer::timeout, tci_loop7_, &QEventLoop::quit);
- connect( this, &TCITransceiver::tci_done7, tci_loop7_, &QEventLoop::quit);
- }
- if (!tci_loop8_) {
- tci_loop8_ = new QEventLoop {this};
- }
- if (!tci_timer8_) {
- tci_timer8_ = new QTimer {this};
- tci_timer8_ -> setSingleShot(true);
- connect( tci_timer8_, &QTimer::timeout, tci_loop8_, &QEventLoop::quit);
- connect( this, &TCITransceiver::tci_done8, tci_loop8_, &QEventLoop::quit);
- }
-
- tx_fifo = 0; tx_top_ = true;
- tci_Ready = false;
- ESDR3 = false;
- HPSDR = false;
- band_change = false;
- trxA = 0;
- trxB = 0;
- busy_rx_frequency_ = false;
- busy_mode_ = false;
- busy_other_frequency_ = false;
- busy_split_ = false;
- busy_drive_ = false;
- busy_PTT_ = false;
- busy_rx2_ = false;
- rx2_ = false;
- requested_rx2_ = false;
- started_rx2_ = false;
- split_ = false;
- requested_split_ = false;
- started_split_ = false;
- PTT_ = false;
- requested_PTT_ = false;
- mode_ = "";
- requested_mode_ = "";
- started_mode_ = "";
- requested_rx_frequency_ = "";
- rx_frequency_ = "";
- requested_other_frequency_ = "";
- other_frequency_ = "";
- requested_drive_ = "";
- drive_ = "";
- level_ = -54;
- txAtten = 45;
- power_ = 0;
- swr_ = 0;
- m_bufferPos = 0;
- m_downSampleFactor =4;
- m_ns = 999;
- audio_ = false;
- requested_stream_audio_ = false;
- stream_audio_ = false;
- _power_ = false;
- CAT_TRACE ("TCITransceiver entered TCI do_start and url " + url_.toString() + " rig_power:" + QString::number(rig_power_) + " rig_power_off:" + QString::number(rig_power_off_) + " tci_audio:" + QString::number(tci_audio_) + " do_snr:" + QString::number(do_snr_) + " do_pwr:" + QString::number(do_pwr_) + '\n');
- commander_->open (url_);
- tci_done6();
- mysleep6(2000);
- busy_split_ = true;
- const QString cmd = CmdSplitEnable + SmDP + "false" + SmTZ;
- sendTextMessage(cmd);
- //mysleep6(500);
- busy_split_ = false;
- if (error_.isEmpty()) {
- tci_Ready = true;
- if (!_power_) {
- if (rig_power_) {
- rig_power(true);
- mysleep6(1000);
- if(!_power_) throw error {tr ("TCI SDR could not be switched on")};
- } else {
- tci_Ready = false;
- throw error {tr ("TCI SDR is not switched on")};
- }
- }
- if (rx_ == "1" && !rx2_) {
- rx2_enable (true);
- if (!rx2_) {
- tci_Ready = false;
- throw error {tr ("TCI RX2 could not be enabled")};
- }
- }
- if (tci_audio_) {
- stream_audio (true);
- mysleep6(500);
- if (!stream_audio_) {
- tci_Ready = false;
- throw error {tr ("TCI Audio could not be switched on")};
- }
- }
- if (ESDR3) {
- const QString cmd = CmdRxSensorsEnable + SmDP + (do_snr_ ? "true" : "false") + SmCM + "500" + SmTZ;
- sendTextMessage(cmd);
- } else if (do_snr_) {
- const QString cmd = CmdSmeter + SmDP + rx_ + SmCM + "0" + SmTZ;
- sendTextMessage(cmd);
- }
-// if (!requested_rx_frequency_.isEmpty()) do_frequency(string_to_frequency (requested_rx_frequency_),get_mode(true),false);
-// if (!requested_other_frequency_.isEmpty()) do_tx_frequency(string_to_frequency (requested_other_frequency_),get_mode(true),false);
-// else if (requested_split_ != split_) {rig_split();}
-
- do_poll ();
- if (ESDR3) {
- const QString cmd = CmdTxSensorsEnable + SmDP + (do_pwr_ ? "true" : "false") + SmCM + "500" + SmTZ;
- sendTextMessage(cmd);
- }
- if (stream_audio_) do_audio(true);
-
- CAT_TRACE ("TCITransceiver started\n");
- return 0;
- } else {
- CAT_TRACE("TCITransceiver not started with error " + error_ + '\n');
-
- if (error_.isEmpty())
- throw error {tr ("TCI could not be opened")};
- else
- throw error {error_};
- }
-}
-
-void TCITransceiver::do_stop ()
-{
- CAT_TRACE ("TCITransceiver TCI close\n");
- //printf ("TCI close\n");
- if (!commander_) return;
- if (stream_audio_ && tci_Ready && inConnected && _power_) {
- stream_audio (false);
- mysleep1(500);
- CAT_TRACE ("TCI audio closed\n");
- //printf ("TCI audio closed\n");
- }
- if (tci_Ready && inConnected && _power_) {
- requested_other_frequency_ = "";
- busy_split_ = true;
- const QString cmd = CmdSplitEnable + SmDP + "false" + SmTZ;
- sendTextMessage(cmd);
- mysleep1(500);
- busy_split_ = false;
- requested_split_ = false;
- rig_split();
- if (started_mode_ != mode_) sendTextMessage(mode_to_command(started_mode_));
- if (!started_rx2_ && rx2_) {
- rx2_enable (false);
- }
- }
- if (_power_ && rig_power_off_ && tci_Ready && inConnected) {
- rig_power(false);
- mysleep1(500);
- CAT_TRACE ("TCI power down\n");
- //printf ("TCI power down\n");
- }
- tci_Ready = false;
- if (commander_)
- {
- if (inConnected) commander_->close(QWebSocketProtocol::CloseCodeNormal,"end");
- delete commander_, commander_ = nullptr;
- CAT_TRACE ("deleted commander & closed websocket & deleted:");
- }
- if (tci_timer1_)
- {
- if (tci_timer1_->isActive()) tci_timer1_->stop();
- // tci_timer1_->deleteLater(), tci_timer1_ = nullptr;
- CAT_TRACE ("timer1 ");
- }
- if (tci_loop1_)
- {
- tci_loop1_->quit();
- // tci_loop1_->deleteLater(), tci_loop1_ = nullptr;
- CAT_TRACE ("loop1 ");
- }
- if (tci_timer2_)
- {
- if (tci_timer2_->isActive()) tci_timer2_->stop();
- // tci_timer2_->deleteLater(), tci_timer2_ = nullptr;
- CAT_TRACE ("timer2 ");
- }
- if (tci_loop2_)
- {
- tci_loop2_->quit();
- // tci_loop2_->deleteLater(), tci_loop2_ = nullptr;
- CAT_TRACE ("loop2 ");
- }
- if (tci_timer3_)
- {
- if (tci_timer3_->isActive()) tci_timer3_->stop();
- // tci_timer3_->deleteLater(), tci_timer3_ = nullptr;
- CAT_TRACE ("timer3 ");
- }
- if (tci_loop3_)
- {
- tci_loop3_->quit();
- // tci_loop3_->deleteLater(), tci_loop3_ = nullptr;
- CAT_TRACE ("loop3 ");
- }
- if (tci_timer4_)
- {
- if (tci_timer4_->isActive()) tci_timer4_->stop();
- // tci_timer4_->deleteLater(), tci_timer4_ = nullptr;
- CAT_TRACE ("timer4 ");
- }
- if (tci_loop4_)
- {
- tci_loop4_->quit();
- // tci_loop4_->deleteLater(), tci_loop4_ = nullptr;
- CAT_TRACE ("loop4 ");
- }
- if (tci_timer5_)
- {
- if (tci_timer5_->isActive()) tci_timer5_->stop();
- // tci_timer5_->deleteLater(), tci_timer5_ = nullptr;
- CAT_TRACE ("timer5 ");
- }
- if (tci_loop5_)
- {
- tci_loop5_->quit();
- // tci_loop5_->deleteLater(), tci_loop5_ = nullptr;
- CAT_TRACE ("loop5 ");
- }
- if (tci_timer6_)
- {
- if (tci_timer6_->isActive()) tci_timer6_->stop();
- // tci_timer6_->deleteLater(), tci_timer6_ = nullptr;
- CAT_TRACE ("timer6 ");
- }
- if (tci_loop6_)
- {
- tci_loop6_->quit();
- // tci_loop6_->deleteLater(), tci_loop6_ = nullptr;
- CAT_TRACE ("loop6 ");
- }
- if (tci_timer7_)
- {
- if (tci_timer7_->isActive()) tci_timer7_->stop();
- // tci_timer7_->deleteLater(), tci_timer7_ = nullptr;
- CAT_TRACE ("timer7 ");
- }
- if (tci_loop7_)
- {
- tci_loop7_->quit();
- // tci_loop7_->deleteLater(), tci_loop7_ = nullptr;
- CAT_TRACE ("loop7 ");
- }
- if (tci_timer8_)
- {
- if (tci_timer8_->isActive()) tci_timer8_->stop();
- // tci_timer8_->deleteLater(), tci_timer8_ = nullptr;
- CAT_TRACE ("timer8 ");
- }
- if (tci_loop8_)
- {
- tci_loop8_->quit();
- // tci_loop8_->deleteLater(), tci_loop8_ = nullptr;
- CAT_TRACE ("loop8 ");
- }
-
- if (wrapped_) wrapped_->stop ();
- CAT_TRACE ("& closed TCITransceiver\n");
-}
-
-void TCITransceiver::onMessageReceived(const QString &str)
-{
- qDebug() << "From WEB" << str;
- QStringList cmd_list = str.split(";", SkipEmptyParts);
- for (QString cmds : cmd_list){
- QStringList cmd = cmds.split(":", SkipEmptyParts);
- QStringList args = cmd.last().split(",", SkipEmptyParts);
- Tci_Cmd idCmd = mapCmd_[cmd.first()];
- if (idCmd != Cmd_Power && idCmd != Cmd_SWR && idCmd != Cmd_Smeter && idCmd != Cmd_AppFocus && idCmd != Cmd_RxSensors && idCmd != Cmd_TxSensors) { printf("%s TCI message received:|%s| ",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),str.toStdString().c_str()); printf("idCmd : %d args : %s\n",idCmd,args.join("|").toStdString().c_str());}
- qDebug() << cmds << idCmd;
- if (idCmd <=0) continue;
-
- switch (idCmd) {
- case Cmd_Smeter:
- if(args.at(0)==rx_ && args.at(1) == "0") level_ = args.at(2).toInt() + 73;
- break;
- case Cmd_RxSensors:
- if(args.at(0)==rx_) level_ = args.at(1).split(".")[0].toInt() + 73;
- printf("Smeter=%d\n",level_);
- break;
- case Cmd_TxSensors:
- if(args.at(0)==rx_) {
- power_ = 10 * args.at(3).split(".")[0].toInt() + args.at(3).split(".")[1].toInt();
- swr_ = 10 * args.at(4).split(".")[0].toInt() + args.at(4).split(".")[1].toInt();
- printf("Power=%d SWR=%d\n",power_,swr_);
- }
- break;
- case Cmd_SWR:
- printf("%s Cmd_SWR : %s\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),args.join("|").toStdString().c_str());
- swr_ = 10 * args.at(0).split(".")[0].toInt() + args.at(0).split(".")[1].toInt();
- break;
- case Cmd_Power:
- power_ = 10 * args.at(0).split(".")[0].toInt() + args.at(0).split(".")[1].toInt();
- printf("%s Cmd_Power : %s %d\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),args.join("|").toStdString().c_str(),power_);
- break;
- case Cmd_VFO:
- printf("%s Cmd_VFO : %s\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),args.join("|").toStdString().c_str());
- printf("band_change:%d busy_other_frequency_:%d timer1_remaining:%d timer2_remaining:%d",band_change,busy_other_frequency_,tci_timer7_->remainingTime(),tci_timer2_->remainingTime()); //was timer1 and timer2
- if(args.at(0)==rx_ && args.at(1) == "0") {
- if (args.at(2).left(1) != "-") rx_frequency_ = args.at(2);
- CAT_TRACE("Rx VFO Frequency from SDR is :");
- CAT_TRACE(rx_frequency_);
- if (!tci_Ready && requested_rx_frequency_.isEmpty()) requested_rx_frequency_ = rx_frequency_;
- if (busy_rx_frequency_ && !band_change) {
- printf (" cmdvfo0 done1");
- tci_done7(); //was tci_done1 (do_frequency)
- } else if (!tci_timer2_->isActive() && split_) {
- printf (" cmdvfo0 timer2 start 210");
- tci_timer2_->start(210);
- }
- }
- else if (args.at(0)==rx_ && args.at(1) == "1") {
- if (args.at(2).left(1) != "-") other_frequency_ = args.at(2);
- CAT_TRACE("Tx VFO (other) Frequency from SDR is :");
- CAT_TRACE(other_frequency_);
- if (!tci_Ready && requested_other_frequency_.isEmpty()) requested_other_frequency_ = other_frequency_;
- if (band_change && tci_timer7_->isActive()) { //was tci_timer1
- printf (" cmdvfo1 done1");
- band_change = false;
- tci_timer2_->start(210);
- tci_done7(); //was tci_done1 (do_frequency)
- } else if (busy_other_frequency_) {
- printf (" cmdvfo1 done2");
- tci_done2();
- } else if (tci_timer2_->isActive()) {
- printf (" cmdvfo1 timer2 reset 210");
- tci_timer2_->start(210);
- } else if (other_frequency_ != requested_other_frequency_ && tci_Ready && split_ && !tci_timer2_->isActive()) {
- printf (" cmdvfo1 timer2 start 210");
- tci_timer2_->start(210);
- }
- }
- break;
- case Cmd_Mode:
- printf("%s Cmd_Mode : %s\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),args.join("|").toStdString().c_str());
- if(args.at(0)==rx_) {
- if (ESDR3 || HPSDR) {
- if (args.at(1) == "0" ) mode_ = args.at(2).toLower(); else mode_ = args.at(1).toLower();
- } else mode_ = args.at(1);
- if (started_mode_.isEmpty()) started_mode_ = mode_;
- if (busy_mode_) return; // was tci_done1();
- else if (!requested_mode_.isEmpty() && requested_mode_ != mode_ && !band_change) {
- sendTextMessage(mode_to_command(requested_mode_));
- }
- }
- break;
- case Cmd_SplitEnable:
- printf("%s Cmd_SplitEnable : %s\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),args.join("|").toStdString().c_str());
- if(args.at(0)==rx_) {
- if (args.at(1) == "false") split_ = false;
- else if (args.at(1) == "true") split_ = true;
- if (!tci_Ready) {started_split_ = split_;}
- else if (busy_split_) tci_done5(); //was tci_done2
- else if (requested_split_ != split_ && !tci_timer5_->isActive()) { //was tci_timer2
- CAT_TRACE("tci_timer5 started in onMessageReceived-Cmd_SplitEnable");
- tci_timer5_->start(210); //was tci_timer2
- rig_split();
- }
- }
- break;
- case Cmd_Drive:
- printf("%s Cmd_Drive : %s\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),args.join("|").toStdString().c_str());
- if((!ESDR3 && !HPSDR) || args.at(0)==rx_) {
- if (ESDR3 || HPSDR) drive_ = args.at(1); else drive_ = args.at(0);
- if (requested_drive_.isEmpty()) requested_drive_ = drive_;
- busy_drive_ = false;
- }
- break;
- case Cmd_Volume:
- break;
- case Cmd_Trx:
- printf("%s Cmd_Trx : %s\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),args.join("|").toStdString().c_str());
- if(args.at(0)==rx_) {
- if (args.at(1) == "false") PTT_ = false;
- else if (args.at(1) == "true") PTT_ = true;
- if (tci_Ready && requested_PTT_ == PTT_) tci_done3();
- else if (tci_Ready && !PTT_) {
- requested_PTT_ = PTT_;
- update_PTT(PTT_);
- power_ = 0; if (do_pwr_) update_power (0);
- swr_ = 0; if (do_pwr_) update_swr (0);
- }
- }
- break;
- case Cmd_AudioStart:
- printf("%s Cmd_AudioStart : %s\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),args.join("|").toStdString().c_str());
- if(args.at(0)==rx_) {
- stream_audio_ = true;
- if (tci_Ready) {
- printf ("cmdaudiostart done1\n");
- tci_done7(); //was tci_done1 (do_frequency)
- }
- }
- break;
- case Cmd_RxEnable:
- printf("%s Cmd_RxEnable : %s\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),args.join("|").toStdString().c_str());
- if(args.at(0)=="1") {
- if (args.at(1) == "false") rx2_ = false;
- else if (args.at(1) == "true") rx2_ = true;
- if(!tci_Ready) {requested_rx2_ = rx2_; started_rx2_ = rx2_;}
- else if (tci_Ready && busy_rx2_ && requested_rx2_ == rx2_) {
- tci_done4();
- }
- }
- break;
- case Cmd_AudioStop:
- printf("%s CmdAudioStop : %s\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),args.join("|").toStdString().c_str());
- if(args.at(0)==rx_) {
- stream_audio_ = false;
- if (tci_Ready) {
- printf ("cmdaudiostop done1\n");
- tci_done7(); //was tci_done1 (do_frequency)
- }
- }
- break;
- case Cmd_Start:
- printf("%s CmdStart : %s\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),args.join("|").toStdString().c_str());
- _power_ = true;
- printf ("cmdstart done1\n");
- if (tci_Ready) {
- tci_done7(); //was tci_done1 (do_frequency)
- }
- break;
- case Cmd_Stop:
- printf("%s CmdStop : %s\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),args.join("|").toStdString().c_str());
- if (tci_Ready && PTT_) {
- PTT_ = false;
- requested_PTT_ = PTT_;
- update_PTT(PTT_);
- power_ = 0; if (do_pwr_) update_power (0);
- swr_ = 0; if (do_pwr_) update_swr (0);
- m_state = Idle;
- Q_EMIT tci_mod_active(m_state != Idle);
- }
- _power_ = false;
- if (tci_timer1_->isActive()) { //was tci_timer1
- printf ("cmdstop done1\n");
- tci_done1();
- } else {
- tci_Ready = false;
- }
- break;
- case Cmd_Version:
- printf("%s CmdVersion : %s\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),args.join("|").toStdString().c_str());
- if(args.at(0)=="ExpertSDR3") ESDR3 = true;
- else if (args.at(0)=="Thetis") HPSDR = true;
- break;
- case Cmd_Device:
- printf("%s CmdDevice : %s\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),args.join("|").toStdString().c_str());
- if((args.at(0)=="SunSDR2DX" || args.at(0)=="SunSDR2PRO") && !ESDR3) tx_top_ = false;
- printf ("tx_top_:%d\n",tx_top_);
- break;
- case Cmd_Ready:
- printf("%s CmdReady : %s\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),args.join("|").toStdString().c_str());
- tci_done7(); //was tci_done1 (do_frequency)
- break;
-
- default:
- break;
- }
- }
-}
-
-void TCITransceiver::sendTextMessage(const QString &message)
-{
- if (inConnected) {
- commander_->sendTextMessage(message);
- CAT_TRACE ("TCI Command Sent: " + message + '\n');
- }
-}
-
-void TCITransceiver::onBinaryReceived(const QByteArray &data)
-{
- Data_Stream *pStream = (Data_Stream*)(data.data());
- if (pStream->type != last_type) {
- last_type = pStream->type;
- }
- if (pStream->type == Iq_Stream){
- bool tx = false;
- if (pStream->receiver == 0){
- tx = trxA == 0;
- trxA = 1;
- }
- if (pStream->receiver == 1) {
- tx = trxB == 0;
- trxB = 1;
- }
- printf("sendIqData\n");
- emit sendIqData(pStream->receiver,pStream->length,pStream->data,tx);
- qDebug() << "IQ" << data.size() << pStream->length;
- } else if (pStream->type == RxAudioStream && audio_ && pStream->receiver == rx_.toUInt()) {
- writeAudioData(pStream->data,pStream->length);
- } else if (pStream->type == TxChrono && pStream->receiver == rx_.toUInt()) {
- mtx_.lock(); tx_fifo += 1; tx_fifo &= 7;
- int ssize = AudioHeaderSize+pStream->length*sizeof(float)*2;
- quint16 tehtud;
- if (m_tx1[tx_fifo].size() != ssize) m_tx1[tx_fifo].resize(ssize);
- Data_Stream * pOStream1 = (Data_Stream*)(m_tx1[tx_fifo].data());
- pOStream1->receiver = pStream->receiver;
- pOStream1->sampleRate = pStream->sampleRate;
- pOStream1->format = pStream->format;
- pOStream1->codec = 0;
- pOStream1->crc = 0;
- pOStream1->length = pStream->length;
- pOStream1->type = TxAudioStream;
- tehtud = readAudioData(pOStream1->data,pOStream1->length, txAtten);
- if (tehtud && tehtud != pOStream1->length) {
- quint16 valmis = tehtud;
- tehtud = readAudioData(pOStream1->data + valmis,pOStream1->length - valmis,txAtten);
- }
- tx_fifo2 = tx_fifo; mtx_.unlock();
- if (!inConnected || commander_->sendBinaryMessage(m_tx1[tx_fifo2]) != m_tx1[tx_fifo2].size()) {
- }
- }
-}
-
-void TCITransceiver::txAudioData(quint32 len, float * data)
-{
- QByteArray tx;
- tx.resize(AudioHeaderSize+len*sizeof(float)*2);
- Data_Stream * pStream = (Data_Stream*)(tx.data());
- pStream->receiver = 0;
- pStream->sampleRate = audioSampleRate;
- pStream->format = 3;
- pStream->codec = 0;
- pStream->crc = 0;
- pStream->length = len;
- pStream->type = TxAudioStream;
- memcpy(pStream->data,data,len*sizeof(float)*2);
- commander_->sendBinaryMessage(tx);
-}
-
-quint32 TCITransceiver::writeAudioData (float * data, qint32 maxSize)
-{
- static unsigned mstr0=999999;
- qint64 ms0 = QDateTime::currentMSecsSinceEpoch() % 86400000;
- unsigned mstr = ms0 % int(1000.0*m_period); // ms into the nominal Tx start time
- if(mstr < mstr0/2) { //When mstr has wrapped around to 0, restart the buffer
- dec_data.params.kin = 0;
- m_bufferPos = 0;
- }
- mstr0=mstr;
-
- if(data != NULL) {
- // block below adjusts receive audio attenuation
- quint64 i = 0;
- float * data1 = (float*)malloc(maxSize * sizeof(float));
- for(i=0;i<(quint64)maxSize;i++) {
- data1[i] = ((float)(pow(10, 0.05*rxAtten) * data[i]));
- }
-
- // no torn frames
- Q_ASSERT (!(maxSize % static_cast<qint32> (bytesPerFrame)));
-
- // these are in terms of input frames (not down sampled)
- size_t framesAcceptable ((sizeof (dec_data.d2) /
- sizeof (dec_data.d2[0]) - dec_data.params.kin) * m_downSampleFactor);
- size_t framesAccepted (qMin (static_cast<size_t> (maxSize /
- bytesPerFrame), framesAcceptable));
-
- if (framesAccepted < static_cast<size_t> (maxSize / bytesPerFrame)) {
- qDebug () << "dropped " << maxSize / bytesPerFrame - framesAccepted
- << " frames of data on the floor!"
- << dec_data.params.kin << mstr;
- }
-
- for (unsigned remaining = framesAccepted; remaining; ) {
- size_t numFramesProcessed (qMin (m_samplesPerFFT *
- m_downSampleFactor - m_bufferPos, remaining));
-
- if(m_downSampleFactor > 1) {
- store (&data1[(framesAccepted - remaining) * bytesPerFrame],
- numFramesProcessed, &m_buffer[m_bufferPos]);
- m_bufferPos += numFramesProcessed;
-
- if(m_bufferPos==m_samplesPerFFT*m_downSampleFactor) {
- qint32 framesToProcess (m_samplesPerFFT * m_downSampleFactor);
- qint32 framesAfterDownSample (m_samplesPerFFT);
- if(m_downSampleFactor > 1 && dec_data.params.kin>=0 &&
- dec_data.params.kin < (NTMAX*12000 - framesAfterDownSample)) {
- fil4_(&m_buffer[0], &framesToProcess, &dec_data.d2[dec_data.params.kin],
- &framesAfterDownSample, &dec_data.d2[dec_data.params.kin]);
- dec_data.params.kin += framesAfterDownSample;
- } else {
- qDebug() << "framesToProcess = " << framesToProcess;
- qDebug() << "dec_data.params.kin = " << dec_data.params.kin;
- qDebug() << "framesAfterDownSample" << framesAfterDownSample;
- }
- Q_EMIT tciframeswritten (dec_data.params.kin);
- m_bufferPos = 0;
- }
-
- } else {
- store (&data1[(framesAccepted - remaining) * bytesPerFrame],
- numFramesProcessed, &dec_data.d2[dec_data.params.kin]);
- m_bufferPos += numFramesProcessed;
- dec_data.params.kin += numFramesProcessed;
- if (m_bufferPos == static_cast<unsigned> (m_samplesPerFFT)) {
- Q_EMIT tciframeswritten (dec_data.params.kin);
- m_bufferPos = 0;
- }
- }
- remaining -= numFramesProcessed;
- }
-
- free(data1);
-}
- return maxSize; // we drop any data past the end of the buffer on
- // the floor until the next period starts
-}
-
-void TCITransceiver::rx2_enable (bool on)
-{
- printf("%s TCI rx2_enable:%d->%d busy:%d\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),rx2_,on,busy_rx2_);
- if (busy_rx2_) return;
- requested_rx2_ = on;
- busy_rx2_ = true;
- const QString cmd = CmdRxEnable + SmDP + "1" + SmCM + (requested_rx2_ ? "true" : "false") + SmTZ;
- sendTextMessage(cmd);
- mysleep4(1000);
- busy_rx2_ = false;
-}
-
-void TCITransceiver::rig_split ()
-{
- printf("%s TCI rig_split:%d->%d busy:%d\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),split_,requested_split_,busy_split_);
- if (busy_split_) return;
- if (tci_timer5_->isActive()) mysleep5(0);
- busy_split_ = true;
- const QString cmd = CmdSplitEnable + SmDP + rx_ + SmCM + "false" + SmTZ; // changed from below so split always false
- //const QString cmd = CmdSplitEnable + SmDP + rx_ + SmCM + (requested_split_ ? "true" : "false") + SmTZ;
- sendTextMessage(cmd);
- mysleep5(500);
- busy_split_ = false;
- if (requested_split_ == split_) update_split (split_);
-}
-
-void TCITransceiver::rig_power (bool on)
-{
- TRACE_CAT ("TCITransceiver", on << state ());
- printf("%s TCI rig_power:%d _power_:%d\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),on,_power_);
- if (on != _power_) {
- if (on) {
- const QString cmd = CmdStart + SmTZ;
- sendTextMessage(cmd);
- } else {
- const QString cmd = CmdStop + SmTZ;
- sendTextMessage(cmd);
- }
- }
-}
-
-void TCITransceiver::stream_audio (bool on)
-{
- TRACE_CAT ("TCITransceiver", on << state ());
- if (on != stream_audio_ && tci_Ready) {
- requested_stream_audio_ = on;
- if (on) {
- const QString cmd = CmdAudioStart + SmDP + rx_ + SmTZ;
- sendTextMessage(cmd);
- } else {
- const QString cmd = CmdAudioStop + SmDP + rx_ + SmTZ;
- sendTextMessage(cmd);
- }
- }
-}
-
-void TCITransceiver::do_audio (bool on)
-{
- TRACE_CAT ("TCITransceiver", on << state ());
- if (on) {
- dec_data.params.kin = 0;
- m_bufferPos = 0;
- }
- audio_ = on;
-}
-
-void TCITransceiver::do_period (double period)
-{
- TRACE_CAT ("TCITransceiver", period << state ());
- m_period = period;
-}
-
-void TCITransceiver::do_volume (qreal volume)
-{
- rxAtten = volume;
-}
-
-
-void TCITransceiver::do_txvolume (qreal txvolume)
-{
- txAtten = txvolume;
-}
-
-void TCITransceiver::do_blocksize (qint32 blocksize)
-{
- TRACE_CAT ("TCITransceiver", blocksize << state ());
- m_samplesPerFFT = blocksize;
-}
-
-void TCITransceiver::do_ptt (bool on)
-{
- TRACE_CAT ("TCITransceiver", on << state ());
- if (use_for_ptt_) {
- if (on != PTT_) {
- if (!inConnected && !error_.isEmpty()) throw error {error_};
- else if (busy_PTT_ || !tci_Ready || !_power_) return;
- else busy_PTT_ = true;
- requested_PTT_ = on;
- if (ESDR3) {
- const QString cmd = CmdTrx + SmDP + rx_ + SmCM + (on ? "true" : "false") + SmCM + "tci"+ SmTZ;
- sendTextMessage(cmd);
- } else {
- const QString cmd = CmdTrx + SmDP + rx_ + SmCM + (on ? "true" : "false") + SmTZ;
- sendTextMessage(cmd);
- }
- mysleep3(1000);
- busy_PTT_ = false;
- if (requested_PTT_ == PTT_) {
- update_PTT(PTT_);
- if (PTT_ && do_snr_) {
- update_level (-54);
- } else {
- power_ = 0;
- if (do_pwr_) update_power (0);
- swr_ = 0;
- if (do_pwr_) update_swr (0);
- }
- } else {
- printf("%s TCI failed set ptt %d->%d\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),PTT_,requested_PTT_);
- error_ = tr ("TCI failed to set ptt");
- tci_Ready = false;
- throw error {tr ("TCI failed to set ptt")};
- }
- } else update_PTT(on);
- }
- else
- {
- TRACE_CAT ("TCITransceiver", "TCI should use PTT via CAT");
- throw error {tr ("TCI should use PTT via CAT")};
- }
-}
-
-void TCITransceiver::do_frequency (Frequency f, MODE m, bool no_ignore)
-{
- qDebug() << no_ignore;
- TRACE_CAT ("TCITransceiver", f << state ());
- auto f_string = frequency_to_string (f);
- if (busy_rx_frequency_) {
- return;
- } else {
- requested_rx_frequency_ = f_string;
- requested_mode_ = map_mode (m);
- }
- if (tci_Ready && _power_) {
- if ((rx_frequency_ != requested_rx_frequency_)) {
- busy_rx_frequency_ = true;
- band_change = abs(rx_frequency_.toInt()-requested_rx_frequency_.toInt()) > 1000000;
- const QString cmd = CmdVFO + SmDP + rx_ + SmCM + "0" + SmCM + requested_rx_frequency_ + SmTZ;
- if(f > 100000 && f< 250000000000) sendTextMessage(cmd);
- mysleep7(2000);
- // if (band_change) mysleep7(500);
- band_change2 = abs(rx_frequency_.toInt()-requested_rx_frequency_.toInt()) > 1000000;
- if (!band_change2) update_rx_frequency (f);
- //if (requested_rx_frequency_ == rx_frequency_) update_rx_frequency (f);
- else {
- printf("%s TCI failed set rxfreq:%s->%s\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),rx_frequency_.toStdString().c_str(),requested_rx_frequency_.toStdString().c_str());
- error_ = tr ("TCI failed set rxfreq");
- CAT_TRACE("TCI failed set rxfreq. Rx freq is:");
- CAT_TRACE(rx_frequency_);
- CAT_TRACE("TCI failed set rxfreq. Requested Rx freq is:");
- CAT_TRACE(requested_rx_frequency_);
- printf("rx_frequency is %s and requested_rx_frequency is %s\n",rx_frequency_.toStdString().c_str(),requested_rx_frequency_.toStdString().c_str());
- tci_Ready = false;
- throw error {tr ("TCI failed set rxfreq")};
- }
- busy_rx_frequency_ = false;
- } else update_rx_frequency (string_to_frequency (rx_frequency_));
-
- if (!requested_mode_.isEmpty() && requested_mode_ != mode_ && !busy_mode_) {
- busy_mode_ = true;
- sendTextMessage(mode_to_command(requested_mode_));
- mysleep7(1000);
- if (requested_mode_.isEmpty() || requested_mode_ == mode_) update_mode (m);
- else {
- printf("%s TCI failed set mode %s->%s",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),mode_.toStdString().c_str(),requested_mode_.toStdString().c_str());
- error_ = tr ("TCI failed set mode");
- // tci_Ready = false;
- // throw error {tr ("TCI failed set mode")};
- }
- busy_mode_ = false;
- }
- } else {
- update_rx_frequency (f);
- update_mode (m);
- }
-}
-
-void TCITransceiver::do_tx_frequency (Frequency tx, MODE mode, bool no_ignore)
-{
- TRACE_CAT ("%s TCITransceiver", tx << state ());
- auto f_string = frequency_to_string (tx);
- if (tci_Ready && busy_other_frequency_ && no_ignore) {
- CAT_TRACE("TCI do_txfrequency critical no_ignore set tx vfo will be missed\n");
- printf("%s TCI do_txfrequency critical no_ignore set tx vfo will be missed\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str());
- }
- if (busy_other_frequency_) return;
- requested_other_frequency_ = f_string;
- requested_mode_ = map_mode (mode);
- if (tx) {
- requested_split_ = true;
- if (tci_Ready && _power_) {
- if (band_change && !tci_timer2_->isActive()) {
- if (!HPSDR) {
- mysleep2(210);
- } else {
- mysleep2(2000);
- }
- } else {
- if (tci_timer2_->isActive()) mysleep2(0);
- }
- if (requested_split_ != split_) rig_split();
- else update_split (split_);
- if (other_frequency_ != requested_other_frequency_) {
- busy_other_frequency_ = true;
- printf("%s TCI VFO1 command sent\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str());
- const QString cmd = CmdVFO + SmDP + rx_ + SmCM + "1" + SmCM + requested_other_frequency_ + SmTZ;
- if(tx > 100000 && tx < 250000000000) sendTextMessage(cmd);
- mysleep2(1000);
- other_band_change = abs(other_frequency_.toInt()-requested_other_frequency_.toInt()) > 1000000;
- if (!other_band_change) update_other_frequency (tx);
- // if (requested_other_frequency_ == other_frequency_) update_other_frequency (tx);
- else {
- printf("%s TCI failed set txfreq:%s->%s\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),other_frequency_.toStdString().c_str(),requested_other_frequency_.toStdString().c_str());
- CAT_TRACE("TCI failed set txfreq");
- // error_ = tr ("TCI failed set txfreq");
- // tci_Ready = false;
- // throw error {tr ("TCI failed set txfreq")};
- }
- busy_other_frequency_ = false;
- } else update_other_frequency (string_to_frequency (other_frequency_));
-
- } else {
- update_split (requested_split_);
- update_other_frequency (tx);
- }
- }
- else {
- requested_split_ = false;
- requested_other_frequency_ = "";
- if (tci_Ready && _power_) {
- if (band_change) {
- mysleep2(2000);
- if (!HPSDR) mysleep2(200);
- }
- if (tci_timer2_->isActive()) mysleep2(0);
- if (requested_split_ != split_) rig_split();
- else update_split (split_);
- update_other_frequency (tx);
- } else {
- update_split (requested_split_);
- update_other_frequency (tx);
- }
- }
-}
-
-//do_mode is never called.
-void TCITransceiver::do_mode (MODE m)
-{
- TRACE_CAT ("TCITransceiver", m << state ());
- auto m_string = map_mode (m);
- if (requested_mode_ != m_string) requested_mode_ = m_string;
- if (!requested_mode_.isEmpty() && mode_ != requested_mode_ && !busy_mode_) {
- busy_mode_ = true;
- sendTextMessage(mode_to_command(requested_mode_));
- mysleep8(1000);
- if (requested_mode_ == mode_) update_mode (m);
- else {
- printf("%s TCI failed set mode %s->%s",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),mode_.toStdString().c_str(),requested_mode_.toStdString().c_str());
- error_ = tr ("TCI failed set mode");
- // tci_Ready = false;
- // throw error {tr ("TCI failed set mode")};
- }
- busy_mode_ = false;
- }
-}
-
-void TCITransceiver::do_poll ()
-{
- if (!error_.isEmpty()) {tci_Ready = false; throw error {error_};}
- else if (!tci_Ready) throw error {tr ("TCI could not be opened")};
- update_rx_frequency (string_to_frequency (rx_frequency_));
- update_split(split_);
- if (state ().split ()) {
- if (other_frequency_ == requested_other_frequency_) update_other_frequency (string_to_frequency (other_frequency_));
- else if (!busy_rx_frequency_) do_tx_frequency(string_to_frequency (requested_other_frequency_),get_mode(true),false);
- }
- update_mode (get_mode());
- if (do_pwr_ && PTT_) {update_power (power_ * 100); update_swr (swr_*10);}
- if (do_snr_ && !PTT_) {
- update_level (level_);
- if(!ESDR3) {
- const QString cmd = CmdSmeter + SmDP + rx_ + SmCM + "0" + SmTZ;
- sendTextMessage(cmd);
- }
- }
-}
-
-auto TCITransceiver::get_mode (bool requested) -> MODE
-{
- MODE m {UNK};
- if (requested) {
- if ("am" == requested_mode_)
- {
- m = AM;
- }
- else if ("cw" == requested_mode_)
- {
- m = CW;
- }
- else if ("wfm" == requested_mode_)
- {
- m = FM;
- }
- else if ("nfm" == requested_mode_)
- {
- m = DIG_FM;
- }
- else if ("lsb" == requested_mode_)
- {
- m = LSB;
- }
- else if ("usb" == requested_mode_)
- {
- m = USB;
- }
- else if ("digl" == requested_mode_)
- {
- m = DIG_L;
- }
- else if ("digu" == requested_mode_)
- {
- m = DIG_U;
- }
- } else {
- if ("am" == mode_)
- {
- m = AM;
- }
- else if ("cw" == mode_)
- {
- m = CW;
- }
- else if ("wfm" == mode_)
- {
- m = FM;
- }
- else if ("nfm" == mode_)
- {
- m = DIG_FM;
- }
- else if ("lsb" == mode_)
- {
- m = LSB;
- }
- else if ("usb" == mode_)
- {
- m = USB;
- }
- else if ("digl" == mode_)
- {
- m = DIG_L;
- }
- else if ("digu" == mode_)
- {
- m = DIG_U;
- }
- }
- return m;
-}
-
-QString TCITransceiver::mode_to_command (QString m_string) const
-{
- // if (ESDR3) {
- // const QString cmd = CmdMode + SmDP + rx_ + SmCM + m_string.toUpper() + SmTZ;
- // return cmd;
- // } else {
- const QString cmd = CmdMode + SmDP + rx_ + SmCM + m_string + SmTZ;
- return cmd;
- // }
-}
-
-QString TCITransceiver::frequency_to_string (Frequency f) const
-{
- // number is localized and in kHz, avoid floating point translation
- // errors by adding a small number (0.1Hz)
- auto f_string = QString {}.setNum(f);
- printf ("frequency_to_string3 |%s|\n",f_string.toStdString().c_str());
- return f_string;
-}
-
-auto TCITransceiver::string_to_frequency (QString s) const -> Frequency
-{
- // temporary hack because Commander is returning invalid UTF-8 bytes
- s.replace (QChar {QChar::ReplacementCharacter}, locale_.groupSeparator ());
-
- bool ok;
-
- auto f = QLocale::c ().toDouble (s, &ok); // temporary fix
-
- if (!ok)
- {
- printf("Frequency rejected is ***%s***\n",s.toStdString().c_str());
- // throw error {tr ("TCI sent an unrecognized frequency") + " |" + s + "|"};
- }
- return f;
-}
-
-/*
- * mysleep1 is used in do_stop
- * mysleep2 is used in do_tx_frequency
- * mysleep3 is used in do_ptt
- * mysleep4 is used in rx2_enable
- * mysleep5 is used in rig_split
- * mysleep6 is used in do_start
- * mysleep7 is used in do_frequency
- * mysleep8 is used in do_mode which is never called
- * */
-
-void TCITransceiver::mysleep1 (int ms)
-{
- //printf("%s TCI sleep1 start %d %d\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),ms,tci_timer1_->isActive());
- if (ms) tci_timer1_->start(ms);
- tci_loop1_->exec();
- if (tci_timer1_->isActive() && tci_Ready) tci_timer1_->stop();
-}
-void TCITransceiver::mysleep2 (int ms)
-{
- if (ms) tci_timer2_->start(ms);
- tci_loop2_->exec();
- if (tci_timer2_->isActive()) tci_timer2_->stop();
-}
-void TCITransceiver::mysleep3 (int ms)
-{
- if (ms) tci_timer3_->start(ms);
- tci_loop3_->exec();
- if (tci_timer3_->isActive()) tci_timer3_->stop();
-}
-void TCITransceiver::mysleep4 (int ms)
-{
- if (ms) tci_timer4_->start(ms);
- tci_loop4_->exec();
- if (tci_timer4_->isActive()) tci_timer4_->stop();
-}
-void TCITransceiver::mysleep5 (int ms)
-{
- if((tci_loop5_ && (tci_loop5_->isRunning())) || (tci_timer5_ && tci_timer5_->isActive())) return;
- if (ms) tci_timer5_->start(ms);
- tci_loop5_->exec();
- if (tci_timer5_->isActive()) tci_timer5_->stop();
-}
-void TCITransceiver::mysleep6 (int ms)
-{
- if (ms) tci_timer6_->start(ms);
- tci_loop6_->exec();
- if (tci_timer6_->isActive()) tci_timer6_->stop();
-}
-void TCITransceiver::mysleep7 (int ms)
-{
- if (ms) tci_timer7_->start(ms);
- tci_loop7_->exec();
- if (tci_timer7_->isActive()) tci_timer7_->stop();
-}
-void TCITransceiver::mysleep8 (int ms)
-{
- if (ms) tci_timer8_->start(ms);
- tci_loop8_->exec();
- if (tci_timer8_->isActive()) tci_timer8_->stop();
-}
-// Modulator part
-
-void TCITransceiver::do_modulator_start (QString mode, unsigned symbolsLength, double framesPerSymbol,
- double frequency, double toneSpacing, bool synchronize, bool fastMode, double dBSNR, double TRperiod)
-{
- // Time according to this computer which becomes our base time
- qint64 ms0 = QDateTime::currentMSecsSinceEpoch() % 86400000;
- qDebug() << "ModStart" << QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.sss");
- unsigned mstr = ms0 % int(1000.0*m_period); // ms into the nominal Tx start time
- if (m_state != Idle) {
- // stop ();
- throw error {tr ("TCI modulator not Idle")};
- }
- m_quickClose = false;
- m_symbolsLength = symbolsLength;
- m_isym0 = std::numeric_limits<unsigned>::max (); // big number
- m_frequency0 = 0.;
- m_phi = 0.;
- m_addNoise = dBSNR < 0.;
- m_nsps = framesPerSymbol;
- m_trfrequency = frequency;
- m_amp = std::numeric_limits<qint16>::max ();
- m_toneSpacing = toneSpacing;
- m_bFastMode=fastMode;
- m_TRperiod=TRperiod;
- unsigned delay_ms=1000;
-
- if((mode=="FT8" and m_nsps==1920) or (mode=="FST4" and m_nsps==720)) delay_ms=500; //FT8, FST4-15
- if((mode=="FT8" and m_nsps==1024)) delay_ms=400; //SuperFox Qary Polar Code transmission
- if(mode=="Q65" and m_nsps<=3600) delay_ms=500; //Q65-15 and Q65-30
- if(mode=="FT4") delay_ms=300; //FT4
-
- // noise generator parameters
- if (m_addNoise) {
- m_snr = qPow (10.0, 0.05 * (dBSNR - 6.0));
- m_fac = 3000.0;
- if (m_snr > 1.0) m_fac = 3000.0 / m_snr;
- }
-
- // round up to an exact portion of a second that allows for startup delays
- auto mstr2 = mstr - delay_ms;
- if (mstr <= delay_ms) {
- m_ic = 0;
- } else {
- m_ic = mstr2 * (audioSampleRate / 1000);
- }
-
- m_silentFrames = 0;
- // calculate number of silent frames to send
- if (m_ic == 0 && synchronize && !m_tuning) {
- m_silentFrames = audioSampleRate / (1000 / delay_ms) - (mstr * (audioSampleRate / 1000));
- }
- m_state = (synchronize && m_silentFrames) ?
- Synchronizing : Active;
- printf("%s TCI modulator startdelay_ms=%d ASR=%d mstr=%d mstr2=%d m_ic=%d s_Frames=%lld synchronize=%d m_tuning=%d State=%d\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),delay_ms,audioSampleRate,mstr,mstr2,m_ic,m_silentFrames,synchronize,m_tuning,m_state);
- Q_EMIT tci_mod_active(m_state != Idle);
-}
-
-void TCITransceiver::do_tune (bool newState)
-{
- m_tuning = newState;
- if (!m_tuning) do_modulator_stop (true);
-}
-
-void TCITransceiver::do_modulator_stop (bool quick)
-{
- m_quickClose = quick;
- if(m_state != Idle) {
- m_state = Idle;
- Q_EMIT tci_mod_active(m_state != Idle);
- }
- tx_audio_ = false;
-}
-
-quint16 TCITransceiver::readAudioData (float * data, qint32 maxSize, qreal txAtten)
-{
- double toneFrequency=1500.0;
- if(m_nsps==6) {
- toneFrequency=1000.0;
- m_trfrequency=1000.0;
- m_frequency0=1000.0;
- }
- if(maxSize==0) return 0;
-
- qreal newVolume = pow(2.22222 * (45 - txAtten) * 0.01,2);
- //printf("txAtten is %f and newVolume is %f\n",txAtten, newVolume);
-
- qint64 numFrames (maxSize/bytesPerFrame);
- float * samples (reinterpret_cast<float *> (data));
- float * end (samples + numFrames * bytesPerFrame);
- qint64 framesGenerated (0);
-
- switch (m_state)
- {
- case Synchronizing:
- {
- if (m_silentFrames) { // send silence up to first second
- framesGenerated = qMin (m_silentFrames, numFrames);
- for ( ; samples != end; samples = load (0, samples)) { // silence
- }
- m_silentFrames -= framesGenerated;
- return framesGenerated * bytesPerFrame;
- }
- m_state = Active;
- Q_EMIT tci_mod_active(m_state != Idle);
- m_cwLevel = false;
- m_ramp = 0; // prepare for CW wave shaping
- }
- // fall through
-
- case Active:
- {
- unsigned int isym=0;
- qint16 sample=0;
- if(!m_tuning) isym=m_ic/(4.0*m_nsps); // Actual fsample=48000
- bool slowCwId=((isym >= m_symbolsLength) && (icw[0] > 0));
- m_nspd=2560; // 22.5 WPM
-
- if(m_TRperiod > 16.0 && slowCwId) { // Transmit CW ID?
- m_dphi = m_twoPi*m_trfrequency/audioSampleRate;
- unsigned ic0 = m_symbolsLength * 4 * m_nsps;
- unsigned j(0);
-
- while (samples != end) {
- j = (m_ic - ic0)/m_nspd + 1; // symbol of this sample
- bool level {bool (icw[j])};
- m_phi += m_dphi;
- if (m_phi > m_twoPi) m_phi -= m_twoPi;
- sample=0;
- float amp=32767.0;
- float x=0.0;
- if(m_ramp!=0) {
- x=qSin(float(m_phi));
- if(SOFT_KEYING) {
- amp=qAbs(qint32(m_ramp));
- if(amp>32767.0) amp=32767.0;
- }
- sample=round(newVolume * amp * x);
- }
- if (int (j) <= icw[0] && j < NUM_CW_SYMBOLS) { // stopu condition
- samples = load (postProcessSample (sample), samples);
- ++framesGenerated;
- ++m_ic;
- } else {
- m_state = Idle;
- Q_EMIT tci_mod_active(m_state != Idle);
- return framesGenerated * bytesPerFrame;
- }
-
- // adjust ramp
- if ((m_ramp != 0 && m_ramp != std::numeric_limits<qint16>::min ()) || level != m_cwLevel) {
- // either ramp has terminated at max/min or direction has changed
- m_ramp += RAMP_INCREMENT; // ramp
- }
- m_cwLevel = level;
- }
- return framesGenerated * bytesPerFrame;
- } //End of code for CW ID
-
- double const baud (12000.0 / m_nsps);
- // fade out parameters (no fade out for tuning)
- unsigned int i0,i1;
- if(m_tuning) {
- i1 = i0 = (m_bFastMode ? 999999 : 9999) * m_nsps;
- } else {
- i0=(m_symbolsLength - 0.017) * 4.0 * m_nsps;
- i1= m_symbolsLength * 4.0 * m_nsps;
- }
- if(m_bFastMode and !m_tuning) {
- i1=m_TRperiod*48000.0 - 24000.0;
- i0=i1-816;
- }
-
- sample=0;
- for (unsigned i = 0; i < numFrames && m_ic <= i1; ++i) {
- isym=0;
- if(!m_tuning and m_TRperiod!=3.0) isym=m_ic/(4.0*m_nsps); //Actual fsample=48000
- if(m_bFastMode) isym=isym%m_symbolsLength;
- if (isym != m_isym0 || m_trfrequency != m_frequency0) {
- if(itone[0]>=100) {
- m_toneFrequency0=itone[0];
- } else {
- if(m_toneSpacing==0.0) {
- m_toneFrequency0=m_trfrequency + itone[isym]*baud;
- } else {
- m_toneFrequency0=m_trfrequency + itone[isym]*m_toneSpacing;
- }
- }
- m_dphi = m_twoPi * m_toneFrequency0 / audioSampleRate;
- m_isym0 = isym;
- m_frequency0 = m_trfrequency; //???
- }
-
- int j=m_ic/480;
- if(m_fSpread>0.0 and j!=m_j0) {
-#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
- float x1=QRandomGenerator::global ()->generateDouble ();
- float x2=QRandomGenerator::global ()->generateDouble ();
-#else
- float x1=(float)qrand()/RAND_MAX;
- float x2=(float)qrand()/RAND_MAX;
-#endif
- toneFrequency = m_toneFrequency0 + 0.5*m_fSpread*(x1+x2-1.0);
- m_dphi = m_twoPi * toneFrequency / audioSampleRate;
- m_j0=j;
- }
-
- m_phi += m_dphi;
- if (m_phi > m_twoPi) m_phi -= m_twoPi;
- //ramp for first tone
- if (m_ic==0) m_amp = m_amp * 0.008144735;
- if (m_ic > 0 and m_ic < 191) m_amp = m_amp / 0.975;
- //ramp for last tone
- if (m_ic > i0) m_amp = 0.99 * m_amp;
- if (m_ic > i1) m_amp = 0.0;
- sample=qRound(newVolume * m_amp*qSin(m_phi));
-
- //transmit from a precomputed FT8 wave[] array:
- if(!m_tuning and (m_toneSpacing < 0.0)) {
- m_amp=32767.0;
- sample=qRound(newVolume * m_amp*foxcom_.wave[m_ic]);
- }
- samples = load (postProcessSample (sample), samples);
- ++framesGenerated;
- ++m_ic;
- }
-
- if (m_amp == 0.0) { // TODO G4WJS: compare double with zero might not be wise
- if (icw[0] == 0) {
- // no CW ID to send
- m_state = Idle;
- Q_EMIT tci_mod_active(m_state != Idle);
- return framesGenerated * bytesPerFrame;
- }
- m_phi = 0.0;
- }
-
- m_frequency0 = m_trfrequency;
- // done for this chunk - continue on next call
- if (samples != end && framesGenerated) {
- }
- while (samples != end) { // pad block with silence
- samples = load (0, samples);
- ++framesGenerated;
- }
- return framesGenerated * bytesPerFrame;
- }
- // fall through
-
- case Idle:
- while (samples != end) samples = load (0, samples);
- }
-
- Q_ASSERT (Idle == m_state);
- return 0;
-}
-
-qint16 TCITransceiver::postProcessSample (qint16 sample) const
-{
- if (m_addNoise) { // Test frame, we'll add noise
- qint32 s = m_fac * (gran () + sample * m_snr / 32768.0);
- if (s > std::numeric_limits<qint16>::max ()) {
- s = std::numeric_limits<qint16>::max ();
- }
- if (s < std::numeric_limits<qint16>::min ()) {
- s = std::numeric_limits<qint16>::min ();
- }
- sample = s;
- }
- return sample;
-}
+#include "Transceiver/TCITransceiver.hpp" + +#include <QRegularExpression> +#include <QLocale> +#include <QThread> +#include <qmath.h> + +#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) +#include <QRandomGenerator> +#endif + +#include <QString> +#include "widgets/itoneAndicw.h" +#include "Network/NetworkServerLookup.hpp" +#include "moc_TCITransceiver.cpp" + +#include <QStandardPaths> +#include <QDir> +#include <QDebug> +#include <QDateTime> +#include <QTimer> + +namespace +{ + char const * const TCI_transceiver_1_name {"TCI Client RX1"}; + char const * const TCI_transceiver_2_name {"TCI Client RX2"}; + + QString map_mode (Transceiver::MODE mode) + { + switch (mode) + { + case Transceiver::AM: return "am"; + case Transceiver::CW: return "cw"; +// case Transceiver::CW_R: return "CW-R"; + case Transceiver::USB: return "usb"; + case Transceiver::LSB: return "lsb"; +// case Transceiver::FSK: return "RTTY"; +// case Transceiver::FSK_R: return "RTTY-R"; + case Transceiver::DIG_L: return "digl"; + case Transceiver::DIG_U: return "digu"; + case Transceiver::FM: return "wfm"; + case Transceiver::DIG_FM: + return "nfm"; + default: break; + } + return ""; + } + static const QString SmTZ(";"); + static const QString SmDP(":"); + static const QString SmCM(","); + static const QString SmTrue("true"); + static const QString SmFalse("false"); + + // Command maps + static const QString CmdDevice("device"); + static const QString CmdReceiveOnly("receive_only"); + static const QString CmdTrxCount("trx_count"); + static const QString CmdChannelCount("channels_count"); + static const QString CmdVfoLimits("vfo_limits"); + static const QString CmdIfLimits("if_limits"); + static const QString CmdModeList("modulations_list"); + static const QString CmdMode("modulation"); + static const QString CmdReady("ready"); + static const QString CmdStop("stop"); + static const QString CmdStart("start"); + static const QString CmdPreamp("preamp"); + static const QString CmdDds("dds"); + static const QString CmdIf("if"); + static const QString CmdTrx("trx"); + static const QString CmdRxEnable("rx_enable"); + static const QString CmdTxEnable("tx_enable"); + static const QString CmdRxChannelEnable("rx_channel_enable"); + static const QString CmdRitEnable("rit_enable"); + static const QString CmdRitOffset("rit_offset"); + static const QString CmdXitEnable("xit_enable"); + static const QString CmdXitOffset("xit_offset"); + static const QString CmdSplitEnable("split_enable"); + static const QString CmdIqSR("iq_samplerate"); + static const QString CmdIqStart("iq_start"); + static const QString CmdIqStop("iq_stop"); + static const QString CmdCWSpeed("cw_macros_speed"); + static const QString CmdCWDelay("cw_macros_delay"); + static const QString CmdSpot("spot"); + static const QString CmdSpotDelete("spot_delete"); + static const QString CmdFilterBand("rx_filter_band"); + static const QString CmdVFO("vfo"); + static const QString CmdVersion("protocol"); //protocol:esdr,1.2; + static const QString CmdTune("tune"); + static const QString CmdRxMute("rx_mute"); + static const QString CmdSmeter("rx_smeter"); + static const QString CmdPower("tx_power"); + static const QString CmdSWR("tx_swr"); + static const QString CmdECoderRX("ecoder_switch_rx"); + static const QString CmdECoderVFO("ecoder_switch_channel"); + static const QString CmdAudioSR("audio_samplerate"); + static const QString CmdAudioStart("audio_start"); + static const QString CmdAudioStop("audio_stop"); + static const QString CmdAppFocus("app_focus"); + static const QString CmdVolume("volume"); + static const QString CmdSqlEnable("sql_enable"); + static const QString CmdSqlLevel("sql_level"); + static const QString CmdDrive("drive"); + static const QString CmdTuneDrive("tune_drive"); + static const QString CmdMute("mute"); + static const QString CmdRxSensorsEnable("rx_sensors_enable"); + static const QString CmdTxSensorsEnable("tx_sensors_enable"); + static const QString CmdRxSensors("rx_sensors"); + static const QString CmdTxSensors("tx_sensors"); + static const QString CmdAgcMode("agc_mode"); + static const QString CmdAgcGain("agc_gain"); + static const QString CmdLock("lock"); +} + +extern "C" { + void fil4_(qint16*, qint32*, qint16*, qint32*, short int*); +} +extern dec_data dec_data; + +extern float gran(); // Noise generator (for tests only) + +#define RAMP_INCREMENT 64 // MUST be an integral factor of 2^16 + +#if defined (WSJT_SOFT_KEYING) +# define SOFT_KEYING WSJT_SOFT_KEYING +#else +# define SOFT_KEYING 1 +#endif + +double constexpr TCITransceiver::m_twoPi; + +void TCITransceiver::register_transceivers (logger_type *, TransceiverFactory::Transceivers * registry, unsigned id1, unsigned id2) +{ + (*registry)[TCI_transceiver_1_name] = TransceiverFactory::Capabilities {id1, TransceiverFactory::Capabilities::tci, true}; + (*registry)[TCI_transceiver_2_name] = TransceiverFactory::Capabilities {id2, TransceiverFactory::Capabilities::tci, true}; +} + +static constexpr quint32 AudioHeaderSize = 16u*sizeof(quint32); + +TCITransceiver::TCITransceiver (logger_type * logger, std::unique_ptr<TransceiverBase> wrapped,QString const& rignr, + QString const& address, bool use_for_ptt, + int poll_interval, QObject * parent) + : PollingTransceiver {logger, poll_interval, parent} + , wrapped_ {std::move (wrapped)} + , rx_ {rignr} + , server_ {address} + , use_for_ptt_ {use_for_ptt} + , errortable {tr("ConnectionRefused"), + tr("RemoteHostClosed"), + tr("HostNotFound"), + tr("SocketAccess"), + tr("SocketResource"), + tr("SocketTimeout"), + tr("DatagramTooLarge"), + tr("Network"), + tr("AddressInUse"), + tr("SocketAddressNotAvailable"), + tr("UnsupportedSocketOperation"), + tr("UnfinishedSocketOperation"), + tr("ProxyAuthenticationRequired"), + tr("SslHandshakeFailed"), + tr("ProxyConnectionRefused"), + tr("ProxyConnectionClosed"), + tr("ProxyConnectionTimeout"), + tr("ProxyNotFound"), + tr("ProxyProtocol"), + tr("Operation"), + tr("SslInternal"), + tr("SslInvalidUserData"), + tr("Temporary"), + tr("UnknownSocket") } + , error_ {""} + , do_snr_ {(poll_interval & do__snr) == do__snr} + , do_pwr_ {(poll_interval & do__pwr) == do__pwr} + , rig_power_ {(poll_interval & rig__power) == rig__power} + , rig_power_off_ {(poll_interval & rig__power_off) == rig__power_off} + , tci_audio_ {(poll_interval & tci__audio) == tci__audio} + , commander_ {nullptr} + , tci_timer1_ {nullptr} + , tci_loop1_ {nullptr} + , tci_timer2_ {nullptr} + , tci_loop2_ {nullptr} + , tci_timer3_ {nullptr} + , tci_loop3_ {nullptr} + , tci_timer4_ {nullptr} + , tci_loop4_ {nullptr} + , tci_timer5_ {nullptr} + , tci_loop5_ {nullptr} + , tci_timer6_ {nullptr} + , tci_loop6_ {nullptr} + , tci_timer7_ {nullptr} + , tci_loop7_ {nullptr} + , tci_timer8_ {nullptr} + , tci_loop8_ {nullptr} + , wavptr_ {nullptr} + , m_downSampleFactor {4} + , m_buffer ((m_downSampleFactor > 1) ? + new short [max_buffer_size * m_downSampleFactor] : nullptr) + , m_quickClose {false} + , m_phi {0.0} + , m_toneSpacing {0.0} + , m_fSpread {0.0} + , m_state {Idle} + , m_tuning {false} + , m_cwLevel {false} + , m_j0 {-1} + , m_toneFrequency0 {1500.0} + , wav_file_ {QDir(QStandardPaths::writableLocation (QStandardPaths::DataLocation)).absoluteFilePath ("tx.wav").toStdString()} +{ + m_samplesPerFFT = 6912 / 2; + tci_Ready = false; + trxA = 0; + trxB = 0; + cntIQ = 0; + bIQ = false; + inConnected = false; + audioSampleRate = 48000u; + mapCmd_[CmdDevice] = Cmd_Device; + mapCmd_[CmdReceiveOnly] = Cmd_ReceiveOnly; + mapCmd_[CmdTrxCount] = Cmd_TrxCount; + mapCmd_[CmdChannelCount] = Cmd_ChannelCount; + mapCmd_[CmdVfoLimits] = Cmd_VfoLimits; + mapCmd_[CmdIfLimits] = Cmd_IfLimits; + mapCmd_[CmdModeList] = Cmd_ModeList; + mapCmd_[CmdMode] = Cmd_Mode; + mapCmd_[CmdReady] = Cmd_Ready; + mapCmd_[CmdStop] = Cmd_Stop; + mapCmd_[CmdStart] = Cmd_Start; + mapCmd_[CmdPreamp] = Cmd_Preamp; + mapCmd_[CmdDds] = Cmd_Dds; + mapCmd_[CmdIf] = Cmd_If; + mapCmd_[CmdTrx] = Cmd_Trx; + mapCmd_[CmdRxEnable] = Cmd_RxEnable; + mapCmd_[CmdTxEnable] = Cmd_TxEnable; + mapCmd_[CmdRxChannelEnable] = Cmd_RxChannelEnable; + mapCmd_[CmdRitEnable] = Cmd_RitEnable; + mapCmd_[CmdRitOffset] = Cmd_RitOffset; + mapCmd_[CmdXitEnable] = Cmd_XitEnable; + mapCmd_[CmdXitOffset] = Cmd_XitOffset; + mapCmd_[CmdSplitEnable] = Cmd_SplitEnable; + mapCmd_[CmdIqSR] = Cmd_IqSR; + mapCmd_[CmdIqStart] = Cmd_IqStart; + mapCmd_[CmdIqStop] = Cmd_IqStop; + mapCmd_[CmdCWSpeed] = Cmd_CWSpeed; + mapCmd_[CmdCWDelay] = Cmd_CWDelay; + mapCmd_[CmdFilterBand] = Cmd_FilterBand; + mapCmd_[CmdVFO] = Cmd_VFO; + mapCmd_[CmdVersion] = Cmd_Version; + mapCmd_[CmdTune] = Cmd_Tune; + mapCmd_[CmdRxMute] = Cmd_RxMute; + mapCmd_[CmdSmeter] = Cmd_Smeter; + mapCmd_[CmdPower] = Cmd_Power; + mapCmd_[CmdSWR] = Cmd_SWR; + mapCmd_[CmdECoderRX] = Cmd_ECoderRX; + mapCmd_[CmdECoderVFO] = Cmd_ECoderVFO; + mapCmd_[CmdAudioSR] = Cmd_AudioSR; + mapCmd_[CmdAudioStart] = Cmd_AudioStart; + mapCmd_[CmdAudioStop] = Cmd_AudioStop; + mapCmd_[CmdAppFocus] = Cmd_AppFocus; + mapCmd_[CmdVolume] = Cmd_Volume; + mapCmd_[CmdSqlEnable] = Cmd_SqlEnable; + mapCmd_[CmdSqlLevel] = Cmd_SqlLevel; + mapCmd_[CmdDrive] = Cmd_Drive; + mapCmd_[CmdTuneDrive] = Cmd_TuneDrive; + mapCmd_[CmdMute] = Cmd_Mute; + mapCmd_[CmdRxSensorsEnable] = Cmd_RxSensorsEnable; + mapCmd_[CmdTxSensorsEnable] = Cmd_TxSensorsEnable; + mapCmd_[CmdRxSensors] = Cmd_RxSensors; + mapCmd_[CmdTxSensors] = Cmd_TxSensors; + mapCmd_[CmdAgcMode] = Cmd_AgcMode; + mapCmd_[CmdAgcGain] = Cmd_AgcGain; + mapCmd_[CmdLock] = Cmd_Lock; +} + +void TCITransceiver::onConnected() +{ + inConnected = true; + CAT_TRACE ("TCITransceiver entered TCI onConnected and inConnected==true\n"); +} + +void TCITransceiver::onDisconnected() +{ + inConnected = false; + CAT_TRACE ("TCITransceiver entered TCI onDisonnected and inConnected==false\n"); +} + + +void TCITransceiver::onError(QAbstractSocket::SocketError err) +{ + qDebug() << "WebInThread::onError"; + CAT_TRACE ("TCITransceiver entered TCI onError and ErrorNumber is " + QString::number(err) + '\n'); + error_ = tr ("TCI websocket error: %1").arg (errortable.at (err)); +} + +int TCITransceiver::do_start () +{ + if (tci_audio_) QThread::currentThread()->setPriority(QThread::HighPriority); + CAT_TRACE ("TCITransceiver entered TCI do_start and tci_Ready is " + QString::number(tci_Ready) + '\n'); + qDebug () << "qDebug says do_start tci_Ready is: " << tci_Ready; + if (wrapped_) wrapped_->start (0); + url_.setUrl("ws://" + server_); //server_ + if (url_.host() == "") url_.setHost("localhost"); + if (url_.port() == -1) url_.setPort(40001); + + if (!commander_) { + commander_ = new QWebSocket {}; // QObject takes ownership + CAT_TRACE ("TCITransceiver entered TCI do_start and commander created\n"); + //printf ("commander created\n"); + connect(commander_,SIGNAL(connected()),this,SLOT(onConnected())); + connect(commander_,SIGNAL(disconnected()),this,SLOT(onDisconnected())); + connect(commander_,SIGNAL(binaryMessageReceived(QByteArray)),this,SLOT(onBinaryReceived(QByteArray))); + connect(commander_,SIGNAL(textMessageReceived(QString)),this,SLOT(onMessageReceived(QString))); + connect(commander_,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(onError(QAbstractSocket::SocketError))); + } + if (!tci_loop1_) { + tci_loop1_ = new QEventLoop {this}; + } + if (!tci_timer1_) { + tci_timer1_ = new QTimer {this}; + tci_timer1_ -> setSingleShot(true); + connect( tci_timer1_, &QTimer::timeout, tci_loop1_, &QEventLoop::quit); + connect( this, &TCITransceiver::tci_done1, tci_loop1_, &QEventLoop::quit); + } + if (!tci_loop2_) { + tci_loop2_ = new QEventLoop {this}; + } + if (!tci_timer2_) { + tci_timer2_ = new QTimer {this}; + tci_timer2_ -> setSingleShot(true); + connect( tci_timer2_, &QTimer::timeout, tci_loop2_, &QEventLoop::quit); + connect( this, &TCITransceiver::tci_done2, tci_loop2_, &QEventLoop::quit); + } + if (!tci_loop3_) { + tci_loop3_ = new QEventLoop {this}; + } + if (!tci_timer3_) { + tci_timer3_ = new QTimer {this}; + tci_timer3_ -> setSingleShot(true); + connect( tci_timer3_, &QTimer::timeout, tci_loop3_, &QEventLoop::quit); + connect( this, &TCITransceiver::tci_done3, tci_loop3_, &QEventLoop::quit); + } + if (!tci_loop4_) { + tci_loop4_ = new QEventLoop {this}; + } + if (!tci_timer4_) { + tci_timer4_ = new QTimer {this}; + tci_timer4_ -> setSingleShot(true); + connect( tci_timer4_, &QTimer::timeout, tci_loop4_, &QEventLoop::quit); + connect( this, &TCITransceiver::tci_done4, tci_loop4_, &QEventLoop::quit); + } + if (!tci_loop5_) { + tci_loop5_ = new QEventLoop {this}; + } + if (!tci_timer5_) { + tci_timer5_ = new QTimer {this}; + tci_timer5_ -> setSingleShot(true); + connect( tci_timer5_, &QTimer::timeout, tci_loop5_, &QEventLoop::quit); + connect( this, &TCITransceiver::tci_done5, tci_loop5_, &QEventLoop::quit); + } + if (!tci_loop6_) { + tci_loop6_ = new QEventLoop {this}; + } + if (!tci_timer6_) { + tci_timer6_ = new QTimer {this}; + tci_timer6_ -> setSingleShot(true); + connect( tci_timer6_, &QTimer::timeout, tci_loop6_, &QEventLoop::quit); + connect( this, &TCITransceiver::tci_done6, tci_loop6_, &QEventLoop::quit); + } + if (!tci_loop7_) { + tci_loop7_ = new QEventLoop {this}; + } + if (!tci_timer7_) { + tci_timer7_ = new QTimer {this}; + tci_timer7_ -> setSingleShot(true); + connect( tci_timer7_, &QTimer::timeout, tci_loop7_, &QEventLoop::quit); + connect( this, &TCITransceiver::tci_done7, tci_loop7_, &QEventLoop::quit); + } + if (!tci_loop8_) { + tci_loop8_ = new QEventLoop {this}; + } + if (!tci_timer8_) { + tci_timer8_ = new QTimer {this}; + tci_timer8_ -> setSingleShot(true); + connect( tci_timer8_, &QTimer::timeout, tci_loop8_, &QEventLoop::quit); + connect( this, &TCITransceiver::tci_done8, tci_loop8_, &QEventLoop::quit); + } + + tx_fifo = 0; tx_top_ = true; + tci_Ready = false; + ESDR3 = false; + HPSDR = false; + band_change = false; + trxA = 0; + trxB = 0; + busy_rx_frequency_ = false; + busy_mode_ = false; + busy_other_frequency_ = false; + busy_split_ = false; + busy_drive_ = false; + busy_PTT_ = false; + busy_rx2_ = false; + rx2_ = false; + requested_rx2_ = false; + started_rx2_ = false; + split_ = false; + requested_split_ = false; + started_split_ = false; + PTT_ = false; + requested_PTT_ = false; + mode_ = ""; + requested_mode_ = ""; + started_mode_ = ""; + requested_rx_frequency_ = ""; + rx_frequency_ = ""; + requested_other_frequency_ = ""; + other_frequency_ = ""; + requested_drive_ = ""; + drive_ = ""; + level_ = -54; + txAtten = 45; + power_ = 0; + swr_ = 0; + m_bufferPos = 0; + m_downSampleFactor =4; + m_ns = 999; + audio_ = false; + requested_stream_audio_ = false; + stream_audio_ = false; + _power_ = false; + CAT_TRACE ("TCITransceiver entered TCI do_start and url " + url_.toString() + " rig_power:" + QString::number(rig_power_) + " rig_power_off:" + QString::number(rig_power_off_) + " tci_audio:" + QString::number(tci_audio_) + " do_snr:" + QString::number(do_snr_) + " do_pwr:" + QString::number(do_pwr_) + '\n'); + commander_->open (url_); + tci_done6(); + mysleep6(2000); + busy_split_ = true; + const QString cmd = CmdSplitEnable + SmDP + "false" + SmTZ; + sendTextMessage(cmd); + //mysleep6(500); + busy_split_ = false; + if (error_.isEmpty()) { + tci_Ready = true; + if (!_power_) { + if (rig_power_) { + rig_power(true); + mysleep6(1000); + if(!_power_) throw error {tr ("TCI SDR could not be switched on")}; + } else { + tci_Ready = false; + throw error {tr ("TCI SDR is not switched on")}; + } + } + if (rx_ == "1" && !rx2_) { + rx2_enable (true); + if (!rx2_) { + tci_Ready = false; + throw error {tr ("TCI RX2 could not be enabled")}; + } + } + if (tci_audio_) { + stream_audio (true); + mysleep6(500); + if (!stream_audio_) { + tci_Ready = false; + throw error {tr ("TCI Audio could not be switched on")}; + } + } + if (ESDR3) { + const QString cmd = CmdRxSensorsEnable + SmDP + (do_snr_ ? "true" : "false") + SmCM + "500" + SmTZ; + sendTextMessage(cmd); + } else if (do_snr_) { + const QString cmd = CmdSmeter + SmDP + rx_ + SmCM + "0" + SmTZ; + sendTextMessage(cmd); + } +// if (!requested_rx_frequency_.isEmpty()) do_frequency(string_to_frequency (requested_rx_frequency_),get_mode(true),false); +// if (!requested_other_frequency_.isEmpty()) do_tx_frequency(string_to_frequency (requested_other_frequency_),get_mode(true),false); +// else if (requested_split_ != split_) {rig_split();} + + do_poll (); + if (ESDR3) { + const QString cmd = CmdTxSensorsEnable + SmDP + (do_pwr_ ? "true" : "false") + SmCM + "500" + SmTZ; + sendTextMessage(cmd); + } + if (stream_audio_) do_audio(true); + + CAT_TRACE ("TCITransceiver started\n"); + return 0; + } else { + CAT_TRACE("TCITransceiver not started with error " + error_ + '\n'); + + if (error_.isEmpty()) + throw error {tr ("TCI could not be opened")}; + else + throw error {error_}; + } +} + +void TCITransceiver::do_stop () +{ + CAT_TRACE ("TCITransceiver TCI close\n"); + //printf ("TCI close\n"); + if (!commander_) return; + if (stream_audio_ && tci_Ready && inConnected && _power_) { + stream_audio (false); + mysleep1(500); + CAT_TRACE ("TCI audio closed\n"); + //printf ("TCI audio closed\n"); + } + if (tci_Ready && inConnected && _power_) { + requested_other_frequency_ = ""; + busy_split_ = true; + const QString cmd = CmdSplitEnable + SmDP + "false" + SmTZ; + sendTextMessage(cmd); + mysleep1(500); + busy_split_ = false; + requested_split_ = false; + rig_split(); + if (started_mode_ != mode_) sendTextMessage(mode_to_command(started_mode_)); + if (!started_rx2_ && rx2_) { + rx2_enable (false); + } + } + if (_power_ && rig_power_off_ && tci_Ready && inConnected) { + rig_power(false); + mysleep1(500); + CAT_TRACE ("TCI power down\n"); + //printf ("TCI power down\n"); + } + tci_Ready = false; + if (commander_) + { + if (inConnected) commander_->close(QWebSocketProtocol::CloseCodeNormal,"end"); + delete commander_, commander_ = nullptr; + CAT_TRACE ("deleted commander & closed websocket & deleted:"); + } + if (tci_timer1_) + { + if (tci_timer1_->isActive()) tci_timer1_->stop(); + // tci_timer1_->deleteLater(), tci_timer1_ = nullptr; + CAT_TRACE ("timer1 "); + } + if (tci_loop1_) + { + tci_loop1_->quit(); + // tci_loop1_->deleteLater(), tci_loop1_ = nullptr; + CAT_TRACE ("loop1 "); + } + if (tci_timer2_) + { + if (tci_timer2_->isActive()) tci_timer2_->stop(); + // tci_timer2_->deleteLater(), tci_timer2_ = nullptr; + CAT_TRACE ("timer2 "); + } + if (tci_loop2_) + { + tci_loop2_->quit(); + // tci_loop2_->deleteLater(), tci_loop2_ = nullptr; + CAT_TRACE ("loop2 "); + } + if (tci_timer3_) + { + if (tci_timer3_->isActive()) tci_timer3_->stop(); + // tci_timer3_->deleteLater(), tci_timer3_ = nullptr; + CAT_TRACE ("timer3 "); + } + if (tci_loop3_) + { + tci_loop3_->quit(); + // tci_loop3_->deleteLater(), tci_loop3_ = nullptr; + CAT_TRACE ("loop3 "); + } + if (tci_timer4_) + { + if (tci_timer4_->isActive()) tci_timer4_->stop(); + // tci_timer4_->deleteLater(), tci_timer4_ = nullptr; + CAT_TRACE ("timer4 "); + } + if (tci_loop4_) + { + tci_loop4_->quit(); + // tci_loop4_->deleteLater(), tci_loop4_ = nullptr; + CAT_TRACE ("loop4 "); + } + if (tci_timer5_) + { + if (tci_timer5_->isActive()) tci_timer5_->stop(); + // tci_timer5_->deleteLater(), tci_timer5_ = nullptr; + CAT_TRACE ("timer5 "); + } + if (tci_loop5_) + { + tci_loop5_->quit(); + // tci_loop5_->deleteLater(), tci_loop5_ = nullptr; + CAT_TRACE ("loop5 "); + } + if (tci_timer6_) + { + if (tci_timer6_->isActive()) tci_timer6_->stop(); + // tci_timer6_->deleteLater(), tci_timer6_ = nullptr; + CAT_TRACE ("timer6 "); + } + if (tci_loop6_) + { + tci_loop6_->quit(); + // tci_loop6_->deleteLater(), tci_loop6_ = nullptr; + CAT_TRACE ("loop6 "); + } + if (tci_timer7_) + { + if (tci_timer7_->isActive()) tci_timer7_->stop(); + // tci_timer7_->deleteLater(), tci_timer7_ = nullptr; + CAT_TRACE ("timer7 "); + } + if (tci_loop7_) + { + tci_loop7_->quit(); + // tci_loop7_->deleteLater(), tci_loop7_ = nullptr; + CAT_TRACE ("loop7 "); + } + if (tci_timer8_) + { + if (tci_timer8_->isActive()) tci_timer8_->stop(); + // tci_timer8_->deleteLater(), tci_timer8_ = nullptr; + CAT_TRACE ("timer8 "); + } + if (tci_loop8_) + { + tci_loop8_->quit(); + // tci_loop8_->deleteLater(), tci_loop8_ = nullptr; + CAT_TRACE ("loop8 "); + } + + if (wrapped_) wrapped_->stop (); + CAT_TRACE ("& closed TCITransceiver\n"); +} + +void TCITransceiver::onMessageReceived(const QString &str) +{ + qDebug() << "From WEB" << str; + QStringList cmd_list = str.split(";", SkipEmptyParts); + for (QString cmds : cmd_list){ + QStringList cmd = cmds.split(":", SkipEmptyParts); + QStringList args = cmd.last().split(",", SkipEmptyParts); + Tci_Cmd idCmd = mapCmd_[cmd.first()]; + if (idCmd != Cmd_Power && idCmd != Cmd_SWR && idCmd != Cmd_Smeter && idCmd != Cmd_AppFocus && idCmd != Cmd_RxSensors && idCmd != Cmd_TxSensors) { printf("%s TCI message received:|%s| ",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),str.toStdString().c_str()); printf("idCmd : %d args : %s\n",idCmd,args.join("|").toStdString().c_str());} + qDebug() << cmds << idCmd; + if (idCmd <=0) continue; + + switch (idCmd) { + case Cmd_Smeter: + if(args.at(0)==rx_ && args.at(1) == "0") level_ = args.at(2).toInt() + 73; + break; + case Cmd_RxSensors: + if(args.at(0)==rx_) level_ = args.at(1).split(".")[0].toInt() + 73; + printf("Smeter=%d\n",level_); + break; + case Cmd_TxSensors: + if(args.at(0)==rx_) { + power_ = 10 * args.at(3).split(".")[0].toInt() + args.at(3).split(".")[1].toInt(); + swr_ = 10 * args.at(4).split(".")[0].toInt() + args.at(4).split(".")[1].toInt(); + printf("Power=%d SWR=%d\n",power_,swr_); + } + break; + case Cmd_SWR: + printf("%s Cmd_SWR : %s\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),args.join("|").toStdString().c_str()); + swr_ = 10 * args.at(0).split(".")[0].toInt() + args.at(0).split(".")[1].toInt(); + break; + case Cmd_Power: + power_ = 10 * args.at(0).split(".")[0].toInt() + args.at(0).split(".")[1].toInt(); + printf("%s Cmd_Power : %s %d\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),args.join("|").toStdString().c_str(),power_); + break; + case Cmd_VFO: + printf("%s Cmd_VFO : %s\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),args.join("|").toStdString().c_str()); + printf("band_change:%d busy_other_frequency_:%d timer1_remaining:%d timer2_remaining:%d",band_change,busy_other_frequency_,tci_timer7_->remainingTime(),tci_timer2_->remainingTime()); //was timer1 and timer2 + if(args.at(0)==rx_ && args.at(1) == "0") { + if (args.at(2).left(1) != "-") rx_frequency_ = args.at(2); + CAT_TRACE("Rx VFO Frequency from SDR is :"); + CAT_TRACE(rx_frequency_); + if (!tci_Ready && requested_rx_frequency_.isEmpty()) requested_rx_frequency_ = rx_frequency_; + if (busy_rx_frequency_ && !band_change) { + printf (" cmdvfo0 done1"); + tci_done7(); //was tci_done1 (do_frequency) + } else if (!tci_timer2_->isActive() && split_) { + printf (" cmdvfo0 timer2 start 210"); + tci_timer2_->start(210); + } + } + else if (args.at(0)==rx_ && args.at(1) == "1") { + if (args.at(2).left(1) != "-") other_frequency_ = args.at(2); + CAT_TRACE("Tx VFO (other) Frequency from SDR is :"); + CAT_TRACE(other_frequency_); + if (!tci_Ready && requested_other_frequency_.isEmpty()) requested_other_frequency_ = other_frequency_; + if (band_change && tci_timer7_->isActive()) { //was tci_timer1 + printf (" cmdvfo1 done1"); + band_change = false; + tci_timer2_->start(210); + tci_done7(); //was tci_done1 (do_frequency) + } else if (busy_other_frequency_) { + printf (" cmdvfo1 done2"); + tci_done2(); + } else if (tci_timer2_->isActive()) { + printf (" cmdvfo1 timer2 reset 210"); + tci_timer2_->start(210); + } else if (other_frequency_ != requested_other_frequency_ && tci_Ready && split_ && !tci_timer2_->isActive()) { + printf (" cmdvfo1 timer2 start 210"); + tci_timer2_->start(210); + } + } + break; + case Cmd_Mode: + printf("%s Cmd_Mode : %s\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),args.join("|").toStdString().c_str()); + if(args.at(0)==rx_) { + if (ESDR3 || HPSDR) { + if (args.at(1) == "0" ) mode_ = args.at(2).toLower(); else mode_ = args.at(1).toLower(); + } else mode_ = args.at(1); + if (started_mode_.isEmpty()) started_mode_ = mode_; + if (busy_mode_) return; // was tci_done1(); + else if (!requested_mode_.isEmpty() && requested_mode_ != mode_ && !band_change) { + sendTextMessage(mode_to_command(requested_mode_)); + } + } + break; + case Cmd_SplitEnable: + printf("%s Cmd_SplitEnable : %s\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),args.join("|").toStdString().c_str()); + if(args.at(0)==rx_) { + if (args.at(1) == "false") split_ = false; + else if (args.at(1) == "true") split_ = true; + if (!tci_Ready) {started_split_ = split_;} + else if (busy_split_) tci_done5(); //was tci_done2 + else if (requested_split_ != split_ && !tci_timer5_->isActive()) { //was tci_timer2 + CAT_TRACE("tci_timer5 started in onMessageReceived-Cmd_SplitEnable"); + tci_timer5_->start(210); //was tci_timer2 + rig_split(); + } + } + break; + case Cmd_Drive: + printf("%s Cmd_Drive : %s\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),args.join("|").toStdString().c_str()); + if((!ESDR3 && !HPSDR) || args.at(0)==rx_) { + if (ESDR3 || HPSDR) drive_ = args.at(1); else drive_ = args.at(0); + if (requested_drive_.isEmpty()) requested_drive_ = drive_; + busy_drive_ = false; + } + break; + case Cmd_Volume: + break; + case Cmd_Trx: + printf("%s Cmd_Trx : %s\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),args.join("|").toStdString().c_str()); + if(args.at(0)==rx_) { + if (args.at(1) == "false") PTT_ = false; + else if (args.at(1) == "true") PTT_ = true; + if (tci_Ready && requested_PTT_ == PTT_) tci_done3(); + else if (tci_Ready && !PTT_) { + requested_PTT_ = PTT_; + update_PTT(PTT_); + power_ = 0; if (do_pwr_) update_power (0); + swr_ = 0; if (do_pwr_) update_swr (0); + } + } + break; + case Cmd_AudioStart: + printf("%s Cmd_AudioStart : %s\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),args.join("|").toStdString().c_str()); + if(args.at(0)==rx_) { + stream_audio_ = true; + if (tci_Ready) { + printf ("cmdaudiostart done1\n"); + tci_done7(); //was tci_done1 (do_frequency) + } + } + break; + case Cmd_RxEnable: + printf("%s Cmd_RxEnable : %s\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),args.join("|").toStdString().c_str()); + if(args.at(0)=="1") { + if (args.at(1) == "false") rx2_ = false; + else if (args.at(1) == "true") rx2_ = true; + if(!tci_Ready) {requested_rx2_ = rx2_; started_rx2_ = rx2_;} + else if (tci_Ready && busy_rx2_ && requested_rx2_ == rx2_) { + tci_done4(); + } + } + break; + case Cmd_AudioStop: + printf("%s CmdAudioStop : %s\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),args.join("|").toStdString().c_str()); + if(args.at(0)==rx_) { + stream_audio_ = false; + if (tci_Ready) { + printf ("cmdaudiostop done1\n"); + tci_done7(); //was tci_done1 (do_frequency) + } + } + break; + case Cmd_Start: + printf("%s CmdStart : %s\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),args.join("|").toStdString().c_str()); + _power_ = true; + printf ("cmdstart done1\n"); + if (tci_Ready) { + tci_done7(); //was tci_done1 (do_frequency) + } + break; + case Cmd_Stop: + printf("%s CmdStop : %s\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),args.join("|").toStdString().c_str()); + if (tci_Ready && PTT_) { + PTT_ = false; + requested_PTT_ = PTT_; + update_PTT(PTT_); + power_ = 0; if (do_pwr_) update_power (0); + swr_ = 0; if (do_pwr_) update_swr (0); + m_state = Idle; + Q_EMIT tci_mod_active(m_state != Idle); + } + _power_ = false; + if (tci_timer1_->isActive()) { //was tci_timer1 + printf ("cmdstop done1\n"); + tci_done1(); + } else { + tci_Ready = false; + } + break; + case Cmd_Version: + printf("%s CmdVersion : %s\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),args.join("|").toStdString().c_str()); + if(args.at(0)=="ExpertSDR3") ESDR3 = true; + else if (args.at(0)=="Thetis") HPSDR = true; + break; + case Cmd_Device: + printf("%s CmdDevice : %s\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),args.join("|").toStdString().c_str()); + if((args.at(0)=="SunSDR2DX" || args.at(0)=="SunSDR2PRO") && !ESDR3) tx_top_ = false; + printf ("tx_top_:%d\n",tx_top_); + break; + case Cmd_Ready: + printf("%s CmdReady : %s\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),args.join("|").toStdString().c_str()); + tci_done7(); //was tci_done1 (do_frequency) + break; + + default: + break; + } + } +} + +void TCITransceiver::sendTextMessage(const QString &message) +{ + if (inConnected) { + commander_->sendTextMessage(message); + CAT_TRACE ("TCI Command Sent: " + message + '\n'); + } +} + +void TCITransceiver::onBinaryReceived(const QByteArray &data) +{ + Data_Stream *pStream = (Data_Stream*)(data.data()); + if (pStream->type != last_type) { + last_type = pStream->type; + } + if (pStream->type == Iq_Stream){ + bool tx = false; + if (pStream->receiver == 0){ + tx = trxA == 0; + trxA = 1; + } + if (pStream->receiver == 1) { + tx = trxB == 0; + trxB = 1; + } + printf("sendIqData\n"); + emit sendIqData(pStream->receiver,pStream->length,pStream->data,tx); + qDebug() << "IQ" << data.size() << pStream->length; + } else if (pStream->type == RxAudioStream && audio_ && pStream->receiver == rx_.toUInt()) { + writeAudioData(pStream->data,pStream->length); + } else if (pStream->type == TxChrono && pStream->receiver == rx_.toUInt()) { + mtx_.lock(); tx_fifo += 1; tx_fifo &= 7; + int ssize = AudioHeaderSize+pStream->length*sizeof(float)*2; + quint16 tehtud; + if (m_tx1[tx_fifo].size() != ssize) m_tx1[tx_fifo].resize(ssize); + Data_Stream * pOStream1 = (Data_Stream*)(m_tx1[tx_fifo].data()); + pOStream1->receiver = pStream->receiver; + pOStream1->sampleRate = pStream->sampleRate; + pOStream1->format = pStream->format; + pOStream1->codec = 0; + pOStream1->crc = 0; + pOStream1->length = pStream->length; + pOStream1->type = TxAudioStream; + tehtud = readAudioData(pOStream1->data,pOStream1->length, txAtten); + if (tehtud && tehtud != pOStream1->length) { + quint16 valmis = tehtud; + tehtud = readAudioData(pOStream1->data + valmis,pOStream1->length - valmis,txAtten); + } + tx_fifo2 = tx_fifo; mtx_.unlock(); + if (!inConnected || commander_->sendBinaryMessage(m_tx1[tx_fifo2]) != m_tx1[tx_fifo2].size()) { + } + } +} + +void TCITransceiver::txAudioData(quint32 len, float * data) +{ + QByteArray tx; + tx.resize(AudioHeaderSize+len*sizeof(float)*2); + Data_Stream * pStream = (Data_Stream*)(tx.data()); + pStream->receiver = 0; + pStream->sampleRate = audioSampleRate; + pStream->format = 3; + pStream->codec = 0; + pStream->crc = 0; + pStream->length = len; + pStream->type = TxAudioStream; + memcpy(pStream->data,data,len*sizeof(float)*2); + commander_->sendBinaryMessage(tx); +} + +quint32 TCITransceiver::writeAudioData (float * data, qint32 maxSize) +{ + static unsigned mstr0=999999; + qint64 ms0 = QDateTime::currentMSecsSinceEpoch() % 86400000; + unsigned mstr = ms0 % int(1000.0*m_period); // ms into the nominal Tx start time + if(mstr < mstr0/2) { //When mstr has wrapped around to 0, restart the buffer + dec_data.params.kin = 0; + m_bufferPos = 0; + } + mstr0=mstr; + + if(data != NULL) { + // block below adjusts receive audio attenuation + quint64 i = 0; + float * data1 = (float*)malloc(maxSize * sizeof(float)); + for(i=0;i<(quint64)maxSize;i++) { + data1[i] = ((float)(pow(10, 0.05*rxAtten) * data[i])); + } + + // no torn frames + Q_ASSERT (!(maxSize % static_cast<qint32> (bytesPerFrame))); + + // these are in terms of input frames (not down sampled) + size_t framesAcceptable ((sizeof (dec_data.d2) / + sizeof (dec_data.d2[0]) - dec_data.params.kin) * m_downSampleFactor); + size_t framesAccepted (qMin (static_cast<size_t> (maxSize / + bytesPerFrame), framesAcceptable)); + + if (framesAccepted < static_cast<size_t> (maxSize / bytesPerFrame)) { + qDebug () << "dropped " << maxSize / bytesPerFrame - framesAccepted + << " frames of data on the floor!" + << dec_data.params.kin << mstr; + } + + for (unsigned remaining = framesAccepted; remaining; ) { + size_t numFramesProcessed (qMin (m_samplesPerFFT * + m_downSampleFactor - m_bufferPos, remaining)); + + if(m_downSampleFactor > 1) { + store (&data1[(framesAccepted - remaining) * bytesPerFrame], + numFramesProcessed, &m_buffer[m_bufferPos]); + m_bufferPos += numFramesProcessed; + + if(m_bufferPos==m_samplesPerFFT*m_downSampleFactor) { + qint32 framesToProcess (m_samplesPerFFT * m_downSampleFactor); + qint32 framesAfterDownSample (m_samplesPerFFT); + if(m_downSampleFactor > 1 && dec_data.params.kin>=0 && + dec_data.params.kin < (NTMAX*12000 - framesAfterDownSample)) { + fil4_(&m_buffer[0], &framesToProcess, &dec_data.d2[dec_data.params.kin], + &framesAfterDownSample, &dec_data.d2[dec_data.params.kin]); + dec_data.params.kin += framesAfterDownSample; + } else { + qDebug() << "framesToProcess = " << framesToProcess; + qDebug() << "dec_data.params.kin = " << dec_data.params.kin; + qDebug() << "framesAfterDownSample" << framesAfterDownSample; + } + Q_EMIT tciframeswritten (dec_data.params.kin); + m_bufferPos = 0; + } + + } else { + store (&data1[(framesAccepted - remaining) * bytesPerFrame], + numFramesProcessed, &dec_data.d2[dec_data.params.kin]); + m_bufferPos += numFramesProcessed; + dec_data.params.kin += numFramesProcessed; + if (m_bufferPos == static_cast<unsigned> (m_samplesPerFFT)) { + Q_EMIT tciframeswritten (dec_data.params.kin); + m_bufferPos = 0; + } + } + remaining -= numFramesProcessed; + } + + free(data1); +} + return maxSize; // we drop any data past the end of the buffer on + // the floor until the next period starts +} + +void TCITransceiver::rx2_enable (bool on) +{ + printf("%s TCI rx2_enable:%d->%d busy:%d\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),rx2_,on,busy_rx2_); + if (busy_rx2_) return; + requested_rx2_ = on; + busy_rx2_ = true; + const QString cmd = CmdRxEnable + SmDP + "1" + SmCM + (requested_rx2_ ? "true" : "false") + SmTZ; + sendTextMessage(cmd); + mysleep4(1000); + busy_rx2_ = false; +} + +void TCITransceiver::rig_split () +{ + printf("%s TCI rig_split:%d->%d busy:%d\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),split_,requested_split_,busy_split_); + if (busy_split_) return; + if (tci_timer5_->isActive()) mysleep5(0); + busy_split_ = true; + const QString cmd = CmdSplitEnable + SmDP + rx_ + SmCM + "false" + SmTZ; // changed from below so split always false + //const QString cmd = CmdSplitEnable + SmDP + rx_ + SmCM + (requested_split_ ? "true" : "false") + SmTZ; + sendTextMessage(cmd); + mysleep5(500); + busy_split_ = false; + if (requested_split_ == split_) update_split (split_); +} + +void TCITransceiver::rig_power (bool on) +{ + TRACE_CAT ("TCITransceiver", on << state ()); + printf("%s TCI rig_power:%d _power_:%d\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),on,_power_); + if (on != _power_) { + if (on) { + const QString cmd = CmdStart + SmTZ; + sendTextMessage(cmd); + } else { + const QString cmd = CmdStop + SmTZ; + sendTextMessage(cmd); + } + } +} + +void TCITransceiver::stream_audio (bool on) +{ + TRACE_CAT ("TCITransceiver", on << state ()); + if (on != stream_audio_ && tci_Ready) { + requested_stream_audio_ = on; + if (on) { + const QString cmd = CmdAudioStart + SmDP + rx_ + SmTZ; + sendTextMessage(cmd); + } else { + const QString cmd = CmdAudioStop + SmDP + rx_ + SmTZ; + sendTextMessage(cmd); + } + } +} + +void TCITransceiver::do_audio (bool on) +{ + TRACE_CAT ("TCITransceiver", on << state ()); + if (on) { + dec_data.params.kin = 0; + m_bufferPos = 0; + } + audio_ = on; +} + +void TCITransceiver::do_period (double period) +{ + TRACE_CAT ("TCITransceiver", period << state ()); + m_period = period; +} + +void TCITransceiver::do_volume (qreal volume) +{ + rxAtten = volume; +} + + +void TCITransceiver::do_txvolume (qreal txvolume) +{ + txAtten = txvolume; +} + +void TCITransceiver::do_blocksize (qint32 blocksize) +{ + TRACE_CAT ("TCITransceiver", blocksize << state ()); + m_samplesPerFFT = blocksize; +} + +void TCITransceiver::do_ptt (bool on) +{ + TRACE_CAT ("TCITransceiver", on << state ()); + if (use_for_ptt_) { + if (on != PTT_) { + if (!inConnected && !error_.isEmpty()) throw error {error_}; + else if (busy_PTT_ || !tci_Ready || !_power_) return; + else busy_PTT_ = true; + requested_PTT_ = on; + if (ESDR3) { + const QString cmd = CmdTrx + SmDP + rx_ + SmCM + (on ? "true" : "false") + SmCM + "tci"+ SmTZ; + sendTextMessage(cmd); + } else { + const QString cmd = CmdTrx + SmDP + rx_ + SmCM + (on ? "true" : "false") + SmTZ; + sendTextMessage(cmd); + } + mysleep3(1000); + busy_PTT_ = false; + if (requested_PTT_ == PTT_) { + update_PTT(PTT_); + if (PTT_ && do_snr_) { + update_level (-54); + } else { + power_ = 0; + if (do_pwr_) update_power (0); + swr_ = 0; + if (do_pwr_) update_swr (0); + } + } else { + printf("%s TCI failed set ptt %d->%d\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),PTT_,requested_PTT_); + error_ = tr ("TCI failed to set ptt"); + tci_Ready = false; + throw error {tr ("TCI failed to set ptt")}; + } + } else update_PTT(on); + } + else + { + TRACE_CAT ("TCITransceiver", "TCI should use PTT via CAT"); + throw error {tr ("TCI should use PTT via CAT")}; + } +} + +void TCITransceiver::do_frequency (Frequency f, MODE m, bool no_ignore) +{ + qDebug() << no_ignore; + TRACE_CAT ("TCITransceiver", f << state ()); + auto f_string = frequency_to_string (f); + if (busy_rx_frequency_) { + return; + } else { + requested_rx_frequency_ = f_string; + requested_mode_ = map_mode (m); + } + if (tci_Ready && _power_) { + if ((rx_frequency_ != requested_rx_frequency_)) { + busy_rx_frequency_ = true; + band_change = abs(rx_frequency_.toInt()-requested_rx_frequency_.toInt()) > 1000000; + const QString cmd = CmdVFO + SmDP + rx_ + SmCM + "0" + SmCM + requested_rx_frequency_ + SmTZ; + if(f > 100000 && f< 250000000000) sendTextMessage(cmd); + mysleep7(2000); + // if (band_change) mysleep7(500); + band_change2 = abs(rx_frequency_.toInt()-requested_rx_frequency_.toInt()) > 1000000; + if (!band_change2) update_rx_frequency (f); + //if (requested_rx_frequency_ == rx_frequency_) update_rx_frequency (f); + else { + printf("%s TCI failed set rxfreq:%s->%s\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),rx_frequency_.toStdString().c_str(),requested_rx_frequency_.toStdString().c_str()); + error_ = tr ("TCI failed set rxfreq"); + CAT_TRACE("TCI failed set rxfreq. Rx freq is:"); + CAT_TRACE(rx_frequency_); + CAT_TRACE("TCI failed set rxfreq. Requested Rx freq is:"); + CAT_TRACE(requested_rx_frequency_); + printf("rx_frequency is %s and requested_rx_frequency is %s\n",rx_frequency_.toStdString().c_str(),requested_rx_frequency_.toStdString().c_str()); + tci_Ready = false; + throw error {tr ("TCI failed set rxfreq")}; + } + busy_rx_frequency_ = false; + } else update_rx_frequency (string_to_frequency (rx_frequency_)); + + if (!requested_mode_.isEmpty() && requested_mode_ != mode_ && !busy_mode_) { + busy_mode_ = true; + sendTextMessage(mode_to_command(requested_mode_)); + mysleep7(1000); + if (requested_mode_.isEmpty() || requested_mode_ == mode_) update_mode (m); + else { + printf("%s TCI failed set mode %s->%s",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),mode_.toStdString().c_str(),requested_mode_.toStdString().c_str()); + error_ = tr ("TCI failed set mode"); + // tci_Ready = false; + // throw error {tr ("TCI failed set mode")}; + } + busy_mode_ = false; + } + } else { + update_rx_frequency (f); + update_mode (m); + } +} + +void TCITransceiver::do_tx_frequency (Frequency tx, MODE mode, bool no_ignore) +{ + TRACE_CAT ("%s TCITransceiver", tx << state ()); + auto f_string = frequency_to_string (tx); + if (tci_Ready && busy_other_frequency_ && no_ignore) { + CAT_TRACE("TCI do_txfrequency critical no_ignore set tx vfo will be missed\n"); + printf("%s TCI do_txfrequency critical no_ignore set tx vfo will be missed\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str()); + } + if (busy_other_frequency_) return; + requested_other_frequency_ = f_string; + requested_mode_ = map_mode (mode); + if (tx) { + requested_split_ = true; + if (tci_Ready && _power_) { + if (band_change && !tci_timer2_->isActive()) { + if (!HPSDR) { + mysleep2(210); + } else { + mysleep2(2000); + } + } else { + if (tci_timer2_->isActive()) mysleep2(0); + } + if (requested_split_ != split_) rig_split(); + else update_split (split_); + if (other_frequency_ != requested_other_frequency_) { + busy_other_frequency_ = true; + printf("%s TCI VFO1 command sent\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str()); + const QString cmd = CmdVFO + SmDP + rx_ + SmCM + "1" + SmCM + requested_other_frequency_ + SmTZ; + if(tx > 100000 && tx < 250000000000) sendTextMessage(cmd); + mysleep2(1000); + other_band_change = abs(other_frequency_.toInt()-requested_other_frequency_.toInt()) > 1000000; + if (!other_band_change) update_other_frequency (tx); + // if (requested_other_frequency_ == other_frequency_) update_other_frequency (tx); + else { + printf("%s TCI failed set txfreq:%s->%s\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),other_frequency_.toStdString().c_str(),requested_other_frequency_.toStdString().c_str()); + CAT_TRACE("TCI failed set txfreq"); + // error_ = tr ("TCI failed set txfreq"); + // tci_Ready = false; + // throw error {tr ("TCI failed set txfreq")}; + } + busy_other_frequency_ = false; + } else update_other_frequency (string_to_frequency (other_frequency_)); + + } else { + update_split (requested_split_); + update_other_frequency (tx); + } + } + else { + requested_split_ = false; + requested_other_frequency_ = ""; + if (tci_Ready && _power_) { + if (band_change) { + mysleep2(2000); + if (!HPSDR) mysleep2(200); + } + if (tci_timer2_->isActive()) mysleep2(0); + if (requested_split_ != split_) rig_split(); + else update_split (split_); + update_other_frequency (tx); + } else { + update_split (requested_split_); + update_other_frequency (tx); + } + } +} + +//do_mode is never called. +void TCITransceiver::do_mode (MODE m) +{ + TRACE_CAT ("TCITransceiver", m << state ()); + auto m_string = map_mode (m); + if (requested_mode_ != m_string) requested_mode_ = m_string; + if (!requested_mode_.isEmpty() && mode_ != requested_mode_ && !busy_mode_) { + busy_mode_ = true; + sendTextMessage(mode_to_command(requested_mode_)); + mysleep8(1000); + if (requested_mode_ == mode_) update_mode (m); + else { + printf("%s TCI failed set mode %s->%s",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),mode_.toStdString().c_str(),requested_mode_.toStdString().c_str()); + error_ = tr ("TCI failed set mode"); + // tci_Ready = false; + // throw error {tr ("TCI failed set mode")}; + } + busy_mode_ = false; + } +} + +void TCITransceiver::do_poll () +{ + if (!error_.isEmpty()) {tci_Ready = false; throw error {error_};} + else if (!tci_Ready) throw error {tr ("TCI could not be opened")}; + update_rx_frequency (string_to_frequency (rx_frequency_)); + update_split(split_); + if (state ().split ()) { + if (other_frequency_ == requested_other_frequency_) update_other_frequency (string_to_frequency (other_frequency_)); + else if (!busy_rx_frequency_) do_tx_frequency(string_to_frequency (requested_other_frequency_),get_mode(true),false); + } + update_mode (get_mode()); + if (do_pwr_ && PTT_) {update_power (power_ * 100); update_swr (swr_*10);} + if (do_snr_ && !PTT_) { + update_level (level_); + if(!ESDR3) { + const QString cmd = CmdSmeter + SmDP + rx_ + SmCM + "0" + SmTZ; + sendTextMessage(cmd); + } + } +} + +auto TCITransceiver::get_mode (bool requested) -> MODE +{ + MODE m {UNK}; + if (requested) { + if ("am" == requested_mode_) + { + m = AM; + } + else if ("cw" == requested_mode_) + { + m = CW; + } + else if ("wfm" == requested_mode_) + { + m = FM; + } + else if ("nfm" == requested_mode_) + { + m = DIG_FM; + } + else if ("lsb" == requested_mode_) + { + m = LSB; + } + else if ("usb" == requested_mode_) + { + m = USB; + } + else if ("digl" == requested_mode_) + { + m = DIG_L; + } + else if ("digu" == requested_mode_) + { + m = DIG_U; + } + } else { + if ("am" == mode_) + { + m = AM; + } + else if ("cw" == mode_) + { + m = CW; + } + else if ("wfm" == mode_) + { + m = FM; + } + else if ("nfm" == mode_) + { + m = DIG_FM; + } + else if ("lsb" == mode_) + { + m = LSB; + } + else if ("usb" == mode_) + { + m = USB; + } + else if ("digl" == mode_) + { + m = DIG_L; + } + else if ("digu" == mode_) + { + m = DIG_U; + } + } + return m; +} + +QString TCITransceiver::mode_to_command (QString m_string) const +{ + // if (ESDR3) { + // const QString cmd = CmdMode + SmDP + rx_ + SmCM + m_string.toUpper() + SmTZ; + // return cmd; + // } else { + const QString cmd = CmdMode + SmDP + rx_ + SmCM + m_string + SmTZ; + return cmd; + // } +} + +QString TCITransceiver::frequency_to_string (Frequency f) const +{ + // number is localized and in kHz, avoid floating point translation + // errors by adding a small number (0.1Hz) + auto f_string = QString {}.setNum(f); + printf ("frequency_to_string3 |%s|\n",f_string.toStdString().c_str()); + return f_string; +} + +auto TCITransceiver::string_to_frequency (QString s) const -> Frequency +{ + // temporary hack because Commander is returning invalid UTF-8 bytes + s.replace (QChar {QChar::ReplacementCharacter}, locale_.groupSeparator ()); + + bool ok; + + auto f = QLocale::c ().toDouble (s, &ok); // temporary fix + + if (!ok) + { + printf("Frequency rejected is ***%s***\n",s.toStdString().c_str()); + // throw error {tr ("TCI sent an unrecognized frequency") + " |" + s + "|"}; + } + return f; +} + +/* + * mysleep1 is used in do_stop + * mysleep2 is used in do_tx_frequency + * mysleep3 is used in do_ptt + * mysleep4 is used in rx2_enable + * mysleep5 is used in rig_split + * mysleep6 is used in do_start + * mysleep7 is used in do_frequency + * mysleep8 is used in do_mode which is never called + * */ + +void TCITransceiver::mysleep1 (int ms) +{ + //printf("%s TCI sleep1 start %d %d\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),ms,tci_timer1_->isActive()); + if (ms) tci_timer1_->start(ms); + tci_loop1_->exec(); + if (tci_timer1_->isActive() && tci_Ready) tci_timer1_->stop(); +} +void TCITransceiver::mysleep2 (int ms) +{ + if (ms) tci_timer2_->start(ms); + tci_loop2_->exec(); + if (tci_timer2_->isActive()) tci_timer2_->stop(); +} +void TCITransceiver::mysleep3 (int ms) +{ + if (ms) tci_timer3_->start(ms); + tci_loop3_->exec(); + if (tci_timer3_->isActive()) tci_timer3_->stop(); +} +void TCITransceiver::mysleep4 (int ms) +{ + if (ms) tci_timer4_->start(ms); + tci_loop4_->exec(); + if (tci_timer4_->isActive()) tci_timer4_->stop(); +} +void TCITransceiver::mysleep5 (int ms) +{ + if((tci_loop5_ && (tci_loop5_->isRunning())) || (tci_timer5_ && tci_timer5_->isActive())) return; + if (ms) tci_timer5_->start(ms); + tci_loop5_->exec(); + if (tci_timer5_->isActive()) tci_timer5_->stop(); +} +void TCITransceiver::mysleep6 (int ms) +{ + if (ms) tci_timer6_->start(ms); + tci_loop6_->exec(); + if (tci_timer6_->isActive()) tci_timer6_->stop(); +} +void TCITransceiver::mysleep7 (int ms) +{ + if (ms) tci_timer7_->start(ms); + tci_loop7_->exec(); + if (tci_timer7_->isActive()) tci_timer7_->stop(); +} +void TCITransceiver::mysleep8 (int ms) +{ + if (ms) tci_timer8_->start(ms); + tci_loop8_->exec(); + if (tci_timer8_->isActive()) tci_timer8_->stop(); +} +// Modulator part + +void TCITransceiver::do_modulator_start (QString mode, unsigned symbolsLength, double framesPerSymbol, + double frequency, double toneSpacing, bool synchronize, bool fastMode, double dBSNR, double TRperiod) +{ + // Time according to this computer which becomes our base time + qint64 ms0 = QDateTime::currentMSecsSinceEpoch() % 86400000; + qDebug() << "ModStart" << QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.sss"); + unsigned mstr = ms0 % int(1000.0*m_period); // ms into the nominal Tx start time + if (m_state != Idle) { + // stop (); + throw error {tr ("TCI modulator not Idle")}; + } + m_quickClose = false; + m_symbolsLength = symbolsLength; + m_isym0 = std::numeric_limits<unsigned>::max (); // big number + m_frequency0 = 0.; + m_phi = 0.; + m_addNoise = dBSNR < 0.; + m_nsps = framesPerSymbol; + m_trfrequency = frequency; + m_amp = std::numeric_limits<qint16>::max (); + m_toneSpacing = toneSpacing; + m_bFastMode=fastMode; + m_TRperiod=TRperiod; + unsigned delay_ms=1000; + + if((mode=="FT8" and m_nsps==1920) or (mode=="FST4" and m_nsps==720)) delay_ms=500; //FT8, FST4-15 + if((mode=="FT8" and m_nsps==1024)) delay_ms=400; //SuperFox Qary Polar Code transmission + if(mode=="Q65" and m_nsps<=3600) delay_ms=500; //Q65-15 and Q65-30 + if(mode=="FT4") delay_ms=300; //FT4 + + // noise generator parameters + if (m_addNoise) { + m_snr = qPow (10.0, 0.05 * (dBSNR - 6.0)); + m_fac = 3000.0; + if (m_snr > 1.0) m_fac = 3000.0 / m_snr; + } + + // round up to an exact portion of a second that allows for startup delays + auto mstr2 = mstr - delay_ms; + if (mstr <= delay_ms) { + m_ic = 0; + } else { + m_ic = mstr2 * (audioSampleRate / 1000); + } + + m_silentFrames = 0; + // calculate number of silent frames to send + if (m_ic == 0 && synchronize && !m_tuning) { + m_silentFrames = audioSampleRate / (1000 / delay_ms) - (mstr * (audioSampleRate / 1000)); + } + m_state = (synchronize && m_silentFrames) ? + Synchronizing : Active; + printf("%s TCI modulator startdelay_ms=%d ASR=%d mstr=%d mstr2=%d m_ic=%d s_Frames=%lld synchronize=%d m_tuning=%d State=%d\n",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),delay_ms,audioSampleRate,mstr,mstr2,m_ic,m_silentFrames,synchronize,m_tuning,m_state); + Q_EMIT tci_mod_active(m_state != Idle); +} + +void TCITransceiver::do_tune (bool newState) +{ + m_tuning = newState; + if (!m_tuning) do_modulator_stop (true); +} + +void TCITransceiver::do_modulator_stop (bool quick) +{ + m_quickClose = quick; + if(m_state != Idle) { + m_state = Idle; + Q_EMIT tci_mod_active(m_state != Idle); + } + tx_audio_ = false; +} + +quint16 TCITransceiver::readAudioData (float * data, qint32 maxSize, qreal txAtten) +{ + double toneFrequency=1500.0; + if(m_nsps==6) { + toneFrequency=1000.0; + m_trfrequency=1000.0; + m_frequency0=1000.0; + } + if(maxSize==0) return 0; + + qreal newVolume = pow(2.22222 * (45 - txAtten) * 0.01,2); + //printf("txAtten is %f and newVolume is %f\n",txAtten, newVolume); + + qint64 numFrames (maxSize/bytesPerFrame); + float * samples (reinterpret_cast<float *> (data)); + float * end (samples + numFrames * bytesPerFrame); + qint64 framesGenerated (0); + + switch (m_state) + { + case Synchronizing: + { + if (m_silentFrames) { // send silence up to first second + framesGenerated = qMin (m_silentFrames, numFrames); + for ( ; samples != end; samples = load (0, samples)) { // silence + } + m_silentFrames -= framesGenerated; + return framesGenerated * bytesPerFrame; + } + m_state = Active; + Q_EMIT tci_mod_active(m_state != Idle); + m_cwLevel = false; + m_ramp = 0; // prepare for CW wave shaping + } + // fall through + + case Active: + { + unsigned int isym=0; + qint16 sample=0; + if(!m_tuning) isym=m_ic/(4.0*m_nsps); // Actual fsample=48000 + bool slowCwId=((isym >= m_symbolsLength) && (icw[0] > 0)); + m_nspd=2560; // 22.5 WPM + + if(m_TRperiod > 16.0 && slowCwId) { // Transmit CW ID? + m_dphi = m_twoPi*m_trfrequency/audioSampleRate; + unsigned ic0 = m_symbolsLength * 4 * m_nsps; + unsigned j(0); + + while (samples != end) { + j = (m_ic - ic0)/m_nspd + 1; // symbol of this sample + bool level {bool (icw[j])}; + m_phi += m_dphi; + if (m_phi > m_twoPi) m_phi -= m_twoPi; + sample=0; + float amp=32767.0; + float x=0.0; + if(m_ramp!=0) { + x=qSin(float(m_phi)); + if(SOFT_KEYING) { + amp=qAbs(qint32(m_ramp)); + if(amp>32767.0) amp=32767.0; + } + sample=round(newVolume * amp * x); + } + if (int (j) <= icw[0] && j < NUM_CW_SYMBOLS) { // stopu condition + samples = load (postProcessSample (sample), samples); + ++framesGenerated; + ++m_ic; + } else { + m_state = Idle; + Q_EMIT tci_mod_active(m_state != Idle); + return framesGenerated * bytesPerFrame; + } + + // adjust ramp + if ((m_ramp != 0 && m_ramp != std::numeric_limits<qint16>::min ()) || level != m_cwLevel) { + // either ramp has terminated at max/min or direction has changed + m_ramp += RAMP_INCREMENT; // ramp + } + m_cwLevel = level; + } + return framesGenerated * bytesPerFrame; + } //End of code for CW ID + + double const baud (12000.0 / m_nsps); + // fade out parameters (no fade out for tuning) + unsigned int i0,i1; + if(m_tuning) { + i1 = i0 = (m_bFastMode ? 999999 : 9999) * m_nsps; + } else { + i0=(m_symbolsLength - 0.017) * 4.0 * m_nsps; + i1= m_symbolsLength * 4.0 * m_nsps; + } + if(m_bFastMode and !m_tuning) { + i1=m_TRperiod*48000.0 - 24000.0; + i0=i1-816; + } + + sample=0; + for (unsigned i = 0; i < numFrames && m_ic <= i1; ++i) { + isym=0; + if(!m_tuning and m_TRperiod!=3.0) isym=m_ic/(4.0*m_nsps); //Actual fsample=48000 + if(m_bFastMode) isym=isym%m_symbolsLength; + if (isym != m_isym0 || m_trfrequency != m_frequency0) { + if(itone[0]>=100) { + m_toneFrequency0=itone[0]; + } else { + if(m_toneSpacing==0.0) { + m_toneFrequency0=m_trfrequency + itone[isym]*baud; + } else { + m_toneFrequency0=m_trfrequency + itone[isym]*m_toneSpacing; + } + } + m_dphi = m_twoPi * m_toneFrequency0 / audioSampleRate; + m_isym0 = isym; + m_frequency0 = m_trfrequency; //??? + } + + int j=m_ic/480; + if(m_fSpread>0.0 and j!=m_j0) { +#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) + float x1=QRandomGenerator::global ()->generateDouble (); + float x2=QRandomGenerator::global ()->generateDouble (); +#else + float x1=(float)qrand()/RAND_MAX; + float x2=(float)qrand()/RAND_MAX; +#endif + toneFrequency = m_toneFrequency0 + 0.5*m_fSpread*(x1+x2-1.0); + m_dphi = m_twoPi * toneFrequency / audioSampleRate; + m_j0=j; + } + + m_phi += m_dphi; + if (m_phi > m_twoPi) m_phi -= m_twoPi; + //ramp for first tone + if (m_ic==0) m_amp = m_amp * 0.008144735; + if (m_ic > 0 and m_ic < 191) m_amp = m_amp / 0.975; + //ramp for last tone + if (m_ic > i0) m_amp = 0.99 * m_amp; + if (m_ic > i1) m_amp = 0.0; + sample=qRound(newVolume * m_amp*qSin(m_phi)); + + //transmit from a precomputed FT8 wave[] array: + if(!m_tuning and (m_toneSpacing < 0.0)) { + m_amp=32767.0; + sample=qRound(newVolume * m_amp*foxcom_.wave[m_ic]); + } + samples = load (postProcessSample (sample), samples); + ++framesGenerated; + ++m_ic; + } + + if (m_amp == 0.0) { // TODO G4WJS: compare double with zero might not be wise + if (icw[0] == 0) { + // no CW ID to send + m_state = Idle; + Q_EMIT tci_mod_active(m_state != Idle); + return framesGenerated * bytesPerFrame; + } + m_phi = 0.0; + } + + m_frequency0 = m_trfrequency; + // done for this chunk - continue on next call + if (samples != end && framesGenerated) { + } + while (samples != end) { // pad block with silence + samples = load (0, samples); + ++framesGenerated; + } + return framesGenerated * bytesPerFrame; + } + // fall through + + case Idle: + while (samples != end) samples = load (0, samples); + } + + Q_ASSERT (Idle == m_state); + return 0; +} + +qint16 TCITransceiver::postProcessSample (qint16 sample) const +{ + if (m_addNoise) { // Test frame, we'll add noise + qint32 s = m_fac * (gran () + sample * m_snr / 32768.0); + if (s > std::numeric_limits<qint16>::max ()) { + s = std::numeric_limits<qint16>::max (); + } + if (s < std::numeric_limits<qint16>::min ()) { + s = std::numeric_limits<qint16>::min (); + } + sample = s; + } + return sample; +} diff --git a/Transceiver/TCITransceiver.hpp b/Transceiver/TCITransceiver.hpp index efb4756e..5518b449 100755..100644 --- a/Transceiver/TCITransceiver.hpp +++ b/Transceiver/TCITransceiver.hpp @@ -1,358 +1,358 @@ -#ifndef TCI_TRANSCEIVER_HPP__
-#define TCI_TRANSCEIVER_HPP__
-
-#include <memory>
-
-#include "TransceiverFactory.hpp"
-#include "PollingTransceiver.hpp"
-#include "commons.h"
-
-#include <QtWebSockets/QWebSocket>
-#include <QTimer>
-#include <QEventLoop>
-#include <mutex>
-
-typedef float REAL;
-
-class QWebSocket;
-class QByteArray;
-class QString;
-//
-// TCI Interface
-//
-
-typedef struct
-{
- quint32 receiver; //!< software receiver number
- quint32 sampleRate; //!< sampling frequency
- quint32 format; //!< data field format (0 - int16, 1 - int24, 2 - int32, 3 - float32, 4 - float64)
- quint32 codec; //!< compression algorithm (not implemented), always 0
- quint32 crc; //!< checksum
- quint32 length; //!< data field length number of float numbers
- quint32 type; //!< data stream type
- quint32 reserv[9]; //!< reserved
- float data[8192]; //!< data field
-}Data_Stream;
-
-typedef enum
-{
- Iq_Stream = 0,
- RxAudioStream,
- TxAudioStream,
- TxChrono,
-}Stream_Type;
-
-class TCITransceiver final
- : public PollingTransceiver
-{
- Q_OBJECT; // for translation context
-
-public:
- static void register_transceivers (logger_type *, TransceiverFactory::Transceivers *, unsigned id1, unsigned id2);
-
- // takes ownership of wrapped Transceiver
- explicit TCITransceiver (logger_type * logger, std::unique_ptr<TransceiverBase> wrapped, QString const& rignr,
- QString const& address, bool use_for_ptt,
- int poll_interval, QObject * parent = nullptr);
-
-enum Tci_Cmd {
-Cmd_Unknown,
-Cmd_Device,
-Cmd_ReceiveOnly,
-Cmd_TrxCount,
-Cmd_ChannelCount,
-Cmd_VfoLimits,
-Cmd_IfLimits,
-Cmd_ModeList,
-Cmd_Mode,
-Cmd_Ready,
-Cmd_Stop,
-Cmd_Start,
-Cmd_Preamp,
-Cmd_Dds,
-Cmd_If,
-Cmd_Trx,
-Cmd_RxEnable,
-Cmd_TxEnable,
-Cmd_RxChannelEnable,
-Cmd_RitEnable,
-Cmd_RitOffset,
-Cmd_XitEnable,
-Cmd_XitOffset,
-Cmd_SplitEnable,
-Cmd_IqSR,
-Cmd_IqStart,
-Cmd_IqStop,
-Cmd_CWSpeed,
-Cmd_CWDelay,
-Cmd_Spot,
-Cmd_SpotDelete,
-Cmd_FilterBand,
-Cmd_VFO,
-Cmd_Version,
-Cmd_Tune,
-Cmd_RxMute,
-Cmd_Smeter,
-Cmd_Power,
-Cmd_SWR,
-Cmd_ECoderRX,
-Cmd_ECoderVFO,
-Cmd_AudioSR,
-Cmd_AudioStart,
-Cmd_AudioStop,
-Cmd_AppFocus,
-Cmd_Volume,
-Cmd_SqlEnable,
-Cmd_SqlLevel,
-Cmd_Drive,
-Cmd_TuneDrive,
-Cmd_Mute,
-Cmd_RxSensorsEnable,
-Cmd_TxSensorsEnable,
-Cmd_RxSensors,
-Cmd_TxSensors,
-Cmd_AgcMode,
-Cmd_AgcGain,
-Cmd_Lock
-};
-Q_ENUM (Tci_Cmd);
-
-qreal rxAtten;
-qreal txAtten;
-
-public slots:
-// void close();
- void sendTextMessage(const QString &message);
-// void trxChanged(quint32 trx, bool state);
- void txAudioData(quint32 len, float * data);
-// void setAudioSampleRate(const quint32 &sr);
-
-private slots:
- void onBinaryReceived(const QByteArray &data);
- void onMessageReceived(const QString &str);
- void onError(QAbstractSocket::SocketError err);
- void onConnected();
- void onDisconnected();
-
-signals:
- void sendIqData(int, quint32, float*, bool);
- void sendAudioData(int, quint32, float*);
- void receiveIQ(bool,int);
- void txAudioChrono(quint32);
- void tci_done1();
- void tci_done2();
- void tci_done3();
- void tci_done4();
- void tci_done5();
- void tci_done6();
- void tci_done7();
- void tci_done8();
-
-protected:
- int do_start () override;
- void do_stop () override;
- void do_frequency (Frequency, MODE, bool no_ignore) override;
- void do_tx_frequency (Frequency, MODE, bool no_ignore) override;
- void do_mode (MODE) override;
- void do_ptt (bool on) override;
-
- void do_poll () override;
-//for Audio
- void do_audio (bool on) override;
- void do_tune (bool on) override;
- void do_period(double period) override;
- void do_blocksize(qint32 blocksize) override;
- void do_spread(double spread) override {m_fSpread=spread;}
- void do_nsym(int nsym) override {m_symbolsLength=nsym;}
- void do_trfrequency(double newfrequency) override {m_trfrequency = newfrequency;}
- void do_volume (qreal volume) override;
- void do_txvolume (qreal txvolume) override;
-//bounch
- void do_modulator_start(QString jtmode, unsigned symbolsLength, double framesPerSymbol, double frequency,
- double toneSpacing, bool synchronize = true, bool fastmode=false, double dBSNR = 99., double TRperiod=60.0) override;
- void do_modulator_stop(bool quick = false) override;
-
- void rx2_enable (bool on);
- void rig_split ();
- void rig_power (bool on);
- void stream_audio (bool on);
- void store (float * source, size_t numFrames, qint16 * dest)
- {
- static constexpr float K = 0x7FFF;
- for (size_t i {0}; i < numFrames; ++i) {
- dest[i] = static_cast<int16_t>(K*source[i*2]);
- }
-
- }
-
- float * load (qint16 sample, float * dest)
-
- {
- static constexpr float K1 = 0.999/0x7FFF;
- static constexpr float K2 = 0.499/0x7FFF;
- float value;
- if (tx_top_) value = K1*static_cast<float>(sample);
- else value = K2*static_cast<float>(sample);
- *dest++ = value;
- *dest++ = value;
-
- return dest;
- }
- enum ModulatorState {Synchronizing, Active, Idle};
-
-private:
- MODE get_mode (bool requested = false);
- QString frequency_to_string (Frequency) const;
- Frequency string_to_frequency (QString) const;
- void mysleep1 (int ms = 1);
- void mysleep2 (int ms = 1);
- void mysleep3 (int ms = 1);
- void mysleep4 (int ms = 1);
- void mysleep5 (int ms = 1);
- void mysleep6 (int ms = 1);
- void mysleep7 (int ms = 1);
- void mysleep8 (int ms = 1);
- QString mode_to_command (QString) const;
- std::unique_ptr<TransceiverBase> wrapped_; // may be null
- QString rx_;
- QString server_;
- bool use_for_ptt_;
- QStringList errortable;
- QString error_;
- bool do_snr_;
- bool do_pwr_;
- bool rig_power_;
- bool rig_power_off_;
- bool tci_audio_;
- bool _power_;
- QWebSocket * commander_;
- QLocale locale_;
- QTimer * tci_timer1_;
- QEventLoop * tci_loop1_;
- QTimer * tci_timer2_;
- QEventLoop * tci_loop2_;
- QTimer * tci_timer3_;
- QEventLoop * tci_loop3_;
- QTimer * tci_timer4_;
- QEventLoop * tci_loop4_;
- QTimer * tci_timer5_;
- QEventLoop * tci_loop5_;
- QTimer * tci_timer6_;
- QEventLoop * tci_loop6_;
- QTimer * tci_timer7_;
- QEventLoop * tci_loop7_;
- QTimer * tci_timer8_;
- QEventLoop * tci_loop8_;
- int nIqBytes;
- bool inConnected;
- bool tci_Ready;
- bool ESDR3;
- bool HPSDR;
- bool tx_top_;
- bool band_change;
- bool band_change2;
- bool other_band_change;
- QUrl url_;
- quint32 audioSampleRate;
- FILE * wavptr_;
- QByteArray t_iqData;
- int trxA;
- int trxB;
- int cntIQ;
- bool bIQ;
-
-// CAT internal variables
- QString requested_mode_;
- QString mode_;
- QString started_mode_;
- QString requested_rx_frequency_;
- QString rx_frequency_;
- QString requested_other_frequency_;
- QString other_frequency_;
- QString requested_drive_;
- QString drive_;
-
- bool requested_stream_audio_;
- bool stream_audio_;
- bool audio_;
- bool tx_audio_;
- bool requested_PTT_;
- bool PTT_;
- bool requested_split_;
- bool split_;
- bool started_split_;
- bool requested_rx2_;
- bool rx2_;
- bool started_rx2_;
- unsigned int power_;
- unsigned int swr_;
- int level_;
- bool busy_rx_frequency_;
- bool busy_mode_;
- bool busy_other_frequency_;
- bool busy_split_;
- bool busy_drive_;
- bool busy_PTT_;
- bool busy_rx2_;
- QHash<QString,Tci_Cmd> mapCmd_;
- // from Detector
- void clear (); // discard buffer contents
-
- double m_period = 15.0;
- unsigned m_downSampleFactor;
- qint32 m_samplesPerFFT; // after any down sampling
- qint32 m_ns;
- static size_t const max_buffer_size {7 * 512};
- QScopedArrayPointer<short> m_buffer; // de-interleaved sample buffer
- // big enough for all the
- // samples for one increment of
- // data (a signals worth) at
- // the input sample rate
- unsigned m_bufferPos;
- quint32 writeAudioData (float * data, qint32 maxSize);
- static size_t const bytesPerFrame = 2;
- // from Modulator
- quint16 readAudioData (float * data, qint32 maxSize, qreal txVolume);
- qint16 postProcessSample (qint16 sample) const;
- bool m_quickClose = false;
-
- unsigned m_symbolsLength;
-
- static double constexpr m_twoPi = 2.0 * 3.141592653589793238462;
- unsigned m_nspd = 2048 + 512; // CW ID WPM factor = 22.5 WPM
-
- double m_phi;
- double m_dphi;
- double m_amp;
- double m_nsps;
- double m_trfrequency;
- double m_frequency0;
- double m_snr;
- double m_fac;
- double m_toneSpacing;
- double m_fSpread;
- double m_TRperiod;
-
- qint64 m_silentFrames;
- qint16 m_ramp;
- ModulatorState m_state;
-
- bool m_tuning;
- bool m_addNoise;
- bool m_bFastMode;
-
- bool m_cwLevel;
- unsigned m_ic;
- unsigned m_isym0;
- int m_j0;
- double m_toneFrequency0;
-
- QByteArray m_tx1[8];
- int tx_fifo, tx_fifo2;
- quint32 last_type;
- std::string debug_file_;
- std::string wav_file_;
- std::mutex mtx_;
-};
-
-#endif
+#ifndef TCI_TRANSCEIVER_HPP__ +#define TCI_TRANSCEIVER_HPP__ + +#include <memory> + +#include "TransceiverFactory.hpp" +#include "PollingTransceiver.hpp" +#include "commons.h" + +#include <QtWebSockets/QWebSocket> +#include <QTimer> +#include <QEventLoop> +#include <mutex> + +typedef float REAL; + +class QWebSocket; +class QByteArray; +class QString; +// +// TCI Interface +// + +typedef struct +{ + quint32 receiver; //!< software receiver number + quint32 sampleRate; //!< sampling frequency + quint32 format; //!< data field format (0 - int16, 1 - int24, 2 - int32, 3 - float32, 4 - float64) + quint32 codec; //!< compression algorithm (not implemented), always 0 + quint32 crc; //!< checksum + quint32 length; //!< data field length number of float numbers + quint32 type; //!< data stream type + quint32 reserv[9]; //!< reserved + float data[8192]; //!< data field +}Data_Stream; + +typedef enum +{ + Iq_Stream = 0, + RxAudioStream, + TxAudioStream, + TxChrono, +}Stream_Type; + +class TCITransceiver final + : public PollingTransceiver +{ + Q_OBJECT; // for translation context + +public: + static void register_transceivers (logger_type *, TransceiverFactory::Transceivers *, unsigned id1, unsigned id2); + + // takes ownership of wrapped Transceiver + explicit TCITransceiver (logger_type * logger, std::unique_ptr<TransceiverBase> wrapped, QString const& rignr, + QString const& address, bool use_for_ptt, + int poll_interval, QObject * parent = nullptr); + +enum Tci_Cmd { +Cmd_Unknown, +Cmd_Device, +Cmd_ReceiveOnly, +Cmd_TrxCount, +Cmd_ChannelCount, +Cmd_VfoLimits, +Cmd_IfLimits, +Cmd_ModeList, +Cmd_Mode, +Cmd_Ready, +Cmd_Stop, +Cmd_Start, +Cmd_Preamp, +Cmd_Dds, +Cmd_If, +Cmd_Trx, +Cmd_RxEnable, +Cmd_TxEnable, +Cmd_RxChannelEnable, +Cmd_RitEnable, +Cmd_RitOffset, +Cmd_XitEnable, +Cmd_XitOffset, +Cmd_SplitEnable, +Cmd_IqSR, +Cmd_IqStart, +Cmd_IqStop, +Cmd_CWSpeed, +Cmd_CWDelay, +Cmd_Spot, +Cmd_SpotDelete, +Cmd_FilterBand, +Cmd_VFO, +Cmd_Version, +Cmd_Tune, +Cmd_RxMute, +Cmd_Smeter, +Cmd_Power, +Cmd_SWR, +Cmd_ECoderRX, +Cmd_ECoderVFO, +Cmd_AudioSR, +Cmd_AudioStart, +Cmd_AudioStop, +Cmd_AppFocus, +Cmd_Volume, +Cmd_SqlEnable, +Cmd_SqlLevel, +Cmd_Drive, +Cmd_TuneDrive, +Cmd_Mute, +Cmd_RxSensorsEnable, +Cmd_TxSensorsEnable, +Cmd_RxSensors, +Cmd_TxSensors, +Cmd_AgcMode, +Cmd_AgcGain, +Cmd_Lock +}; +Q_ENUM (Tci_Cmd); + +qreal rxAtten; +qreal txAtten; + +public slots: +// void close(); + void sendTextMessage(const QString &message); +// void trxChanged(quint32 trx, bool state); + void txAudioData(quint32 len, float * data); +// void setAudioSampleRate(const quint32 &sr); + +private slots: + void onBinaryReceived(const QByteArray &data); + void onMessageReceived(const QString &str); + void onError(QAbstractSocket::SocketError err); + void onConnected(); + void onDisconnected(); + +signals: + void sendIqData(int, quint32, float*, bool); + void sendAudioData(int, quint32, float*); + void receiveIQ(bool,int); + void txAudioChrono(quint32); + void tci_done1(); + void tci_done2(); + void tci_done3(); + void tci_done4(); + void tci_done5(); + void tci_done6(); + void tci_done7(); + void tci_done8(); + +protected: + int do_start () override; + void do_stop () override; + void do_frequency (Frequency, MODE, bool no_ignore) override; + void do_tx_frequency (Frequency, MODE, bool no_ignore) override; + void do_mode (MODE) override; + void do_ptt (bool on) override; + + void do_poll () override; +//for Audio + void do_audio (bool on) override; + void do_tune (bool on) override; + void do_period(double period) override; + void do_blocksize(qint32 blocksize) override; + void do_spread(double spread) override {m_fSpread=spread;} + void do_nsym(int nsym) override {m_symbolsLength=nsym;} + void do_trfrequency(double newfrequency) override {m_trfrequency = newfrequency;} + void do_volume (qreal volume) override; + void do_txvolume (qreal txvolume) override; +//bounch + void do_modulator_start(QString jtmode, unsigned symbolsLength, double framesPerSymbol, double frequency, + double toneSpacing, bool synchronize = true, bool fastmode=false, double dBSNR = 99., double TRperiod=60.0) override; + void do_modulator_stop(bool quick = false) override; + + void rx2_enable (bool on); + void rig_split (); + void rig_power (bool on); + void stream_audio (bool on); + void store (float * source, size_t numFrames, qint16 * dest) + { + static constexpr float K = 0x7FFF; + for (size_t i {0}; i < numFrames; ++i) { + dest[i] = static_cast<int16_t>(K*source[i*2]); + } + + } + + float * load (qint16 sample, float * dest) + + { + static constexpr float K1 = 0.999/0x7FFF; + static constexpr float K2 = 0.499/0x7FFF; + float value; + if (tx_top_) value = K1*static_cast<float>(sample); + else value = K2*static_cast<float>(sample); + *dest++ = value; + *dest++ = value; + + return dest; + } + enum ModulatorState {Synchronizing, Active, Idle}; + +private: + MODE get_mode (bool requested = false); + QString frequency_to_string (Frequency) const; + Frequency string_to_frequency (QString) const; + void mysleep1 (int ms = 1); + void mysleep2 (int ms = 1); + void mysleep3 (int ms = 1); + void mysleep4 (int ms = 1); + void mysleep5 (int ms = 1); + void mysleep6 (int ms = 1); + void mysleep7 (int ms = 1); + void mysleep8 (int ms = 1); + QString mode_to_command (QString) const; + std::unique_ptr<TransceiverBase> wrapped_; // may be null + QString rx_; + QString server_; + bool use_for_ptt_; + QStringList errortable; + QString error_; + bool do_snr_; + bool do_pwr_; + bool rig_power_; + bool rig_power_off_; + bool tci_audio_; + bool _power_; + QWebSocket * commander_; + QLocale locale_; + QTimer * tci_timer1_; + QEventLoop * tci_loop1_; + QTimer * tci_timer2_; + QEventLoop * tci_loop2_; + QTimer * tci_timer3_; + QEventLoop * tci_loop3_; + QTimer * tci_timer4_; + QEventLoop * tci_loop4_; + QTimer * tci_timer5_; + QEventLoop * tci_loop5_; + QTimer * tci_timer6_; + QEventLoop * tci_loop6_; + QTimer * tci_timer7_; + QEventLoop * tci_loop7_; + QTimer * tci_timer8_; + QEventLoop * tci_loop8_; + int nIqBytes; + bool inConnected; + bool tci_Ready; + bool ESDR3; + bool HPSDR; + bool tx_top_; + bool band_change; + bool band_change2; + bool other_band_change; + QUrl url_; + quint32 audioSampleRate; + FILE * wavptr_; + QByteArray t_iqData; + int trxA; + int trxB; + int cntIQ; + bool bIQ; + +// CAT internal variables + QString requested_mode_; + QString mode_; + QString started_mode_; + QString requested_rx_frequency_; + QString rx_frequency_; + QString requested_other_frequency_; + QString other_frequency_; + QString requested_drive_; + QString drive_; + + bool requested_stream_audio_; + bool stream_audio_; + bool audio_; + bool tx_audio_; + bool requested_PTT_; + bool PTT_; + bool requested_split_; + bool split_; + bool started_split_; + bool requested_rx2_; + bool rx2_; + bool started_rx2_; + unsigned int power_; + unsigned int swr_; + int level_; + bool busy_rx_frequency_; + bool busy_mode_; + bool busy_other_frequency_; + bool busy_split_; + bool busy_drive_; + bool busy_PTT_; + bool busy_rx2_; + QHash<QString,Tci_Cmd> mapCmd_; + // from Detector + void clear (); // discard buffer contents + + double m_period = 15.0; + unsigned m_downSampleFactor; + qint32 m_samplesPerFFT; // after any down sampling + qint32 m_ns; + static size_t const max_buffer_size {7 * 512}; + QScopedArrayPointer<short> m_buffer; // de-interleaved sample buffer + // big enough for all the + // samples for one increment of + // data (a signals worth) at + // the input sample rate + unsigned m_bufferPos; + quint32 writeAudioData (float * data, qint32 maxSize); + static size_t const bytesPerFrame = 2; + // from Modulator + quint16 readAudioData (float * data, qint32 maxSize, qreal txVolume); + qint16 postProcessSample (qint16 sample) const; + bool m_quickClose = false; + + unsigned m_symbolsLength; + + static double constexpr m_twoPi = 2.0 * 3.141592653589793238462; + unsigned m_nspd = 2048 + 512; // CW ID WPM factor = 22.5 WPM + + double m_phi; + double m_dphi; + double m_amp; + double m_nsps; + double m_trfrequency; + double m_frequency0; + double m_snr; + double m_fac; + double m_toneSpacing; + double m_fSpread; + double m_TRperiod; + + qint64 m_silentFrames; + qint16 m_ramp; + ModulatorState m_state; + + bool m_tuning; + bool m_addNoise; + bool m_bFastMode; + + bool m_cwLevel; + unsigned m_ic; + unsigned m_isym0; + int m_j0; + double m_toneFrequency0; + + QByteArray m_tx1[8]; + int tx_fifo, tx_fifo2; + quint32 last_type; + std::string debug_file_; + std::string wav_file_; + std::mutex mtx_; +}; + +#endif diff --git a/Transceiver/Transceiver.cpp b/Transceiver/Transceiver.cpp index 8c250360..c6dea805 100755..100644 --- a/Transceiver/Transceiver.cpp +++ b/Transceiver/Transceiver.cpp @@ -1,102 +1,102 @@ -#include "Transceiver.hpp"
-
-#include <ostream>
-
-#include "moc_Transceiver.cpp"
-
-Transceiver::Transceiver (logger_type * logger, QObject * parent)
- : QObject {parent}
- , logger_ {logger}
-{
-}
-
-#if !defined (QT_NO_DEBUG_STREAM)
-QDebug operator << (QDebug d, Transceiver::TransceiverState const& s)
-{
- d.nospace ()
- << "Transceiver::TransceiverState(online: " << (s.online_ ? "yes" : "no")
- << " Frequency {" << s.rx_frequency_ << "Hz, " << s.tx_frequency_ << "Hz} " << s.mode_
- << "; SPLIT: " << (Transceiver::TransceiverState::Split::on == s.split_ ? "on" : Transceiver::TransceiverState::Split::off == s.split_ ? "off" : "unknown")
- << "; PTT: " << (s.ptt_ ? "on" : "off")
- << "; AUDIO: " << (s.audio_ ? "on" : "off")
- << "; TX_AUDIO: " << (s.tx_audio_ ? "on" : "off")
- << "; TUNE: " << (s.tune_ ? "on" : "off")
- << "; QUICK: " << (s.quick_ ? "on" : "off")
- << "; PERIOD: " << s.period_ << "sec."
- << "; BLOCKSIZE: " << s.blocksize_
- << "; SYMBOLSLENGTH: " << s.symbolslength_
- << "; FRAMESPERSYMBOL: " << s.framespersymbol_
- << "; TRFREQUENCY: " << s.trfrequency_ << "Hz"
- << "; TONESPACING: " << s.tonespacing_
- << "; SYNCHRONIZE: " << (s.synchronize_ ? "on" : "off")
- << "; DBSNR: " << s.dbsnr_
- << "; TRPERIOD: " << s.trperiod_ << "sec."
- << "; SPREAD: " << s.spread_
- << "; NSYM: " << s.nsym_
- << "; VOLUME: " << s.volume_
- << "; TXVOLUME: " << s.txvolume_
- << "; LEVEL: " << s.level_ << "dBm"
- << "; POWER: " << s.power_ << "mWatts"
- << "; SWR: " << s.swr_
- << ")\n";
- return d.space ();
-}
-#endif
-
-std::ostream& operator << (std::ostream& os, Transceiver::MODE m)
-{
- auto const& mo = Transceiver::staticMetaObject; \
- return os << mo.enumerator (mo.indexOfEnumerator ("MODE")).valueToKey (static_cast<int> (m)); \
-}
-
-std::ostream& operator << (std::ostream& os, Transceiver::TransceiverState const& s)
-{
- return os
- << "Transceiver::TransceiverState(online: " << (s.online_ ? "yes" : "no")
- << " Frequency {" << s.rx_frequency_ << "Hz, " << s.tx_frequency_ << "Hz} Mode: " << s.mode_
- << "; SPLIT: " << (Transceiver::TransceiverState::Split::on == s.split_ ? "on" : Transceiver::TransceiverState::Split::off == s.split_ ? "off" : "unknown")
- << "; PTT: " << (s.ptt_ ? "on" : "off")
- << "; POWER: " << s.power_ << "mWatts"
- << "; SWR: " << s.swr_
- << "; TUNE: " << s.tune_
- << ")\n";
-}
-
-ENUM_QDATASTREAM_OPS_IMPL (Transceiver, MODE);
-
-ENUM_CONVERSION_OPS_IMPL (Transceiver, MODE);
-
-bool operator != (Transceiver::TransceiverState const& lhs, Transceiver::TransceiverState const& rhs)
-{
- return lhs.online_ != rhs.online_
- || lhs.rx_frequency_ != rhs.rx_frequency_
- || lhs.tx_frequency_ != rhs.tx_frequency_
- || lhs.mode_ != rhs.mode_
- || lhs.split_ != rhs.split_
- || lhs.ptt_ != rhs.ptt_
- || lhs.audio_ != rhs.audio_
- || lhs.tx_audio_ != rhs.tx_audio_
- || lhs.tune_ != rhs.tune_
- || lhs.quick_ != rhs.quick_
- || lhs.period_ != rhs.period_
- || lhs.blocksize_ != rhs.blocksize_
- || lhs.symbolslength_ != rhs.symbolslength_
- || lhs.framespersymbol_ != rhs.framespersymbol_
- || lhs.trfrequency_ != rhs.trfrequency_
- || lhs.tonespacing_ != rhs.tonespacing_
- || lhs.synchronize_ != rhs.synchronize_
- || lhs.dbsnr_ != rhs.dbsnr_
- || lhs.trperiod_ != rhs.trperiod_
- || lhs.spread_ != rhs.spread_
- || lhs.nsym_ != rhs.nsym_
- || lhs.volume_ != rhs.volume_
- || lhs.txvolume_ != rhs.txvolume_
- || lhs.level_ != rhs.level_
- || lhs.power_ != rhs.power_
- || lhs.swr_ != rhs.swr_;
-}
-
-bool operator == (Transceiver::TransceiverState const& lhs, Transceiver::TransceiverState const& rhs)
-{
- return !(lhs != rhs);
-}
+#include "Transceiver.hpp" + +#include <ostream> + +#include "moc_Transceiver.cpp" + +Transceiver::Transceiver (logger_type * logger, QObject * parent) + : QObject {parent} + , logger_ {logger} +{ +} + +#if !defined (QT_NO_DEBUG_STREAM) +QDebug operator << (QDebug d, Transceiver::TransceiverState const& s) +{ + d.nospace () + << "Transceiver::TransceiverState(online: " << (s.online_ ? "yes" : "no") + << " Frequency {" << s.rx_frequency_ << "Hz, " << s.tx_frequency_ << "Hz} " << s.mode_ + << "; SPLIT: " << (Transceiver::TransceiverState::Split::on == s.split_ ? "on" : Transceiver::TransceiverState::Split::off == s.split_ ? "off" : "unknown") + << "; PTT: " << (s.ptt_ ? "on" : "off") + << "; AUDIO: " << (s.audio_ ? "on" : "off") + << "; TX_AUDIO: " << (s.tx_audio_ ? "on" : "off") + << "; TUNE: " << (s.tune_ ? "on" : "off") + << "; QUICK: " << (s.quick_ ? "on" : "off") + << "; PERIOD: " << s.period_ << "sec." + << "; BLOCKSIZE: " << s.blocksize_ + << "; SYMBOLSLENGTH: " << s.symbolslength_ + << "; FRAMESPERSYMBOL: " << s.framespersymbol_ + << "; TRFREQUENCY: " << s.trfrequency_ << "Hz" + << "; TONESPACING: " << s.tonespacing_ + << "; SYNCHRONIZE: " << (s.synchronize_ ? "on" : "off") + << "; DBSNR: " << s.dbsnr_ + << "; TRPERIOD: " << s.trperiod_ << "sec." + << "; SPREAD: " << s.spread_ + << "; NSYM: " << s.nsym_ + << "; VOLUME: " << s.volume_ + << "; TXVOLUME: " << s.txvolume_ + << "; LEVEL: " << s.level_ << "dBm" + << "; POWER: " << s.power_ << "mWatts" + << "; SWR: " << s.swr_ + << ")\n"; + return d.space (); +} +#endif + +std::ostream& operator << (std::ostream& os, Transceiver::MODE m) +{ + auto const& mo = Transceiver::staticMetaObject; \ + return os << mo.enumerator (mo.indexOfEnumerator ("MODE")).valueToKey (static_cast<int> (m)); \ +} + +std::ostream& operator << (std::ostream& os, Transceiver::TransceiverState const& s) +{ + return os + << "Transceiver::TransceiverState(online: " << (s.online_ ? "yes" : "no") + << " Frequency {" << s.rx_frequency_ << "Hz, " << s.tx_frequency_ << "Hz} Mode: " << s.mode_ + << "; SPLIT: " << (Transceiver::TransceiverState::Split::on == s.split_ ? "on" : Transceiver::TransceiverState::Split::off == s.split_ ? "off" : "unknown") + << "; PTT: " << (s.ptt_ ? "on" : "off") + << "; POWER: " << s.power_ << "mWatts" + << "; SWR: " << s.swr_ + << "; TUNE: " << s.tune_ + << ")\n"; +} + +ENUM_QDATASTREAM_OPS_IMPL (Transceiver, MODE); + +ENUM_CONVERSION_OPS_IMPL (Transceiver, MODE); + +bool operator != (Transceiver::TransceiverState const& lhs, Transceiver::TransceiverState const& rhs) +{ + return lhs.online_ != rhs.online_ + || lhs.rx_frequency_ != rhs.rx_frequency_ + || lhs.tx_frequency_ != rhs.tx_frequency_ + || lhs.mode_ != rhs.mode_ + || lhs.split_ != rhs.split_ + || lhs.ptt_ != rhs.ptt_ + || lhs.audio_ != rhs.audio_ + || lhs.tx_audio_ != rhs.tx_audio_ + || lhs.tune_ != rhs.tune_ + || lhs.quick_ != rhs.quick_ + || lhs.period_ != rhs.period_ + || lhs.blocksize_ != rhs.blocksize_ + || lhs.symbolslength_ != rhs.symbolslength_ + || lhs.framespersymbol_ != rhs.framespersymbol_ + || lhs.trfrequency_ != rhs.trfrequency_ + || lhs.tonespacing_ != rhs.tonespacing_ + || lhs.synchronize_ != rhs.synchronize_ + || lhs.dbsnr_ != rhs.dbsnr_ + || lhs.trperiod_ != rhs.trperiod_ + || lhs.spread_ != rhs.spread_ + || lhs.nsym_ != rhs.nsym_ + || lhs.volume_ != rhs.volume_ + || lhs.txvolume_ != rhs.txvolume_ + || lhs.level_ != rhs.level_ + || lhs.power_ != rhs.power_ + || lhs.swr_ != rhs.swr_; +} + +bool operator == (Transceiver::TransceiverState const& lhs, Transceiver::TransceiverState const& rhs) +{ + return !(lhs != rhs); +} diff --git a/Transceiver/Transceiver.hpp b/Transceiver/Transceiver.hpp index 35591878..16c2e9f0 100755..100644 --- a/Transceiver/Transceiver.hpp +++ b/Transceiver/Transceiver.hpp @@ -1,275 +1,275 @@ -#ifndef TRANSCEIVER_HPP__
-#define TRANSCEIVER_HPP__
-
-#include <iosfwd>
-
-#include <boost/log/trivial.hpp>
-#include <boost/log/sources/severity_channel_logger.hpp>
-
-#include <QObject>
-
-#include "qt_helpers.hpp"
-#include "Radio.hpp"
-
-class QString;
-
-//
-// Abstract Transceiver Interface
-//
-// This is the minimal generic interface to a rig as required by
-// wsjtx.
-//
-// Responsibilities
-//
-// Provides a Qt slot to set the frequency, mode and PTT of some
-// transceiver. This is a Qt slot so that it may be invoked across a
-// thread boundary.
-//
-// Provides a synchronisation Qt slot which should be implemented in
-// sub-classes in such a way that normal operation of the rig is not
-// disturbed. This is intended to be use to poll rig state
-// periodically and changing VFO to read the other VFO frequency or
-// mode for example should not be done since the operator may be
-// tuning the VFO at the time and would be surprised by an unprompted
-// VFO change.
-//
-// Provides a control interface using Qt slots to start and stop the
-// rig control and PTT connections.
-//
-// These are Qt slots rather than the constructor and destructor
-// because it is expected that the concrete Transceiver
-// implementations will run in a separate thread from where they are
-// constructed.
-//
-// Qt signals are defined to notify clients of asynchronous rig state
-// changes and failures. These can and are expected to cross thread
-// boundaries.
-//
-// A signal finished() is defined that concrete Transceiver
-// implementations must emit when they are ripe for destruction. This
-// is intended to be used by clients that move the Transceiver
-// instance to a thread and need to use QObject::deleteLater() to
-// safely dispose of the Transceiver instance. Implementations should
-// expect Qt slot calls after emitting finished, it is up to the
-// implementation whether these slot invocations are ignored.
-//
-class Transceiver
- : public QObject
-{
- Q_OBJECT
-
-public:
- using Frequency = Radio::Frequency;
- using logger_type = boost::log::sources::severity_channel_logger_mt<boost::log::trivial::severity_level>;
-
-protected:
- Transceiver (logger_type *, QObject * parent);
- logger_type& logger () const {return *logger_;}
-
-public:
- virtual ~Transceiver () {}
-
- enum MODE {UNK, CW, CW_R, USB, LSB, FSK, FSK_R, DIG_U, DIG_L, AM, FM, DIG_FM};
- Q_ENUM (MODE)
-
- //
- // Aggregation of all of the rig and PTT state accessible via this
- // interface.
- //
- class TransceiverState
- {
- public:
- TransceiverState ()
- : online_ {false}
- , rx_frequency_ {0}
- , tx_frequency_ {0}
- , mode_ {UNK}
- , split_ {Split::unknown}
- , ptt_ {false}
- , audio_ {false}
- , tx_audio_ {false}
- , tune_ {false}
- , quick_ {false}
- , period_ {120.0}
- , blocksize_ {3456}
- , symbolslength_ {79}
- , framespersymbol_ {1920.0}
- , trfrequency_ {1500.0}
- , tonespacing_ {-3.0}
- , synchronize_ {true}
- , dbsnr_ {99.}
- , trperiod_ {60.0}
- , spread_ {0.0}
- , nsym_ {79}
- , volume_ {0}
- , txvolume_(0)
- , level_ {0}
- , power_ {0}
- , swr_ {0}
- , jtmode_ {"FT8"} //w3sz tci
- , fastmode_ {false} //w3sz tci
- {
- }
-
- bool online () const {return online_;}
- Frequency frequency () const {return rx_frequency_;}
- Frequency tx_frequency () const {return tx_frequency_;}
- bool split () const {return Split::on == split_;}
- MODE mode () const {return mode_;}
- bool ptt () const {return ptt_;}
- bool audio () const {return audio_;}
- bool tx_audio () const {return tx_audio_;}
- bool tune () const {return tune_;}
- bool quick () const {return quick_;}
- double period () const {return period_;}
- qint32 blocksize () const {return blocksize_;}
- unsigned symbolslength () const {return symbolslength_;}
- double framespersymbol () const {return framespersymbol_;}
- double trfrequency () const {return trfrequency_;}
- double tonespacing () const {return tonespacing_;}
- bool synchronize () const {return synchronize_;}
- double dbsnr () const {return dbsnr_;}
- double trperiod () const {return trperiod_;}
- double spread () const {return spread_;}
- int nsym () const {return nsym_;}
- qreal volume () const {return volume_;}
- qreal txvolume () const {return txvolume_;}
- int level () const {return level_;}
- unsigned int power () const {return power_;}
- unsigned int swr () const {return swr_;}
- QString jtmode () const {return jtmode_;} //w3sz tci
- bool fastmode () const {return fastmode_;} //w3sz tci
-
- void online (bool state) {online_ = state;}
- void frequency (Frequency f) {rx_frequency_ = f;}
- void tx_frequency (Frequency f) {tx_frequency_ = f;}
- void split (bool state) {split_ = state ? Split::on : Split::off;}
- void mode (MODE m) {mode_ = m;}
- void ptt (bool state) {ptt_ = state;}
- void audio (bool state) {audio_ = state;}
- void tx_audio (bool state) {tx_audio_ = state;}
- void tune (bool state) {tune_ = state;}
- void quick (bool state) {quick_ = state;}
- void period (double period) {period_ = period;}
- void blocksize (qint32 blocksize) {blocksize_ = blocksize;}
- void symbolslength (unsigned symbolslength) {symbolslength_ = symbolslength;}
- void framespersymbol (double framespersymbol) {framespersymbol_ = framespersymbol;}
- void trfrequency (double trfrequency) {trfrequency_ = trfrequency;}
- void tonespacing (double tonespacing) {tonespacing_ = tonespacing;}
- void synchronize (bool synchronize) {synchronize_ = synchronize;}
- void dbsnr (double dbsnr) {dbsnr_ = dbsnr;}
- void trperiod (double trperiod) {trperiod_ = trperiod;}
- void spread (double spread) {spread_ = spread;}
- void nsym (int nsym) {nsym_ = nsym;}
- void volume (qreal volume) {volume_ = volume;}
- void txvolume (qreal txvolume) {txvolume_ = txvolume;}
- void level (int strength) {level_ = strength;}
- void power (unsigned int mwpower) {power_ = mwpower;}
- void swr (unsigned int mswr) {swr_ = mswr;}
- void jtmode(QString jtmode) {jtmode_ = jtmode;} //w3sz tci
- void fastmode(bool fastmode) {fastmode_ = fastmode;} //w3sz tci
-
- private:
- bool online_;
- Frequency rx_frequency_;
- Frequency tx_frequency_; // 0 means use Rx
- MODE mode_;
- enum class Split {unknown, off, on} split_;
- bool ptt_;
- bool audio_;
- bool tx_audio_;
- bool tune_;
- bool quick_;
- double period_;
- qint32 blocksize_;
- unsigned symbolslength_;
- double framespersymbol_;
- double trfrequency_;
- double tonespacing_;
- bool synchronize_;
- double dbsnr_;
- double trperiod_;
- double spread_;
- int nsym_;
- qreal volume_;
- qreal txvolume_;
- int level_;
- unsigned int power_;
- unsigned int swr_;
- QString jtmode_; //w3sz tci
- bool fastmode_; //w3sz tci
-
- // Don't forget to update the debug print and != operator if you
- // add more members here
-
- friend QDebug operator << (QDebug, TransceiverState const&);
- friend bool operator != (TransceiverState const&, TransceiverState const&);
- friend std::ostream& operator << (std::ostream&, Transceiver::TransceiverState const&);
- };
-
- //
- // The following slots and signals are expected to all run in the
- // same thread which is not necessarily the main GUI thread. It is
- // up to the client of the Transceiver class to organise the
- // allocation to a thread and the lifetime of the object instances.
- //
-
- // Apply state changes to the rig. The sequence_number parameter
- // will be included in any status updates generated after this
- // transaction is processed. The sequence number may be used to
- // ignore any status updates until the results of this transaction
- // have been processed thus avoiding any unwanted "ping-pong" due to
- // signals crossing in transit.
- Q_SLOT virtual void set (Transceiver::TransceiverState const&,
- unsigned sequence_number) noexcept = 0;
-
- // Connect and disconnect.
- Q_SLOT virtual void start (unsigned sequence_number) noexcept = 0;
- Q_SLOT virtual void stop () noexcept = 0;
-
- //
- // asynchronous status updates
- //
-
- // 0 - 1Hz
- // 1 - 10Hz rounded
- // -1 - 10Hz truncated
- // 2 - 100Hz rounded
- // -2 - 100Hz truncated
- Q_SIGNAL void resolution (int);
-
- // rig audio data transfer w3sz tci
- Q_SIGNAL void tciframeswritten (qint64);
-
- // rig audio data transfer w3sz tci
- Q_SIGNAL void tci_mod_active (bool);
-
- // rig state changed
- Q_SIGNAL void update (Transceiver::TransceiverState const&,
- unsigned sequence_number) const;
- // something went wrong - not recoverable, start new instance
- Q_SIGNAL void failure (QString const& reason) const;
-
- // Ready to be destroyed.
- Q_SIGNAL void finished () const;
-
-private:
- logger_type mutable * logger_;
-};
-
-Q_DECLARE_METATYPE (Transceiver::TransceiverState);
-
-#if !defined (QT_NO_DEBUG_STREAM)
-QDebug operator << (QDebug, Transceiver::TransceiverState const&);
-#endif
-
-std::ostream& operator << (std::ostream&, Transceiver::MODE);
-std::ostream& operator << (std::ostream&, Transceiver::TransceiverState const&);
-
-ENUM_QDATASTREAM_OPS_DECL (Transceiver, MODE);
-ENUM_CONVERSION_OPS_DECL (Transceiver, MODE);
-
-bool operator != (Transceiver::TransceiverState const&, Transceiver::TransceiverState const&);
-bool operator == (Transceiver::TransceiverState const&, Transceiver::TransceiverState const&);
-
-#endif
+#ifndef TRANSCEIVER_HPP__ +#define TRANSCEIVER_HPP__ + +#include <iosfwd> + +#include <boost/log/trivial.hpp> +#include <boost/log/sources/severity_channel_logger.hpp> + +#include <QObject> + +#include "qt_helpers.hpp" +#include "Radio.hpp" + +class QString; + +// +// Abstract Transceiver Interface +// +// This is the minimal generic interface to a rig as required by +// wsjtx. +// +// Responsibilities +// +// Provides a Qt slot to set the frequency, mode and PTT of some +// transceiver. This is a Qt slot so that it may be invoked across a +// thread boundary. +// +// Provides a synchronisation Qt slot which should be implemented in +// sub-classes in such a way that normal operation of the rig is not +// disturbed. This is intended to be use to poll rig state +// periodically and changing VFO to read the other VFO frequency or +// mode for example should not be done since the operator may be +// tuning the VFO at the time and would be surprised by an unprompted +// VFO change. +// +// Provides a control interface using Qt slots to start and stop the +// rig control and PTT connections. +// +// These are Qt slots rather than the constructor and destructor +// because it is expected that the concrete Transceiver +// implementations will run in a separate thread from where they are +// constructed. +// +// Qt signals are defined to notify clients of asynchronous rig state +// changes and failures. These can and are expected to cross thread +// boundaries. +// +// A signal finished() is defined that concrete Transceiver +// implementations must emit when they are ripe for destruction. This +// is intended to be used by clients that move the Transceiver +// instance to a thread and need to use QObject::deleteLater() to +// safely dispose of the Transceiver instance. Implementations should +// expect Qt slot calls after emitting finished, it is up to the +// implementation whether these slot invocations are ignored. +// +class Transceiver + : public QObject +{ + Q_OBJECT + +public: + using Frequency = Radio::Frequency; + using logger_type = boost::log::sources::severity_channel_logger_mt<boost::log::trivial::severity_level>; + +protected: + Transceiver (logger_type *, QObject * parent); + logger_type& logger () const {return *logger_;} + +public: + virtual ~Transceiver () {} + + enum MODE {UNK, CW, CW_R, USB, LSB, FSK, FSK_R, DIG_U, DIG_L, AM, FM, DIG_FM}; + Q_ENUM (MODE) + + // + // Aggregation of all of the rig and PTT state accessible via this + // interface. + // + class TransceiverState + { + public: + TransceiverState () + : online_ {false} + , rx_frequency_ {0} + , tx_frequency_ {0} + , mode_ {UNK} + , split_ {Split::unknown} + , ptt_ {false} + , audio_ {false} + , tx_audio_ {false} + , tune_ {false} + , quick_ {false} + , period_ {120.0} + , blocksize_ {3456} + , symbolslength_ {79} + , framespersymbol_ {1920.0} + , trfrequency_ {1500.0} + , tonespacing_ {-3.0} + , synchronize_ {true} + , dbsnr_ {99.} + , trperiod_ {60.0} + , spread_ {0.0} + , nsym_ {79} + , volume_ {0} + , txvolume_(0) + , level_ {0} + , power_ {0} + , swr_ {0} + , jtmode_ {"FT8"} //w3sz tci + , fastmode_ {false} //w3sz tci + { + } + + bool online () const {return online_;} + Frequency frequency () const {return rx_frequency_;} + Frequency tx_frequency () const {return tx_frequency_;} + bool split () const {return Split::on == split_;} + MODE mode () const {return mode_;} + bool ptt () const {return ptt_;} + bool audio () const {return audio_;} + bool tx_audio () const {return tx_audio_;} + bool tune () const {return tune_;} + bool quick () const {return quick_;} + double period () const {return period_;} + qint32 blocksize () const {return blocksize_;} + unsigned symbolslength () const {return symbolslength_;} + double framespersymbol () const {return framespersymbol_;} + double trfrequency () const {return trfrequency_;} + double tonespacing () const {return tonespacing_;} + bool synchronize () const {return synchronize_;} + double dbsnr () const {return dbsnr_;} + double trperiod () const {return trperiod_;} + double spread () const {return spread_;} + int nsym () const {return nsym_;} + qreal volume () const {return volume_;} + qreal txvolume () const {return txvolume_;} + int level () const {return level_;} + unsigned int power () const {return power_;} + unsigned int swr () const {return swr_;} + QString jtmode () const {return jtmode_;} //w3sz tci + bool fastmode () const {return fastmode_;} //w3sz tci + + void online (bool state) {online_ = state;} + void frequency (Frequency f) {rx_frequency_ = f;} + void tx_frequency (Frequency f) {tx_frequency_ = f;} + void split (bool state) {split_ = state ? Split::on : Split::off;} + void mode (MODE m) {mode_ = m;} + void ptt (bool state) {ptt_ = state;} + void audio (bool state) {audio_ = state;} + void tx_audio (bool state) {tx_audio_ = state;} + void tune (bool state) {tune_ = state;} + void quick (bool state) {quick_ = state;} + void period (double period) {period_ = period;} + void blocksize (qint32 blocksize) {blocksize_ = blocksize;} + void symbolslength (unsigned symbolslength) {symbolslength_ = symbolslength;} + void framespersymbol (double framespersymbol) {framespersymbol_ = framespersymbol;} + void trfrequency (double trfrequency) {trfrequency_ = trfrequency;} + void tonespacing (double tonespacing) {tonespacing_ = tonespacing;} + void synchronize (bool synchronize) {synchronize_ = synchronize;} + void dbsnr (double dbsnr) {dbsnr_ = dbsnr;} + void trperiod (double trperiod) {trperiod_ = trperiod;} + void spread (double spread) {spread_ = spread;} + void nsym (int nsym) {nsym_ = nsym;} + void volume (qreal volume) {volume_ = volume;} + void txvolume (qreal txvolume) {txvolume_ = txvolume;} + void level (int strength) {level_ = strength;} + void power (unsigned int mwpower) {power_ = mwpower;} + void swr (unsigned int mswr) {swr_ = mswr;} + void jtmode(QString jtmode) {jtmode_ = jtmode;} //w3sz tci + void fastmode(bool fastmode) {fastmode_ = fastmode;} //w3sz tci + + private: + bool online_; + Frequency rx_frequency_; + Frequency tx_frequency_; // 0 means use Rx + MODE mode_; + enum class Split {unknown, off, on} split_; + bool ptt_; + bool audio_; + bool tx_audio_; + bool tune_; + bool quick_; + double period_; + qint32 blocksize_; + unsigned symbolslength_; + double framespersymbol_; + double trfrequency_; + double tonespacing_; + bool synchronize_; + double dbsnr_; + double trperiod_; + double spread_; + int nsym_; + qreal volume_; + qreal txvolume_; + int level_; + unsigned int power_; + unsigned int swr_; + QString jtmode_; //w3sz tci + bool fastmode_; //w3sz tci + + // Don't forget to update the debug print and != operator if you + // add more members here + + friend QDebug operator << (QDebug, TransceiverState const&); + friend bool operator != (TransceiverState const&, TransceiverState const&); + friend std::ostream& operator << (std::ostream&, Transceiver::TransceiverState const&); + }; + + // + // The following slots and signals are expected to all run in the + // same thread which is not necessarily the main GUI thread. It is + // up to the client of the Transceiver class to organise the + // allocation to a thread and the lifetime of the object instances. + // + + // Apply state changes to the rig. The sequence_number parameter + // will be included in any status updates generated after this + // transaction is processed. The sequence number may be used to + // ignore any status updates until the results of this transaction + // have been processed thus avoiding any unwanted "ping-pong" due to + // signals crossing in transit. + Q_SLOT virtual void set (Transceiver::TransceiverState const&, + unsigned sequence_number) noexcept = 0; + + // Connect and disconnect. + Q_SLOT virtual void start (unsigned sequence_number) noexcept = 0; + Q_SLOT virtual void stop () noexcept = 0; + + // + // asynchronous status updates + // + + // 0 - 1Hz + // 1 - 10Hz rounded + // -1 - 10Hz truncated + // 2 - 100Hz rounded + // -2 - 100Hz truncated + Q_SIGNAL void resolution (int); + + // rig audio data transfer w3sz tci + Q_SIGNAL void tciframeswritten (qint64); + + // rig audio data transfer w3sz tci + Q_SIGNAL void tci_mod_active (bool); + + // rig state changed + Q_SIGNAL void update (Transceiver::TransceiverState const&, + unsigned sequence_number) const; + // something went wrong - not recoverable, start new instance + Q_SIGNAL void failure (QString const& reason) const; + + // Ready to be destroyed. + Q_SIGNAL void finished () const; + +private: + logger_type mutable * logger_; +}; + +Q_DECLARE_METATYPE (Transceiver::TransceiverState); + +#if !defined (QT_NO_DEBUG_STREAM) +QDebug operator << (QDebug, Transceiver::TransceiverState const&); +#endif + +std::ostream& operator << (std::ostream&, Transceiver::MODE); +std::ostream& operator << (std::ostream&, Transceiver::TransceiverState const&); + +ENUM_QDATASTREAM_OPS_DECL (Transceiver, MODE); +ENUM_CONVERSION_OPS_DECL (Transceiver, MODE); + +bool operator != (Transceiver::TransceiverState const&, Transceiver::TransceiverState const&); +bool operator == (Transceiver::TransceiverState const&, Transceiver::TransceiverState const&); + +#endif diff --git a/Transceiver/TransceiverBase.cpp b/Transceiver/TransceiverBase.cpp index c0107835..72f6fafb 100755..100644 --- a/Transceiver/TransceiverBase.cpp +++ b/Transceiver/TransceiverBase.cpp @@ -1,373 +1,373 @@ -#include "TransceiverBase.hpp"
-
-#include <exception>
-
-#include <QString>
-#include <QTimer>
-#include <QThread>
-#include <QDebug>
-
-#include "moc_TransceiverBase.cpp"
-
-namespace
-{
- auto const unexpected = TransceiverBase::tr ("Unexpected rig error");
-}
-
-void TransceiverBase::start (unsigned sequence_number) noexcept
-{
- CAT_TRACE ("#: " << sequence_number);
-
- QString message;
- try
- {
- last_sequence_number_ = sequence_number;
- may_update u {this, true};
- shutdown ();
- startup ();
- }
- catch (std::exception const& e)
- {
- CAT_TRACE ("#: " << sequence_number << " what: " << e.what ());
- message = e.what ();
- }
- catch (...)
- {
- CAT_TRACE ("#: " << sequence_number);
- message = unexpected;
- }
- if (!message.isEmpty ())
- {
- offline (message);
- }
-}
-
-void TransceiverBase::set (TransceiverState const& s,
- unsigned sequence_number) noexcept
-{
- CAT_TRACE ("#: " << s);
-
- try {
- do_txvolume (s.txvolume());
- } catch(...) {printf("Setting tx attenuation failed");}
-
- try {
- do_volume (s.volume());
- } catch(...) {printf("Setting rx attenuation failed");}
-
- QString message;
- try
- {
- last_sequence_number_ = sequence_number;
- may_update u {this, true};
- bool was_online {requested_.online ()};
- if (!s.online () && was_online)
- {
- shutdown ();
- }
- else if (s.online () && !was_online)
- {
- shutdown ();
- startup ();
- }
- if (requested_.online ())
- {
- bool audio_cmd {false};
- if (requested_.blocksize() != s.blocksize()) {
- do_blocksize (s.blocksize());
- audio_cmd = true;
- requested_.blocksize (s.blocksize ());
- }
- if (requested_.period() != s.period()) {
- do_period (s.period());
- audio_cmd = true;
- requested_.period (s.period ());
- }
- if (requested_.spread() != s.spread()) {
- do_spread (s.spread());
- audio_cmd = true;
- requested_.spread (s.spread ());
- }
- if (requested_.nsym() != s.nsym()) {
- do_nsym (s.nsym());
- audio_cmd = true;
- requested_.nsym (s.nsym ());
- }
- if (requested_.trfrequency() != s.trfrequency()) {
- do_trfrequency (s.trfrequency());
- audio_cmd = true;
- requested_.trfrequency (s.trfrequency ());
- }
- if (requested_.audio() != s.audio()) {
- do_audio (s.audio());
- audio_cmd = true;
- requested_.audio (s.audio ());
- }
- if (requested_.tx_audio() != s.tx_audio()) {
- if (s.tx_audio()) {
- do_modulator_start(s.jtmode(), s.symbolslength (), s.framespersymbol (), s.trfrequency (), s.tonespacing (), s.synchronize (),s.fastmode(), s.dbsnr (), s.trperiod ());
- requested_.symbolslength(s.symbolslength ());
- requested_.framespersymbol(s.framespersymbol ());
- requested_.trfrequency(s.trfrequency ());
- requested_.tonespacing(s.tonespacing ());
- requested_.synchronize(s.synchronize ());
- requested_.dbsnr(s.dbsnr ());
- requested_.trperiod(s.trperiod ());
- } else {
- do_modulator_stop(s.quick ());
- requested_.quick (s.quick ());
- }
- audio_cmd = true;
-
- requested_.tx_audio (s.tx_audio ());
- }
-
- if (requested_.tune() != s.tune()) {
- do_tune (s.tune());
- audio_cmd = true;
- requested_.tune (s.tune ());
- }
- if (!audio_cmd) {
- bool ptt_on {false};
- bool ptt_off {false};
- if (s.ptt () != requested_.ptt ())
- {
- ptt_on = s.ptt ();
- ptt_off = !s.ptt ();
- }
- if (ptt_off)
- {
- do_ptt (false);
- do_post_ptt (false);
- if (!requested_.audio()) QThread::msleep (100); // some rigs cannot process CAT
- // commands while switching from
- // Tx to Rx
- }
-
- if (s.frequency () // ignore bogus zero frequencies
- && ((s.frequency () != requested_.frequency () // and QSY
- || (s.mode () != UNK && s.mode () != requested_.mode ())))) // or mode change
- {
- requested_.frequency (s.frequency ());
- requested_.mode (s.mode ());
- do_frequency (s.frequency (), s.mode (), ptt_off);
- do_post_frequency (s.frequency (), s.mode ());
-
- // record what actually changed
- requested_.frequency (actual_.frequency ());
- requested_.mode (actual_.mode ());
- }
- else if (!s.tx_frequency ()
- || (s.tx_frequency () > 10000 // ignore bogus startup values
- && s.tx_frequency () < std::numeric_limits<Frequency>::max () - 10000))
- {
- if ((s.tx_frequency () != requested_.tx_frequency () // and QSY
- || (s.mode () != UNK && s.mode () != requested_.mode ())) // or mode change
- // || s.split () != requested_.split ())) // or split change
- || (s.tx_frequency () && ptt_on)) // or about to tx split
- {
- requested_.tx_frequency (s.tx_frequency ());
- requested_.split (s.tx_frequency () != 0);
- do_tx_frequency (s.tx_frequency (), s.mode (), ptt_on);
- do_post_tx_frequency (s.tx_frequency (), s.mode ());
-
- // record what actually changed
- requested_.tx_frequency (actual_.tx_frequency ());
- requested_.split (actual_.split ());
- }
- }
- if (ptt_on)
- {
- do_ptt (true);
- do_post_ptt (true);
- QThread::msleep (100); // some rigs cannot process CAT
- // commands while switching from
- // Rx to Tx
- }
-
- // record what actually changed
- if (ptt_on || ptt_off) requested_.ptt (actual_.ptt ());
- }
- }
- }
- catch (std::exception const& e)
- {
- CAT_TRACE ("#: " << sequence_number << " what: " << e.what ());
- message = e.what ();
- }
- catch (...)
- {
- CAT_TRACE ("#: " << sequence_number << " " << sequence_number);
- message = unexpected;
- }
- if (!message.isEmpty ())
- {
- offline (message);
- }
-}
-
-void TransceiverBase::startup ()
-{
- CAT_TRACE ("startup\n");
- QString message;
- try
- {
- actual_.online (true);
- requested_.online (true);
- auto res = do_start ();
- do_post_start ();
- Q_EMIT resolution (res);
- }
- catch (std::exception const& e)
- {
- CAT_TRACE ("startup" << " what: " << e.what () << '\n');
- message = e.what ();
- }
- catch (...)
- {
- CAT_TRACE ("startup error: unexpected\n");
- message = unexpected;
- }
- if (!message.isEmpty ())
- {
- offline (message);
- }
-}
-
-void TransceiverBase::shutdown ()
-{
- CAT_TRACE ("shutdown\n");
- may_update u {this};
- if (requested_.online ())
- {
- try
- {
- // try and ensure PTT isn't left set
- do_ptt (false);
- do_post_ptt (false);
- if (requested_.split ())
- {
- // try and reset split mode
- do_tx_frequency (0, UNK, true);
- do_post_tx_frequency (0, UNK);
- update_split(false); //w3sz tci
- }
- }
- catch (...)
- {
- CAT_TRACE ("shutdown\n");
- // don't care about exceptions
- }
- }
- do_stop();
- do_post_stop ();
- actual_ = TransceiverState {};
- requested_ = TransceiverState {};
-}
-
-void TransceiverBase::stop () noexcept
-{
- CAT_TRACE ("stop");
- QString message;
- try
- {
- shutdown ();
- }
- catch (std::exception const& e)
- {
- CAT_TRACE ("stop" << " what: " << e.what ());
- message = e.what ();
- }
- catch (...)
- {
- CAT_TRACE ("stop");
- message = unexpected;
- }
- if (!message.isEmpty ())
- {
- offline (message);
- }
- else
- {
- Q_EMIT finished ();
- }
-}
-
-void TransceiverBase::update_rx_frequency (Frequency rx)
-{
- CAT_TRACE ("frequency: " << rx);
- if (rx)
- {
- actual_.frequency (rx);
- requested_.frequency (rx); // track rig changes
- }
-}
-
-void TransceiverBase::update_other_frequency (Frequency tx)
-{
- CAT_TRACE ("frequency: " << tx);
- actual_.tx_frequency (tx);
-}
-
-void TransceiverBase::update_split (bool state)
-{
- CAT_TRACE ("state: " << state);
- actual_.split (state);
-}
-
-void TransceiverBase::update_mode (MODE m)
-{
- CAT_TRACE ("mode: " << m);
- actual_.mode (m);
- requested_.mode (m); // track rig changes
-}
-
-void TransceiverBase::update_PTT (bool state)
-{
- CAT_TRACE ("state: " << state);
- actual_.ptt (state);
-}
-
-void TransceiverBase::update_level (int l)
-{
- CAT_TRACE ("level: " << l);
- actual_.level (l);
- // requested_.level (l); // track rig changes
-}
-
-void TransceiverBase::update_power (unsigned int p)
-{
- CAT_TRACE ("power: " << p);
- actual_.power (p);
-}
-
-void TransceiverBase::update_swr (unsigned int p)
-{
- CAT_TRACE ("swr: " << p);
- actual_.swr (p);
-}
-
-void TransceiverBase::update_complete (bool force_signal)
-{
- CAT_TRACE ("force signal: " << force_signal) << '\n';
- if ((do_pre_update () && actual_ != last_) || force_signal)
- {
- Q_EMIT update (actual_, last_sequence_number_);
- last_ = actual_;
- }
-}
-
-void TransceiverBase::offline (QString const& reason)
-{
- CAT_TRACE ("reason: " << reason << '\n');
- Q_EMIT failure (reason);
- try
- {
- shutdown ();
- }
- catch (...)
- {
- CAT_TRACE ("reason: " << reason);
- // don't care
- }
-}
+#include "TransceiverBase.hpp" + +#include <exception> + +#include <QString> +#include <QTimer> +#include <QThread> +#include <QDebug> + +#include "moc_TransceiverBase.cpp" + +namespace +{ + auto const unexpected = TransceiverBase::tr ("Unexpected rig error"); +} + +void TransceiverBase::start (unsigned sequence_number) noexcept +{ + CAT_TRACE ("#: " << sequence_number); + + QString message; + try + { + last_sequence_number_ = sequence_number; + may_update u {this, true}; + shutdown (); + startup (); + } + catch (std::exception const& e) + { + CAT_TRACE ("#: " << sequence_number << " what: " << e.what ()); + message = e.what (); + } + catch (...) + { + CAT_TRACE ("#: " << sequence_number); + message = unexpected; + } + if (!message.isEmpty ()) + { + offline (message); + } +} + +void TransceiverBase::set (TransceiverState const& s, + unsigned sequence_number) noexcept +{ + CAT_TRACE ("#: " << s); + + try { + do_txvolume (s.txvolume()); + } catch(...) {printf("Setting tx attenuation failed");} + + try { + do_volume (s.volume()); + } catch(...) {printf("Setting rx attenuation failed");} + + QString message; + try + { + last_sequence_number_ = sequence_number; + may_update u {this, true}; + bool was_online {requested_.online ()}; + if (!s.online () && was_online) + { + shutdown (); + } + else if (s.online () && !was_online) + { + shutdown (); + startup (); + } + if (requested_.online ()) + { + bool audio_cmd {false}; + if (requested_.blocksize() != s.blocksize()) { + do_blocksize (s.blocksize()); + audio_cmd = true; + requested_.blocksize (s.blocksize ()); + } + if (requested_.period() != s.period()) { + do_period (s.period()); + audio_cmd = true; + requested_.period (s.period ()); + } + if (requested_.spread() != s.spread()) { + do_spread (s.spread()); + audio_cmd = true; + requested_.spread (s.spread ()); + } + if (requested_.nsym() != s.nsym()) { + do_nsym (s.nsym()); + audio_cmd = true; + requested_.nsym (s.nsym ()); + } + if (requested_.trfrequency() != s.trfrequency()) { + do_trfrequency (s.trfrequency()); + audio_cmd = true; + requested_.trfrequency (s.trfrequency ()); + } + if (requested_.audio() != s.audio()) { + do_audio (s.audio()); + audio_cmd = true; + requested_.audio (s.audio ()); + } + if (requested_.tx_audio() != s.tx_audio()) { + if (s.tx_audio()) { + do_modulator_start(s.jtmode(), s.symbolslength (), s.framespersymbol (), s.trfrequency (), s.tonespacing (), s.synchronize (),s.fastmode(), s.dbsnr (), s.trperiod ()); + requested_.symbolslength(s.symbolslength ()); + requested_.framespersymbol(s.framespersymbol ()); + requested_.trfrequency(s.trfrequency ()); + requested_.tonespacing(s.tonespacing ()); + requested_.synchronize(s.synchronize ()); + requested_.dbsnr(s.dbsnr ()); + requested_.trperiod(s.trperiod ()); + } else { + do_modulator_stop(s.quick ()); + requested_.quick (s.quick ()); + } + audio_cmd = true; + + requested_.tx_audio (s.tx_audio ()); + } + + if (requested_.tune() != s.tune()) { + do_tune (s.tune()); + audio_cmd = true; + requested_.tune (s.tune ()); + } + if (!audio_cmd) { + bool ptt_on {false}; + bool ptt_off {false}; + if (s.ptt () != requested_.ptt ()) + { + ptt_on = s.ptt (); + ptt_off = !s.ptt (); + } + if (ptt_off) + { + do_ptt (false); + do_post_ptt (false); + if (!requested_.audio()) QThread::msleep (100); // some rigs cannot process CAT + // commands while switching from + // Tx to Rx + } + + if (s.frequency () // ignore bogus zero frequencies + && ((s.frequency () != requested_.frequency () // and QSY + || (s.mode () != UNK && s.mode () != requested_.mode ())))) // or mode change + { + requested_.frequency (s.frequency ()); + requested_.mode (s.mode ()); + do_frequency (s.frequency (), s.mode (), ptt_off); + do_post_frequency (s.frequency (), s.mode ()); + + // record what actually changed + requested_.frequency (actual_.frequency ()); + requested_.mode (actual_.mode ()); + } + else if (!s.tx_frequency () + || (s.tx_frequency () > 10000 // ignore bogus startup values + && s.tx_frequency () < std::numeric_limits<Frequency>::max () - 10000)) + { + if ((s.tx_frequency () != requested_.tx_frequency () // and QSY + || (s.mode () != UNK && s.mode () != requested_.mode ())) // or mode change + // || s.split () != requested_.split ())) // or split change + || (s.tx_frequency () && ptt_on)) // or about to tx split + { + requested_.tx_frequency (s.tx_frequency ()); + requested_.split (s.tx_frequency () != 0); + do_tx_frequency (s.tx_frequency (), s.mode (), ptt_on); + do_post_tx_frequency (s.tx_frequency (), s.mode ()); + + // record what actually changed + requested_.tx_frequency (actual_.tx_frequency ()); + requested_.split (actual_.split ()); + } + } + if (ptt_on) + { + do_ptt (true); + do_post_ptt (true); + QThread::msleep (100); // some rigs cannot process CAT + // commands while switching from + // Rx to Tx + } + + // record what actually changed + if (ptt_on || ptt_off) requested_.ptt (actual_.ptt ()); + } + } + } + catch (std::exception const& e) + { + CAT_TRACE ("#: " << sequence_number << " what: " << e.what ()); + message = e.what (); + } + catch (...) + { + CAT_TRACE ("#: " << sequence_number << " " << sequence_number); + message = unexpected; + } + if (!message.isEmpty ()) + { + offline (message); + } +} + +void TransceiverBase::startup () +{ + CAT_TRACE ("startup\n"); + QString message; + try + { + actual_.online (true); + requested_.online (true); + auto res = do_start (); + do_post_start (); + Q_EMIT resolution (res); + } + catch (std::exception const& e) + { + CAT_TRACE ("startup" << " what: " << e.what () << '\n'); + message = e.what (); + } + catch (...) + { + CAT_TRACE ("startup error: unexpected\n"); + message = unexpected; + } + if (!message.isEmpty ()) + { + offline (message); + } +} + +void TransceiverBase::shutdown () +{ + CAT_TRACE ("shutdown\n"); + may_update u {this}; + if (requested_.online ()) + { + try + { + // try and ensure PTT isn't left set + do_ptt (false); + do_post_ptt (false); + if (requested_.split ()) + { + // try and reset split mode + do_tx_frequency (0, UNK, true); + do_post_tx_frequency (0, UNK); + update_split(false); //w3sz tci + } + } + catch (...) + { + CAT_TRACE ("shutdown\n"); + // don't care about exceptions + } + } + do_stop(); + do_post_stop (); + actual_ = TransceiverState {}; + requested_ = TransceiverState {}; +} + +void TransceiverBase::stop () noexcept +{ + CAT_TRACE ("stop"); + QString message; + try + { + shutdown (); + } + catch (std::exception const& e) + { + CAT_TRACE ("stop" << " what: " << e.what ()); + message = e.what (); + } + catch (...) + { + CAT_TRACE ("stop"); + message = unexpected; + } + if (!message.isEmpty ()) + { + offline (message); + } + else + { + Q_EMIT finished (); + } +} + +void TransceiverBase::update_rx_frequency (Frequency rx) +{ + CAT_TRACE ("frequency: " << rx); + if (rx) + { + actual_.frequency (rx); + requested_.frequency (rx); // track rig changes + } +} + +void TransceiverBase::update_other_frequency (Frequency tx) +{ + CAT_TRACE ("frequency: " << tx); + actual_.tx_frequency (tx); +} + +void TransceiverBase::update_split (bool state) +{ + CAT_TRACE ("state: " << state); + actual_.split (state); +} + +void TransceiverBase::update_mode (MODE m) +{ + CAT_TRACE ("mode: " << m); + actual_.mode (m); + requested_.mode (m); // track rig changes +} + +void TransceiverBase::update_PTT (bool state) +{ + CAT_TRACE ("state: " << state); + actual_.ptt (state); +} + +void TransceiverBase::update_level (int l) +{ + CAT_TRACE ("level: " << l); + actual_.level (l); + // requested_.level (l); // track rig changes +} + +void TransceiverBase::update_power (unsigned int p) +{ + CAT_TRACE ("power: " << p); + actual_.power (p); +} + +void TransceiverBase::update_swr (unsigned int p) +{ + CAT_TRACE ("swr: " << p); + actual_.swr (p); +} + +void TransceiverBase::update_complete (bool force_signal) +{ + CAT_TRACE ("force signal: " << force_signal) << '\n'; + if ((do_pre_update () && actual_ != last_) || force_signal) + { + Q_EMIT update (actual_, last_sequence_number_); + last_ = actual_; + } +} + +void TransceiverBase::offline (QString const& reason) +{ + CAT_TRACE ("reason: " << reason << '\n'); + Q_EMIT failure (reason); + try + { + shutdown (); + } + catch (...) + { + CAT_TRACE ("reason: " << reason); + // don't care + } +} diff --git a/Transceiver/TransceiverBase.hpp b/Transceiver/TransceiverBase.hpp index 70887874..ee5f8c1c 100755..100644 --- a/Transceiver/TransceiverBase.hpp +++ b/Transceiver/TransceiverBase.hpp @@ -1,195 +1,195 @@ -#ifndef TRANSCEIVER_BASE_HPP__
-#define TRANSCEIVER_BASE_HPP__
-
-#include <stdexcept>
-
-#include <QString>
-
-#include "Logger.hpp"
-#include "Transceiver.hpp"
-
-//
-// Base Transceiver Implementation
-//
-// Behaviour common to all Transceiver implementations.
-//
-// Collaborations
-//
-// Implements the Transceiver abstract interface as template methods
-// and provides a new abstract interface with similar functionality
-// (do_XXXXX operations). Provides and calls abstract interface that
-// gets called post the above operations (do_post_XXXXX) to allow
-// caching implementation etc.
-//
-// A key factor is to catch all exceptions thrown by sub-class
-// implementations where the template method is a Qt slot which is
-// therefore likely to be called by Qt which doesn't handle
-// exceptions. Any exceptions are converted to Transceiver::failure()
-// signals.
-//
-// Sub-classes update the stored state via a protected interface.
-//
-// Responsibilities:
-//
-// Wrap incoming Transceiver messages catching all exceptions in Qt
-// slot driven messages and converting them to Qt signals. This is
-// done because exceptions make concrete Transceiver implementations
-// simpler to write, but exceptions cannot cross signal/slot
-// boundaries (especially across threads). This also removes any
-// requirement for the client code to handle exceptions.
-//
-// Maintain the state of the concrete Transceiver instance that is
-// passed back via the Transceiver::update(TransceiverState) signal,
-// it is still the responsibility of concrete Transceiver
-// implementations to emit the state_change signal when they have a
-// status update.
-//
-// Maintain a go/no-go status for concrete Transceiver
-// implementations ensuring only a valid sequence of messages are
-// passed. A concrete Transceiver instance must be started before it
-// can receive messages, any exception thrown takes the Transceiver
-// offline.
-//
-// Implements methods that concrete Transceiver implementations use
-// to update the Transceiver state. These do not signal state change
-// to clients as this is the responsibility of the concrete
-// Transceiver implementation, thus allowing multiple state component
-// updates to be signalled together if required.
-//
-class TransceiverBase
- : public Transceiver
-{
- Q_OBJECT;
-
-protected:
- TransceiverBase (logger_type * logger, QObject * parent)
- : Transceiver {logger, parent}
- , last_sequence_number_ {0}
- {}
-
-public:
- //
- // Implement the Transceiver abstract interface.
- //
- void start (unsigned sequence_number) noexcept override final;
- void set (TransceiverState const&,
- unsigned sequence_number) noexcept override final;
- void stop () noexcept override final;
-
- //
- // Query operations
- //
- TransceiverState const& state () const {return actual_;}
-
-protected:
- //
- // Error exception which is thrown to signal unexpected errors.
- //
- struct error
- : public std::runtime_error
- {
- explicit error (char const * const msg) : std::runtime_error (msg) {}
- explicit error (QString const& msg) : std::runtime_error (msg.toStdString ()) {}
- };
-
- // Template methods that sub classes implement to do what they need to do.
- //
- // These methods may throw exceptions to signal errors.
- virtual int do_start () = 0; // returns resolution, See Transceiver::resolution
- virtual void do_post_start () {}
-
- virtual void do_stop () = 0;
- virtual void do_post_stop () {}
-
- virtual void do_frequency (Frequency, MODE, bool no_ignore) = 0;
- virtual void do_post_frequency (Frequency, MODE) {}
-
- virtual void do_tx_frequency (Frequency, MODE, bool no_ignore) = 0;
- virtual void do_post_tx_frequency (Frequency, MODE) {}
-
- virtual void do_mode (MODE) = 0;
- virtual void do_post_mode (MODE) {}
-
- virtual void do_ptt (bool = true) = 0;
- virtual void do_post_ptt (bool = true) {}
-
- // this is the rig tuning -- use false if need to turn off tune -- do we need that for anyone?
- virtual void do_audio (bool = false) {}
- virtual void do_tune (bool = false) {}
- virtual void do_period (double) {}
- virtual void do_blocksize (qint32) {}
- virtual void do_spread(double) {}
- virtual void do_nsym(int) {}
- virtual void do_trfrequency(double) {}
- virtual void do_volume (qreal) {}
- virtual void do_txvolume (qreal) {}
- //parameters are MODE,symbolslength,framespersymbol,trfrequency,tonespacing,synchronize,FASTMODE,dbsdr,trperiod //parameters added by w3sz are in bold
- virtual void do_modulator_start(QString, unsigned, double, double, double, bool, bool, double, double) {}
- virtual void do_modulator_stop(bool) {}
-
- virtual bool do_pre_update () {return true;}
-
- // sub classes report rig state changes with these methods
- void update_rx_frequency (Frequency);
- void update_other_frequency (Frequency = 0);
- void update_split (bool);
- void update_mode (MODE);
- void update_PTT (bool = true);
- void update_level (int = 0);
- void update_power (unsigned int = 0);
- void update_swr (unsigned int = 0);
-
- // Calling this eventually triggers the Transceiver::update(State) signal.
- void update_complete (bool force_signal = false);
-
- // sub class may asynchronously take the rig offline by calling this
- void offline (QString const& reason);
-
-private:
- void startup ();
- void shutdown ();
- bool maybe_low_resolution (Frequency low_res, Frequency high_res);
-
- // use this convenience class to notify in update methods
- class may_update
- {
- public:
- explicit may_update (TransceiverBase * self, bool force_signal = false)
- : self_ {self}
- , force_signal_ {force_signal}
- {}
- ~may_update () {self_->update_complete (force_signal_);}
- private:
- TransceiverBase * self_;
- bool force_signal_;
- };
-
- TransceiverState requested_;
- TransceiverState actual_;
- TransceiverState last_;
- unsigned last_sequence_number_; // from set state operation
-};
-
-// some loggimg macros
-#define CAT_TRACE(MSG) LOG_LOG_LOCATION (logger (), trace, MSG)
-#define CAT_DEBUG(MSG) LOG_LOG_LOCATION (logger (), debug, MSG)
-#define CAT_INFO(MSG) LOG_LOG_LOCATION (logger (), info, MSG)
-#define CAT_WARNING(MSG) LOG_LOG_LOCATION (logger (), warning, MSG)
-#define CAT_ERROR(MSG) LOG_LOG_LOCATION (logger (), error, MSG)
-#define CAT_FATAL(MSG) LOG_LOG_LOCATION (logger (), fatal, MSG)
-
-// some trace macros
-#if WSJT_TRACE_CAT
-#define TRACE_CAT(FAC, MSG) qDebug () << QString {"%1::%2:"}.arg ((FAC)).arg (__func__) << MSG
-#else
-#define TRACE_CAT(FAC, MSG)
-#endif
-
-#if WSJT_TRACE_CAT && WSJT_TRACE_CAT_POLLS
-#define TRACE_CAT_POLL(FAC, MSG) qDebug () << QString {"%1::%2:"}.arg ((FAC)).arg (__func__) << MSG
-#else
-#define TRACE_CAT_POLL(FAC, MSG)
-#endif
-
-
-#endif
+#ifndef TRANSCEIVER_BASE_HPP__ +#define TRANSCEIVER_BASE_HPP__ + +#include <stdexcept> + +#include <QString> + +#include "Logger.hpp" +#include "Transceiver.hpp" + +// +// Base Transceiver Implementation +// +// Behaviour common to all Transceiver implementations. +// +// Collaborations +// +// Implements the Transceiver abstract interface as template methods +// and provides a new abstract interface with similar functionality +// (do_XXXXX operations). Provides and calls abstract interface that +// gets called post the above operations (do_post_XXXXX) to allow +// caching implementation etc. +// +// A key factor is to catch all exceptions thrown by sub-class +// implementations where the template method is a Qt slot which is +// therefore likely to be called by Qt which doesn't handle +// exceptions. Any exceptions are converted to Transceiver::failure() +// signals. +// +// Sub-classes update the stored state via a protected interface. +// +// Responsibilities: +// +// Wrap incoming Transceiver messages catching all exceptions in Qt +// slot driven messages and converting them to Qt signals. This is +// done because exceptions make concrete Transceiver implementations +// simpler to write, but exceptions cannot cross signal/slot +// boundaries (especially across threads). This also removes any +// requirement for the client code to handle exceptions. +// +// Maintain the state of the concrete Transceiver instance that is +// passed back via the Transceiver::update(TransceiverState) signal, +// it is still the responsibility of concrete Transceiver +// implementations to emit the state_change signal when they have a +// status update. +// +// Maintain a go/no-go status for concrete Transceiver +// implementations ensuring only a valid sequence of messages are +// passed. A concrete Transceiver instance must be started before it +// can receive messages, any exception thrown takes the Transceiver +// offline. +// +// Implements methods that concrete Transceiver implementations use +// to update the Transceiver state. These do not signal state change +// to clients as this is the responsibility of the concrete +// Transceiver implementation, thus allowing multiple state component +// updates to be signalled together if required. +// +class TransceiverBase + : public Transceiver +{ + Q_OBJECT; + +protected: + TransceiverBase (logger_type * logger, QObject * parent) + : Transceiver {logger, parent} + , last_sequence_number_ {0} + {} + +public: + // + // Implement the Transceiver abstract interface. + // + void start (unsigned sequence_number) noexcept override final; + void set (TransceiverState const&, + unsigned sequence_number) noexcept override final; + void stop () noexcept override final; + + // + // Query operations + // + TransceiverState const& state () const {return actual_;} + +protected: + // + // Error exception which is thrown to signal unexpected errors. + // + struct error + : public std::runtime_error + { + explicit error (char const * const msg) : std::runtime_error (msg) {} + explicit error (QString const& msg) : std::runtime_error (msg.toStdString ()) {} + }; + + // Template methods that sub classes implement to do what they need to do. + // + // These methods may throw exceptions to signal errors. + virtual int do_start () = 0; // returns resolution, See Transceiver::resolution + virtual void do_post_start () {} + + virtual void do_stop () = 0; + virtual void do_post_stop () {} + + virtual void do_frequency (Frequency, MODE, bool no_ignore) = 0; + virtual void do_post_frequency (Frequency, MODE) {} + + virtual void do_tx_frequency (Frequency, MODE, bool no_ignore) = 0; + virtual void do_post_tx_frequency (Frequency, MODE) {} + + virtual void do_mode (MODE) = 0; + virtual void do_post_mode (MODE) {} + + virtual void do_ptt (bool = true) = 0; + virtual void do_post_ptt (bool = true) {} + + // this is the rig tuning -- use false if need to turn off tune -- do we need that for anyone? + virtual void do_audio (bool = false) {} + virtual void do_tune (bool = false) {} + virtual void do_period (double) {} + virtual void do_blocksize (qint32) {} + virtual void do_spread(double) {} + virtual void do_nsym(int) {} + virtual void do_trfrequency(double) {} + virtual void do_volume (qreal) {} + virtual void do_txvolume (qreal) {} + //parameters are MODE,symbolslength,framespersymbol,trfrequency,tonespacing,synchronize,FASTMODE,dbsdr,trperiod //parameters added by w3sz are in bold + virtual void do_modulator_start(QString, unsigned, double, double, double, bool, bool, double, double) {} + virtual void do_modulator_stop(bool) {} + + virtual bool do_pre_update () {return true;} + + // sub classes report rig state changes with these methods + void update_rx_frequency (Frequency); + void update_other_frequency (Frequency = 0); + void update_split (bool); + void update_mode (MODE); + void update_PTT (bool = true); + void update_level (int = 0); + void update_power (unsigned int = 0); + void update_swr (unsigned int = 0); + + // Calling this eventually triggers the Transceiver::update(State) signal. + void update_complete (bool force_signal = false); + + // sub class may asynchronously take the rig offline by calling this + void offline (QString const& reason); + +private: + void startup (); + void shutdown (); + bool maybe_low_resolution (Frequency low_res, Frequency high_res); + + // use this convenience class to notify in update methods + class may_update + { + public: + explicit may_update (TransceiverBase * self, bool force_signal = false) + : self_ {self} + , force_signal_ {force_signal} + {} + ~may_update () {self_->update_complete (force_signal_);} + private: + TransceiverBase * self_; + bool force_signal_; + }; + + TransceiverState requested_; + TransceiverState actual_; + TransceiverState last_; + unsigned last_sequence_number_; // from set state operation +}; + +// some loggimg macros +#define CAT_TRACE(MSG) LOG_LOG_LOCATION (logger (), trace, MSG) +#define CAT_DEBUG(MSG) LOG_LOG_LOCATION (logger (), debug, MSG) +#define CAT_INFO(MSG) LOG_LOG_LOCATION (logger (), info, MSG) +#define CAT_WARNING(MSG) LOG_LOG_LOCATION (logger (), warning, MSG) +#define CAT_ERROR(MSG) LOG_LOG_LOCATION (logger (), error, MSG) +#define CAT_FATAL(MSG) LOG_LOG_LOCATION (logger (), fatal, MSG) + +// some trace macros +#if WSJT_TRACE_CAT +#define TRACE_CAT(FAC, MSG) qDebug () << QString {"%1::%2:"}.arg ((FAC)).arg (__func__) << MSG +#else +#define TRACE_CAT(FAC, MSG) +#endif + +#if WSJT_TRACE_CAT && WSJT_TRACE_CAT_POLLS +#define TRACE_CAT_POLL(FAC, MSG) qDebug () << QString {"%1::%2:"}.arg ((FAC)).arg (__func__) << MSG +#else +#define TRACE_CAT_POLL(FAC, MSG) +#endif + + +#endif diff --git a/Transceiver/TransceiverFactory.cpp b/Transceiver/TransceiverFactory.cpp index 2146eac2..323a882a 100755..100644 --- a/Transceiver/TransceiverFactory.cpp +++ b/Transceiver/TransceiverFactory.cpp @@ -1,243 +1,243 @@ -#include "TransceiverFactory.hpp"
-
-#include <QMetaType>
-
-#include "HamlibTransceiver.hpp"
-#include "TCITransceiver.hpp"
-#include "DXLabSuiteCommanderTransceiver.hpp"
-#include "HRDTransceiver.hpp"
-#include "EmulateSplitTransceiver.hpp"
-
-#if defined (WIN32)
-#include "OmniRigTransceiver.hpp"
-#endif
-
-#include "moc_TransceiverFactory.cpp"
-
-// we use the hamlib "Hamlib Dummy" transceiver for non-CAT radios,
-// this allows us to still use the hamlib PTT control features for a
-// unified PTT control solution
-
-char const * const TransceiverFactory::basic_transceiver_name_ = "None";
-
-namespace
-{
- enum // supported non-hamlib radio interfaces
- {
- NonHamlibBaseId = 99899
- , TCI1Id
- , TCI2Id
- , CommanderId
- , HRDId
- , OmniRigOneId
- , OmniRigTwoId
- };
-}
-
-TransceiverFactory::TransceiverFactory ()
- : logger_ (boost::log::keywords::channel = "RIGCTRL")
-{
- HamlibTransceiver::register_transceivers (&logger_, &transceivers_);
- TCITransceiver::register_transceivers (&logger_, &transceivers_, TCI1Id, TCI2Id);
- DXLabSuiteCommanderTransceiver::register_transceivers (&logger_, &transceivers_, CommanderId);
- HRDTransceiver::register_transceivers (&logger_, &transceivers_, HRDId);
-
-#if defined (WIN32)
- // OmniRig is ActiveX/COM server so only on Windows
- OmniRigTransceiver::register_transceivers (&logger_, &transceivers_, OmniRigOneId, OmniRigTwoId);
-#endif
-}
-
-TransceiverFactory::~TransceiverFactory ()
-{
- HamlibTransceiver::unregister_transceivers ();
-}
-
-auto TransceiverFactory::supported_transceivers () const -> Transceivers const&
-{
- return transceivers_;
-}
-
-auto TransceiverFactory::CAT_port_type (QString const& name) const -> Capabilities::PortType
-{
- return supported_transceivers ()[name].port_type_;
-}
-
-bool TransceiverFactory::has_CAT_PTT (QString const& name) const
-{
- return
- supported_transceivers ()[name].has_CAT_PTT_
- || supported_transceivers ()[name].model_number_ > NonHamlibBaseId;
-}
-
-bool TransceiverFactory::has_CAT_PTT_mic_data (QString const& name) const
-{
- return supported_transceivers ()[name].has_CAT_PTT_mic_data_;
-}
-
-bool TransceiverFactory::has_CAT_indirect_serial_PTT (QString const& name) const
-{
- return supported_transceivers ()[name].has_CAT_indirect_serial_PTT_;
-}
-
-bool TransceiverFactory::has_asynchronous_CAT (QString const& name) const
-{
- return supported_transceivers ()[name].asynchronous_;
-}
-
-std::unique_ptr<Transceiver> TransceiverFactory::create (ParameterPack const& params, QThread * target_thread)
-{
- std::unique_ptr<Transceiver> result;
- switch (supported_transceivers ()[params.rig_name].model_number_)
- {
- case TCI1Id:
- {
- std::unique_ptr<TransceiverBase> basic_transceiver;
-
- // wrap the basic Transceiver object instance with a decorator object that talks to TCI Commander
- result.reset (new TCITransceiver {&logger_, std::move (basic_transceiver), "0", params.tci_port, PTT_method_CAT == params.ptt_type, params.poll_interval});
- if (target_thread)
- {
- result->moveToThread (target_thread);
- }
- }
- break;
-
- case TCI2Id:
- {
- std::unique_ptr<TransceiverBase> basic_transceiver;
-
- // wrap the basic Transceiver object instance with a decorator object that talks to TCI Commander
- result.reset (new TCITransceiver {&logger_, std::move (basic_transceiver), "1", params.tci_port, PTT_method_CAT == params.ptt_type, params.poll_interval});
- if (target_thread)
- {
- result->moveToThread (target_thread);
- }
- }
- break;
-
- case CommanderId:
- {
- std::unique_ptr<TransceiverBase> basic_transceiver;
- if (PTT_method_CAT != params.ptt_type)
- {
- // we start with a dummy HamlibTransceiver object instance that can support direct PTT
- basic_transceiver.reset (new HamlibTransceiver {&logger_, params.ptt_type, params.ptt_port});
- if (target_thread)
- {
- basic_transceiver.get ()->moveToThread (target_thread);
- }
- }
-
- // wrap the basic Transceiver object instance with a decorator object that talks to DX Lab Suite Commander
- result.reset (new DXLabSuiteCommanderTransceiver {&logger_, std::move (basic_transceiver), params.network_port, PTT_method_CAT == params.ptt_type, params.poll_interval});
- if (target_thread)
- {
- result->moveToThread (target_thread);
- }
- }
- break;
-
- case HRDId:
- {
- std::unique_ptr<TransceiverBase> basic_transceiver;
- if (PTT_method_CAT != params.ptt_type)
- {
- // we start with a dummy HamlibTransceiver object instance that can support direct PTT
- basic_transceiver.reset (new HamlibTransceiver {&logger_, params.ptt_type, params.ptt_port});
- if (target_thread)
- {
- basic_transceiver.get ()->moveToThread (target_thread);
- }
- }
-
- // wrap the basic Transceiver object instance with a decorator object that talks to ham Radio Deluxe
- result.reset (new HRDTransceiver {&logger_, std::move (basic_transceiver), params.network_port, PTT_method_CAT == params.ptt_type, params.audio_source, params.poll_interval});
- if (target_thread)
- {
- result->moveToThread (target_thread);
- }
- }
- break;
-
-#if defined (WIN32)
- case OmniRigOneId:
- {
- std::unique_ptr<TransceiverBase> basic_transceiver;
- if (PTT_method_CAT != params.ptt_type && "CAT" != params.ptt_port)
- {
- // we start with a dummy HamlibTransceiver object instance that can support direct PTT
- basic_transceiver.reset (new HamlibTransceiver {&logger_, params.ptt_type, params.ptt_port});
- if (target_thread)
- {
- basic_transceiver.get ()->moveToThread (target_thread);
- }
- }
-
- // wrap the basic Transceiver object instance with a decorator object that talks to OmniRig rig one
- result.reset (new OmniRigTransceiver {&logger_, std::move (basic_transceiver), OmniRigTransceiver::One, params.ptt_type, params.ptt_port});
- if (target_thread)
- {
- result->moveToThread (target_thread);
- }
- }
- break;
-
- case OmniRigTwoId:
- {
- std::unique_ptr<TransceiverBase> basic_transceiver;
- if (PTT_method_CAT != params.ptt_type && "CAT" != params.ptt_port)
- {
- // we start with a dummy HamlibTransceiver object instance that can support direct PTT
- basic_transceiver.reset (new HamlibTransceiver {&logger_, params.ptt_type, params.ptt_port});
- if (target_thread)
- {
- basic_transceiver.get ()->moveToThread (target_thread);
- }
- }
-
- // wrap the basic Transceiver object instance with a decorator object that talks to OmniRig rig two
- result.reset (new OmniRigTransceiver {&logger_, std::move (basic_transceiver), OmniRigTransceiver::Two, params.ptt_type, params.ptt_port});
- if (target_thread)
- {
- result->moveToThread (target_thread);
- }
- }
- break;
-#endif
-
- default:
- result.reset (new HamlibTransceiver {&logger_, supported_transceivers ()[params.rig_name].model_number_, params});
- if (target_thread)
- {
- result->moveToThread (target_thread);
- }
- break;
- }
-
- if (split_mode_emulate == params.split_mode)
- {
- // wrap the Transceiver object instance with a decorator that emulates split mode
- result.reset (new EmulateSplitTransceiver {&logger_, std::move (result)});
- if (target_thread)
- {
- result->moveToThread (target_thread);
- }
- }
-
- return result;
-}
-
-ENUM_QDATASTREAM_OPS_IMPL (TransceiverFactory, DataBits);
-ENUM_QDATASTREAM_OPS_IMPL (TransceiverFactory, StopBits);
-ENUM_QDATASTREAM_OPS_IMPL (TransceiverFactory, Handshake);
-ENUM_QDATASTREAM_OPS_IMPL (TransceiverFactory, PTTMethod);
-ENUM_QDATASTREAM_OPS_IMPL (TransceiverFactory, TXAudioSource);
-ENUM_QDATASTREAM_OPS_IMPL (TransceiverFactory, SplitMode);
-
-ENUM_CONVERSION_OPS_IMPL (TransceiverFactory, DataBits);
-ENUM_CONVERSION_OPS_IMPL (TransceiverFactory, StopBits);
-ENUM_CONVERSION_OPS_IMPL (TransceiverFactory, Handshake);
-ENUM_CONVERSION_OPS_IMPL (TransceiverFactory, PTTMethod);
-ENUM_CONVERSION_OPS_IMPL (TransceiverFactory, TXAudioSource);
-ENUM_CONVERSION_OPS_IMPL (TransceiverFactory, SplitMode);
+#include "TransceiverFactory.hpp" + +#include <QMetaType> + +#include "HamlibTransceiver.hpp" +#include "TCITransceiver.hpp" +#include "DXLabSuiteCommanderTransceiver.hpp" +#include "HRDTransceiver.hpp" +#include "EmulateSplitTransceiver.hpp" + +#if defined (WIN32) +#include "OmniRigTransceiver.hpp" +#endif + +#include "moc_TransceiverFactory.cpp" + +// we use the hamlib "Hamlib Dummy" transceiver for non-CAT radios, +// this allows us to still use the hamlib PTT control features for a +// unified PTT control solution + +char const * const TransceiverFactory::basic_transceiver_name_ = "None"; + +namespace +{ + enum // supported non-hamlib radio interfaces + { + NonHamlibBaseId = 99899 + , TCI1Id + , TCI2Id + , CommanderId + , HRDId + , OmniRigOneId + , OmniRigTwoId + }; +} + +TransceiverFactory::TransceiverFactory () + : logger_ (boost::log::keywords::channel = "RIGCTRL") +{ + HamlibTransceiver::register_transceivers (&logger_, &transceivers_); + TCITransceiver::register_transceivers (&logger_, &transceivers_, TCI1Id, TCI2Id); + DXLabSuiteCommanderTransceiver::register_transceivers (&logger_, &transceivers_, CommanderId); + HRDTransceiver::register_transceivers (&logger_, &transceivers_, HRDId); + +#if defined (WIN32) + // OmniRig is ActiveX/COM server so only on Windows + OmniRigTransceiver::register_transceivers (&logger_, &transceivers_, OmniRigOneId, OmniRigTwoId); +#endif +} + +TransceiverFactory::~TransceiverFactory () +{ + HamlibTransceiver::unregister_transceivers (); +} + +auto TransceiverFactory::supported_transceivers () const -> Transceivers const& +{ + return transceivers_; +} + +auto TransceiverFactory::CAT_port_type (QString const& name) const -> Capabilities::PortType +{ + return supported_transceivers ()[name].port_type_; +} + +bool TransceiverFactory::has_CAT_PTT (QString const& name) const +{ + return + supported_transceivers ()[name].has_CAT_PTT_ + || supported_transceivers ()[name].model_number_ > NonHamlibBaseId; +} + +bool TransceiverFactory::has_CAT_PTT_mic_data (QString const& name) const +{ + return supported_transceivers ()[name].has_CAT_PTT_mic_data_; +} + +bool TransceiverFactory::has_CAT_indirect_serial_PTT (QString const& name) const +{ + return supported_transceivers ()[name].has_CAT_indirect_serial_PTT_; +} + +bool TransceiverFactory::has_asynchronous_CAT (QString const& name) const +{ + return supported_transceivers ()[name].asynchronous_; +} + +std::unique_ptr<Transceiver> TransceiverFactory::create (ParameterPack const& params, QThread * target_thread) +{ + std::unique_ptr<Transceiver> result; + switch (supported_transceivers ()[params.rig_name].model_number_) + { + case TCI1Id: + { + std::unique_ptr<TransceiverBase> basic_transceiver; + + // wrap the basic Transceiver object instance with a decorator object that talks to TCI Commander + result.reset (new TCITransceiver {&logger_, std::move (basic_transceiver), "0", params.tci_port, PTT_method_CAT == params.ptt_type, params.poll_interval}); + if (target_thread) + { + result->moveToThread (target_thread); + } + } + break; + + case TCI2Id: + { + std::unique_ptr<TransceiverBase> basic_transceiver; + + // wrap the basic Transceiver object instance with a decorator object that talks to TCI Commander + result.reset (new TCITransceiver {&logger_, std::move (basic_transceiver), "1", params.tci_port, PTT_method_CAT == params.ptt_type, params.poll_interval}); + if (target_thread) + { + result->moveToThread (target_thread); + } + } + break; + + case CommanderId: + { + std::unique_ptr<TransceiverBase> basic_transceiver; + if (PTT_method_CAT != params.ptt_type) + { + // we start with a dummy HamlibTransceiver object instance that can support direct PTT + basic_transceiver.reset (new HamlibTransceiver {&logger_, params.ptt_type, params.ptt_port}); + if (target_thread) + { + basic_transceiver.get ()->moveToThread (target_thread); + } + } + + // wrap the basic Transceiver object instance with a decorator object that talks to DX Lab Suite Commander + result.reset (new DXLabSuiteCommanderTransceiver {&logger_, std::move (basic_transceiver), params.network_port, PTT_method_CAT == params.ptt_type, params.poll_interval}); + if (target_thread) + { + result->moveToThread (target_thread); + } + } + break; + + case HRDId: + { + std::unique_ptr<TransceiverBase> basic_transceiver; + if (PTT_method_CAT != params.ptt_type) + { + // we start with a dummy HamlibTransceiver object instance that can support direct PTT + basic_transceiver.reset (new HamlibTransceiver {&logger_, params.ptt_type, params.ptt_port}); + if (target_thread) + { + basic_transceiver.get ()->moveToThread (target_thread); + } + } + + // wrap the basic Transceiver object instance with a decorator object that talks to ham Radio Deluxe + result.reset (new HRDTransceiver {&logger_, std::move (basic_transceiver), params.network_port, PTT_method_CAT == params.ptt_type, params.audio_source, params.poll_interval}); + if (target_thread) + { + result->moveToThread (target_thread); + } + } + break; + +#if defined (WIN32) + case OmniRigOneId: + { + std::unique_ptr<TransceiverBase> basic_transceiver; + if (PTT_method_CAT != params.ptt_type && "CAT" != params.ptt_port) + { + // we start with a dummy HamlibTransceiver object instance that can support direct PTT + basic_transceiver.reset (new HamlibTransceiver {&logger_, params.ptt_type, params.ptt_port}); + if (target_thread) + { + basic_transceiver.get ()->moveToThread (target_thread); + } + } + + // wrap the basic Transceiver object instance with a decorator object that talks to OmniRig rig one + result.reset (new OmniRigTransceiver {&logger_, std::move (basic_transceiver), OmniRigTransceiver::One, params.ptt_type, params.ptt_port}); + if (target_thread) + { + result->moveToThread (target_thread); + } + } + break; + + case OmniRigTwoId: + { + std::unique_ptr<TransceiverBase> basic_transceiver; + if (PTT_method_CAT != params.ptt_type && "CAT" != params.ptt_port) + { + // we start with a dummy HamlibTransceiver object instance that can support direct PTT + basic_transceiver.reset (new HamlibTransceiver {&logger_, params.ptt_type, params.ptt_port}); + if (target_thread) + { + basic_transceiver.get ()->moveToThread (target_thread); + } + } + + // wrap the basic Transceiver object instance with a decorator object that talks to OmniRig rig two + result.reset (new OmniRigTransceiver {&logger_, std::move (basic_transceiver), OmniRigTransceiver::Two, params.ptt_type, params.ptt_port}); + if (target_thread) + { + result->moveToThread (target_thread); + } + } + break; +#endif + + default: + result.reset (new HamlibTransceiver {&logger_, supported_transceivers ()[params.rig_name].model_number_, params}); + if (target_thread) + { + result->moveToThread (target_thread); + } + break; + } + + if (split_mode_emulate == params.split_mode) + { + // wrap the Transceiver object instance with a decorator that emulates split mode + result.reset (new EmulateSplitTransceiver {&logger_, std::move (result)}); + if (target_thread) + { + result->moveToThread (target_thread); + } + } + + return result; +} + +ENUM_QDATASTREAM_OPS_IMPL (TransceiverFactory, DataBits); +ENUM_QDATASTREAM_OPS_IMPL (TransceiverFactory, StopBits); +ENUM_QDATASTREAM_OPS_IMPL (TransceiverFactory, Handshake); +ENUM_QDATASTREAM_OPS_IMPL (TransceiverFactory, PTTMethod); +ENUM_QDATASTREAM_OPS_IMPL (TransceiverFactory, TXAudioSource); +ENUM_QDATASTREAM_OPS_IMPL (TransceiverFactory, SplitMode); + +ENUM_CONVERSION_OPS_IMPL (TransceiverFactory, DataBits); +ENUM_CONVERSION_OPS_IMPL (TransceiverFactory, StopBits); +ENUM_CONVERSION_OPS_IMPL (TransceiverFactory, Handshake); +ENUM_CONVERSION_OPS_IMPL (TransceiverFactory, PTTMethod); +ENUM_CONVERSION_OPS_IMPL (TransceiverFactory, TXAudioSource); +ENUM_CONVERSION_OPS_IMPL (TransceiverFactory, SplitMode); diff --git a/Transceiver/TransceiverFactory.hpp b/Transceiver/TransceiverFactory.hpp index 220b333f..3d9390d8 100755..100644 --- a/Transceiver/TransceiverFactory.hpp +++ b/Transceiver/TransceiverFactory.hpp @@ -1,193 +1,193 @@ -#ifndef TRANSCEIVER_FACTORY_HPP__
-#define TRANSCEIVER_FACTORY_HPP__
-
-#include <memory>
-
-#include <boost/log/trivial.hpp>
-#include <boost/log/sources/severity_channel_logger.hpp>
-
-#include <QObject>
-#include <QMap>
-
-#include "Transceiver.hpp"
-
-#include "qt_helpers.hpp"
-
-class QString;
-class QThread;
-class QDir;
-
-//
-// Transceiver Factory
-//
-class TransceiverFactory
- : public QObject
-{
- Q_OBJECT
-
-public:
- //
- // Capabilities of a Transceiver that can be determined without
- // actually instantiating one, these are for use in Configuration
- // GUI behaviour determination
- //
- struct Capabilities
- {
- enum PortType {none, serial, network, usb, tci};
-
- explicit Capabilities (unsigned model_number = 0
- , PortType port_type = none
- , bool has_CAT_PTT = false
- , bool has_CAT_PTT_mic_data = false
- , bool has_CAT_indirect_serial_PTT = false
- , bool asynchronous = false)
- : model_number_ {model_number}
- , port_type_ {port_type}
- , has_CAT_PTT_ {has_CAT_PTT}
- , has_CAT_PTT_mic_data_ {has_CAT_PTT_mic_data}
- , has_CAT_indirect_serial_PTT_ {has_CAT_indirect_serial_PTT}
- , asynchronous_ {asynchronous}
- {
- }
-
- unsigned model_number_;
- PortType port_type_;
- bool has_CAT_PTT_;
- bool has_CAT_PTT_mic_data_;
- bool has_CAT_indirect_serial_PTT_; // OmniRig controls RTS/DTR via COM interface
- bool asynchronous_;
- };
-
- //
- // Dictionary of Transceiver types Capabilities
- //
- typedef QMap<QString, Capabilities> Transceivers;
-
- //
- // various Transceiver parameters
- //
- enum DataBits {seven_data_bits = 7, eight_data_bits, default_data_bits};
- Q_ENUM (DataBits)
- enum StopBits {one_stop_bit = 1, two_stop_bits, default_stop_bits};
- Q_ENUM (StopBits)
- enum Handshake {handshake_default, handshake_none, handshake_XonXoff, handshake_hardware};
- Q_ENUM (Handshake)
- enum PTTMethod {PTT_method_VOX, PTT_method_CAT, PTT_method_DTR, PTT_method_RTS};
- Q_ENUM (PTTMethod)
- enum TXAudioSource {TX_audio_source_front, TX_audio_source_rear};
- Q_ENUM (TXAudioSource)
- enum SplitMode {split_mode_none, split_mode_rig, split_mode_emulate};
- Q_ENUM (SplitMode)
-
- #define do__snr 0x10000
- #define do__pwr 0x20000
- #define rig__power 0x40000
- #define rig__power_off 0x80000
- #define tci__audio 0x100000
- #define tci__agcc 0x200000
- #define ptt__share 0x400000
-
- TransceiverFactory ();
- ~TransceiverFactory ();
-
- static char const * const basic_transceiver_name_; // dummy transceiver is basic model
-
- //
- // fetch all supported rigs as a list of name and model id
- //
- Transceivers const& supported_transceivers () const;
-
- // supported model queries
- Capabilities::PortType CAT_port_type (QString const& name) const; // how to talk to CAT
- bool has_CAT_PTT (QString const& name) const; // can be keyed via CAT
- bool has_CAT_PTT_mic_data (QString const& name) const; // Tx audio port is switchable via CAT
- bool has_CAT_indirect_serial_PTT (QString const& name) const; // Can PTT via CAT port use DTR or RTS (OmniRig for example)
- bool has_asynchronous_CAT (QString const& name) const; // CAT asynchronous rather than polled
-
- struct ParameterPack
- {
- QString rig_name; // from supported_transceivers () key
- QString serial_port; // serial port device name or empty
- QString network_port; // hostname:port or empty
- QString usb_port; // [vid[:pid[:vendor[:product]]]]
- QString tci_port; // hostname:port or empty
- int baud;
- DataBits data_bits;
- StopBits stop_bits;
- Handshake handshake;
- bool force_dtr;
- bool dtr_high; // to power interface
- bool force_rts;
- bool rts_high; // to power interface
- PTTMethod ptt_type; // "CAT" | "DTR" | "RTS" | "VOX"
- TXAudioSource audio_source; // some rigs allow audio routing
- // to Mic/Data connector
- SplitMode split_mode; // how to support split TX mode
- QString ptt_port; // serial port device name or special
- // value "CAT"
- int poll_interval; // in seconds for interfaces that
- // require polling for state changes
-
- bool operator == (ParameterPack const& rhs) const
- {
- return rhs.rig_name == rig_name
- && rhs.serial_port == serial_port
- && rhs.network_port == network_port
- && rhs.usb_port == usb_port
- && rhs.tci_port == tci_port
- && rhs.baud == baud
- && rhs.data_bits == data_bits
- && rhs.stop_bits == stop_bits
- && rhs.handshake == handshake
- && rhs.force_dtr == force_dtr
- && rhs.dtr_high == dtr_high
- && rhs.force_rts == force_rts
- && rhs.rts_high == rts_high
- && rhs.ptt_type == ptt_type
- && rhs.audio_source == audio_source
- && rhs.split_mode == split_mode
- && rhs.ptt_port == ptt_port
- && rhs.poll_interval == poll_interval
- ;
- }
- };
-
- // make a new Transceiver instance
- //
- // cat_port, cat_baud, cat_data_bits, cat_stop_bits, cat_handshake,
- // cat_dtr_control, cat_rts_control are only relevant to interfaces
- // that are served by Hamlib
- //
- // PTT port and to some extent ptt_type are independent of interface
- // type
- //
- std::unique_ptr<Transceiver> create (ParameterPack const&, QThread * target_thread = nullptr);
-
- //w3sz using logger_type = boost::log::sources::severity_channel_logger_mt<boost::log::trivial::severity_level>;
-
-private:
- Transceiver::logger_type mutable logger_;
- Transceivers transceivers_;
-};
-
-inline
-bool operator != (TransceiverFactory::ParameterPack const& lhs, TransceiverFactory::ParameterPack const& rhs)
-{
- return !(lhs == rhs);
-}
-
-ENUM_QDATASTREAM_OPS_DECL (TransceiverFactory, DataBits);
-ENUM_QDATASTREAM_OPS_DECL (TransceiverFactory, StopBits);
-ENUM_QDATASTREAM_OPS_DECL (TransceiverFactory, Handshake);
-ENUM_QDATASTREAM_OPS_DECL (TransceiverFactory, PTTMethod);
-ENUM_QDATASTREAM_OPS_DECL (TransceiverFactory, TXAudioSource);
-ENUM_QDATASTREAM_OPS_DECL (TransceiverFactory, SplitMode);
-
-ENUM_CONVERSION_OPS_DECL (TransceiverFactory, DataBits);
-ENUM_CONVERSION_OPS_DECL (TransceiverFactory, StopBits);
-ENUM_CONVERSION_OPS_DECL (TransceiverFactory, Handshake);
-ENUM_CONVERSION_OPS_DECL (TransceiverFactory, PTTMethod);
-ENUM_CONVERSION_OPS_DECL (TransceiverFactory, TXAudioSource);
-ENUM_CONVERSION_OPS_DECL (TransceiverFactory, SplitMode);
-
-#endif
+#ifndef TRANSCEIVER_FACTORY_HPP__ +#define TRANSCEIVER_FACTORY_HPP__ + +#include <memory> + +#include <boost/log/trivial.hpp> +#include <boost/log/sources/severity_channel_logger.hpp> + +#include <QObject> +#include <QMap> + +#include "Transceiver.hpp" + +#include "qt_helpers.hpp" + +class QString; +class QThread; +class QDir; + +// +// Transceiver Factory +// +class TransceiverFactory + : public QObject +{ + Q_OBJECT + +public: + // + // Capabilities of a Transceiver that can be determined without + // actually instantiating one, these are for use in Configuration + // GUI behaviour determination + // + struct Capabilities + { + enum PortType {none, serial, network, usb, tci}; + + explicit Capabilities (unsigned model_number = 0 + , PortType port_type = none + , bool has_CAT_PTT = false + , bool has_CAT_PTT_mic_data = false + , bool has_CAT_indirect_serial_PTT = false + , bool asynchronous = false) + : model_number_ {model_number} + , port_type_ {port_type} + , has_CAT_PTT_ {has_CAT_PTT} + , has_CAT_PTT_mic_data_ {has_CAT_PTT_mic_data} + , has_CAT_indirect_serial_PTT_ {has_CAT_indirect_serial_PTT} + , asynchronous_ {asynchronous} + { + } + + unsigned model_number_; + PortType port_type_; + bool has_CAT_PTT_; + bool has_CAT_PTT_mic_data_; + bool has_CAT_indirect_serial_PTT_; // OmniRig controls RTS/DTR via COM interface + bool asynchronous_; + }; + + // + // Dictionary of Transceiver types Capabilities + // + typedef QMap<QString, Capabilities> Transceivers; + + // + // various Transceiver parameters + // + enum DataBits {seven_data_bits = 7, eight_data_bits, default_data_bits}; + Q_ENUM (DataBits) + enum StopBits {one_stop_bit = 1, two_stop_bits, default_stop_bits}; + Q_ENUM (StopBits) + enum Handshake {handshake_default, handshake_none, handshake_XonXoff, handshake_hardware}; + Q_ENUM (Handshake) + enum PTTMethod {PTT_method_VOX, PTT_method_CAT, PTT_method_DTR, PTT_method_RTS}; + Q_ENUM (PTTMethod) + enum TXAudioSource {TX_audio_source_front, TX_audio_source_rear}; + Q_ENUM (TXAudioSource) + enum SplitMode {split_mode_none, split_mode_rig, split_mode_emulate}; + Q_ENUM (SplitMode) + + #define do__snr 0x10000 + #define do__pwr 0x20000 + #define rig__power 0x40000 + #define rig__power_off 0x80000 + #define tci__audio 0x100000 + #define tci__agcc 0x200000 + #define ptt__share 0x400000 + + TransceiverFactory (); + ~TransceiverFactory (); + + static char const * const basic_transceiver_name_; // dummy transceiver is basic model + + // + // fetch all supported rigs as a list of name and model id + // + Transceivers const& supported_transceivers () const; + + // supported model queries + Capabilities::PortType CAT_port_type (QString const& name) const; // how to talk to CAT + bool has_CAT_PTT (QString const& name) const; // can be keyed via CAT + bool has_CAT_PTT_mic_data (QString const& name) const; // Tx audio port is switchable via CAT + bool has_CAT_indirect_serial_PTT (QString const& name) const; // Can PTT via CAT port use DTR or RTS (OmniRig for example) + bool has_asynchronous_CAT (QString const& name) const; // CAT asynchronous rather than polled + + struct ParameterPack + { + QString rig_name; // from supported_transceivers () key + QString serial_port; // serial port device name or empty + QString network_port; // hostname:port or empty + QString usb_port; // [vid[:pid[:vendor[:product]]]] + QString tci_port; // hostname:port or empty + int baud; + DataBits data_bits; + StopBits stop_bits; + Handshake handshake; + bool force_dtr; + bool dtr_high; // to power interface + bool force_rts; + bool rts_high; // to power interface + PTTMethod ptt_type; // "CAT" | "DTR" | "RTS" | "VOX" + TXAudioSource audio_source; // some rigs allow audio routing + // to Mic/Data connector + SplitMode split_mode; // how to support split TX mode + QString ptt_port; // serial port device name or special + // value "CAT" + int poll_interval; // in seconds for interfaces that + // require polling for state changes + + bool operator == (ParameterPack const& rhs) const + { + return rhs.rig_name == rig_name + && rhs.serial_port == serial_port + && rhs.network_port == network_port + && rhs.usb_port == usb_port + && rhs.tci_port == tci_port + && rhs.baud == baud + && rhs.data_bits == data_bits + && rhs.stop_bits == stop_bits + && rhs.handshake == handshake + && rhs.force_dtr == force_dtr + && rhs.dtr_high == dtr_high + && rhs.force_rts == force_rts + && rhs.rts_high == rts_high + && rhs.ptt_type == ptt_type + && rhs.audio_source == audio_source + && rhs.split_mode == split_mode + && rhs.ptt_port == ptt_port + && rhs.poll_interval == poll_interval + ; + } + }; + + // make a new Transceiver instance + // + // cat_port, cat_baud, cat_data_bits, cat_stop_bits, cat_handshake, + // cat_dtr_control, cat_rts_control are only relevant to interfaces + // that are served by Hamlib + // + // PTT port and to some extent ptt_type are independent of interface + // type + // + std::unique_ptr<Transceiver> create (ParameterPack const&, QThread * target_thread = nullptr); + + //w3sz using logger_type = boost::log::sources::severity_channel_logger_mt<boost::log::trivial::severity_level>; + +private: + Transceiver::logger_type mutable logger_; + Transceivers transceivers_; +}; + +inline +bool operator != (TransceiverFactory::ParameterPack const& lhs, TransceiverFactory::ParameterPack const& rhs) +{ + return !(lhs == rhs); +} + +ENUM_QDATASTREAM_OPS_DECL (TransceiverFactory, DataBits); +ENUM_QDATASTREAM_OPS_DECL (TransceiverFactory, StopBits); +ENUM_QDATASTREAM_OPS_DECL (TransceiverFactory, Handshake); +ENUM_QDATASTREAM_OPS_DECL (TransceiverFactory, PTTMethod); +ENUM_QDATASTREAM_OPS_DECL (TransceiverFactory, TXAudioSource); +ENUM_QDATASTREAM_OPS_DECL (TransceiverFactory, SplitMode); + +ENUM_CONVERSION_OPS_DECL (TransceiverFactory, DataBits); +ENUM_CONVERSION_OPS_DECL (TransceiverFactory, StopBits); +ENUM_CONVERSION_OPS_DECL (TransceiverFactory, Handshake); +ENUM_CONVERSION_OPS_DECL (TransceiverFactory, PTTMethod); +ENUM_CONVERSION_OPS_DECL (TransceiverFactory, TXAudioSource); +ENUM_CONVERSION_OPS_DECL (TransceiverFactory, SplitMode); + +#endif |
