This commit is contained in:
Timur A. Fatkhullin 2025-10-29 18:47:24 +03:00
parent 6a72ead855
commit 50e79aa0ae
18 changed files with 273 additions and 62 deletions

View File

@ -10,7 +10,7 @@ set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake")
find_package(ASIO QUIET)
if (ASIO_FOUND)
# message(STATUS "ASIO library was found")
message(STATUS "ASIO library was found in the host system")
else()
message(STATUS "ASIO library was not found! Try to download it!")
@ -33,6 +33,26 @@ else()
find_package(ASIO)
endif()
find_package(cxxopts QUIET CONFIG)
if (cxxopts_FOUND)
message(STATUS "CXXOPTS library was found in the host system")
else()
message(STATUS "CXXOPTS library was not found! Try to download it!")
include(FetchContent)
include(ExternalProject)
FetchContent_Declare(cxxopts_lib
SOURCE_DIR ${CMAKE_BINARY_DIR}/cxxopts_lib
BINARY_DIR ${CMAKE_BINARY_DIR}
GIT_REPOSITORY "https://github.com/jarro2783/cxxopts.git"
GIT_TAG "v3.3.1"
GIT_SHALLOW TRUE
GIT_SUBMODULES ""
GIT_PROGRESS TRUE
)
FetchContent_MakeAvailable(cxxopts_lib)
endif()
set(ASIBFM700_LIB_SRC asibfm700_common.h asibfm700_servocontroller.h asibfm700_servocontroller.cpp)
@ -44,8 +64,14 @@ add_library(${ASIBFM700_LIB} STATIC ${ASIBFM700_LIB_SRC}
asibfm700_netserver.h
)
target_include_directories(${ASIBFM700_LIB} PRIVATE mcc spdlog ${ERFA_INCLUDE_DIR})
target_link_libraries(${ASIBFM700_LIB} PRIVATE mcc spdlog)
target_include_directories(${ASIBFM700_LIB} PUBLIC mcc spdlog ${ERFA_INCLUDE_DIR})
target_link_libraries(${ASIBFM700_LIB} mcc spdlog ${ERFA_LIBFILE})
set(ASIBFM700_NETSERVER_APP asibfm700_netserver)
add_executable(${ASIBFM700_NETSERVER_APP} asibfm700_netserver_main.cpp)
# target_include_directories(${ASIBFM700_NETSERVER_APP} PRIVATE mcc spdlog)
target_link_libraries(${ASIBFM700_NETSERVER_APP} PRIVATE mcc spdlog ${ASIBFM700_LIB})
option(WITH_TESTS "Build tests" ON)

View File

