diff --git a/include/mcc/mcc_generic_movecontrols.h b/include/mcc/mcc_generic_movecontrols.h index 32eefc1..3f9c281 100644 --- a/include/mcc/mcc_generic_movecontrols.h +++ b/include/mcc/mcc_generic_movecontrols.h @@ -242,6 +242,8 @@ protected: enum class MccGenericMovementControlsPolicy : int { POLICY_ASYNC, POLICY_BLOCKING }; + +/* template class MccGenericMovementControls @@ -704,6 +706,330 @@ protected: } } }; +*/ + +template +class MccGenericMovementControls +{ +public: + static constexpr MccGenericMovementControlsPolicy executePolicy = EXEC_POLICY; + + static constexpr std::chrono::seconds defaultWaitTimeout{3}; + + typedef MccError error_t; + + typedef PARAMS_T movement_params_t; + + template SLEW_FUNC_T, std::invocable<> TRACK_FUNC_T, std::invocable<> STOP_FUNC_T> + MccGenericMovementControls(SLEW_FUNC_T&& slew_func, TRACK_FUNC_T&& track_func, STOP_FUNC_T&& stop_func) + : _slewFunc(std::forward(slew_func)), + _trackFunc(std::forward(track_func)), + _stopFunc(std::forward(stop_func)) + { + if constexpr (executePolicy == MccGenericMovementControlsPolicy::POLICY_ASYNC) { + startAsyncMovementCycle(); + } + } + + MccGenericMovementControls(const MccGenericMovementControls&) = delete; + MccGenericMovementControls(MccGenericMovementControls&& other) = default; + + MccGenericMovementControls& operator=(const MccGenericMovementControls&) = delete; + MccGenericMovementControls& operator=(MccGenericMovementControls&&) = default; + + virtual ~MccGenericMovementControls() + { + if constexpr (executePolicy == MccGenericMovementControlsPolicy::POLICY_ASYNC) { + stopAsyncMovementCycle(); + } + } + + + template + void stopAsyncMovementCycle(this SelfT&& self) + requires(EXEC_POLICY == MccGenericMovementControlsPolicy::POLICY_ASYNC) + { + *self._fsmState = STATE_IDLE; + self._fstStopSource.request_stop(); + + self._wakeupRequest->test_and_set(); + self._wakeupRequest->notify_all(); + + std::this_thread::sleep_for(std::chrono::milliseconds(200)); + + if (self._fstFuture.valid()) { + auto status = self._fstFuture.wait_for(self._waitTimeout->load()); + } + } + + template + void startAsyncMovementCycle(this SelfT& self) + requires(EXEC_POLICY == MccGenericMovementControlsPolicy::POLICY_ASYNC) + { + using self_t = std::decay_t; + + if (self._fstFuture.valid()) { + self.stopAsyncMovementCycle(); + } + + *self._stopMovementRequest = false; + + self._fstStopSource = std::stop_source{}; + + *self._fsmState = STATE_IDLE; + + // start thread of movements + self._fstFuture = std::async( + std::launch::async, + [&self](std::stop_token stoken) mutable { + // auto do_state = self._fsmState->load(); + int to_state; + + std::string log_str; + while (!stoken.stop_requested()) { + log_str = std::format("\n{:*^80}\n", " WAIT LOCK "); + if constexpr (mcc_generic_mount_c) { + self.logTrace(log_str); + } else { + std::println("{}", log_str); + } + + // wait here ... + self._wakeupRequest->wait(false, std::memory_order_relaxed); + + self._wakeupRequest->clear(); + + + to_state = self._fsmState->load(); + + log_str = std::format(" UNLOCKED TO STATE {} ", to_state == STATE_STOP ? "STOP" + : to_state == STATE_SLEW ? "SLEW" + : to_state == STATE_TRACK ? "TRACK" + : "UNKNOWN"); + + log_str = std::format("\n{:*^80}\n", log_str); + if constexpr (mcc_generic_mount_c) { + self.logTrace(log_str); + } else { + std::println("{}", log_str); + } + + switch (to_state) { + case STATE_SLEW: + self._slewFunc(self._slewAndStop->load()); + break; + case STATE_TRACK: + self._trackFunc(); + break; + case STATE_STOP: + self._stopFunc(); + break; + } + } + }, + self._fstStopSource.get_token()); + } + + error_t slewToTarget(bool slew_and_stop) + { + if constexpr (executePolicy == MccGenericMovementControlsPolicy::POLICY_ASYNC) { + *_fsmState = STATE_SLEW; + + *_slewAndStop = slew_and_stop; + + _wakeupRequest->test_and_set(); + _wakeupRequest->notify_one(); + + return MccGenericMovementControlsErrorCode::ERROR_OK; + } else if constexpr (executePolicy == MccGenericMovementControlsPolicy::POLICY_BLOCKING) { + return _slewFunc(slew_and_stop); + } else { + static_assert(false, "UNKNOWN EXECUTION POLICY!"); + } + } + + error_t trackTarget() + { + if constexpr (executePolicy == MccGenericMovementControlsPolicy::POLICY_ASYNC) { + *_fsmState = STATE_TRACK; + + + _wakeupRequest->test_and_set(); + _wakeupRequest->notify_one(); + + return MccGenericMovementControlsErrorCode::ERROR_OK; + } else if constexpr (executePolicy == MccGenericMovementControlsPolicy::POLICY_BLOCKING) { + return _trackFunc(); + } else { + static_assert(false, "UNKNOWN EXECUTION POLICY!"); + } + } + + error_t stopMount() + { + if constexpr (executePolicy == MccGenericMovementControlsPolicy::POLICY_ASYNC) { + *_fsmState = STATE_STOP; + + _wakeupRequest->test_and_set(); + _wakeupRequest->notify_one(); + + return MccGenericMovementControlsErrorCode::ERROR_OK; + } else if constexpr (executePolicy == MccGenericMovementControlsPolicy::POLICY_BLOCKING) { + return _stopFunc(); + } else { + static_assert(false, "UNKNOWN EXECUTION POLICY!"); + } + } + + error_t setMovementParams(movement_params_t const& pars) + { + std::lock_guard lock{*_currentMovementParamsMutex}; + + _currentMovementParams = pars; + + return MccGenericMovementControlsErrorCode::ERROR_OK; + } + + movement_params_t getMovementParams() const + { + std::lock_guard lock{*_currentMovementParamsMutex}; + + return _currentMovementParams; + } + +protected: + std::unique_ptr _currentMovementParamsMutex{new std::mutex{}}; + PARAMS_T _currentMovementParams{}; + + std::unique_ptr _stopMovementRequest{new std::atomic_bool{false}}; + + std::function _slewFunc{}; + std::function _trackFunc{}; + std::function _stopFunc{}; + + std::unique_ptr> _waitTimeout{ + new std::atomic{defaultWaitTimeout}}; + + + + std::conditional_t, + std::nullptr_t> + _fstFuture{}; + + std::stop_source _fstStopSource{}; + + std::unique_ptr _wakeupRequest{new std::atomic_flag}; + std::unique_ptr _slewAndStop{new std::atomic_bool{false}}; + + enum { STATE_IDLE = 0x00, STATE_SLEW = 0x01, STATE_TRACK = 0x02, STATE_STOP = 0x04 }; + + std::unique_ptr _fsmState{new std::atomic_int}; + + // utility methods + + // the method calculates the change in coordinates of a point over a given time given the current speed and braking + // acceleration. a position after given 'time' interval is returned + auto coordsAfterTime(mcc_coord_pair_c auto const& cp, + mcc_coord_pair_c auto const& speedXY, // in radians per seconds + mcc_coord_pair_c auto const& braking_accelXY, // in radians per seconds in square + traits::mcc_time_duration_c auto const& time, + mcc_coord_pair_c auto* dxy = nullptr) + { + // time to stop mount with given current speed and constant braking acceleration + double tx_stop = std::abs(speedXY.x()) / braking_accelXY.x(); + double ty_stop = std::abs(speedXY.y()) / braking_accelXY.y(); + + using secs_t = std::chrono::duration; // seconds as double + + double tx = std::chrono::duration_cast(time).count(); + double ty = std::chrono::duration_cast(time).count(); + + if (std::isfinite(tx_stop) && (tx > tx_stop)) { + tx = tx_stop; + } + if (std::isfinite(ty_stop) && (ty > ty_stop)) { + ty = ty_stop; + } + + // the distance: + // here, one must take into account the sign of the speed!!! + double dx = speedXY.x() * tx - std::copysign(braking_accelXY.x(), speedXY.x()) * tx * tx / 2.0; + double dy = speedXY.y() * ty - std::copysign(braking_accelXY.y(), speedXY.y()) * ty * ty / 2.0; + + std::remove_cvref_t cp_res{}; + cp_res.setEpoch(cp.epoch() + time); + + cp_res.setX((double)cp.x() + dx); + cp_res.setY((double)cp.y() + dy); + + if (dxy) { + dxy->setX(dx); + dxy->setY(dy); + dxy->setEpoch(cp_res.epoch()); + } + + return cp_res; + } + + auto coordsAfterTime(mcc_skypoint_c auto const& sp, + mcc_coord_pair_c auto const& speedXY, // in radians per seconds + mcc_coord_pair_c auto const& braking_accelXY, // in radians per seconds in square + traits::mcc_time_duration_c auto const& time, + mcc_coord_pair_c auto* dxy = nullptr) + { + auto run_func = [&, this](auto& cp) { + sp.toAtSameEpoch(cp); + + auto new_cp = coordsAfterTime(cp, speedXY, braking_accelXY, time, dxy); + + std::remove_cvref_t sp_res{}; + + sp_res.from(cp); + + return sp_res; + }; + + switch (sp.pairKind()) { + case MccCoordPairKind::COORDS_KIND_RADEC_ICRS: { + MccSkyRADEC_ICRS rd; + return run_func(rd); + }; + case MccCoordPairKind::COORDS_KIND_RADEC_OBS: { + MccSkyRADEC_OBS rd; + return run_func(rd); + }; + case MccCoordPairKind::COORDS_KIND_RADEC_APP: { + MccSkyRADEC_APP rd; + return run_func(rd); + }; + case MccCoordPairKind::COORDS_KIND_HADEC_OBS: { + MccSkyHADEC_OBS hd; + return run_func(hd); + }; + case MccCoordPairKind::COORDS_KIND_HADEC_APP: { + MccSkyHADEC_APP hd; + return run_func(hd); + }; + case MccCoordPairKind::COORDS_KIND_AZZD: { + MccSkyAZZD azzd; + return run_func(azzd); + }; + case MccCoordPairKind::COORDS_KIND_AZALT: { + MccSkyAZALT azalt; + return run_func(azalt); + }; + case MccCoordPairKind::COORDS_KIND_GENERIC: + case MccCoordPairKind::COORDS_KIND_XY: { + MccGenXY xy; + return run_func(xy); + }; + default: + return sp; + } + } +}; template diff --git a/include/mcc/mcc_telemetry.h b/include/mcc/mcc_telemetry.h index 0457760..37f21f4 100644 --- a/include/mcc/mcc_telemetry.h +++ b/include/mcc/mcc_telemetry.h @@ -102,6 +102,7 @@ inline std::error_code make_error_code(MccTelemetryErrorCode ec) } +/* template class MccTelemetry : public mcc_telemetry_interface_t @@ -132,60 +133,361 @@ public: static constexpr std::chrono::milliseconds _defaultTelemetryDataTimeout{500}; - /* - MccTelemetry(HARDWARE_T* hardware, mcc_pcm_c auto* pcm) : _hardware(hardware) - { - _updateFunc = [pcm, this](telemetry_data_t* tdata) { - if (tdata == nullptr) { - return MccTelemetryErrorCode::ERROR_NULLPTR; + + +MccTelemetry(HARDWARE_T* hardware, mcc_pcm_c auto* pcm) +{ + _updatingStopSource = std::stop_source{}; + + _dataUpdatingRequested->clear(); + _dataUpdatingStart->clear(); + + // start thread for data updating + _updatingFuture = std::async( + std::launch::async, + [this](std::stop_token stoken, HARDWARE_T* hw, auto* pcm_ptr) { + while (!stoken.stop_requested()) { + _dataUpdatingRequested->wait(false); + + if (!stoken.stop_requested()) { + std::lock_guard lock{*_timeoutMutex}; + + _dataUpdatingStart->test_and_set(); + _dataUpdatingStart->notify_all(); + + if (_tdataPtr != nullptr && hw && pcm_ptr) { + _lastUpdateError = MccTelemetryErrorCode::ERROR_OK; + + // get hardware state (coordinates, speeds and so on) + auto hw_err = hw->hardwareGetState(&_tdataPtr->hwState); + if (hw_err) { + _lastUpdateError = mcc_deduced_err(hw_err, MccTelemetryErrorCode::ERROR_HARDWARE_GETSTATE); + } else { + // compute PCM corrections and observed (corrected for PCM) mount coordinates + auto pcm_err = pcm_ptr->computePCM(_tdataPtr->hwState.XY, &(_tdataPtr->pcmCorrection), + &(_tdataPtr->mountPos)); + + if (!pcm_err) { + // set target coordinates + if (_enteredTargetPos.pairKind() == MccCoordPairKind::COORDS_KIND_XY) { + // hardware coordinates + MccGenXY xy; + auto ccte_err = _enteredTargetPos.toAtSameEpoch(xy); + + if (!ccte_err) { + decltype(_tdataPtr->pcmCorrection) pcm_corr; + + pcm_err = pcm_ptr->computePCM(xy, &pcm_corr, &_tdataPtr->targetPos); + if (pcm_err) { + _lastUpdateError = + mcc_deduced_err(pcm_err, MccTelemetryErrorCode::ERROR_PCM_COMP); + } + + _tdataPtr->pcmReverseCorrection.pcmX = -pcm_corr.pcmX; + _tdataPtr->pcmReverseCorrection.pcmY = -pcm_corr.pcmY; + } else { + _lastUpdateError = + mcc_deduced_err(ccte_err, MccTelemetryErrorCode::ERROR_COORD_TRANSFORM); + } + + } else { // observed, apparent or ICRS + // _tdataPtr->targetPos = _enteredTargetPos; + using pcm_t = std::remove_pointer_t; + + std::conditional_t, MccSkyHADEC_OBS, + std::conditional_t, + MccSkyAZZD, std::nullptr_t>> + cp; + + static_assert(!std::is_null_pointer_v, "UNKNOW MOUNT TYPE!"); + + // calculate target celestial coordinates (of the same type as .mountPos) at the + // epoch of the current mount position + cp.setEpoch(_tdataPtr->mountPos.epoch()); + auto ccte_err = _enteredTargetPos.to(cp); + if (ccte_err) { + _lastUpdateError = + mcc_deduced_err(ccte_err, MccTelemetryErrorCode::ERROR_COORD_TRANSFORM); + } else { + _tdataPtr->targetPos.from(cp); + + // calculate reverse PCM corrections for the current target position and + // its encoder XY + auto pcm_err = pcm_ptr->computeInversePCM(_tdataPtr->targetPos, + &_tdataPtr->pcmReverseCorrection, + &_tdataPtr->targetXY); + if (pcm_err) { + _lastUpdateError = + mcc_deduced_err(pcm_err, MccTelemetryErrorCode::ERROR_PCM_COMP); + } + } + } + } else { + _lastUpdateError = mcc_deduced_err(pcm_err, MccTelemetryErrorCode::ERROR_PCM_COMP); + } + } + + } else { + _lastUpdateError = MccTelemetryErrorCode::ERROR_NULLPTR; + } + + _dataUpdatingStart->clear(); + _dataUpdatingRequested->clear(); + } } + }, + _updatingStopSource.get_token(), hardware, pcm); + + + _updateFunc = [hw = hardware, pcm_ptr = pcm, this](telemetry_data_t* tdata) mutable -> error_t { + _tdataPtr = tdata; + if (_tdataPtr != nullptr && hw && pcm_ptr) { + _lastUpdateError = MccTelemetryErrorCode::ERROR_OK; // get hardware state (coordinates, speeds and so on) - auto hw_err = _hardware->hardwareGetState(&(tdata->hwState)); + auto hw_err = hw->hardwareGetState(&_tdataPtr->hwState); if (hw_err) { - return mcc_deduced_err(hw_err, MccTelemetryErrorCode::ERROR_HARDWARE_GETSTATE); - } + _lastUpdateError = mcc_deduced_err(hw_err, MccTelemetryErrorCode::ERROR_HARDWARE_GETSTATE); + } else { + // compute PCM corrections and observed (corrected for PCM) mount coordinates + auto pcm_err = + pcm_ptr->computePCM(_tdataPtr->hwState.XY, &(_tdataPtr->pcmCorrection), &(_tdataPtr->mountPos)); - // compute PCM corrections and observed (corrected for PCM) mount coordinates - auto pcm_err = pcm->computePCM(tdata->hwState.XY, &(tdata->pcmCorrection), &(tdata->mountPos)); + if (!pcm_err) { + // set target coordinates + if (_enteredTargetPos.pairKind() == MccCoordPairKind::COORDS_KIND_XY) { + // hardware coordinates + MccGenXY xy; + auto ccte_err = _enteredTargetPos.toAtSameEpoch(xy); - if (pcm_err) { - return mcc_deduced_err(pcm_err, MccTelemetryErrorCode::ERROR_PCM_COMP); - } + if (!ccte_err) { + decltype(_tdataPtr->pcmCorrection) pcm_corr; - return MccTelemetryErrorCode::ERROR_OK; - }; + pcm_err = pcm_ptr->computePCM(xy, &pcm_corr, &_tdataPtr->targetPos); + if (pcm_err) { + _lastUpdateError = mcc_deduced_err(pcm_err, MccTelemetryErrorCode::ERROR_PCM_COMP); + } + _tdataPtr->pcmReverseCorrection.pcmX = -pcm_corr.pcmX; + _tdataPtr->pcmReverseCorrection.pcmY = -pcm_corr.pcmY; + } else { + _lastUpdateError = mcc_deduced_err(ccte_err, MccTelemetryErrorCode::ERROR_COORD_TRANSFORM); + } - _updatingStopSource = std::stop_source{}; + } else { // observed, apparent or ICRS + // _tdataPtr->targetPos = _enteredTargetPos; + using pcm_t = std::remove_pointer_t; - _dataUpdatingRequested->clear(); - _dataUpdatingStart->clear(); + std::conditional_t< + mcc_is_equatorial_mount, MccSkyHADEC_OBS, + std::conditional_t, MccSkyAZZD, std::nullptr_t>> + cp; - // start thread for data updating - _updatingFuture = std::async( - std::launch::async, - [this](std::stop_token stoken, telemetry_data_t* tdata) { - while (!stoken.stop_requested()) { - _dataUpdatingRequested->wait(false); + static_assert(!std::is_null_pointer_v, "UNKNOW MOUNT TYPE!"); - if (!stoken.stop_requested()) { - std::lock_guard lock{*_timeoutMutex}; + // calculate target celestial coordinates (of the same type as .mountPos) at the + // epoch of the current mount position + cp.setEpoch(_tdataPtr->mountPos.epoch()); + auto ccte_err = _enteredTargetPos.to(cp); + if (ccte_err) { + _lastUpdateError = mcc_deduced_err(ccte_err, MccTelemetryErrorCode::ERROR_COORD_TRANSFORM); + } else { + _tdataPtr->targetPos.from(cp); - _dataUpdatingStart->test_and_set(); - _dataUpdatingStart->notify_all(); - - _lastUpdateError = _updateFunc(tdata); - - _dataUpdatingStart->clear(); - _dataUpdatingRequested->clear(); + // calculate reverse PCM corrections for the current target position and + // its encoder XY + auto pcm_err = pcm_ptr->computeInversePCM( + _tdataPtr->targetPos, &_tdataPtr->pcmReverseCorrection, &_tdataPtr->targetXY); + if (pcm_err) { + _lastUpdateError = mcc_deduced_err(pcm_err, MccTelemetryErrorCode::ERROR_PCM_COMP); + } + } } + } else { + _lastUpdateError = mcc_deduced_err(pcm_err, MccTelemetryErrorCode::ERROR_PCM_COMP); } - }, - _updatingStopSource.get_token(), _tdataPtr); + } + + } else { + _lastUpdateError = MccTelemetryErrorCode::ERROR_NULLPTR; + } + + return _lastUpdateError; + }; +} + +MccTelemetry(MccTelemetry&&) = default; +MccTelemetry& operator=(MccTelemetry&&) = default; + +MccTelemetry(const MccTelemetry&) = delete; +MccTelemetry& operator=(const MccTelemetry&) = delete; + + +~MccTelemetry() +{ + _tdataPtr = nullptr; + + _updatingStopSource.request_stop(); + + // trigger updating and exit from the inner loop of the hardware polling thread (see constructor) + _dataUpdatingRequested->test_and_set(); + // _dataUpdatingRequested->notify_one(); + _dataUpdatingRequested->notify_all(); + + if (_updatingFuture.valid()) { + // try to exit correctly + _updatingFuture.wait_for(std::chrono::seconds(1)); } +} + +error_t setPointingTarget(mcc_skypoint_c auto const& sp) +{ + std::lock_guard lock{*_updateMutex}; + + _enteredTargetPos = sp; + + return MccTelemetryErrorCode::ERROR_OK; +} + + +auto getPointingTarget() const +{ + std::lock_guard lock{*_updateMutex}; + + return _enteredTargetPos; +} + + +// error_t getPointingTarget(mcc_skypoint_c auto* sp) +// { +// if (sp) { +// *sp = _enteredTargetPos; +// } + +// return MccTelemetryErrorCode::ERROR_OK; +// } + + +// +// blocks the current thread until telemetry data is received. +// the maximum blocking time is equal to the set timeout (see setTelemetryDataTimeout method) +// +error_t telemetryData(telemetry_data_t* tdata) +{ + std::lock_guard lock{*_updateMutex}; + + _lastUpdateError = MccTelemetryErrorCode::ERROR_OK; + + // 12.10.2026: try to catch dead-lock + // use here mutex-free non-timedout implementation + return _updateFunc(tdata); + // tdata = _tdataPtr; + + _tdataPtr = tdata; + + // trigger updating + _dataUpdatingRequested->test_and_set(); + _dataUpdatingRequested->notify_one(); + + // wait for updating start + _dataUpdatingStart->wait(false); + if (_timeoutMutex->try_lock_for(_telemetryDataTimeout->load())) { + _timeoutMutex->unlock(); + } else { + _lastUpdateError = MccTelemetryErrorCode::ERROR_DATA_TIMEOUT; + } + + return _lastUpdateError; +} + + +// +// Set a timeout for the telemetry receiving process +// +template +void setTelemetryDataTimeout(DT const& timeout) +{ + if constexpr (std::floating_point) { + if (utils::isEqual(timeout.count(), 0.0) || timeout.count() < 0.0) { + return; + } + } else { + if (timeout.count() <= 0.0) { + return; + } + } + + *_telemetryDataTimeout = std::chrono::duration_cast(timeout); +} + +template +DT getTelemetryDataTimeout() const +{ + return std::chrono::duration_cast
(_telemetryDataTimeout->load()); +} + +std::chrono::milliseconds getTelemetryDataTimeout() const +{ + return getTelemetryDataTimeout(); +} + +private: +// HARDWARE_T* _hardware{nullptr}; +MccSkyPoint _enteredTargetPos{}; + +std::function _updateFunc{}; +telemetry_data_t* _tdataPtr; + +std::unique_ptr _dataUpdatingRequested{new std::atomic_flag{}}; +std::unique_ptr _dataUpdatingStart{new std::atomic_flag{}}; +std::unique_ptr _timeoutMutex{new std::timed_mutex()}; + +std::stop_source _updatingStopSource{}; + +error_t _lastUpdateError{MccTelemetryErrorCode::ERROR_OK}; + +std::unique_ptr> _telemetryDataTimeout{ + new std::atomic{_defaultTelemetryDataTimeout}}; + +std::unique_ptr _updateMutex{new std::mutex{}}; + +std::future _updatingFuture{}; +}; + + */ + +template +class MccTelemetry : public mcc_telemetry_interface_t +{ +public: + typedef HARDWARE_T hardware_t; + + typedef MccError error_t; + + + struct telemetry_data_t { + MccSkyPoint targetPos{}; // celestial coordinates + + MccGenXY targetXY{}; // encoder coordinates + + struct { + double pcmX{}, pcmY{}; + } pcmReverseCorrection{}; + + MccSkyPoint mountPos{}; // celestial coordinates + + typename HARDWARE_T::hardware_state_t hwState{}; // here encoder coordinates + + struct { + double pcmX{}, pcmY{}; + } pcmCorrection{}; + }; + + static constexpr std::chrono::milliseconds _defaultTelemetryDataTimeout{500}; + + // the pointers 'hardware' and 'pcm' must be valid during the class life-time MccTelemetry(HARDWARE_T* hardware, mcc_pcm_c auto* pcm) { _updatingStopSource = std::stop_source{}; @@ -193,118 +495,20 @@ public: _dataUpdatingRequested->clear(); _dataUpdatingStart->clear(); - // start thread for data updating - _updatingFuture = std::async( - std::launch::async, - [this](std::stop_token stoken, HARDWARE_T* hw, auto* pcm_ptr) { - while (!stoken.stop_requested()) { - _dataUpdatingRequested->wait(false); - if (!stoken.stop_requested()) { - std::lock_guard lock{*_timeoutMutex}; - - _dataUpdatingStart->test_and_set(); - _dataUpdatingStart->notify_all(); - - if (_tdataPtr != nullptr && hw && pcm_ptr) { - _lastUpdateError = MccTelemetryErrorCode::ERROR_OK; - - // get hardware state (coordinates, speeds and so on) - auto hw_err = hw->hardwareGetState(&_tdataPtr->hwState); - if (hw_err) { - _lastUpdateError = - mcc_deduced_err(hw_err, MccTelemetryErrorCode::ERROR_HARDWARE_GETSTATE); - } else { - // compute PCM corrections and observed (corrected for PCM) mount coordinates - auto pcm_err = pcm_ptr->computePCM(_tdataPtr->hwState.XY, &(_tdataPtr->pcmCorrection), - &(_tdataPtr->mountPos)); - - if (!pcm_err) { - // set target coordinates - if (_enteredTargetPos.pairKind() == MccCoordPairKind::COORDS_KIND_XY) { - // hardware coordinates - MccGenXY xy; - auto ccte_err = _enteredTargetPos.toAtSameEpoch(xy); - - if (!ccte_err) { - decltype(_tdataPtr->pcmCorrection) pcm_corr; - - pcm_err = pcm_ptr->computePCM(xy, &pcm_corr, &_tdataPtr->targetPos); - if (pcm_err) { - _lastUpdateError = - mcc_deduced_err(pcm_err, MccTelemetryErrorCode::ERROR_PCM_COMP); - } - - _tdataPtr->pcmReverseCorrection.pcmX = -pcm_corr.pcmX; - _tdataPtr->pcmReverseCorrection.pcmY = -pcm_corr.pcmY; - } else { - _lastUpdateError = - mcc_deduced_err(ccte_err, MccTelemetryErrorCode::ERROR_COORD_TRANSFORM); - } - - } else { // observed, apparent or ICRS - // _tdataPtr->targetPos = _enteredTargetPos; - using pcm_t = std::remove_pointer_t; - - std::conditional_t, - MccSkyHADEC_OBS, - std::conditional_t, - MccSkyAZZD, std::nullptr_t>> - cp; - - static_assert(!std::is_null_pointer_v, "UNKNOW MOUNT TYPE!"); - - // calculate target celestial coordinates (of the same type as .mountPos) at the - // epoch of the current mount position - cp.setEpoch(_tdataPtr->mountPos.epoch()); - auto ccte_err = _enteredTargetPos.to(cp); - if (ccte_err) { - _lastUpdateError = - mcc_deduced_err(ccte_err, MccTelemetryErrorCode::ERROR_COORD_TRANSFORM); - } else { - _tdataPtr->targetPos.from(cp); - - // calculate reverse PCM corrections for the current target position and - // its encoder XY - auto pcm_err = pcm_ptr->computeInversePCM(_tdataPtr->targetPos, - &_tdataPtr->pcmReverseCorrection, - &_tdataPtr->targetXY); - if (pcm_err) { - _lastUpdateError = - mcc_deduced_err(pcm_err, MccTelemetryErrorCode::ERROR_PCM_COMP); - } - } - } - } else { - _lastUpdateError = mcc_deduced_err(pcm_err, MccTelemetryErrorCode::ERROR_PCM_COMP); - } - } - - } else { - _lastUpdateError = MccTelemetryErrorCode::ERROR_NULLPTR; - } - - _dataUpdatingStart->clear(); - _dataUpdatingRequested->clear(); - } - } - }, - _updatingStopSource.get_token(), hardware, pcm); - - - _updateFunc = [hw=hardware, pcm_ptr=pcm, this](telemetry_data_t* tdata) mutable -> error_t { - _tdataPtr = tdata; - if (_tdataPtr != nullptr && hw && pcm_ptr) { + _updateFunc = [hw = hardware, pcm_ptr = pcm, this](telemetry_data_t* tdata_ptr) mutable -> error_t { + if (tdata_ptr != nullptr && hw && pcm_ptr) { _lastUpdateError = MccTelemetryErrorCode::ERROR_OK; + telemetry_data_t tdata; + // get hardware state (coordinates, speeds and so on) - auto hw_err = hw->hardwareGetState(&_tdataPtr->hwState); + auto hw_err = hw->hardwareGetState(&tdata.hwState); if (hw_err) { _lastUpdateError = mcc_deduced_err(hw_err, MccTelemetryErrorCode::ERROR_HARDWARE_GETSTATE); } else { // compute PCM corrections and observed (corrected for PCM) mount coordinates - auto pcm_err = - pcm_ptr->computePCM(_tdataPtr->hwState.XY, &(_tdataPtr->pcmCorrection), &(_tdataPtr->mountPos)); + auto pcm_err = pcm_ptr->computePCM(tdata.hwState.XY, &(tdata.pcmCorrection), &(tdata.mountPos)); if (!pcm_err) { // set target coordinates @@ -314,45 +518,46 @@ public: auto ccte_err = _enteredTargetPos.toAtSameEpoch(xy); if (!ccte_err) { - decltype(_tdataPtr->pcmCorrection) pcm_corr; + decltype(tdata.pcmCorrection) pcm_corr; - pcm_err = pcm_ptr->computePCM(xy, &pcm_corr, &_tdataPtr->targetPos); + pcm_err = pcm_ptr->computePCM(xy, &pcm_corr, &tdata.targetPos); if (pcm_err) { _lastUpdateError = mcc_deduced_err(pcm_err, MccTelemetryErrorCode::ERROR_PCM_COMP); } - _tdataPtr->pcmReverseCorrection.pcmX = -pcm_corr.pcmX; - _tdataPtr->pcmReverseCorrection.pcmY = -pcm_corr.pcmY; + tdata.pcmReverseCorrection.pcmX = -pcm_corr.pcmX; + tdata.pcmReverseCorrection.pcmY = -pcm_corr.pcmY; } else { _lastUpdateError = mcc_deduced_err(ccte_err, MccTelemetryErrorCode::ERROR_COORD_TRANSFORM); } } else { // observed, apparent or ICRS - // _tdataPtr->targetPos = _enteredTargetPos; using pcm_t = std::remove_pointer_t; - std::conditional_t< - mcc_is_equatorial_mount, MccSkyHADEC_OBS, - std::conditional_t, MccSkyAZZD, std::nullptr_t>> - cp; + // std::conditional_t< + // mcc_is_equatorial_mount, MccSkyHADEC_OBS, + // std::conditional_t, MccSkyAZZD, + // std::nullptr_t>> cp; + + mcc_deduced_coord_pair_t cp; static_assert(!std::is_null_pointer_v, "UNKNOW MOUNT TYPE!"); // calculate target celestial coordinates (of the same type as .mountPos) at the // epoch of the current mount position - cp.setEpoch(_tdataPtr->mountPos.epoch()); + cp.setEpoch(tdata.mountPos.epoch()); auto ccte_err = _enteredTargetPos.to(cp); if (ccte_err) { _lastUpdateError = mcc_deduced_err(ccte_err, MccTelemetryErrorCode::ERROR_COORD_TRANSFORM); } else { - _tdataPtr->targetPos.from(cp); + tdata.targetPos.from(cp); // calculate reverse PCM corrections for the current target position and // its encoder XY - auto pcm_err = pcm_ptr->computeInversePCM( - _tdataPtr->targetPos, &_tdataPtr->pcmReverseCorrection, &_tdataPtr->targetXY); + auto pcm_err = pcm_ptr->computeInversePCM(tdata.targetPos, &tdata.pcmReverseCorrection, + &tdata.targetXY); if (pcm_err) { _lastUpdateError = mcc_deduced_err(pcm_err, MccTelemetryErrorCode::ERROR_PCM_COMP); } @@ -363,36 +568,33 @@ public: } } + if (!_lastUpdateError) { + *tdata_ptr = std::move(tdata); + } + } else { _lastUpdateError = MccTelemetryErrorCode::ERROR_NULLPTR; } - return _lastUpdateError; + + return _lastUpdateError; }; } - MccTelemetry(MccTelemetry&&) = default; - MccTelemetry& operator=(MccTelemetry&&) = default; - - MccTelemetry(const MccTelemetry&) = delete; - MccTelemetry& operator=(const MccTelemetry&) = delete; + ~MccTelemetry() = default; - ~MccTelemetry() + // + // blocks the current thread until telemetry data is received. + // the maximum blocking time is equal to the set timeout (see setTelemetryDataTimeout method) + // + error_t telemetryData(telemetry_data_t* tdata) { - _tdataPtr = nullptr; + std::lock_guard lock{*_updateMutex}; - _updatingStopSource.request_stop(); + _lastUpdateError = MccTelemetryErrorCode::ERROR_OK; - // trigger updating and exit from the inner loop of the hardware polling thread (see constructor) - _dataUpdatingRequested->test_and_set(); - // _dataUpdatingRequested->notify_one(); - _dataUpdatingRequested->notify_all(); - - if (_updatingFuture.valid()) { - // try to exit correctly - _updatingFuture.wait_for(std::chrono::seconds(1)); - } + return _updateFunc(tdata); } error_t setPointingTarget(mcc_skypoint_c auto const& sp) @@ -412,50 +614,6 @@ public: return _enteredTargetPos; } - - // error_t getPointingTarget(mcc_skypoint_c auto* sp) - // { - // if (sp) { - // *sp = _enteredTargetPos; - // } - - // return MccTelemetryErrorCode::ERROR_OK; - // } - - - // - // blocks the current thread until telemetry data is received. - // the maximum blocking time is equal to the set timeout (see setTelemetryDataTimeout method) - // - error_t telemetryData(telemetry_data_t* tdata) - { - std::lock_guard lock{*_updateMutex}; - - _lastUpdateError = MccTelemetryErrorCode::ERROR_OK; - - // 12.10.2026: try to catch dead-lock - // use here mutex-free non-timedout implementation - return _updateFunc(tdata); -// tdata = _tdataPtr; - - _tdataPtr = tdata; - - // trigger updating - _dataUpdatingRequested->test_and_set(); - _dataUpdatingRequested->notify_one(); - - // wait for updating start - _dataUpdatingStart->wait(false); - if (_timeoutMutex->try_lock_for(_telemetryDataTimeout->load())) { - _timeoutMutex->unlock(); - } else { - _lastUpdateError = MccTelemetryErrorCode::ERROR_DATA_TIMEOUT; - } - - return _lastUpdateError; - } - - // // Set a timeout for the telemetry receiving process // @@ -487,11 +645,9 @@ public: } private: - // HARDWARE_T* _hardware{nullptr}; MccSkyPoint _enteredTargetPos{}; std::function _updateFunc{}; - telemetry_data_t* _tdataPtr; std::unique_ptr _dataUpdatingRequested{new std::atomic_flag{}}; std::unique_ptr _dataUpdatingStart{new std::atomic_flag{}}; @@ -509,5 +665,4 @@ private: std::future _updatingFuture{}; }; - } // namespace mcc::impl