summaryrefslogtreecommitdiff
path: root/Transceiver
diff options
context:
space:
mode:
authorChristoph Berg <myon@debian.org>2026-09-26 23:24:28 +0200
committerChristoph Berg <myon@debian.org>2026-09-26 23:24:28 +0200
commit69344560ea394c06ca94acac46a2e4c3e8b7b229 (patch)
treeebc98370a697a9bbd6b973a14fa5113c475c6db7 /Transceiver
parent3e9d10a67671d0bd5c7b8c3ca8088f1818322eff (diff)
parent059831534c7e884f0a607ed86b582fd00d821731 (diff)
Update upstream source from tag 'upstream/3.2.0_rc1+dfsg'
Update to upstream version '3.2.0~rc1+dfsg' with Debian dir dbff457fd2c3616d5c77b863c7bfb2186ed86047
Diffstat (limited to 'Transceiver')
-rw-r--r--Transceiver/EmulateSplitTransceiver.cpp3
-rw-r--r--Transceiver/HamlibMode.cpp109
-rw-r--r--Transceiver/HamlibMode.hpp16
-rw-r--r--Transceiver/HamlibTransceiver.cpp245
-rw-r--r--Transceiver/HamlibTransceiver.hpp6
-rw-r--r--Transceiver/HamlibVfoRoleState.hpp43
-rw-r--r--Transceiver/TCIProtocol.hpp41
-rw-r--r--Transceiver/TCIStream.hpp170
-rw-r--r--Transceiver/TCITransceiver.cpp736
-rw-r--r--Transceiver/TCITransceiver.hpp116
-rw-r--r--Transceiver/Transceiver.cpp26
-rw-r--r--Transceiver/Transceiver.hpp86
-rw-r--r--Transceiver/TransceiverBase.cpp19
-rw-r--r--Transceiver/TransceiverBase.hpp5
-rw-r--r--Transceiver/TransceiverFactory.cpp10
-rw-r--r--Transceiver/TransceiverFactory.hpp6
-rw-r--r--Transceiver/TxInhibitTransceiver.cpp255
-rw-r--r--Transceiver/TxInhibitTransceiver.hpp67
18 files changed, 1457 insertions, 502 deletions
diff --git a/Transceiver/EmulateSplitTransceiver.cpp b/Transceiver/EmulateSplitTransceiver.cpp
index e7971fef..942ce088 100644
--- a/Transceiver/EmulateSplitTransceiver.cpp
+++ b/Transceiver/EmulateSplitTransceiver.cpp
@@ -18,7 +18,10 @@ EmulateSplitTransceiver::EmulateSplitTransceiver (logger_type * logger,
// parent matching signals.
connect (wrapped_.get (), &Transceiver::resolution, this, &Transceiver::resolution);
connect (wrapped_.get (), &Transceiver::tciframeswritten, this, &Transceiver::tciframeswritten);
+ connect (wrapped_.get (), &Transceiver::receiveAudio, this, &Transceiver::receiveAudio);
connect (wrapped_.get (), &Transceiver::tci_mod_active, this, &Transceiver::tci_mod_active);
+ connect (wrapped_.get (), &Transceiver::txSourceCommitted, this, &Transceiver::txSourceCommitted);
+ connect (wrapped_.get (), &Transceiver::rawTxPlayoutSnapshot, this, &Transceiver::rawTxPlayoutSnapshot);
connect (wrapped_.get (), &Transceiver::finished, this, &Transceiver::finished);
connect (wrapped_.get (), &Transceiver::failure, this, &Transceiver::failure);
}
diff --git a/Transceiver/HamlibMode.cpp b/Transceiver/HamlibMode.cpp
new file mode 100644
index 00000000..dd7ce6a4
--- /dev/null
+++ b/Transceiver/HamlibMode.cpp
@@ -0,0 +1,109 @@
+#include "HamlibMode.hpp"
+
+namespace HamlibMode
+{
+ auto from_hamlib (rmode_t mode) -> Transceiver::MODE
+ {
+ switch (mode)
+ {
+ case RIG_MODE_AM:
+ case RIG_MODE_SAM:
+ case RIG_MODE_AMS:
+ case RIG_MODE_DSB:
+ return Transceiver::AM;
+
+ case RIG_MODE_CW:
+ return Transceiver::CW;
+
+ case RIG_MODE_CWR:
+ return Transceiver::CW_R;
+
+ case RIG_MODE_USB:
+ case RIG_MODE_ECSSUSB:
+ case RIG_MODE_SAH:
+ case RIG_MODE_FAX:
+ return Transceiver::USB;
+
+ case RIG_MODE_LSB:
+ case RIG_MODE_ECSSLSB:
+ case RIG_MODE_SAL:
+ return Transceiver::LSB;
+
+ case RIG_MODE_RTTY:
+ return Transceiver::FSK;
+
+ case RIG_MODE_RTTYR:
+ return Transceiver::FSK_R;
+
+ case RIG_MODE_PKTLSB:
+ case RIG_MODE_LSBD1:
+ case RIG_MODE_LSBD2:
+ case RIG_MODE_LSBD3:
+ return Transceiver::DIG_L;
+
+ case RIG_MODE_PKTUSB:
+ case RIG_MODE_USBD1:
+ case RIG_MODE_USBD2:
+ case RIG_MODE_USBD3:
+ return Transceiver::DIG_U;
+
+ case RIG_MODE_FM:
+ case RIG_MODE_WFM:
+ return Transceiver::FM;
+
+ case RIG_MODE_PKTFM:
+ return Transceiver::DIG_FM;
+
+ default:
+ return Transceiver::UNK;
+ }
+ }
+
+ rmode_t to_hamlib (Transceiver::MODE mode)
+ {
+ switch (mode)
+ {
+ case Transceiver::AM: return RIG_MODE_AM;
+ case Transceiver::CW: return RIG_MODE_CW;
+ case Transceiver::CW_R: return RIG_MODE_CWR;
+ case Transceiver::USB: return RIG_MODE_USB;
+ case Transceiver::LSB: return RIG_MODE_LSB;
+ case Transceiver::FSK: return RIG_MODE_RTTY;
+ case Transceiver::FSK_R: return RIG_MODE_RTTYR;
+ case Transceiver::DIG_L: return RIG_MODE_PKTLSB;
+ case Transceiver::DIG_U: return RIG_MODE_PKTUSB;
+ case Transceiver::FM: return RIG_MODE_FM;
+ case Transceiver::DIG_FM: return RIG_MODE_PKTFM;
+ default: break;
+ }
+ return RIG_MODE_USB;
+ }
+
+ bool satisfies_request (rmode_t requested, rmode_t current)
+ {
+ if (requested == current)
+ {
+ return true;
+ }
+
+ if (RIG_MODE_PKTUSB == requested)
+ {
+ return RIG_MODE_USBD1 == current || RIG_MODE_USBD2 == current
+ || RIG_MODE_USBD3 == current;
+ }
+
+ if (RIG_MODE_PKTLSB == requested)
+ {
+ return RIG_MODE_LSBD1 == current || RIG_MODE_LSBD2 == current
+ || RIG_MODE_LSBD3 == current;
+ }
+
+ return false;
+ }
+
+ bool change_required (Transceiver::MODE requested, rmode_t current)
+ {
+ return Transceiver::UNK != requested
+ && !satisfies_request (to_hamlib (requested), current);
+ }
+}
diff --git a/Transceiver/HamlibMode.hpp b/Transceiver/HamlibMode.hpp
new file mode 100644
index 00000000..5bebf26a
--- /dev/null
+++ b/Transceiver/HamlibMode.hpp
@@ -0,0 +1,16 @@
+#ifndef HAMLIB_MODE_HPP_
+#define HAMLIB_MODE_HPP_
+
+#include <hamlib/rig.h>
+
+#include "Transceiver.hpp"
+
+namespace HamlibMode
+{
+ Transceiver::MODE from_hamlib (rmode_t);
+ rmode_t to_hamlib (Transceiver::MODE);
+ bool satisfies_request (rmode_t requested, rmode_t current);
+ bool change_required (Transceiver::MODE requested, rmode_t current);
+}
+
+#endif
diff --git a/Transceiver/HamlibTransceiver.cpp b/Transceiver/HamlibTransceiver.cpp
index 99b31f5c..2dde9459 100644
--- a/Transceiver/HamlibTransceiver.cpp
+++ b/Transceiver/HamlibTransceiver.cpp
@@ -1,4 +1,5 @@
#include "HamlibTransceiver.hpp"
+#include "HamlibMode.hpp"
#include <cstring>
#include <cmath>
@@ -13,6 +14,13 @@
#include <QJsonValue>
#include <QDebug>
#include <hamlib/rig.h>
+#ifndef HAMLIB_PTTPORT
+#include <hamlib/port.h>
+#endif
+#ifndef HAMLIB_STATE
+#include <hamlib/rig_state.h>
+#endif
+#include "HamlibVfoRoleState.hpp"
#include "pimpl_impl.hpp"
#include "moc_HamlibTransceiver.cpp"
@@ -22,6 +30,32 @@
namespace
{
+ int vfo_list (RIG * rig)
+ {
+ return HAMLIB_STATE (rig)->vfo_list;
+ }
+
+ bool has_vfo (RIG * rig, vfo_t vfo)
+ {
+ return vfo_list (rig) & vfo;
+ }
+
+ vfo_t rx_vfo (RIG * rig)
+ {
+ return has_vfo (rig, RIG_VFO_A) ? RIG_VFO_A : RIG_VFO_MAIN;
+ }
+
+ vfo_t tx_vfo (RIG * rig)
+ {
+ return has_vfo (rig, RIG_VFO_B) ? RIG_VFO_B : RIG_VFO_SUB;
+ }
+
+ bool ptt_port_configured (RIG * rig)
+ {
+ auto ptt_port = HAMLIB_PTTPORT (rig);
+ return ptt_port && RIG_PTT_NONE != ptt_port->type.ptt;
+ }
+
// 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
@@ -116,13 +150,13 @@ namespace
hamlib_tx_vfo_fixup (RIG * rig, vfo_t tx_vfo)
: rig_ {rig}
{
- original_vfo_ = rig_->state.tx_vfo;
- rig_->state.tx_vfo = tx_vfo;
+ original_vfo_ = HAMLIB_STATE (rig_)->tx_vfo;
+ HAMLIB_STATE (rig_)->tx_vfo = tx_vfo;
}
~hamlib_tx_vfo_fixup ()
{
- rig_->state.tx_vfo = original_vfo_;
+ HAMLIB_STATE (rig_)->tx_vfo = original_vfo_;
}
private:
@@ -142,7 +176,6 @@ public:
, back_ptt_port_ {false}
, one_VFO_ {false}
, is_dummy_ {true}
- , reversed_ {false}
, freq_query_works_ {true}
, mode_query_works_ {true}
, split_query_works_ {true}
@@ -165,7 +198,6 @@ public:
, 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)}
@@ -189,7 +221,7 @@ public:
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;
+ std::tuple<vfo_t, vfo_t> get_vfos (bool for_split, bool split_ptt_active) const;
HamlibTransceiver::logger_type mutable * logger_;
unsigned model_;
@@ -206,7 +238,7 @@ public:
static freq_t dummy_frequency_;
static rmode_t dummy_mode_;
- bool mutable reversed_;
+ HamlibVfoRoleState mutable vfo_roles_;
bool freq_query_works_;
bool mode_query_works_;
@@ -283,7 +315,7 @@ void HamlibTransceiver::impl::error_check (int ret_code, QString const& doing) c
}
}
-std::tuple<vfo_t, vfo_t> HamlibTransceiver::impl::get_vfos (bool for_split) const
+std::tuple<vfo_t, vfo_t> HamlibTransceiver::impl::get_vfos (bool for_split, bool split_ptt_active) const
{
if (get_vfo_works_ && rig_get_function_ptr (model_, RIG_FUNCTION_GET_VFO))
{
@@ -291,7 +323,7 @@ std::tuple<vfo_t, vfo_t> HamlibTransceiver::impl::get_vfos (bool for_split) cons
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;
+ vfo_roles_.observe_active_vfo (v, split_ptt_active);
}
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))
{
@@ -300,22 +332,22 @@ std::tuple<vfo_t, vfo_t> HamlibTransceiver::impl::get_vfos (bool for_split) cons
// 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"));
+ error_check (rig_set_vfo (rig_.data (), rx_vfo (rig_.data ())), 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 rx_vfo = ::rx_vfo (rig_.data ());
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)
+ ? ::tx_vfo (rig_.data ())
: rx_vfo;
- if (reversed_)
+ if (vfo_roles_.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);
+ auto vfos = vfo_roles_.resolve (rx_vfo, tx_vfo);
+ CAT_TRACE ("RX VFO=" << rig_strvfo (std::get<0> (vfos)) << " TX VFO=" << rig_strvfo (std::get<1> (vfos)));
+ return vfos;
}
void HamlibTransceiver::impl::set_conf (char const * item, char const * value)
@@ -333,82 +365,15 @@ QByteArray HamlibTransceiver::impl::get_conf (char const * 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
+#if HAVE_HAMLIB_GET_CONF2
+ error_check (rig_get_conf2 (rig_.data (), token, value.data (), value.length ()), tr ("getting a configuration item"));
+#else
+ error_check (rig_get_conf (rig_.data (), token, value.data ()), tr ("getting a configuration item"));
+#endif
}
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)
@@ -467,9 +432,6 @@ HamlibTransceiver::HamlibTransceiver (logger_type * logger,
{
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);
@@ -645,7 +607,7 @@ int HamlibTransceiver::do_start ()
// reset dynamic state
m_->one_VFO_ = false;
- m_->reversed_ = false;
+ m_->vfo_roles_.reset ();
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);
@@ -665,7 +627,7 @@ int HamlibTransceiver::do_start ()
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)
+ if (has_vfo (m_->rig_.data (), RIG_VFO_B))
{
m_->one_VFO_ = true;
}
@@ -706,7 +668,7 @@ int HamlibTransceiver::do_start ()
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);
+ rc = rig_set_vfo (m_->rig_.data (), tx_vfo (m_->rig_.data ()));
if (-RIG_ENAVAIL == rc || -RIG_ENIMPL == rc)
{
// if we are talking to netrigctl then toggle VFO op
@@ -749,7 +711,7 @@ int HamlibTransceiver::do_start ()
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"));
+ m_->error_check (rig_set_vfo (m_->rig_.data (), rx_vfo (m_->rig_.data ())), tr ("setting current VFO"));
}
if (f1 != f2 || m != mb || w != wb) // we must have started with MAIN/A
@@ -783,7 +745,7 @@ int HamlibTransceiver::do_start ()
CAT_TRACE ("rig_get_vfo current VFO=" << rig_strvfo (v));
}
- m_->reversed_ = RIG_VFO_B == v;
+ m_->vfo_roles_.observe_active_vfo (v, false);
if (m_->mode_query_works_ && !(rig_get_caps_int (m_->model_, RIG_CAPS_TARGETABLE_VFO) & RIG_TARGETABLE_MODE))
{
@@ -801,7 +763,7 @@ int HamlibTransceiver::do_start ()
}
}
}
- update_mode (m_->map_mode (m));
+ update_mode (HamlibMode::from_hamlib (m));
}
m_->tickle_hamlib_ = true;
@@ -815,7 +777,7 @@ int HamlibTransceiver::do_start ()
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_));
+ update_mode (HamlibMode::from_hamlib (impl::dummy_mode_));
}
}
@@ -873,7 +835,7 @@ int HamlibTransceiver::do_start ()
do_poll ();
- CAT_TRACE ("finished start " << state () << " reversed=" << m_->reversed_ << " resolution=" << resolution);
+ CAT_TRACE ("finished start " << state () << " reversed=" << m_->vfo_roles_.reversed () << " resolution=" << resolution);
return resolution;
}
@@ -894,12 +856,12 @@ void HamlibTransceiver::do_stop ()
rig_close (m_->rig_.data ());
}
- CAT_TRACE ("state: " << state () << " reversed=" << m_->reversed_);
+ CAT_TRACE ("state: " << state () << " reversed=" << m_->vfo_roles_.reversed ());
}
void HamlibTransceiver::do_frequency (Frequency f, MODE m, bool no_ignore)
{
- CAT_TRACE ("f: " << f << " mode: " << m << " reversed: " << m_->reversed_);
+ CAT_TRACE ("f: " << f << " mode: " << m << " reversed: " << m_->vfo_roles_.reversed ());
// only change when receiving or simplex or direct VFO addressing
// unavailable or forced
@@ -908,7 +870,7 @@ void HamlibTransceiver::do_frequency (Frequency f, MODE m, bool 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))
+ if (!has_vfo (m_->rig_.data (), RIG_VFO_B))
{
target_vfo = RIG_VFO_MAIN; // no VFO A/B so force to Rx on MAIN
}
@@ -919,11 +881,11 @@ void HamlibTransceiver::do_frequency (Frequency f, MODE m, bool no_ignore)
{
rmode_t current_mode;
pbwidth_t current_width;
- auto new_mode = m_->map_mode (m);
+ auto new_mode = HamlibMode::to_hamlib (m);
m_->error_check (rig_get_mode (m_->rig_.data (), target_vfo, &current_mode, &current_width), tr ("getting current VFO mode"));
CAT_TRACE ("rig_get_mode mode=" << rig_strrmode (current_mode) << " bw=" << current_width);
- if (new_mode != current_mode)
+ if (HamlibMode::change_required (m, 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"));
@@ -938,7 +900,16 @@ void HamlibTransceiver::do_frequency (Frequency f, MODE m, bool no_ignore)
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");
+ if (state ().split ())
+ {
+ rmode_t tx_mode;
+ pbwidth_t tx_width;
+ auto rc = rig_get_mode (m_->rig_.data (), RIG_VFO_B, &tx_mode, &tx_width);
+ if (RIG_OK != rc || HamlibMode::change_required (m, tx_mode))
+ {
+ rig_set_mode (m_->rig_.data (), RIG_VFO_B, new_mode, RIG_PASSBAND_NOCHANGE);
+ }
+ }
update_mode (m);
}
}
@@ -946,12 +917,12 @@ void HamlibTransceiver::do_frequency (Frequency f, MODE m, bool no_ignore)
void HamlibTransceiver::do_tx_frequency (Frequency tx, MODE mode, bool no_ignore)
{
- CAT_TRACE ("txf: " << tx << " reversed: " << m_->reversed_);
+ CAT_TRACE ("txf: " << tx << " reversed: " << m_->vfo_roles_.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 vfos = m_->get_vfos (tx, state ().ptt () && state ().split ());
// auto rx_vfo = std::get<0> (vfos); // or use RIG_VFO_CURR
auto tx_vfo = std::get<1> (vfos);
@@ -999,11 +970,11 @@ void HamlibTransceiver::do_tx_frequency (Frequency tx, MODE mode, bool no_ignore
{
rmode_t current_mode;
pbwidth_t current_width;
- auto new_mode = m_->map_mode (mode);
+ auto new_mode = HamlibMode::to_hamlib (mode);
m_->error_check (rig_get_mode (m_->rig_.data (), RIG_VFO_CURR, &current_mode, &current_width), tr ("getting current VFO mode"));
CAT_TRACE ("rig_get_mode mode=" << rig_strrmode (current_mode) << " bw=" << current_width);
- if (new_mode != current_mode)
+ if (HamlibMode::change_required (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"));
@@ -1016,7 +987,22 @@ void HamlibTransceiver::do_tx_frequency (Frequency tx, MODE mode, bool no_ignore
hamlib_tx_vfo_fixup fixup (m_->rig_.data (), tx_vfo);
if (UNK != mode)
{
- auto new_mode = m_->map_mode (mode);
+ auto new_mode = HamlibMode::to_hamlib (mode);
+ rmode_t current_mode;
+ pbwidth_t current_width;
+ int rc;
+ if (state ().split ())
+ {
+ rc = rig_get_split_mode (m_->rig_.data (), RIG_VFO_CURR, &current_mode, &current_width);
+ }
+ else
+ {
+ rc = rig_get_mode (m_->rig_.data (), tx_vfo, &current_mode, &current_width);
+ }
+ if (RIG_OK == rc && HamlibMode::satisfies_request (new_mode, current_mode))
+ {
+ new_mode = current_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"));
@@ -1061,16 +1047,16 @@ void HamlibTransceiver::do_mode (MODE mode)
{
CAT_TRACE (mode);
- auto vfos = m_->get_vfos (state ().split ());
+ auto vfos = m_->get_vfos (state ().split (), state ().ptt () && 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);
+ auto new_mode = HamlibMode::to_hamlib (mode);
vfo_t target_vfo = RIG_VFO_CURR;
- if (!(m_->rig_->state.vfo_list & RIG_VFO_B))
+ if (!has_vfo (m_->rig_.data (), RIG_VFO_B))
{
target_vfo = RIG_VFO_MAIN; // no VFO A/B so force to Rx on MAIN
}
@@ -1081,7 +1067,7 @@ void HamlibTransceiver::do_mode (MODE mode)
m_->error_check (rig_get_mode (m_->rig_.data (), target_vfo, &current_mode, &current_width), tr ("getting current VFO mode"));
CAT_TRACE ("rig_get_mode mode=" << rig_strrmode (current_mode) << " bw=" << current_width);
- if (new_mode != current_mode)
+ if (HamlibMode::change_required (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"));
@@ -1094,7 +1080,7 @@ void HamlibTransceiver::do_mode (MODE mode)
m_->error_check (rig_get_mode (m_->rig_.data (), RIG_VFO_CURR, &current_mode, &current_width), tr ("getting current VFO mode"));
CAT_TRACE ("rig_get_mode mode=" << rig_strrmode (current_mode) << " bw=" << current_width);
- if (new_mode != current_mode)
+ if (HamlibMode::change_required (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"));
@@ -1105,7 +1091,7 @@ void HamlibTransceiver::do_mode (MODE mode)
m_->error_check (rig_get_split_mode (m_->rig_.data (), RIG_VFO_CURR, &current_mode, &current_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)
+ if (HamlibMode::change_required (mode, current_mode))
{
CAT_TRACE ("rig_set_split_mode mode=" << rig_strrmode (new_mode));
hamlib_tx_vfo_fixup fixup (m_->rig_.data (), tx_vfo);
@@ -1127,7 +1113,7 @@ void HamlibTransceiver::do_poll ()
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;
+ m_->vfo_roles_.observe_active_vfo (v, state ().ptt () && state ().split ());
}
if ((WSJT_RIG_NONE_CAN_SPLIT || !m_->is_dummy_)
@@ -1139,10 +1125,6 @@ void HamlibTransceiver::do_poll ()
{
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
{
@@ -1181,11 +1163,8 @@ void HamlibTransceiver::do_poll ()
// 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"));
+ auto vfos = m_->vfo_roles_.resolve (rx_vfo (m_->rig_.data ()), tx_vfo (m_->rig_.data ()));
+ m_->error_check (rig_get_freq (m_->rig_.data (), std::get<1> (vfos), &f), tr ("getting other VFO frequency"));
f = std::round (f);
CAT_TRACE ("rig_get_freq other VFO=" << f);
update_other_frequency (f);
@@ -1206,7 +1185,7 @@ void HamlibTransceiver::do_poll ()
if (RIG_OK == rc)
{
CAT_TRACE ("rig_get_mode mode=" << rig_strrmode (m) << " bw=" << w);
- update_mode (m_->map_mode (m));
+ update_mode (HamlibMode::from_hamlib (m));
}
else
{
@@ -1214,7 +1193,7 @@ void HamlibTransceiver::do_poll ()
}
}
- if (RIG_PTT_NONE != m_->rig_->state.pttport.type.ptt && rig_get_function_ptr (m_->model_, RIG_FUNCTION_GET_PTT))
+ if (ptt_port_configured (m_->rig_.data ()) && 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);
@@ -1281,10 +1260,10 @@ void HamlibTransceiver::do_poll ()
void HamlibTransceiver::do_ptt (bool on)
{
- CAT_TRACE ("PTT: " << on << " " << state () << " reversed=" << m_->reversed_);
+ CAT_TRACE ("PTT: " << on << " " << state () << " reversed=" << m_->vfo_roles_.reversed ());
if (on)
{
- if (RIG_PTT_NONE != m_->rig_->state.pttport.type.ptt)
+ if (ptt_port_configured (m_->rig_.data ()))
{
ptt_on_ = true;
CAT_TRACE ("rig_set_ptt PTT=true");
@@ -1296,7 +1275,7 @@ void HamlibTransceiver::do_ptt (bool on)
}
else
{
- if (RIG_PTT_NONE != m_->rig_->state.pttport.type.ptt)
+ if (ptt_port_configured (m_->rig_.data ()))
{
ptt_on_ = false;
CAT_TRACE ("rig_set_ptt PTT=false");
@@ -1313,7 +1292,7 @@ void HamlibTransceiver::do_tune (bool on)
CAT_TRACE ("Tune: " << on << " " << state ());
if (on)
{
- if (RIG_PTT_NONE != m_->rig_->state.pttport.type.ptt)
+ if (ptt_port_configured (m_->rig_.data ()))
{
update_PTT (true); // we'll change the PTT button while we do this
CAT_TRACE ("rig_vfo_opt RIG_VFO_OP_TUNE=" << on);
@@ -1325,7 +1304,7 @@ void HamlibTransceiver::do_tune (bool on)
#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)
+ if (ptt_port_configured (m_->rig_.data ()))
{
ptt_on_ = false;
CAT_TRACE ("rig_set_ptt PTT=false");
diff --git a/Transceiver/HamlibTransceiver.hpp b/Transceiver/HamlibTransceiver.hpp
index 101cbb9d..9300f64d 100644
--- a/Transceiver/HamlibTransceiver.hpp
+++ b/Transceiver/HamlibTransceiver.hpp
@@ -36,9 +36,9 @@ private:
void do_poll () override;
bool ptt_on_ = false;
- bool do_pwr_;
- bool do_pwr2_;
- bool do_swr_;
+ bool do_pwr_ = false;
+ bool do_pwr2_= false;
+ bool do_swr_ = false;
class impl;
pimpl<impl> m_;
diff --git a/Transceiver/HamlibVfoRoleState.hpp b/Transceiver/HamlibVfoRoleState.hpp
new file mode 100644
index 00000000..c74d0ddf
--- /dev/null
+++ b/Transceiver/HamlibVfoRoleState.hpp
@@ -0,0 +1,43 @@
+#ifndef HAMLIB_VFO_ROLE_STATE_HPP_
+#define HAMLIB_VFO_ROLE_STATE_HPP_
+
+#include <tuple>
+#include <utility>
+
+#include <hamlib/rig.h>
+
+class HamlibVfoRoleState final
+{
+public:
+ void reset () noexcept
+ {
+ reversed_ = false;
+ }
+
+ void observe_active_vfo (vfo_t active_vfo, bool split_ptt_active) noexcept
+ {
+ if (!split_ptt_active)
+ {
+ reversed_ = RIG_VFO_B == active_vfo;
+ }
+ }
+
+ std::tuple<vfo_t, vfo_t> resolve (vfo_t rx_vfo, vfo_t tx_vfo) const noexcept
+ {
+ if (reversed_)
+ {
+ std::swap (rx_vfo, tx_vfo);
+ }
+ return std::make_tuple (rx_vfo, tx_vfo);
+ }
+
+ bool reversed () const noexcept
+ {
+ return reversed_;
+ }
+
+private:
+ bool reversed_ {false};
+};
+
+#endif
diff --git a/Transceiver/TCIProtocol.hpp b/Transceiver/TCIProtocol.hpp
new file mode 100644
index 00000000..9dd2b3dd
--- /dev/null
+++ b/Transceiver/TCIProtocol.hpp
@@ -0,0 +1,41 @@
+#ifndef TCI_PROTOCOL_HPP__
+#define TCI_PROTOCOL_HPP__
+
+#include <QString>
+#include <QtGlobal>
+
+namespace TciProtocol
+{
+ inline bool parse_frequency (QString const& text, quint64 * frequency)
+ {
+ if (!frequency || text.isEmpty ())
+ {
+ return false;
+ }
+
+ for (auto const character : text)
+ {
+ if (character < QLatin1Char {'0'} || character > QLatin1Char {'9'})
+ {
+ return false;
+ }
+ }
+
+ bool ok {false};
+ auto const parsed = text.toULongLong (&ok, 10);
+ if (!ok)
+ {
+ return false;
+ }
+
+ *frequency = parsed;
+ return true;
+ }
+
+ inline bool frequency_difference_exceeds (quint64 lhs, quint64 rhs, quint64 threshold)
+ {
+ return lhs > rhs ? lhs - rhs > threshold : rhs - lhs > threshold;
+ }
+}
+
+#endif
diff --git a/Transceiver/TCIStream.hpp b/Transceiver/TCIStream.hpp
new file mode 100644
index 00000000..5fbb468e
--- /dev/null
+++ b/Transceiver/TCIStream.hpp
@@ -0,0 +1,170 @@
+#ifndef TCI_STREAM_HPP__
+#define TCI_STREAM_HPP__
+
+#include <cstddef>
+#include <limits>
+
+#include <QByteArray>
+#include <QString>
+#include <QVersionNumber>
+#include <QtGlobal>
+
+namespace TciStream
+{
+ quint32 constexpr HeaderSize {16u * sizeof (quint32)};
+ quint32 constexpr MaxFloatSamples {8192u};
+ quint32 constexpr Float32Format {3u};
+ quint32 constexpr UncompressedCodec {0u};
+ quint32 constexpr DefaultChannels {2u};
+
+ struct Header
+ {
+ quint32 receiver;
+ quint32 sampleRate;
+ quint32 format;
+ quint32 codec;
+ quint32 crc;
+ quint32 length;
+ quint32 type;
+ quint32 channels;
+ quint32 reserved[8];
+ };
+
+ static_assert (sizeof (Header) == HeaderSize, "TCI stream header must be 64 bytes");
+ static_assert (offsetof (Header, length) == 20u, "TCI length field offset changed");
+ static_assert (offsetof (Header, type) == 24u, "TCI type field offset changed");
+ static_assert (offsetof (Header, channels) == 28u, "TCI channels field offset changed");
+ static_assert (sizeof (float) == 4u, "TCI float32 streams require 32-bit float");
+
+ enum StreamType : quint32
+ {
+ IqStream = 0u,
+ RxAudioStream,
+ TxAudioStream,
+ TxChrono,
+ };
+
+ inline bool checked_float_frame_size (quint32 scalar_count, int * size)
+ {
+ if (!size || scalar_count > MaxFloatSamples)
+ {
+ return false;
+ }
+
+ auto const payload_bytes = static_cast<quint64> (scalar_count) * sizeof (float);
+ auto const frame_bytes = static_cast<quint64> (HeaderSize) + payload_bytes;
+ if (frame_bytes > static_cast<quint64> ((std::numeric_limits<int>::max) ()))
+ {
+ return false;
+ }
+
+ *size = static_cast<int> (frame_bytes);
+ return true;
+ }
+
+ inline bool prepare_float_frame (QByteArray * frame, quint32 scalar_count)
+ {
+ int frame_size;
+ if (!frame || !checked_float_frame_size (scalar_count, &frame_size))
+ {
+ return false;
+ }
+
+ frame->resize (frame_size);
+ frame->fill ('\0');
+ return true;
+ }
+
+ inline Header * header (QByteArray * frame)
+ {
+ return frame && frame->size () >= static_cast<int> (HeaderSize)
+ ? reinterpret_cast<Header *> (frame->data ()) : nullptr;
+ }
+
+ inline Header const * header (QByteArray const& frame)
+ {
+ return frame.size () >= static_cast<int> (HeaderSize)
+ ? reinterpret_cast<Header const *> (frame.constData ()) : nullptr;
+ }
+
+ inline float * float_payload (QByteArray * frame)
+ {
+ return header (frame)
+ ? reinterpret_cast<float *> (frame->data () + HeaderSize) : nullptr;
+ }
+
+ inline float const * float_payload (QByteArray const& frame)
+ {
+ return header (frame)
+ ? reinterpret_cast<float const *> (frame.constData () + HeaderSize) : nullptr;
+ }
+
+ inline bool has_complete_float_payload (QByteArray const& frame, quint32 scalar_count)
+ {
+ int expected_size;
+ return checked_float_frame_size (scalar_count, &expected_size)
+ && frame.size () >= expected_size;
+ }
+
+ inline bool protocol_has_channels (QString const& version)
+ {
+ auto const parsed = QVersionNumber::fromString (version);
+ return !parsed.isNull ()
+ && QVersionNumber::compare (parsed, QVersionNumber {1, 9}) >= 0;
+ }
+
+ inline quint32 channel_count (Header const& stream, bool channel_field_supported)
+ {
+ if (!channel_field_supported)
+ {
+ return DefaultChannels;
+ }
+ return stream.channels == 1u || stream.channels == 2u ? stream.channels : 0u;
+ }
+
+ inline bool valid_tx_chrono (Header const& stream, bool channel_field_supported,
+ quint32 expected_sample_rate, quint32 * channels)
+ {
+ auto const count = channel_count (stream, channel_field_supported);
+ if (!channels || !count || stream.format != Float32Format
+ || stream.codec != UncompressedCodec || stream.sampleRate != expected_sample_rate
+ || stream.length > MaxFloatSamples || stream.length % count)
+ {
+ return false;
+ }
+
+ *channels = count;
+ return true;
+ }
+
+ inline bool prepare_tx_audio_frame (QByteArray * frame, Header const& chrono,
+ quint32 channels)
+ {
+ if ((channels != 1u && channels != 2u) || chrono.length % channels
+ || !prepare_float_frame (frame, chrono.length))
+ {
+ return false;
+ }
+
+ auto * response = header (frame);
+ response->receiver = chrono.receiver;
+ response->sampleRate = chrono.sampleRate;
+ response->format = Float32Format;
+ response->codec = UncompressedCodec;
+ response->length = chrono.length;
+ response->type = TxAudioStream;
+ response->channels = channels;
+ return true;
+ }
+
+ inline float * write_channel_frame (float sample, quint32 channels, float * destination)
+ {
+ for (quint32 channel = 0u; channel < channels; ++channel)
+ {
+ *destination++ = sample;
+ }
+ return destination;
+ }
+}
+
+#endif
diff --git a/Transceiver/TCITransceiver.cpp b/Transceiver/TCITransceiver.cpp
index 86d8e76e..5ee4bc0b 100644
--- a/Transceiver/TCITransceiver.cpp
+++ b/Transceiver/TCITransceiver.cpp
@@ -1,10 +1,16 @@
#include "Transceiver/TCITransceiver.hpp"
+#include "Transceiver/TCIProtocol.hpp"
#include <QRegularExpression>
-#include <QLocale>
#include <QThread>
#include <qmath.h>
+#include <algorithm>
+#include <cmath>
+#include <cstddef>
+#include <cstring>
+#include <limits>
+
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
#include <QRandomGenerator>
#endif
@@ -18,12 +24,39 @@
#include <QDir>
#include <QDebug>
#include <QDateTime>
+#include <QMutexLocker>
#include <QTimer>
+#include <QVector>
+
+#include "DecDataMutex.hpp"
namespace
{
char const * const TCI_transceiver_1_name {"TCI Client RX1"};
char const * const TCI_transceiver_2_name {"TCI Client RX2"};
+ // Exactly 1 MHz remains within the current band.
+ quint64 constexpr band_change_threshold_hz {1000000u};
+
+ bool has_required_args (QStringList const& args, int required)
+ {
+ return args.size () >= required;
+ }
+
+ bool decimal_tenths (QString const& value, int * result)
+ {
+ auto const parts = value.split ('.');
+ bool whole_ok {false};
+ bool fractional_ok {false};
+ int const whole = parts.value (0).toInt (&whole_ok);
+ int const fractional = parts.value (1).toInt (&fractional_ok);
+ if (!result || parts.size () < 2 || !whole_ok || !fractional_ok)
+ {
+ return false;
+ }
+
+ *result = 10 * whole + fractional;
+ return true;
+ }
QString map_mode (Transceiver::MODE mode)
{
@@ -31,11 +64,8 @@ namespace
{
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";
@@ -51,7 +81,7 @@ namespace
static const QString SmTrue("true");
static const QString SmFalse("false");
- // Command maps
+ // TCI command names
static const QString CmdDevice("device");
static const QString CmdReceiveOnly("receive_only");
static const QString CmdTrxCount("trx_count");
@@ -112,9 +142,9 @@ namespace
}
extern "C" {
- void fil4_(qint16*, qint32*, qint16*, qint32*, short int*);
+ void fil4_state_(qint16*, qint32*, qint16*, qint32*, float*);
}
-extern dec_data dec_data;
+#include "ReceiveAudio.hpp"
extern float gran(); // Noise generator (for tests only)
@@ -134,11 +164,9 @@ void TCITransceiver::register_transceivers (logger_type *, TransceiverFactory::T
(*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)
+ int poll_interval, QObject * parent, ReceiveClock receive_clock)
: PollingTransceiver {logger, poll_interval, parent}
, wrapped_ {std::move (wrapped)}
, rx_ {rignr}
@@ -191,7 +219,6 @@ TCITransceiver::TCITransceiver (logger_type * logger, std::unique_ptr<Transceive
, 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)
@@ -200,12 +227,20 @@ TCITransceiver::TCITransceiver (logger_type * logger, std::unique_ptr<Transceive
, m_toneSpacing {0.0}
, m_fSpread {0.0}
, m_state {Idle}
+ , m_jttyDrainTimer {nullptr}
+ , m_jttyDrainGuard {24000}
+ , m_tciBackendStartSequence {0}
+ , m_tciSuccessfullyWrittenFrames {0}
+ , m_tciStartMsecs {0}
+ , m_tciLastReportMsecs {0}
+ , m_tciFinalSnapshotEmitted {false}
, m_tuning {false}
, m_cwLevel {false}
, m_j0 {-1}
, m_toneFrequency0 {1500.0}
, wav_file_ {QDir(QStandardPaths::writableLocation (QStandardPaths::DataLocation)).absoluteFilePath ("tx.wav").toStdString()}
{
+ receive_clock_ = std::move (receive_clock);
m_samplesPerFFT = 6912 / 2;
tci_Ready = false;
trxA = 0;
@@ -269,6 +304,10 @@ TCITransceiver::TCITransceiver (logger_type * logger, std::unique_ptr<Transceive
mapCmd_[CmdAgcMode] = Cmd_AgcMode;
mapCmd_[CmdAgcGain] = Cmd_AgcGain;
mapCmd_[CmdLock] = Cmd_Lock;
+
+ m_jttyDrainTimer = new QTimer {this};
+ m_jttyDrainTimer->setInterval (25);
+ connect (m_jttyDrainTimer, &QTimer::timeout, this, &TCITransceiver::poll_jtty_drain);
}
void TCITransceiver::onConnected()
@@ -288,7 +327,11 @@ 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));
+ auto const error_index = static_cast<int> (err);
+ auto const error_name = error_index >= 0 && error_index < errortable.size ()
+ ? errortable.at (error_index)
+ : tr ("UnknownSocketError");
+ error_ = tr ("TCI websocket error: %1").arg (error_name);
}
int TCITransceiver::do_start ()
@@ -297,14 +340,13 @@ int TCITransceiver::do_start ()
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_
+ url_.setUrl("ws://" + server_);
if (url_.host() == "") url_.setHost("localhost");
if (url_.port() == -1) url_.setPort(40001);
if (!commander_) {
- commander_ = new QWebSocket {}; // QObject takes ownership
+ commander_ = new QWebSocket {};
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)));
@@ -388,6 +430,7 @@ int TCITransceiver::do_start ()
tci_Ready = false;
ESDR3 = false;
HPSDR = false;
+ stream_channels_supported_ = false;
band_change = false;
trxA = 0;
trxB = 0;
@@ -428,19 +471,17 @@ int TCITransceiver::do_start ()
_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);
+ mysleep7(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);
+ mysleep7(1000);
if(!_power_) throw error {tr ("TCI SDR could not be switched on")};
} else {
tci_Ready = false;
@@ -456,7 +497,7 @@ int TCITransceiver::do_start ()
}
if (tci_audio_) {
stream_audio (true);
- mysleep6(500);
+ mysleep7(500);
if (!stream_audio_) {
tci_Ready = false;
throw error {tr ("TCI Audio could not be switched on")};
@@ -469,10 +510,6 @@ int TCITransceiver::do_start ()
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;
@@ -495,20 +532,18 @@ int TCITransceiver::do_start ()
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);
+ mysleep7(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);
+ mysleep5(500);
busy_split_ = false;
requested_split_ = false;
rig_split();
@@ -521,7 +556,6 @@ void TCITransceiver::do_stop ()
rig_power(false);
mysleep1(500);
CAT_TRACE ("TCI power down\n");
- //printf ("TCI power down\n");
}
tci_Ready = false;
if (commander_)
@@ -530,100 +564,85 @@ void TCITransceiver::do_stop ()
delete commander_, commander_ = nullptr;
CAT_TRACE ("deleted commander & closed websocket & deleted:");
}
+ // The wait helpers are parent-owned and reused when the adapter restarts.
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 ");
}
@@ -637,6 +656,7 @@ void TCITransceiver::onMessageReceived(const QString &str)
QStringList cmd_list = str.split(";", SkipEmptyParts);
for (QString cmds : cmd_list){
QStringList cmd = cmds.split(":", SkipEmptyParts);
+ if (cmd.isEmpty ()) continue;
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());}
@@ -645,53 +665,87 @@ void TCITransceiver::onMessageReceived(const QString &str)
switch (idCmd) {
case Cmd_Smeter:
+ if (!has_required_args (args, 3)) break;
if(args.at(0)==rx_ && args.at(1) == "0") level_ = args.at(2).toInt() + 73;
break;
case Cmd_RxSensors:
+ if (!has_required_args (args, 2)) break;
if(args.at(0)==rx_) level_ = args.at(1).split(".")[0].toInt() + 73;
printf("Smeter=%d\n",level_);
break;
case Cmd_TxSensors:
+ if (!has_required_args (args, 5)) break;
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();
+ int power;
+ int swr;
+ if (!decimal_tenths (args.at (3), &power) ||
+ !decimal_tenths (args.at (4), &swr)) break;
+ power_ = power;
+ swr_ = swr;
printf("Power=%d SWR=%d\n",power_,swr_);
}
break;
case Cmd_SWR:
+ if (!has_required_args (args, 1)) break;
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();
+ {
+ int swr;
+ if (!decimal_tenths (args.at (0), &swr)) break;
+ swr_ = swr;
+ }
break;
case Cmd_Power:
- power_ = 10 * args.at(0).split(".")[0].toInt() + args.at(0).split(".")[1].toInt();
+ if (!has_required_args (args, 1)) break;
+ {
+ int power;
+ if (!decimal_tenths (args.at (0), &power)) break;
+ power_ = power;
+ }
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);
+ 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());
+ if (!has_required_args (args, 1) || args.at (0) != rx_) break;
+ if (!has_required_args (args, 3)
+ || (args.at (1) != "0" && args.at (1) != "1"))
+ {
+ error_ = tr ("TCI sent an invalid VFO frequency");
+ CAT_TRACE (error_);
+ break;
+ }
+ Frequency received_frequency;
+ if (!TciProtocol::parse_frequency (args.at (2), &received_frequency))
+ {
+ error_ = tr ("TCI sent an invalid VFO frequency");
+ CAT_TRACE (error_ + ": " + args.at (2));
+ break;
+ }
+ auto const received_frequency_text = QString::number (received_frequency);
+ if(args.at(1) == "0") {
+ rx_frequency_ = received_frequency_text;
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)
+ tci_done7();
} 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);
+ else {
+ other_frequency_ = received_frequency_text;
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
+ if (band_change && tci_timer7_->isActive()) {
printf (" cmdvfo1 done1");
band_change = false;
tci_timer2_->start(210);
- tci_done7(); //was tci_done1 (do_frequency)
+ tci_done7();
} else if (busy_other_frequency_) {
printf (" cmdvfo1 done2");
tci_done2();
@@ -704,11 +758,18 @@ void TCITransceiver::onMessageReceived(const QString &str)
}
}
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 (!has_required_args (args, 2)) break;
if(args.at(0)==rx_) {
if (ESDR3 || HPSDR) {
- if (args.at(1) == "0" ) mode_ = args.at(2).toLower(); else mode_ = args.at(1).toLower();
+ if (args.at(1) == "0" ) {
+ if (!has_required_args (args, 3)) break;
+ 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_) {
@@ -722,20 +783,22 @@ void TCITransceiver::onMessageReceived(const QString &str)
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 (!has_required_args (args, 2)) break;
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
+ else if (busy_split_) tci_done5();
+ else if (requested_split_ != split_ && !tci_timer5_->isActive()) {
CAT_TRACE("tci_timer5 started in onMessageReceived-Cmd_SplitEnable");
- tci_timer5_->start(210); //was tci_timer2
+ tci_timer5_->start(210);
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 && !has_required_args (args, 1)) || ((ESDR3 || HPSDR) && !has_required_args (args, 2))) break;
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_;
@@ -746,6 +809,7 @@ void TCITransceiver::onMessageReceived(const QString &str)
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 (!has_required_args (args, 2)) break;
if(args.at(0)==rx_) {
if (args.at(1) == "false") PTT_ = false;
else if (args.at(1) == "true") PTT_ = true;
@@ -760,16 +824,18 @@ void TCITransceiver::onMessageReceived(const QString &str)
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 (!has_required_args (args, 1)) break;
if(args.at(0)==rx_) {
stream_audio_ = true;
if (tci_Ready) {
printf ("cmdaudiostart done1\n");
- tci_done7(); //was tci_done1 (do_frequency)
+ tci_done7();
}
}
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 (!has_required_args (args, 2)) break;
if(args.at(0)=="1") {
if (args.at(1) == "false") rx2_ = false;
else if (args.at(1) == "true") rx2_ = true;
@@ -781,11 +847,12 @@ void TCITransceiver::onMessageReceived(const QString &str)
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 (!has_required_args (args, 1)) break;
if(args.at(0)==rx_) {
stream_audio_ = false;
if (tci_Ready) {
printf ("cmdaudiostop done1\n");
- tci_done7(); //was tci_done1 (do_frequency)
+ tci_done7();
}
}
break;
@@ -794,7 +861,7 @@ void TCITransceiver::onMessageReceived(const QString &str)
_power_ = true;
printf ("cmdstart done1\n");
if (tci_Ready) {
- tci_done7(); //was tci_done1 (do_frequency)
+ tci_done7();
}
break;
case Cmd_Stop:
@@ -806,10 +873,11 @@ void TCITransceiver::onMessageReceived(const QString &str)
power_ = 0; if (do_pwr_) update_power (0);
swr_ = 0; if (do_pwr_) update_swr (0);
m_state = Idle;
+ if (m_jttyDrainTimer && m_jttyDrainTimer->isActive ()) m_jttyDrainTimer->stop ();
Q_EMIT tci_mod_active(m_state != Idle);
}
_power_ = false;
- if (tci_timer1_->isActive()) { //was tci_timer1
+ if (tci_timer1_->isActive()) {
printf ("cmdstop done1\n");
tci_done1();
} else {
@@ -818,17 +886,21 @@ void TCITransceiver::onMessageReceived(const QString &str)
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 (!has_required_args (args, 1)) break;
if(args.at(0)=="ExpertSDR3") ESDR3 = true;
else if (args.at(0)=="Thetis") HPSDR = true;
+ stream_channels_supported_ = has_required_args (args, 2)
+ && TciStream::protocol_has_channels (args.at (1));
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 (!has_required_args (args, 1)) break;
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)
+ tci_done7();
break;
default:
@@ -847,11 +919,18 @@ void TCITransceiver::sendTextMessage(const QString &message)
void TCITransceiver::onBinaryReceived(const QByteArray &data)
{
- Data_Stream *pStream = (Data_Stream*)(data.data());
+ auto const * pStream = TciStream::header (data);
+ if (!pStream) {
+ return;
+ }
+
if (pStream->type != last_type) {
last_type = pStream->type;
}
- if (pStream->type == Iq_Stream){
+ if (pStream->type == TciStream::IqStream){
+ if (!TciStream::has_complete_float_payload (data, pStream->length)) {
+ return;
+ }
bool tx = false;
if (pStream->receiver == 0){
tx = trxA == 0;
@@ -862,125 +941,220 @@ void TCITransceiver::onBinaryReceived(const QByteArray &data)
trxB = 1;
}
printf("sendIqData\n");
- emit sendIqData(pStream->receiver,pStream->length,pStream->data,tx);
+ emit sendIqData(pStream->receiver,pStream->length,
+ const_cast<float *> (TciStream::float_payload (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);
+ } else if (pStream->type == TciStream::RxAudioStream && audio_ && pStream->receiver == rx_.toUInt()) {
+ if (!TciStream::has_complete_float_payload (data, pStream->length)) {
+ return;
+ }
+ writeAudioData(const_cast<float *> (TciStream::float_payload (data)),pStream->length);
+ } else if (pStream->type == TciStream::TxChrono && pStream->receiver == rx_.toUInt()) {
+ quint32 channels;
+ if (!TciStream::valid_tx_chrono (*pStream, stream_channels_supported_,
+ audioSampleRate, &channels)) {
+ return;
+ }
+
+ qint64 generatedScalars {0};
+ {
+ std::lock_guard<std::mutex> lock {mtx_};
+ tx_fifo += 1; tx_fifo &= 7;
+ if (!TciStream::prepare_tx_audio_frame (&m_tx1[tx_fifo], *pStream, channels)) {
+ return;
+ }
+
+ auto * response = TciStream::header (&m_tx1[tx_fifo]);
+ auto * payload = TciStream::float_payload (&m_tx1[tx_fifo]);
+ auto generated = readAudioData (payload, response->length, channels, txAtten);
+ generatedScalars = generated;
+ if (generated < response->length) {
+ generatedScalars += readAudioData (payload + generated,
+ response->length - generated,
+ channels, txAtten);
+ }
+ tx_fifo2 = tx_fifo;
}
- tx_fifo2 = tx_fifo; mtx_.unlock();
+
if (!inConnected || commander_->sendBinaryMessage(m_tx1[tx_fifo2]) != m_tx1[tx_fifo2].size()) {
+ return;
}
+
+ // A generated source frame is committed only when its containing WebSocket
+ // response is sent completely; protocol padding past the source extent is
+ // not evidence that omitted source audio reached the radio.
+ qint64 const frames = TxEvidence::interleavedFrameCount (generatedScalars,
+ int (channels));
+ m_tciSuccessfullyWrittenFrames += frames;
+ emit_tci_playout_snapshot (false, m_state == Idle);
}
}
void TCITransceiver::txAudioData(quint32 len, float * data)
{
+ if (len % TciStream::DefaultChannels || (len && !data)) {
+ return;
+ }
+
+ TciStream::Header chrono {};
+ chrono.receiver = 0u;
+ chrono.sampleRate = audioSampleRate;
+ chrono.length = len;
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);
+ if (!TciStream::prepare_tx_audio_frame (&tx, chrono, TciStream::DefaultChannels)) {
+ return;
+ }
+
+ if (len) {
+ std::memcpy (TciStream::float_payload (&tx), data, len * sizeof (float));
+ }
commander_->sendBinaryMessage(tx);
}
+void TCITransceiver::enqueue_jtty_pcm (QByteArray const& samples,
+ TxAudioQueueEpoch epoch,
+ qint64 enqueueId) noexcept
+{
+ qint64 const count = samples.size () / int (sizeof (qint16));
+ if (count <= 0) return;
+
+ qint16 const * pcm = reinterpret_cast<qint16 const *> (samples.constData ());
+ auto const result = m_txAudioQueue.enqueue (pcm, count, epoch);
+ if (!result.accepted)
+ {
+ if (epoch == result.progress.epoch)
+ {
+ CAT_WARNING ("JTTY TCI transmit FIFO overflow; rejecting PCM enqueue\n");
+ }
+ else
+ {
+ CAT_DEBUG ("JTTY TCI transmit queue epoch changed; rejecting stale PCM enqueue\n");
+ }
+ Q_EMIT jtty_enqueue_failed (epoch, enqueueId);
+ return;
+ }
+ Q_EMIT jtty_enqueue_accepted (enqueueId, count, result.progress);
+}
+
+void TCITransceiver::clear_jtty_pcm (TxAudioQueueEpoch epoch) noexcept
+{
+ m_txAudioQueue.clear (epoch);
+}
+
+void TCITransceiver::poll_jtty_drain ()
+{
+ // TCI audio is pulled while responding to TxChrono packets. Emitting the
+ // completion signal here keeps Qt work out of that packet/audio path.
+ auto const drain = m_txAudioQueue.takeDrainReady ();
+ if (drain.ready)
+ {
+ Q_EMIT jtty_drained (drain);
+ }
+}
+
+void TCITransceiver::clear ()
+{
+ m_receiveAudioProducer.reset (m_period);
+ m_bufferPos = 0;
+}
+
quint32 TCITransceiver::writeAudioData (float * data, qint32 maxSize)
{
- static unsigned mstr0=999999;
- qint64 ms0 = QDateTime::currentMSecsSinceEpoch() % 86400000;
+ if (dec_data_input_blocked ()) return maxSize;
+
+ QVector<qint64> frame_counts;
+ QVector<ReceiveAudio> audio;
+ qint64 ms0 = (receive_clock_ ? receive_clock_ ()
+ : 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]));
+ if(data == NULL) {
+ QMutexLocker lock {&dec_data_mutex ()};
+ if (dec_data_input_blocked ()) return maxSize;
+ if(mstr < m_lastPeriodOffsetMs/2) { //When mstr has wrapped around to 0, restart the buffer
+ clear ();
+ }
+ m_lastPeriodOffsetMs=mstr;
+ return maxSize; // we drop any data past the end of the buffer on
+ // the floor until the next period starts
}
- // no torn frames
- Q_ASSERT (!(maxSize % static_cast<qint32> (bytesPerFrame)));
+ double const receiveGain = std::pow (10.0, 0.05 * rxAtten);
- // 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));
+ {
+ QMutexLocker lock {&dec_data_mutex ()};
+ auto& producer = m_receiveAudioProducer.data ();
+ if (dec_data_input_blocked ()) return maxSize;
- if (framesAccepted < static_cast<size_t> (maxSize / bytesPerFrame)) {
- qDebug () << "dropped " << maxSize / bytesPerFrame - framesAccepted
- << " frames of data on the floor!"
- << dec_data.params.kin << mstr;
- }
+ if(mstr < m_lastPeriodOffsetMs/2) { //When mstr has wrapped around to 0, restart the buffer
+ clear ();
+ }
+ m_lastPeriodOffsetMs=mstr;
- for (unsigned remaining = framesAccepted; remaining; ) {
- size_t numFramesProcessed (qMin (m_samplesPerFFT *
- m_downSampleFactor - m_bufferPos, remaining));
+ // no torn frames
+ Q_ASSERT (!(maxSize % static_cast<qint32> (rxChannels)));
- if(m_downSampleFactor > 1) {
- store (&data1[(framesAccepted - remaining) * bytesPerFrame],
- numFramesProcessed, &m_buffer[m_bufferPos]);
- m_bufferPos += numFramesProcessed;
+ // these are in terms of input frames (not down sampled)
+ size_t framesAcceptable ((sizeof producer.d2 /
+ sizeof producer.d2[0] - m_receiveAudioProducer.frames ()) * m_downSampleFactor);
+ size_t framesAccepted (qMin (static_cast<size_t> (maxSize /
+ rxChannels), framesAcceptable));
- 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;
+ if (framesAccepted < static_cast<size_t> (maxSize / rxChannels)) {
+ qDebug () << "dropped " << maxSize / rxChannels - framesAccepted
+ << " frames of data on the floor!"
+ << m_receiveAudioProducer.frames () << mstr;
+ }
+
+ for (unsigned remaining = framesAccepted; remaining; ) {
+ size_t numFramesProcessed (qMin (m_samplesPerFFT *
+ m_downSampleFactor - m_bufferPos, remaining));
+
+ if(m_downSampleFactor > 1) {
+ store (&data[(framesAccepted - remaining) * rxChannels],
+ numFramesProcessed, &m_buffer[m_bufferPos], receiveGain);
+ m_bufferPos += numFramesProcessed;
+
+ if(m_bufferPos==m_samplesPerFFT*m_downSampleFactor) {
+ qint32 framesToProcess (m_samplesPerFFT * m_downSampleFactor);
+ qint32 framesAfterDownSample (m_samplesPerFFT);
+ if(m_downSampleFactor > 1 && m_receiveAudioProducer.frames ()>=0 &&
+ m_receiveAudioProducer.frames () < (NTMAX*12000 - framesAfterDownSample)) {
+ fil4_state_(&m_buffer[0], &framesToProcess,
+ &producer.d2[m_receiveAudioProducer.frames ()],
+ &framesAfterDownSample, m_downsampleState.data ());
+ m_receiveAudioProducer.setFrames (m_receiveAudioProducer.frames () + framesAfterDownSample);
+ } else {
+ qDebug() << "framesToProcess = " << framesToProcess;
+ qDebug() << "receive audio frames = " << m_receiveAudioProducer.frames ();
+ qDebug() << "framesAfterDownSample" << framesAfterDownSample;
+ }
+ frame_counts << m_receiveAudioProducer.frames ();
+ audio << m_receiveAudioProducer.capture (m_receiveAudioProducer.frames (), m_period);
+ m_bufferPos = 0;
}
- 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;
+ } else {
+ store (&data[(framesAccepted - remaining) * rxChannels],
+ numFramesProcessed, &producer.d2[m_receiveAudioProducer.frames ()],
+ receiveGain);
+ m_bufferPos += numFramesProcessed;
+ m_receiveAudioProducer.setFrames (m_receiveAudioProducer.frames () + numFramesProcessed);
+ if (m_bufferPos == static_cast<unsigned> (m_samplesPerFFT)) {
+ frame_counts << m_receiveAudioProducer.frames ();
+ audio << m_receiveAudioProducer.capture (m_receiveAudioProducer.frames (), m_period);
+ m_bufferPos = 0;
+ }
}
+ remaining -= numFramesProcessed;
}
- remaining -= numFramesProcessed;
}
- free(data1);
-}
+ for (auto frames : frame_counts) {
+ Q_EMIT tciframeswritten (frames);
+ }
+ for (auto const& block : audio) Q_EMIT receiveAudio (block);
+
return maxSize; // we drop any data past the end of the buffer on
// the floor until the next period starts
}
@@ -1044,8 +1218,9 @@ void TCITransceiver::do_audio (bool on)
{
TRACE_CAT ("TCITransceiver", on << state ());
if (on) {
- dec_data.params.kin = 0;
+ QMutexLocker lock {&dec_data_mutex ()};
m_bufferPos = 0;
+ if (!dec_data_input_blocked ()) clear ();
}
audio_ = on;
}
@@ -1053,7 +1228,12 @@ void TCITransceiver::do_audio (bool on)
void TCITransceiver::do_period (double period)
{
TRACE_CAT ("TCITransceiver", period << state ());
- m_period = period;
+ if (m_period != period)
+ {
+ QMutexLocker lock {&dec_data_mutex ()};
+ m_period = period;
+ if (!dec_data_input_blocked ()) clear ();
+ }
}
void TCITransceiver::do_volume (qreal volume)
@@ -1130,14 +1310,14 @@ void TCITransceiver::do_frequency (Frequency f, MODE m, bool no_ignore)
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;
+ band_change = TciProtocol::frequency_difference_exceeds (
+ string_to_frequency (rx_frequency_), f, band_change_threshold_hz);
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;
+ band_change2 = TciProtocol::frequency_difference_exceeds (
+ string_to_frequency (rx_frequency_), f, band_change_threshold_hz);
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");
@@ -1160,8 +1340,6 @@ void TCITransceiver::do_frequency (Frequency f, MODE m, bool no_ignore)
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;
}
@@ -1202,15 +1380,12 @@ void TCITransceiver::do_tx_frequency (Frequency tx, MODE mode, bool no_ignore)
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;
+ other_band_change = TciProtocol::frequency_difference_exceeds (
+ string_to_frequency (other_frequency_), tx, band_change_threshold_hz);
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_));
@@ -1239,7 +1414,6 @@ void TCITransceiver::do_tx_frequency (Frequency tx, MODE mode, bool no_ignore)
}
}
-//do_mode is never called.
void TCITransceiver::do_mode (MODE m)
{
TRACE_CAT ("TCITransceiver", m << state ());
@@ -1253,8 +1427,6 @@ void TCITransceiver::do_mode (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;
}
@@ -1356,55 +1528,30 @@ auto TCITransceiver::get_mode (bool requested) -> MODE
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)
+ // Frequency is an integer number of hertz, so decimal conversion is locale-independent.
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
+auto TCITransceiver::string_to_frequency (QString const& 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;
+ Frequency frequency;
+ if (!TciProtocol::parse_frequency (s, &frequency))
+ {
+ throw error {tr ("TCI sent an invalid VFO frequency")};
+ }
+ return frequency;
}
-/*
- * 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();
@@ -1454,39 +1601,40 @@ void TCITransceiver::mysleep8 (int ms)
}
// 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)
+void TCITransceiver::do_modulator_start (TxEvidence::TxRequest const& request)
{
// 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_txMode = request.mode;
+ m_symbolsLength = request.symbols_length;
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_addNoise = request.snr_db < 0.;
+ m_nsps = request.frames_per_symbol;
+ m_trfrequency = request.frequency_hz;
m_amp = std::numeric_limits<qint16>::max ();
- m_toneSpacing = toneSpacing;
- m_bFastMode=fastMode;
- m_TRperiod=TRperiod;
+ m_toneSpacing = request.tone_spacing;
+ m_bFastMode=request.fast_mode;
+ m_TRperiod=request.tr_period_s;
+ m_tuning=request.tuning;
+ m_cwId=request.cw_id;
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
+ if((request.mode=="FT8" and m_nsps==1920) or (request.mode=="FST4" and m_nsps==720)) delay_ms=500; //FT8, FST4-15
+ if((request.mode=="FT8" and m_nsps==1024)) delay_ms=400; //SuperFox Qary Polar Code transmission
+ if(request.mode=="Q65" and m_nsps<=3600) delay_ms=500; //Q65-15 and Q65-30
+ if(request.mode=="FT4") delay_ms=300; //FT4
// noise generator parameters
if (m_addNoise) {
- m_snr = qPow (10.0, 0.05 * (dBSNR - 6.0));
+ m_snr = qPow (10.0, 0.05 * (request.snr_db - 6.0));
m_fac = 3000.0;
if (m_snr > 1.0) m_fac = 3000.0 / m_snr;
}
@@ -1501,13 +1649,28 @@ void TCITransceiver::do_modulator_start (QString mode, unsigned symbolsLength, d
m_silentFrames = 0;
// calculate number of silent frames to send
- if (m_ic == 0 && synchronize && !m_tuning) {
+ if (m_ic == 0 && request.synchronize && !request.tuning) {
m_silentFrames = audioSampleRate / (1000 / delay_ms) - (mstr * (audioSampleRate / 1000));
}
- m_state = (synchronize && m_silentFrames) ?
+ m_state = (request.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);
+ m_txStartSnapshot.session_id = request.session_id;
+ m_txStartSnapshot.generation = request.generation;
+ m_txStartSnapshot.mode = m_txMode;
+ m_txStartSnapshot.sample_rate_hz = int (audioSampleRate);
+ m_txStartSnapshot.committed_end_sample = bounded_source_frames (request.tuning);
+ m_txStartSnapshot.target_known = m_txStartSnapshot.committed_end_sample >= 0;
+ m_txStartSnapshot.diagnostic = tr ("TCI source commitment; playout evidence is protocol-send dead reckoning, not DAC confirmation");
+ ++m_tciBackendStartSequence;
+ m_tciSuccessfullyWrittenFrames = 0;
+ m_tciStartMsecs = QDateTime::currentMSecsSinceEpoch ();
+ m_tciLastReportMsecs = m_tciStartMsecs;
+ m_tciFinalSnapshotEmitted = false;
+ 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,request.synchronize,m_tuning,m_state);
+ if (m_txMode == "JTTY" && !m_jttyDrainTimer->isActive ()) m_jttyDrainTimer->start ();
Q_EMIT tci_mod_active(m_state != Idle);
+ Q_EMIT txSourceCommitted (m_txStartSnapshot);
+ emit_tci_playout_snapshot (true, true);
}
void TCITransceiver::do_tune (bool newState)
@@ -1523,11 +1686,57 @@ void TCITransceiver::do_modulator_stop (bool quick)
m_state = Idle;
Q_EMIT tci_mod_active(m_state != Idle);
}
+ if (m_jttyDrainTimer->isActive ()) m_jttyDrainTimer->stop ();
+ emit_tci_playout_snapshot (false, true);
tx_audio_ = false;
}
-quint16 TCITransceiver::readAudioData (float * data, qint32 maxSize, qreal txAtten)
+qint64 TCITransceiver::bounded_source_frames (bool tuning) const
+{
+ if (tuning || m_txMode == "JTTY" || m_txMode == "CW" || !m_cwId.isEmpty ()) return -1;
+
+ qint64 i1 = qint64 (m_symbolsLength * 4.0 * m_nsps);
+ if (m_bFastMode)
+ {
+ i1 = qint64 (m_TRperiod * 48000.0 - 24000.0);
+ }
+ return TxEvidence::boundedCommittedEndSample (m_silentFrames, m_ic, i1);
+}
+
+void TCITransceiver::emit_tci_playout_snapshot (bool start_event, bool force)
{
+ qint64 const now = QDateTime::currentMSecsSinceEpoch ();
+ bool const final = m_state == Idle;
+ if (!start_event && !force && now - m_tciLastReportMsecs < 1000) return;
+ if (final && m_tciFinalSnapshotEmitted) return;
+
+ TxEvidence::TxRawPlayoutSnapshot snapshot;
+ snapshot.tier = TxEvidence::TxPlayoutTier::DeadReckoning;
+ snapshot.backend_start_sequence = m_tciBackendStartSequence;
+ snapshot.start_event = start_event;
+ snapshot.available = inConnected;
+ snapshot.state = final ? TxEvidence::TxBackendState::Idle : TxEvidence::TxBackendState::Active;
+ snapshot.elapsed_usecs = (now - m_tciStartMsecs) * 1000;
+ snapshot.successfully_written_frames = m_tciSuccessfullyWrittenFrames;
+ snapshot.sample_rate_hz = int (audioSampleRate);
+ snapshot.report_interval_ms = int (now - m_tciLastReportMsecs);
+ snapshot.diagnostic = tr ("TCI WebSocket send progress; no radio DAC or RF playback confirmation");
+ if (m_txMode == "JTTY")
+ {
+ auto const progress = m_txAudioQueue.progress ();
+ snapshot.source_served_frames = progress.served_samples;
+ snapshot.source_total_frames = progress.total_samples;
+ }
+ Q_EMIT rawTxPlayoutSnapshot (snapshot);
+ m_tciLastReportMsecs = now;
+ if (final) m_tciFinalSnapshotEmitted = true;
+}
+
+quint16 TCITransceiver::readAudioData (float * data, qint32 maxSize, quint32 channels, qreal txAtten)
+{
+ Q_ASSERT (channels == 1u || channels == 2u);
+ Q_ASSERT (maxSize >= 0 && !(static_cast<quint32> (maxSize) % channels));
+
double toneFrequency=1500.0;
if(m_nsps==6) {
toneFrequency=1000.0;
@@ -1537,11 +1746,10 @@ quint16 TCITransceiver::readAudioData (float * data, qint32 maxSize, qreal txAtt
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);
+ qint64 numFrames (maxSize/channels);
float * samples (reinterpret_cast<float *> (data));
- float * end (samples + numFrames * bytesPerFrame);
+ float * end (samples + numFrames * channels);
qint64 framesGenerated (0);
switch (m_state)
@@ -1550,10 +1758,10 @@ quint16 TCITransceiver::readAudioData (float * data, qint32 maxSize, qreal txAtt
{
if (m_silentFrames) { // send silence up to first second
framesGenerated = qMin (m_silentFrames, numFrames);
- for ( ; samples != end; samples = load (0, samples)) { // silence
+ for ( ; samples != end; samples = load (0, channels, samples)) { // silence
}
m_silentFrames -= framesGenerated;
- return framesGenerated * bytesPerFrame;
+ return framesGenerated * channels;
}
m_state = Active;
Q_EMIT tci_mod_active(m_state != Idle);
@@ -1564,10 +1772,15 @@ quint16 TCITransceiver::readAudioData (float * data, qint32 maxSize, qreal txAtt
case Active:
{
+ if (m_txMode == "JTTY" && !m_tuning)
+ {
+ return readJttyAudioData (data, maxSize, channels, txAtten);
+ }
+
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));
+ bool slowCwId=((isym >= m_symbolsLength) && !m_cwId.isEmpty ());
m_nspd=2560; // 22.5 WPM
if(m_TRperiod > 16.0 && slowCwId) { // Transmit CW ID?
@@ -1577,7 +1790,13 @@ quint16 TCITransceiver::readAudioData (float * data, qint32 maxSize, qreal txAtt
while (samples != end) {
j = (m_ic - ic0)/m_nspd + 1; // symbol of this sample
- bool level {bool (icw[j])};
+ if (j == 0 || j > static_cast<unsigned> (m_cwId.size ()))
+ {
+ m_state = Idle;
+ Q_EMIT tci_mod_active(m_state != Idle);
+ return framesGenerated * channels;
+ }
+ bool level {bool (m_cwId.at (j - 1))};
m_phi += m_dphi;
if (m_phi > m_twoPi) m_phi -= m_twoPi;
sample=0;
@@ -1591,15 +1810,9 @@ quint16 TCITransceiver::readAudioData (float * data, qint32 maxSize, qreal txAtt
}
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;
- }
+ samples = load (postProcessSample (sample), channels, samples);
+ ++framesGenerated;
+ ++m_ic;
// adjust ramp
if ((m_ramp != 0 && m_ramp != std::numeric_limits<qint16>::min ()) || level != m_cwLevel) {
@@ -1608,7 +1821,7 @@ quint16 TCITransceiver::readAudioData (float * data, qint32 maxSize, qreal txAtt
}
m_cwLevel = level;
}
- return framesGenerated * bytesPerFrame;
+ return framesGenerated * channels;
} //End of code for CW ID
double const baud (12000.0 / m_nsps);
@@ -1674,17 +1887,17 @@ quint16 TCITransceiver::readAudioData (float * data, qint32 maxSize, qreal txAtt
m_amp=32767.0;
sample=qRound(newVolume * m_amp*foxcom_.wave[m_ic]);
}
- samples = load (postProcessSample (sample), samples);
+ samples = load (postProcessSample (sample), channels, samples);
++framesGenerated;
++m_ic;
}
if (m_amp == 0.0) { // TODO G4WJS: compare double with zero might not be wise
- if (icw[0] == 0) {
+ if (m_cwId.isEmpty ()) {
// no CW ID to send
m_state = Idle;
Q_EMIT tci_mod_active(m_state != Idle);
- return framesGenerated * bytesPerFrame;
+ return framesGenerated * channels;
}
m_phi = 0.0;
}
@@ -1694,21 +1907,48 @@ quint16 TCITransceiver::readAudioData (float * data, qint32 maxSize, qreal txAtt
if (samples != end && framesGenerated) {
}
while (samples != end) { // pad block with silence
- samples = load (0, samples);
+ samples = load (0, channels, samples);
++framesGenerated;
}
- return framesGenerated * bytesPerFrame;
+ return framesGenerated * channels;
}
// fall through
case Idle:
- while (samples != end) samples = load (0, samples);
+ while (samples != end) samples = load (0, channels, samples);
}
Q_ASSERT (Idle == m_state);
return 0;
}
+quint16 TCITransceiver::readJttyAudioData (float * data, qint32 maxSize, quint32 channels, qreal txAtten)
+{
+ Q_ASSERT (channels == 1u || channels == 2u);
+ Q_ASSERT (maxSize >= 0 && !(static_cast<quint32> (maxSize) % channels));
+
+ if(maxSize==0) return 0;
+
+ qreal const newVolume = pow(2.22222 * (45 - txAtten) * 0.01,2);
+ qint64 const numFrames (maxSize/channels);
+ float * samples (reinterpret_cast<float *> (data));
+ qint64 framesGenerated (0);
+
+ // JTTY is pre-rendered mono PCM shared with the soundcard path. When the FIFO
+ // runs dry we keep sending silence until the drain guard proves the last real
+ // sample has cleared the backend.
+ for (qint64 i = 0; i < numFrames; ++i)
+ {
+ qint32 sample = qRound (newVolume * m_txAudioQueue.pullSample (m_jttyDrainGuard));
+ if (sample > std::numeric_limits<qint16>::max ()) sample = std::numeric_limits<qint16>::max ();
+ if (sample < std::numeric_limits<qint16>::min ()) sample = std::numeric_limits<qint16>::min ();
+ samples = load (postProcessSample (qint16 (sample)), channels, samples);
+ ++framesGenerated;
+ }
+
+ return framesGenerated * channels;
+}
+
qint16 TCITransceiver::postProcessSample (qint16 sample) const
{
if (m_addNoise) { // Test frame, we'll add noise
diff --git a/Transceiver/TCITransceiver.hpp b/Transceiver/TCITransceiver.hpp
index 5518b449..4f2387b3 100644
--- a/Transceiver/TCITransceiver.hpp
+++ b/Transceiver/TCITransceiver.hpp
@@ -1,15 +1,22 @@
#ifndef TCI_TRANSCEIVER_HPP__
#define TCI_TRANSCEIVER_HPP__
+#include <algorithm>
+#include <array>
+#include <cmath>
#include <memory>
+#include <functional>
#include "TransceiverFactory.hpp"
#include "PollingTransceiver.hpp"
+#include "TCIStream.hpp"
#include "commons.h"
+#include "Audio/TxAudioQueue.hpp"
#include <QtWebSockets/QWebSocket>
#include <QTimer>
#include <QEventLoop>
+#include <QVector>
#include <mutex>
typedef float REAL;
@@ -17,43 +24,22 @@ 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
+ Q_OBJECT;
public:
+ // UTC milliseconds, called on the transceiver thread for receive audio.
+ // An empty provider retains the system-clock behavior.
+ using ReceiveClock = std::function<qint64 ()>;
static void register_transceivers (logger_type *, TransceiverFactory::Transceivers *, unsigned id1, unsigned id2);
- // takes ownership of wrapped Transceiver
+ // Takes ownership of the 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);
+ int poll_interval, QObject * parent = nullptr,
+ ReceiveClock receive_clock = {});
enum Tci_Cmd {
Cmd_Unknown,
@@ -121,11 +107,11 @@ 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);
+ void enqueue_jtty_pcm (QByteArray const& samples, TxAudioQueueEpoch epoch,
+ qint64 enqueueId) noexcept override;
+ void clear_jtty_pcm (TxAudioQueueEpoch epoch) noexcept override;
private slots:
void onBinaryReceived(const QByteArray &data);
@@ -133,6 +119,7 @@ private slots:
void onError(QAbstractSocket::SocketError err);
void onConnected();
void onDisconnected();
+ void poll_jtty_drain ();
signals:
void sendIqData(int, quint32, float*, bool);
@@ -157,7 +144,6 @@ protected:
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;
@@ -167,25 +153,32 @@ protected:
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_start (TxEvidence::TxRequest const&) 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 qint16 tci_audio_sample_to_int16 (float sample)
{
static constexpr float K = 0x7FFF;
- for (size_t i {0}; i < numFrames; ++i) {
- dest[i] = static_cast<int16_t>(K*source[i*2]);
+ if (!std::isfinite (sample)) {
+ return 0;
}
+ sample = std::max (-1.0f, std::min (sample, 1.0f));
+ return static_cast<qint16> (K * sample);
+ }
+ void store (float const * source, size_t numFrames, qint16 * dest,
+ double gain)
+ {
+ for (size_t i {0}; i < numFrames; ++i) {
+ dest[i] = tci_audio_sample_to_int16 (gain * source[i * 2]);
+ }
}
- float * load (qint16 sample, float * dest)
+ float * load (qint16 sample, quint32 channels, float * dest)
{
static constexpr float K1 = 0.999/0x7FFF;
@@ -193,17 +186,14 @@ protected:
float value;
if (tx_top_) value = K1*static_cast<float>(sample);
else value = K2*static_cast<float>(sample);
- *dest++ = value;
- *dest++ = value;
-
- return dest;
+ return TciStream::write_channel_frame (value, channels, 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;
+ Frequency string_to_frequency (QString const&) const;
void mysleep1 (int ms = 1);
void mysleep2 (int ms = 1);
void mysleep3 (int ms = 1);
@@ -226,7 +216,6 @@ private:
bool tci_audio_;
bool _power_;
QWebSocket * commander_;
- QLocale locale_;
QTimer * tci_timer1_;
QEventLoop * tci_loop1_;
QTimer * tci_timer2_;
@@ -243,25 +232,24 @@ private:
QEventLoop * tci_loop7_;
QTimer * tci_timer8_;
QEventLoop * tci_loop8_;
- int nIqBytes;
bool inConnected;
bool tci_Ready;
bool ESDR3;
bool HPSDR;
+ bool stream_channels_supported_ = false;
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
+ // Rig state
QString requested_mode_;
QString mode_;
QString started_mode_;
@@ -295,25 +283,30 @@ private:
bool busy_PTT_;
bool busy_rx2_;
QHash<QString,Tci_Cmd> mapCmd_;
- // from Detector
+ // Receive audio buffering
void clear (); // discard buffer contents
double m_period = 15.0;
+ ReceiveClock receive_clock_;
+ ReceiveAudioProducer m_receiveAudioProducer;
+ std::array<float, 49> m_downsampleState {};
+ unsigned m_lastPeriodOffsetMs = 999999;
unsigned m_downSampleFactor;
qint32 m_samplesPerFFT; // after any down sampling
qint32 m_ns;
+ // m_samplesPerFFT must not exceed this post-downsampling limit; m_buffer
+ // scales it to hold one complete block at the input sample rate.
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);
+ static size_t const rxChannels = 2;
+ // Transmit audio generation
+ quint16 readAudioData (float * data, qint32 maxSize, quint32 channels, qreal txVolume);
+ quint16 readJttyAudioData (float * data, qint32 maxSize, quint32 channels, qreal txVolume);
qint16 postProcessSample (qint16 sample) const;
+ qint64 bounded_source_frames (bool tuning) const;
+ void emit_tci_playout_snapshot (bool start_event, bool force);
bool m_quickClose = false;
unsigned m_symbolsLength;
@@ -334,14 +327,25 @@ private:
double m_TRperiod;
qint64 m_silentFrames;
+ QString m_txMode;
qint16 m_ramp;
ModulatorState m_state;
+ TxAudioQueue m_txAudioQueue;
+ QTimer * m_jttyDrainTimer;
+ qint64 m_jttyDrainGuard;
+ TxEvidence::TxStartSnapshot m_txStartSnapshot;
+ qint64 m_tciBackendStartSequence;
+ qint64 m_tciSuccessfullyWrittenFrames;
+ qint64 m_tciStartMsecs;
+ qint64 m_tciLastReportMsecs;
+ bool m_tciFinalSnapshotEmitted;
bool m_tuning;
bool m_addNoise;
bool m_bFastMode;
bool m_cwLevel;
+ QVector<int> m_cwId;
unsigned m_ic;
unsigned m_isym0;
int m_j0;
diff --git a/Transceiver/Transceiver.cpp b/Transceiver/Transceiver.cpp
index c6dea805..ac85318e 100644
--- a/Transceiver/Transceiver.cpp
+++ b/Transceiver/Transceiver.cpp
@@ -24,13 +24,13 @@ QDebug operator << (QDebug d, Transceiver::TransceiverState const& s)
<< "; 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."
+ << "; SYMBOLSLENGTH: " << s.tx_request_.symbols_length
+ << "; FRAMESPERSYMBOL: " << s.tx_request_.frames_per_symbol
+ << "; TRFREQUENCY: " << s.tx_request_.frequency_hz << "Hz"
+ << "; TONESPACING: " << s.tx_request_.tone_spacing
+ << "; SYNCHRONIZE: " << (s.tx_request_.synchronize ? "on" : "off")
+ << "; DBSNR: " << s.tx_request_.snr_db
+ << "; TRPERIOD: " << s.tx_request_.tr_period_s << "sec."
<< "; SPREAD: " << s.spread_
<< "; NSYM: " << s.nsym_
<< "; VOLUME: " << s.volume_
@@ -38,6 +38,8 @@ QDebug operator << (QDebug d, Transceiver::TransceiverState const& s)
<< "; LEVEL: " << s.level_ << "dBm"
<< "; POWER: " << s.power_ << "mWatts"
<< "; SWR: " << s.swr_
+ << "; TX_SESSION: " << s.tx_request_.session_id.value ()
+ << "; TX_GENERATION: " << s.tx_request_.generation.value ()
<< ")\n";
return d.space ();
}
@@ -59,6 +61,8 @@ std::ostream& operator << (std::ostream& os, Transceiver::TransceiverState const
<< "; POWER: " << s.power_ << "mWatts"
<< "; SWR: " << s.swr_
<< "; TUNE: " << s.tune_
+ << "; TX_SESSION: " << s.tx_request_.session_id.value ()
+ << "; TX_GENERATION: " << s.tx_request_.generation.value ()
<< ")\n";
}
@@ -80,13 +84,7 @@ bool operator != (Transceiver::TransceiverState const& lhs, Transceiver::Transce
|| 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.tx_request_ != rhs.tx_request_
|| lhs.spread_ != rhs.spread_
|| lhs.nsym_ != rhs.nsym_
|| lhs.volume_ != rhs.volume_
diff --git a/Transceiver/Transceiver.hpp b/Transceiver/Transceiver.hpp
index 16c2e9f0..14d1640b 100644
--- a/Transceiver/Transceiver.hpp
+++ b/Transceiver/Transceiver.hpp
@@ -7,12 +7,25 @@
#include <boost/log/sources/severity_channel_logger.hpp>
#include <QObject>
+#include <QByteArray>
#include "qt_helpers.hpp"
#include "Radio.hpp"
+#include "Audio/TxAudioQueue.hpp"
+#include "Audio/TxIdentity.hpp"
+#include "Audio/TxPlaybackEvidence.hpp"
+#include "Audio/TxRequest.hpp"
+#include "ReceiveAudio.hpp"
class QString;
+// Qt 5 moc generates unqualified argument names for these value types.
+using TxSessionId = TxEvidence::TxSessionId;
+using TxGeneration = TxEvidence::TxGeneration;
+using TxStartSnapshot = TxEvidence::TxStartSnapshot;
+using TxRawPlayoutSnapshot = TxEvidence::TxRawPlayoutSnapshot;
+using TxRequest = TxEvidence::TxRequest;
+
//
// Abstract Transceiver Interface
//
@@ -92,13 +105,6 @@ public:
, 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}
@@ -106,8 +112,6 @@ public:
, level_ {0}
, power_ {0}
, swr_ {0}
- , jtmode_ {"FT8"} //w3sz tci
- , fastmode_ {false} //w3sz tci
{
}
@@ -123,13 +127,13 @@ public:
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_;}
+ unsigned symbolslength () const {return tx_request_.symbols_length;}
+ double framespersymbol () const {return tx_request_.frames_per_symbol;}
+ double trfrequency () const {return tx_request_.frequency_hz;}
+ double tonespacing () const {return tx_request_.tone_spacing;}
+ bool synchronize () const {return tx_request_.synchronize;}
+ double dbsnr () const {return tx_request_.snr_db;}
+ double trperiod () const {return tx_request_.tr_period_s;}
double spread () const {return spread_;}
int nsym () const {return nsym_;}
qreal volume () const {return volume_;}
@@ -137,8 +141,11 @@ public:
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
+ QString jtmode () const {return tx_request_.mode;} //w3sz tci
+ bool fastmode () const {return tx_request_.fast_mode;} //w3sz tci
+ TxEvidence::TxSessionId tx_session_id () const {return tx_request_.session_id;}
+ TxEvidence::TxGeneration tx_generation () const {return tx_request_.generation;}
+ TxEvidence::TxRequest const& tx_request () const {return tx_request_;}
void online (bool state) {online_ = state;}
void frequency (Frequency f) {rx_frequency_ = f;}
@@ -152,13 +159,13 @@ public:
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 symbolslength (unsigned symbolslength) {tx_request_.symbols_length = symbolslength;}
+ void framespersymbol (double framespersymbol) {tx_request_.frames_per_symbol = framespersymbol;}
+ void trfrequency (double trfrequency) {tx_request_.frequency_hz = trfrequency;}
+ void tonespacing (double tonespacing) {tx_request_.tone_spacing = tonespacing;}
+ void synchronize (bool synchronize) {tx_request_.synchronize = synchronize;}
+ void dbsnr (double dbsnr) {tx_request_.snr_db = dbsnr;}
+ void trperiod (double trperiod) {tx_request_.tr_period_s = trperiod;}
void spread (double spread) {spread_ = spread;}
void nsym (int nsym) {nsym_ = nsym;}
void volume (qreal volume) {volume_ = volume;}
@@ -166,8 +173,11 @@ public:
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
+ void jtmode(QString jtmode) {tx_request_.mode = jtmode;} //w3sz tci
+ void fastmode(bool fastmode) {tx_request_.fast_mode = fastmode;} //w3sz tci
+ void tx_session_id (TxEvidence::TxSessionId value) {tx_request_.session_id = value;}
+ void tx_generation (TxEvidence::TxGeneration value) {tx_request_.generation = value;}
+ void tx_request (TxEvidence::TxRequest const& request) {tx_request_ = request;}
private:
bool online_;
@@ -182,13 +192,7 @@ public:
bool quick_;
double period_;
qint32 blocksize_;
- unsigned symbolslength_;
- double framespersymbol_;
- double trfrequency_;
- double tonespacing_;
- bool synchronize_;
- double dbsnr_;
- double trperiod_;
+ TxEvidence::TxRequest tx_request_;
double spread_;
int nsym_;
qreal volume_;
@@ -196,8 +200,6 @@ public:
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
@@ -226,6 +228,8 @@ public:
// Connect and disconnect.
Q_SLOT virtual void start (unsigned sequence_number) noexcept = 0;
Q_SLOT virtual void stop () noexcept = 0;
+ Q_SLOT virtual void enqueue_jtty_pcm (QByteArray const&, TxAudioQueueEpoch, qint64) noexcept {}
+ Q_SLOT virtual void clear_jtty_pcm (TxAudioQueueEpoch) noexcept {}
//
// asynchronous status updates
@@ -240,10 +244,20 @@ public:
// rig audio data transfer w3sz tci
Q_SIGNAL void tciframeswritten (qint64);
+ Q_SIGNAL void receiveAudio (ReceiveAudio);
// rig audio data transfer w3sz tci
Q_SIGNAL void tci_mod_active (bool);
+ // Diagnostics only: source commitment and TCI protocol-send progress.
+ Q_SIGNAL void txSourceCommitted (TxEvidence::TxStartSnapshot);
+ Q_SIGNAL void rawTxPlayoutSnapshot (TxEvidence::TxRawPlayoutSnapshot);
+
+ Q_SIGNAL void jtty_drained (TxAudioQueueDrainState drain);
+ Q_SIGNAL void jtty_enqueue_accepted (qint64 enqueueId, qint64 sampleCount,
+ TxAudioQueueProgress progress);
+ Q_SIGNAL void jtty_enqueue_failed (TxAudioQueueEpoch epoch, qint64 enqueueId);
+
// rig state changed
Q_SIGNAL void update (Transceiver::TransceiverState const&,
unsigned sequence_number) const;
diff --git a/Transceiver/TransceiverBase.cpp b/Transceiver/TransceiverBase.cpp
index 72f6fafb..458eade5 100644
--- a/Transceiver/TransceiverBase.cpp
+++ b/Transceiver/TransceiverBase.cpp
@@ -78,10 +78,13 @@ void TransceiverBase::set (TransceiverState const& s,
audio_cmd = true;
requested_.blocksize (s.blocksize ());
}
- if (requested_.period() != s.period()) {
+ if (!period_applied_ || applied_period_ != s.period()) {
+ bool const had_applied_period {period_applied_};
do_period (s.period());
- audio_cmd = true;
requested_.period (s.period ());
+ applied_period_ = s.period ();
+ period_applied_ = true;
+ audio_cmd = audio_cmd || had_applied_period;
}
if (requested_.spread() != s.spread()) {
do_spread (s.spread());
@@ -105,14 +108,8 @@ void TransceiverBase::set (TransceiverState const& s,
}
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 ());
+ do_modulator_start (s.tx_request ());
+ requested_.tx_request (s.tx_request ());
} else {
do_modulator_stop(s.quick ());
requested_.quick (s.quick ());
@@ -263,6 +260,8 @@ void TransceiverBase::shutdown ()
do_post_stop ();
actual_ = TransceiverState {};
requested_ = TransceiverState {};
+ period_applied_ = false;
+ applied_period_ = 0.0;
}
void TransceiverBase::stop () noexcept
diff --git a/Transceiver/TransceiverBase.hpp b/Transceiver/TransceiverBase.hpp
index ee5f8c1c..085fccfc 100644
--- a/Transceiver/TransceiverBase.hpp
+++ b/Transceiver/TransceiverBase.hpp
@@ -123,8 +123,7 @@ protected:
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_start (TxEvidence::TxRequest const&) {}
virtual void do_modulator_stop(bool) {}
virtual bool do_pre_update () {return true;}
@@ -168,6 +167,8 @@ private:
TransceiverState actual_;
TransceiverState last_;
unsigned last_sequence_number_; // from set state operation
+ bool period_applied_ {false};
+ double applied_period_ {0.0};
};
// some loggimg macros
diff --git a/Transceiver/TransceiverFactory.cpp b/Transceiver/TransceiverFactory.cpp
index 323a882a..9f245908 100644
--- a/Transceiver/TransceiverFactory.cpp
+++ b/Transceiver/TransceiverFactory.cpp
@@ -1,4 +1,5 @@
#include "TransceiverFactory.hpp"
+#include "TxInhibitTransceiver.hpp"
#include <QMetaType>
@@ -225,6 +226,15 @@ std::unique_ptr<Transceiver> TransceiverFactory::create (ParameterPack const& pa
}
}
+ if (supports_tx_inhibit (params.ptt_type))
+ {
+ result.reset (new TxInhibitTransceiver {&logger_, std::move (result)});
+ if (target_thread)
+ {
+ result->moveToThread (target_thread);
+ }
+ }
+
return result;
}
diff --git a/Transceiver/TransceiverFactory.hpp b/Transceiver/TransceiverFactory.hpp
index 3d9390d8..a579d451 100644
--- a/Transceiver/TransceiverFactory.hpp
+++ b/Transceiver/TransceiverFactory.hpp
@@ -74,6 +74,12 @@ public:
Q_ENUM (Handshake)
enum PTTMethod {PTT_method_VOX, PTT_method_CAT, PTT_method_DTR, PTT_method_RTS};
Q_ENUM (PTTMethod)
+
+ static bool supports_tx_inhibit (PTTMethod method)
+ {
+ return PTT_method_DTR == method || PTT_method_RTS == method;
+ }
+
enum TXAudioSource {TX_audio_source_front, TX_audio_source_rear};
Q_ENUM (TXAudioSource)
enum SplitMode {split_mode_none, split_mode_rig, split_mode_emulate};
diff --git a/Transceiver/TxInhibitTransceiver.cpp b/Transceiver/TxInhibitTransceiver.cpp
new file mode 100644
index 00000000..6261432b
--- /dev/null
+++ b/Transceiver/TxInhibitTransceiver.cpp
@@ -0,0 +1,255 @@
+#include "TxInhibitTransceiver.hpp"
+
+#include <algorithm>
+#include <limits>
+
+#include <QSet>
+#include <QStringList>
+#include <QTimer>
+
+#include "moc_TxInhibitTransceiver.cpp"
+
+namespace
+{
+ QString const overflow_hold_key;
+
+ QString sanitize_holder (QString const& value)
+ {
+ QString result;
+ result.reserve (std::min (value.size (), 64));
+ for (auto const character : value.left (64))
+ {
+ if (character.isPrint ()) result.append (character);
+ }
+ return result.trimmed ();
+ }
+}
+
+TxInhibitTransceiver::TxInhibitTransceiver (logger_type * logger,
+ std::unique_ptr<Transceiver> wrapped)
+ : Transceiver {logger, nullptr}
+ , wrapped_ {std::move (wrapped)}
+ , expiry_timer_ {new QTimer {this}}
+{
+ Q_ASSERT (wrapped_);
+
+ expiry_timer_->setSingleShot (true);
+ connect (expiry_timer_, &QTimer::timeout, this, &TxInhibitTransceiver::expire_holds);
+
+ connect (wrapped_.get (), &Transceiver::resolution, this, &Transceiver::resolution);
+ connect (wrapped_.get (), &Transceiver::tciframeswritten, this, &Transceiver::tciframeswritten);
+ connect (wrapped_.get (), &Transceiver::receiveAudio, this, &Transceiver::receiveAudio);
+ connect (wrapped_.get (), &Transceiver::tci_mod_active, this, &Transceiver::tci_mod_active);
+ connect (wrapped_.get (), &Transceiver::txSourceCommitted, this, &Transceiver::txSourceCommitted);
+ connect (wrapped_.get (), &Transceiver::rawTxPlayoutSnapshot, this, &Transceiver::rawTxPlayoutSnapshot);
+ connect (wrapped_.get (), &Transceiver::jtty_drained, this, &Transceiver::jtty_drained);
+ connect (wrapped_.get (), &Transceiver::jtty_enqueue_accepted, this, &Transceiver::jtty_enqueue_accepted);
+ connect (wrapped_.get (), &Transceiver::jtty_enqueue_failed, this, &Transceiver::jtty_enqueue_failed);
+ connect (wrapped_.get (), &Transceiver::update, this, &Transceiver::update);
+ connect (wrapped_.get (), &Transceiver::finished, this, &Transceiver::finished);
+ connect (wrapped_.get (), &Transceiver::failure, this, &Transceiver::failure);
+}
+
+void TxInhibitTransceiver::set (TransceiverState const& state,
+ unsigned sequence_number) noexcept
+{
+ requested_ = state;
+ sequence_number_ = sequence_number;
+ have_requested_state_ = true;
+ apply_requested_state ();
+}
+
+void TxInhibitTransceiver::start (unsigned sequence_number) noexcept
+{
+ sequence_number_ = sequence_number;
+ have_effective_state_ = false;
+ monotonic_clock_.start ();
+ started_ = true;
+ emit_status ();
+ wrapped_->start (sequence_number);
+}
+
+void TxInhibitTransceiver::stop () noexcept
+{
+ if (!started_) return;
+
+ expiry_timer_->stop ();
+ holds_.clear ();
+ started_ = false;
+ emit_status ();
+ wrapped_->stop ();
+ have_requested_state_ = false;
+ have_effective_state_ = false;
+}
+
+void TxInhibitTransceiver::enqueue_jtty_pcm (QByteArray const& samples,
+ TxAudioQueueEpoch epoch,
+ qint64 enqueue_id) noexcept
+{
+ wrapped_->enqueue_jtty_pcm (samples, epoch, enqueue_id);
+}
+
+void TxInhibitTransceiver::clear_jtty_pcm (TxAudioQueueEpoch epoch) noexcept
+{
+ wrapped_->clear_jtty_pcm (epoch);
+}
+
+void TxInhibitTransceiver::apply_requested_state () noexcept
+{
+ if (!have_requested_state_ || !started_) return;
+
+ auto effective = requested_;
+ if (!holds_.isEmpty ())
+ {
+ effective.ptt (false);
+ effective.tune (false);
+ }
+
+ auto const previous_ptt = have_effective_state_ && last_effective_.ptt ();
+ auto final_sent = false;
+ if (effective.ptt () != previous_ptt)
+ {
+ if (effective.ptt ())
+ {
+ auto prepare = effective;
+ prepare.ptt (false);
+ if (!have_effective_state_ || prepare != last_effective_)
+ {
+ wrapped_->set (prepare, sequence_number_);
+ }
+ }
+ else
+ {
+ auto unkey = last_effective_;
+ unkey.ptt (false);
+ wrapped_->set (unkey, sequence_number_);
+ final_sent = unkey == effective;
+ }
+ }
+ if (!final_sent) wrapped_->set (effective, sequence_number_);
+ last_effective_ = effective;
+ have_effective_state_ = true;
+}
+
+void TxInhibitTransceiver::emit_status ()
+{
+ Q_EMIT statusChanged (started_, started_ && !holds_.isEmpty (),
+ holder_summary (), hold_rx_, release_rx_, expiries_, invalid_);
+}
+
+void TxInhibitTransceiver::tx_inhibit_invalid (quint64 count)
+{
+ if (!started_ || !count) return;
+ invalid_ += static_cast<quint32> (count);
+ emit_status ();
+}
+
+void TxInhibitTransceiver::expire_holds ()
+{
+ auto const was_inhibited = !holds_.isEmpty ();
+ auto const previous_holder = holder_summary ();
+ auto expired = false;
+ auto const now = monotonic_clock_.elapsed ();
+ for (auto it = holds_.begin (); it != holds_.end ();)
+ {
+ if (it->expires_at <= now)
+ {
+ it = holds_.erase (it);
+ ++expiries_;
+ expired = true;
+ }
+ else
+ {
+ ++it;
+ }
+ }
+
+ if (was_inhibited != !holds_.isEmpty ()) apply_requested_state ();
+ if (expired || was_inhibited != !holds_.isEmpty ()
+ || previous_holder != holder_summary ())
+ {
+ emit_status ();
+ }
+ schedule_expiry ();
+}
+
+QString TxInhibitTransceiver::holder_summary () const
+{
+ QStringList holders;
+ QSet<QString> seen;
+ for (auto it = holds_.cbegin (); it != holds_.cend (); ++it)
+ {
+ if (!it->holder.isEmpty () && !seen.contains (it->holder))
+ {
+ seen.insert (it->holder);
+ holders.append (it->holder);
+ }
+ }
+ holders.sort (Qt::CaseInsensitive);
+ return holders.join (QStringLiteral (", "));
+}
+
+void TxInhibitTransceiver::tx_inhibit_command (QString controller, quint32 ttl_ms, QString station)
+{
+ if (!started_) return;
+ auto const was_inhibited = !holds_.isEmpty ();
+ if (!ttl_ms)
+ {
+ ++release_rx_;
+ holds_.remove (controller);
+ }
+ else
+ {
+ ++hold_rx_;
+ auto const expires_at = monotonic_clock_.elapsed () + ttl_ms;
+ auto const holder = sanitize_holder (station.isEmpty () ? controller : station);
+ auto existing = holds_.find (controller);
+ if (existing != holds_.end ())
+ {
+ *existing = Hold {expires_at, holder};
+ }
+ else
+ {
+ auto const tracked_count = holds_.size ()
+ - (holds_.contains (overflow_hold_key) ? 1 : 0);
+ if (tracked_count < maximum_tracked_holds)
+ {
+ holds_.insert (controller, Hold {expires_at, holder});
+ }
+ else
+ {
+ auto overflow = holds_.find (overflow_hold_key);
+ if (overflow == holds_.end ())
+ {
+ holds_.insert (overflow_hold_key, Hold {expires_at, {}});
+ }
+ else
+ {
+ overflow->expires_at = std::max (overflow->expires_at, expires_at);
+ }
+ }
+ }
+ }
+
+ if (was_inhibited != !holds_.isEmpty ()) apply_requested_state ();
+ emit_status ();
+ schedule_expiry ();
+}
+
+void TxInhibitTransceiver::schedule_expiry ()
+{
+ if (holds_.isEmpty ())
+ {
+ expiry_timer_->stop ();
+ return;
+ }
+
+ auto next_expiry = std::numeric_limits<qint64>::max ();
+ for (auto it = holds_.cbegin (); it != holds_.cend (); ++it)
+ {
+ next_expiry = std::min (next_expiry, it->expires_at);
+ }
+ auto const delay = std::max<qint64> (1, next_expiry - monotonic_clock_.elapsed ());
+ expiry_timer_->start (static_cast<int> (std::min<qint64> (delay,
+ std::numeric_limits<int>::max ())));
+}
diff --git a/Transceiver/TxInhibitTransceiver.hpp b/Transceiver/TxInhibitTransceiver.hpp
new file mode 100644
index 00000000..fb3f0103
--- /dev/null
+++ b/Transceiver/TxInhibitTransceiver.hpp
@@ -0,0 +1,67 @@
+#ifndef TX_INHIBIT_TRANSCEIVER_HPP__
+#define TX_INHIBIT_TRANSCEIVER_HPP__
+
+#include <memory>
+
+#include <QElapsedTimer>
+#include <QHash>
+#include <QString>
+
+#include "Transceiver.hpp"
+
+class QTimer;
+
+class TxInhibitTransceiver final
+ : public Transceiver
+{
+ Q_OBJECT
+
+public:
+ static constexpr int maximum_tracked_holds {64};
+
+ explicit TxInhibitTransceiver (logger_type *, std::unique_ptr<Transceiver>);
+
+ void set (TransceiverState const&, unsigned sequence_number) noexcept override;
+ void start (unsigned sequence_number) noexcept override;
+ void stop () noexcept override;
+ void enqueue_jtty_pcm (QByteArray const&, TxAudioQueueEpoch, qint64) noexcept override;
+ void clear_jtty_pcm (TxAudioQueueEpoch) noexcept override;
+
+ Q_SLOT void tx_inhibit_command (QString controller, quint32 ttl_ms, QString station);
+ Q_SLOT void tx_inhibit_invalid (quint64 count);
+
+ Q_SIGNAL void statusChanged (bool supported, bool inhibited,
+ QString const& holder,
+ quint32 hold_rx, quint32 release_rx,
+ quint32 expiries, quint32 invalid);
+
+private:
+ struct Hold
+ {
+ qint64 expires_at;
+ QString holder;
+ };
+
+ void apply_requested_state () noexcept;
+ void emit_status ();
+ void expire_holds ();
+ QString holder_summary () const;
+ void schedule_expiry ();
+
+ std::unique_ptr<Transceiver> wrapped_;
+ QTimer * expiry_timer_;
+ QElapsedTimer monotonic_clock_;
+ QHash<QString, Hold> holds_;
+ TransceiverState requested_;
+ TransceiverState last_effective_;
+ unsigned sequence_number_ {0};
+ quint32 hold_rx_ {0};
+ quint32 release_rx_ {0};
+ quint32 expiries_ {0};
+ quint32 invalid_ {0};
+ bool have_requested_state_ {false};
+ bool have_effective_state_ {false};
+ bool started_ {false};
+};
+
+#endif