@ -8,22 +8,23 @@ namespace asibfm700
/* CONSTRUCTOR AND DESTRUCTOR */
Asibfm700Mount::Asibfm700Mount(Asibfm700MountConfig const& config,
std::shared_ptr<spdlog::logger> logger,
const auto& pattern_range)
Asibfm700Mount::Asibfm700Mount(Asibfm700MountConfig const& config, std::shared_ptr<spdlog::logger> logger)
: mcc::ccte::erfa::MccCCTE_ERFA({.meteo{.temperature = 10.0, .humidity = 0.5, .pressure = 1010.0},
.wavelength = config.refractWavelength(),
.lat = config.siteLatitude(),
.lon = config.siteLongitude(),
.elev = config.siteElevation()}),
Asibfm700PCM(config.pcmData()),
base_gm_class_t(gm_class_t{AsibFM700ServoController{config.servoControllerConfig()}, mcc::MccTelemetry{this},
Asibfm700PZoneContainer{}, mcc::MccSimpleSlewingModel{this},
mcc::MccSimpleTrackingModel{this}, Asibfm700Logger{std::move(logger), pattern_range}},
Asibfm700StartState{}),
base_gm_class_t(
gm_class_t{AsibFM700ServoController{config.servoControllerConfig()}, mcc::MccTelemetry{this},
Asibfm700PZoneContainer{}, mcc::MccSimpleSlewingModel{this}, mcc::MccSimpleTrackingModel{this},
Asibfm700Logger{std::move(logger), Asibfm700Logger::LOGGER_DEFAULT_FORMAT}},
Asibfm700StartState{}),
_mountConfig(config),
_mountConfigMutex(new std::mutex)
{
addMarkToPatternIdx("ASIB-MOUNT");
logDebug("Create Asibfm700Mount class instance ({})", this->getThreadId());
initMount();

View File

@ -93,9 +93,7 @@ public:
// using Asibfm700PZoneContainer::addPZone;
Asibfm700Mount(Asibfm700MountConfig const& config,
std::shared_ptr<spdlog::logger> logger,
const auto& pattern_range = mcc::utils::MccSpdlogLogger::LOGGER_DEFAULT_FORMAT);
Asibfm700Mount(Asibfm700MountConfig const& config, std::shared_ptr<spdlog::logger> logger);
~Asibfm700Mount();

View File

@ -7,10 +7,11 @@ namespace asibfm700
template <mcc::traits::mcc_range_of_input_char_range R>
Asibfm700MountNetServer::Asibfm700MountNetServer(asio::io_context& ctx,
Asibfm700Mount& mount,
std::shared_ptr<spdlog::logger> logger,
const R& pattern_range)
: base_t(ctx, mount, std::move(logger), pattern_range)
std::shared_ptr<spdlog::logger> logger)
: base_t(ctx, mount, std::move(logger), Asibfm700Logger::LOGGER_DEFAULT_FORMAT)
{
addMarkToPatternIdx("ASIB-NETSERVER");
// to avoid possible compiler optimization (one needs to catch 'mount' strictly by reference)
auto* mount_ptr = &mount;

View File

@ -139,10 +139,7 @@ class Asibfm700MountNetServer : public mcc::network::MccGenericMountNetworkServe
public:
template <mcc::traits::mcc_range_of_input_char_range R = decltype(Asibfm700Logger::LOGGER_DEFAULT_FORMAT)>
Asibfm700MountNetServer(asio::io_context& ctx,
Asibfm700Mount& mount,
std::shared_ptr<spdlog::logger> logger,
const R& pattern_range = Asibfm700Logger::LOGGER_DEFAULT_FORMAT);
Asibfm700MountNetServer(asio::io_context& ctx, Asibfm700Mount& mount, std::shared_ptr<spdlog::logger> logger);
~Asibfm700MountNetServer();

View File

@ -0,0 +1,135 @@
#include <spdlog/sinks/basic_file_sink.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <cxxopts.hpp>
#include <iostream>
#include <asio/thread_pool.hpp>
#include <mcc_netserver_endpoint.h>
#include "asibfm700_netserver.h"
int main(int argc, char* argv[])
{
/* COMMANDLINE OPTS */
cxxopts::Options options(argv[0], "Astrosib (c) BM700 mount server\n");
options.allow_unrecognised_options();
options.add_options()("h,help", "Print usage");
options.add_options()("D,daemon", "Demonize server");
options.add_options()("l,log", "Log filename (use stdout and stderr for standard output and error stream)",
cxxopts::value<std::string>()->default_value(""));
options.add_options()("level", "Log level (see SPDLOG package description for valid values)",
cxxopts::value<std::string>()->default_value("info"));
options.add_options()(
"endpoints",
"endpoints server will be listening for. For 'local' endpoint the '@' symbol at the beginning of the path "
"means "
"abstract namespace socket.",
cxxopts::value<std::vector<std::string>>()->default_value("local://stream/@BM700_SERVER"));
options.positional_help("[endpoint0] [enpoint1] ... [endpointN]");
options.parse_positional({"endpoints"});
asio::io_context ctx(2);
try {
auto opt_result = options.parse(argc, argv);
if (opt_result["help"].count()) {
std::cout << options.help();
std::cout << "\n";
std::cout << "[endpoint0] [enpoint1] ... [endpointN] - endpoints server will be listening for. For 'local' "
"endpoint the '@' symbol at the beginning of the path "
"means abstract namespace socket (e.g. local://stream/@BM700_SERVER)."
<< "\n";
return 0;
}
auto logname = opt_result["log"].as<std::string>();
auto logger = [&logname]() {
if (logname == "stdout") {
return spdlog::stdout_color_mt("console");
} else if (logname == "stderr") {
return spdlog::stderr_color_mt("stderr");
} else if (logname == "") {
return spdlog::null_logger_mt("BM700_SERVER_NULL_LOGGER");
} else {
return spdlog::basic_logger_mt(logname, logname);
}
}();
std::string level_str = opt_result["level"].as<std::string>();
std::ranges::transform(level_str, level_str.begin(), [](const char& c) { return std::tolower(c); });
auto log_level = spdlog::level::from_str(level_str);
logger->set_level(log_level);
logger->flush_on(spdlog::level::trace);
logger->set_pattern("%v");
int w = 90;
// const std::string fmt = std::format("{{:*^{}}}", w);
constexpr std::string_view fmt = "{{:*^90}}";
logger->info("\n\n\n");
logger->info(fmt, "");
logger->info(fmt, " ASTROSIB BM700 MOUNT SERVER ");
auto zt = std::chrono::zoned_time(std::chrono::current_zone(),
std::chrono::floor<std::chrono::seconds>(std::chrono::system_clock::now()));
logger->info(fmt, std::format(" {} ", zt));
logger->info(fmt, "");
logger->info("\n");
asibfm700::Asibfm700MountConfig mount_cfg;
asibfm700::Asibfm700Mount mount(mount_cfg, logger);
asibfm700::Asibfm700MountNetServer server(ctx, mount, logger);
server.setupSignals();
if (opt_result["daemon"].count()) {
server.daemonize();
}
// mcc::MccServerEndpoint epn(std::string_view("local://seqpacket/tmp/BM700_SERVER_SOCK"));
// mcc::MccServerEndpoint epn(std::string_view("local://stream/tmp/BM700_SERVER_SOCK"));
// mcc::MccServerEndpoint epn(std::string_view("local://stream/@tmp/BM700_SERVER_SOCK"));
// mcc::MccServerEndpoint epn(std::string_view("tcp://localhost:12345"));
// asio::co_spawn(ctx, server.listen(epn), asio::detached);
auto epnts = opt_result["endpoints"].as<std::vector<std::string>>();
for (auto& epnt : epnts) {
mcc::network::MccNetServerEndpoint ep(epnt);
if (ep.isValid()) {
ep.makeAbstract('@');
asio::co_spawn(ctx, server.listen(ep), asio::detached);
} else {
std::cerr << "Unrecognized endpoint: '" << epnt << "'! Ignore!\n";
}
}
asio::thread_pool pool(3);
asio::post(pool, [&ctx]() { ctx.run(); });
pool.join();
// ctx.run();
} catch (...) {
}
}

View File

@ -3,6 +3,47 @@
namespace asibfm700
{
const char* AsibFM700ServoControllerErrorCategory::name() const noexcept
{
return "ASIBFM700-ERROR-CATEGORY";
}
std::string AsibFM700ServoControllerErrorCategory::message(int ec) const
{
AsibFM700ServoControllerErrorCode err = static_cast<AsibFM700ServoControllerErrorCode>(ec);
switch (err) {
case AsibFM700ServoControllerErrorCode::ERROR_OK:
return "OK";
case AsibFM700ServoControllerErrorCode::ERROR_FATAL:
return "LibServo fatal error";
case AsibFM700ServoControllerErrorCode::ERROR_BADFORMAT:
return "LibServo wrong arguments of function";
case AsibFM700ServoControllerErrorCode::ERROR_ENCODERDEV:
return "LibServo encoder device error or can't open";
case AsibFM700ServoControllerErrorCode::ERROR_MOUNTDEV:
return "LibServo mount device error or can't open";
case AsibFM700ServoControllerErrorCode::ERROR_FAILED:
return "LibServo failed to run command";
case AsibFM700ServoControllerErrorCode::ERROR_NULLPTR:
return "nullptr argument";
case AsibFM700ServoControllerErrorCode::ERROR_POLLING_TIMEOUT:
return "polling timeout";
default:
return "UNKNOWN";
}
}
const AsibFM700ServoControllerErrorCategory& AsibFM700ServoControllerErrorCategory::get()
{
static const AsibFM700ServoControllerErrorCategory constInst;
return constInst;
}
AsibFM700ServoController::AsibFM700ServoController() : _hardwareConfig(), _setStateMutex(new std::mutex) {}
AsibFM700ServoController::AsibFM700ServoController(hardware_config_t config) : AsibFM700ServoController()
@ -16,6 +57,9 @@ AsibFM700ServoController::AsibFM700ServoController(hardware_config_t config) : A
}
AsibFM700ServoController::~AsibFM700ServoController() {}
constexpr std::string_view AsibFM700ServoController::hardwareName() const
{
return "Sidereal-ServoControllerII";

View File

@ -25,17 +25,17 @@ enum class AsibFM700ServoControllerErrorCode : int {
};
// error category
struct AsibFM700HardwareErrorCategory : public std::error_category {
struct AsibFM700ServoControllerErrorCategory : public std::error_category {
const char* name() const noexcept;
std::string message(int ec) const;
static const AsibFM700HardwareErrorCategory& get();
static const AsibFM700ServoControllerErrorCategory& get();
};
static inline std::error_code make_error_code(AsibFM700ServoControllerErrorCode ec)
{
return std::error_code(static_cast<int>(ec), AsibFM700HardwareErrorCategory::get());
return std::error_code(static_cast<int>(ec), AsibFM700ServoControllerErrorCategory::get());
}
} // namespace asibfm700

View File

@ -62,6 +62,7 @@ add_library(ERFA_LIB STATIC IMPORTED)
set_target_properties(ERFA_LIB PROPERTIES IMPORTED_LOCATION ${CMAKE_BINARY_DIR}/erfa_lib/liberfa.a)
add_dependencies(ERFA_LIB erfalib)
set(ERFA_INCLUDE_DIR ${CMAKE_BINARY_DIR}/erfa_lib)
set(ERFA_LIBFILE ${CMAKE_BINARY_DIR}/erfa_lib/erfa)
# include_directories(${ERFA_INCLUDE_DIR})
message(STATUS ${ERFA_INCLUDE_DIR})

View File

@ -396,7 +396,7 @@ public:
[p_event, states, currentState, this]<traits::fsm_state_c curr_state_t>(curr_state_t*) {
using to_state_t = curr_state_t::transition_t::template find_state_by_event_t<EvT>;
if constexpr (std::holds_alternative<to_state_t>(*currentState)) {
if (std::holds_alternative<to_state_t>(*currentState)) {
// ?!!!! from self
}

View File

@ -168,7 +168,7 @@ public:
SlewModelT(std::move(slew_model)),
TrackModelT(std::move(track_model)),
LoggerT(std::move(logger)),
_mountStatus(new mount_status_t)
_mountStatus(new std::atomic<mount_status_t>)
{
*_mountStatus = mount_status_t::IDLE;
}
@ -481,12 +481,12 @@ protected:
void exit(fsm::traits::fsm_event_c auto& event)
{
exitLog(event);
this->exitLog(event);
}
void enter(fsm::traits::fsm_event_c auto& event)
{
enterLog(event);
this->enterLog(event);
}
};
@ -522,7 +522,7 @@ protected:
void exit(fsm::traits::fsm_event_c auto& event)
{
exitLog(event);
this->exitLog(event);
}
void enter(fsm::traits::fsm_event_c auto& event)
@ -575,12 +575,12 @@ protected:
void exit(fsm::traits::fsm_event_c auto& event)
{
exitLog(event);
this->exitLog(event);
}
void enter(fsm::traits::fsm_event_c auto& event)
{
enterLog(event);
this->enterLog(event);
auto* mount_ptr = event.mount();
@ -633,12 +633,12 @@ protected:
void exit(fsm::traits::fsm_event_c auto& event)
{
exitLog(event);
this->exitLog(event);
}
void enter(fsm::traits::fsm_event_c auto& event)
{
enterLog(event);
this->enterLog(event);
auto* mount_ptr = event.mount();
@ -685,12 +685,12 @@ protected:
void exit(fsm::traits::fsm_event_c auto& event)
{
exitLog(event);
this->exitLog(event);
}
void enter(fsm::traits::fsm_event_c auto& event)
{
enterLog(event);
this->enterLog(event);
auto* mount_ptr = event.mount();
@ -722,7 +722,7 @@ protected:
// just reset error
event.mount()->_lastError = MccGenericFsmMountErrorCode::ERROR_OK;
exitLog(event);
this->exitLog(event);
if constexpr (mcc_generic_log_mount_c<MOUNT_T>) {
event.mount()->logWarn(
@ -736,7 +736,7 @@ protected:
{
event.mount()->_lastError = event.eventData();
enterLog(event);
this->enterLog(event);
if constexpr (mcc_generic_log_mount_c<MOUNT_T>) {
auto err = event.eventData();

View File

@ -75,7 +75,7 @@ struct MccSimpleMovingModelParams {
template <mcc_pzone_container_c PZoneContT>
bool mcc_is_near_pzones(PZoneContT* pz_cont,
mcc_telemetry_c auto const& tdata,
mcc_telemetry_data_c auto const& tdata,
traits::mcc_time_duration_c auto const& min_timeto,
typename PZoneContT::error_t& err)
{
@ -100,7 +100,7 @@ bool mcc_is_near_pzones(PZoneContT* pz_cont,
template <mcc_pzone_container_c PZoneContT>
typename PZoneContT::error_t mcc_find_closest_pzone(PZoneContT* pz_cont,
mcc_telemetry_c auto const& tdata,
mcc_telemetry_data_c auto const& tdata,
mcc_eqt_hrz_coord_c auto* closest_coords)
{
using res_t = std::decay_t<decltype(*closest_coords)>;

View File

@ -211,7 +211,7 @@ public:
template <typename... CtorArgTs>
asio::awaitable<void> listen(std::derived_from<MccServerEndpoint> auto endpoint, CtorArgTs&&... ctor_args)
asio::awaitable<void> listen(std::derived_from<MccNetServerEndpoint> auto endpoint, CtorArgTs&&... ctor_args)
{
if (!endpoint.isValid()) {
logError(std::format("Cannot start listening! Invalid endpoint string representation ('{}')!",

View File

@ -67,7 +67,7 @@ static constexpr bool mcc_char_range_compare(const traits::mcc_char_view auto& w
*/
class MccServerEndpoint
class MccNetServerEndpoint
{
public:
static constexpr std::string_view protoHostDelim = "://";
@ -99,25 +99,25 @@ public:
template <traits::mcc_input_char_range R>
MccServerEndpoint(const R& ept)
MccNetServerEndpoint(const R& ept)
{
fromRange(ept);
}
MccServerEndpoint(const MccServerEndpoint& other)
MccNetServerEndpoint(const MccNetServerEndpoint& other)
{
copyInst(other);
}
MccServerEndpoint(MccServerEndpoint&& other)
MccNetServerEndpoint(MccNetServerEndpoint&& other)
{
moveInst(std::move(other));
}
virtual ~MccServerEndpoint() = default;
virtual ~MccNetServerEndpoint() = default;
MccServerEndpoint& operator=(const MccServerEndpoint& other)
MccNetServerEndpoint& operator=(const MccNetServerEndpoint& other)
{
copyInst(other);
@ -125,7 +125,7 @@ public:
}
MccServerEndpoint& operator=(MccServerEndpoint&& other)
MccNetServerEndpoint& operator=(MccNetServerEndpoint&& other)
{
moveInst(std::move(other));
@ -358,7 +358,7 @@ public:
// add '\0' char (or replace special-meaning char/char-sequence) to construct UNIX abstract namespace
// endpoint path
template <typename T = std::nullptr_t>
MccServerEndpoint& makeAbstract(const T& mark = nullptr)
MccNetServerEndpoint& makeAbstract(const T& mark = nullptr)
requires(traits::mcc_input_char_range<T> || std::same_as<std::remove_cv_t<T>, char> ||
std::is_null_pointer_v<std::remove_cv_t<T>>)
{
@ -397,7 +397,7 @@ protected:
ssize_t idx = 0;
// case-insensitive look-up
bool found = std::ranges::any_of(MccServerEndpoint::validProtoMarks, [&idx, &proto_mark](const auto& el) {
bool found = std::ranges::any_of(MccNetServerEndpoint::validProtoMarks, [&idx, &proto_mark](const auto& el) {
bool ok = utils::mcc_char_range_compare(proto_mark, el, true);
if (!ok) {
@ -449,7 +449,7 @@ protected:
return res;
}
void copyInst(const MccServerEndpoint& other)
void copyInst(const MccNetServerEndpoint& other)
{
if (&other != this) {
if (other._isValid) {
@ -485,7 +485,7 @@ protected:
}
void moveInst(MccServerEndpoint&& other)
void moveInst(MccNetServerEndpoint&& other)
{
if (&other != this) {
if (other._isValid) {

View File

@ -46,7 +46,10 @@ namespace mcc
struct MccPZoneContainerCategory : public std::error_category {
MccPZoneContainerCategory() : std::error_category() {}
const char* name() const noexcept { return "ALTITUDE-LIMIT-PZ"; }
const char* name() const noexcept
{
return "ALTITUDE-LIMIT-PZ";
}
std::string message(int ec) const
{
@ -248,11 +251,14 @@ public:
}
size_t sizePZones() const { return _inZoneFuncCPT.size(); }
size_t sizePZones() const
{
return _inZoneFuncCPT.size();
}
template <typename InputT>
error_t inPZone(InputT coords, bool* common_result, std::ranges::output_range<bool> auto* result = nullptr)
template <typename InputT, std::ranges::output_range<bool> ResT = std::vector<bool>>
error_t inPZone(InputT coords, bool* common_result, ResT* result = nullptr)
requires(mcc_eqt_hrz_coord_c<InputT> || mcc_celestial_point_c<InputT>)
{
if (common_result == nullptr) {
@ -418,7 +424,7 @@ public:
std::ranges::advance(ptr, i);
error_t ret;
if constexpr (mcc_eqt_hrz_coord_c<ResultT>) {
if constexpr (mcc_eqt_hrz_coord_c<std::ranges::range_value_t<ResultT>>) {
MccEqtHrzCoords pt;
mcc_tp2tp(ptr->time_point, pt.time_point);

View File

@ -200,7 +200,7 @@ public:
}
std::chrono::steady_clock::time_point start_slewing_tp, last_adjust_tp;
mcc_tp2tp(hw_state.time_point, start_slewing_tp);
// mcc_tp2tp(hw_state.time_point, start_slewing_tp); // not compiled!!
// double dist, dx, dy, sinY, rate2, xrate;
// std::chrono::duration<double> dtx, dty; // seconds in double

View File

@ -298,7 +298,7 @@ public:
};
*/
_updateFunc = [controls, this](std::stop_token stop_token) {
_updateFunc = [controls, this](std::stop_token stop_token) -> std::error_code {
// first, update mount quantities
typename hardware_t::hardware_state_t hw_pos;
auto hw_err = controls->hardwareGetState(&hw_pos);
@ -619,8 +619,8 @@ public:
std::unique_lock ulock(*_updateMutex);
auto res = _updateCondVar->wait_for(ulock, timeout, [this]() { return *_isDataUpdated; });
if (res == std::cv_status::timeout) {
auto res = _updateCondVar->wait_for(ulock, timeout, [this]() -> bool { return _isDataUpdated.get(); });
if (!res) {
return MccTelemetryErrorCode::ERROR_DATA_TIMEOUT;
}

View File

@ -170,10 +170,12 @@ public:
} else {
static_assert(false, "UNKNOW MOUNT TYPE!");
}
return MccSimpleTrackingModelErrorCode::ERROR_OK;
};
auto target_point = [&, this](MccCelestialPoint* point) {
auto target_point = [&, this](MccCelestialPoint* point) -> std::error_code {
auto dt = std::chrono::duration<double>{tdata.HA} +
_currentParams.timeShiftToTargetPoint * mcc_sideral_to_UT1_ratio; // hour seconds
@ -226,7 +228,7 @@ public:
return mcc_deduce_error_code(pz_err, MccSimpleTrackingModelErrorCode::ERROR_PZONE_CONTAINER_COMP);
}
hw_state.moving_state = CONTROLS_T::hardware_moving_state_t::HW_MOVE_Tracking;
hw_state.moving_state = CONTROLS_T::hardware_moving_state_t::HW_MOVE_TRACKING;
{
std::lock_guard lock{*_currentParamsMutex};
@ -311,7 +313,7 @@ public:
}
// send corrections
hw_state.moving_state = CONTROLS_T::hardware_moving_state_t::HW_MOVE_Tracking;
hw_state.moving_state = CONTROLS_T::hardware_moving_state_t::HW_MOVE_TRACKING;
hw_err = controls->hardwareSetState(hw_state);
if (hw_err) {
*_stopTracking = true;