diff --git a/backend/.clang-format b/backend/.clang-format index 39a8ea0..00955d1 100644 --- a/backend/.clang-format +++ b/backend/.clang-format @@ -93,7 +93,7 @@ BreakBeforeTernaryOperators: true BreakConstructorInitializers: BeforeComma BreakInheritanceList: BeforeColon BreakStringLiterals: true -ColumnLimit: 0 +ColumnLimit: 100 CommentPragmas: '^ IWYU pragma:' CompactNamespaces: false ConstructorInitializerIndentWidth: 4 diff --git a/backend/src/Helpers.hpp b/backend/src/Helpers.hpp index 68e993d..34ada5e 100644 --- a/backend/src/Helpers.hpp +++ b/backend/src/Helpers.hpp @@ -8,6 +8,15 @@ class Helpers { public: + /** + * Cleans up the given frequency value. + * + * This function takes an integer frequency value as input and rounds it up to a valid 8.33 kHz channel. + * The cleaned up frequency value is then returned. + * + * @param frequency The frequency value to be cleaned up. + * @return The cleaned up frequency value. + */ static int CleanUpFrequency(int frequency) { // We don't clean up an unset frequency @@ -18,6 +27,11 @@ class Helpers { return RadioSimulation::round8_33kHzChannel(frequency); } + /** + * Calls the NAPI frontend callback function with an error message. + * + * @param message The error message to pass to the callback. + */ static void CallbackWithError(const std::string& message) { std::lock_guard lock(errorCallbackMutex); @@ -25,15 +39,19 @@ class Helpers { return; } - callbackRef.NonBlockingCall( - [message](Napi::Env env, Napi::Function jsCallback) { - jsCallback.Call({ Napi::String::New(env, "error"), - Napi::String::New(env, message), - Napi::String::New(env, "") }); - }); + callbackRef.NonBlockingCall([message](Napi::Env env, Napi::Function jsCallback) { + jsCallback.Call({ Napi::String::New(env, "error"), Napi::String::New(env, message), + Napi::String::New(env, "") }); + }); } - static std::string ConvertHzToHumanString(int frequencyHz) + /** + * Converts a frequency in Hertz to a human-readable string representation. + * + * @param frequencyHz The frequency in Hertz to convert. + * @return A string representation of the frequency in a human-readable format (e.g. "122.800" for 122800000 Hz) + */ + static std::string ConvertHzToHumanString(unsigned int frequencyHz) { std::string temp = std::to_string(frequencyHz / 1000); return temp.substr(0, 3) + "." + temp.substr(3, 7); diff --git a/backend/src/RemoteData.hpp b/backend/src/RemoteData.hpp index 8b08f46..97b5b7f 100644 --- a/backend/src/RemoteData.hpp +++ b/backend/src/RemoteData.hpp @@ -138,29 +138,35 @@ class RemoteData { int u334 = std::atoi(res3.c_str()) * 1000; int k422 = std::stoi(res2, nullptr, 16) == 10 && pYx ? 1 : 0; - k422 = (u334 != OBS_FREQUENCY || absl::StrContains("_M_", callsign)) && k422 == 1 - ? 1 - : k422 == 1 && absl::EndsWith(callsign, "_SUP") ? 1 - : 0; + k422 = (u334 != OBS_FREQUENCY || absl::StrContains("_M_", callsign)) && k422 == 1 ? 1 + : k422 == 1 && absl::EndsWith(callsign, "_SUP") ? 1 + : 0; + + auto cleanedFrequency = Helpers::CleanUpFrequency(u334); + if (UserSession::callsign == callsign && UserSession::frequency == cleanedFrequency + && UserSession::isATC == (k422 == 1) && UserSession::lat == std::stod(lat) + && UserSession::lon == std::stod(lon)) { + return true; // No changes + } // Update the session info UserSession::callsign = callsign; - UserSession::frequency = Helpers::CleanUpFrequency(u334); + UserSession::frequency = cleanedFrequency; UserSession::isATC = k422 == 1; UserSession::lat = std::stod(lat); UserSession::lon = std::stod(lon); - TRACK_LOG_INFO( - "Updating session data - Callsign: {}, Frequency: {}, ATC: {}", - callsign, UserSession::frequency, k422); + TRACK_LOG_INFO("Updating session data - Callsign: {}, Frequency: {}, ATC: {}, Latitude: " + "{}, Longitude: {}", + callsign, UserSession::frequency, k422, UserSession::lat, UserSession::lon); return true; } static void updateSessionStatus(std::string previousCallsign, bool isConnected) { - if (UserSession::isConnectedToTheNetwork && UserSession::callsign != previousCallsign && !previousCallsign.empty() && isConnected && mClient->IsVoiceConnected()) { - TRACK_LOG_INFO( - "Callsign changed during an active session, " - "disconnecting ({} -> {})", + if (UserSession::isConnectedToTheNetwork && UserSession::callsign != previousCallsign + && !previousCallsign.empty() && isConnected && mClient->IsVoiceConnected()) { + TRACK_LOG_INFO("Callsign changed during an active session, " + "disconnecting ({} -> {})", previousCallsign, UserSession::callsign); mClient->Disconnect(); Helpers::CallbackWithError("Callsign changed during an active session, " @@ -199,12 +205,10 @@ class RemoteData { UserSession::callsign = ""; if (callbackAvailable) { - callbackRef.NonBlockingCall( - [&](Napi::Env env, Napi::Function jsCallback) { - jsCallback.Call({ Napi::String::New(env, "network-disconnected"), - Napi::String::New(env, ""), - Napi::String::New(env, "") }); - }); + callbackRef.NonBlockingCall([&](Napi::Env env, Napi::Function jsCallback) { + jsCallback.Call({ Napi::String::New(env, "network-disconnected"), + Napi::String::New(env, ""), Napi::String::New(env, "") }); + }); } } } @@ -231,12 +235,12 @@ class RemoteData { return; } - callbackRef.NonBlockingCall( - [&](Napi::Env env, Napi::Function jsCallback) { - jsCallback.Call({ Napi::String::New(env, "error"), - Napi::String::New(env, "Slurper is back online. You can now connect to the network."), - Napi::String::New(env, "") }); - }); + callbackRef.NonBlockingCall([&](Napi::Env env, Napi::Function jsCallback) { + jsCallback.Call({ Napi::String::New(env, "error"), + Napi::String::New( + env, "Slurper is back online. You can now connect to the network."), + Napi::String::New(env, "") }); + }); } void notifyUserOfSlurperUnavalability() @@ -253,11 +257,15 @@ class RemoteData { userHasBeenNotifiedOfSlurperUnavailability = true; } - callbackRef.NonBlockingCall( - [&](Napi::Env env, Napi::Function jsCallback) { - jsCallback.Call({ Napi::String::New(env, "error"), - Napi::String::New(env, "Error while parsing slurper data, check the log file. This means your internet may be down or the VATSIM servers may experience an outage. You will not be able to connect until this is resolved. TrackAudio will keep retrying in the background."), - Napi::String::New(env, "") }); - }); + callbackRef.NonBlockingCall([&](Napi::Env env, Napi::Function jsCallback) { + jsCallback.Call({ Napi::String::New(env, "error"), + Napi::String::New(env, + "Error while parsing slurper data, check the log file. This means your " + "internet may be down or the VATSIM servers may " + "experience an outage. You will not be able to connect until this is resolved. " + "TrackAudio will keep retrying in the " + "background."), + Napi::String::New(env, "") }); + }); }; }; \ No newline at end of file diff --git a/backend/src/Shared.hpp b/backend/src/Shared.hpp index 3ec8295..767738c 100644 --- a/backend/src/Shared.hpp +++ b/backend/src/Shared.hpp @@ -8,10 +8,14 @@ #include #include -#define TRACK_LOG_INFO(fmt, ...) LOG_INFO(quill::get_logger("trackaudio_logger"), fmt, ##__VA_ARGS__) -#define TRACK_LOG_WARNING(fmt, ...) LOG_WARNING(quill::get_logger("trackaudio_logger"), fmt, ##__VA_ARGS__) -#define TRACK_LOG_ERROR(fmt, ...) LOG_ERROR(quill::get_logger("trackaudio_logger"), fmt, ##__VA_ARGS__) -#define TRACK_LOG_CRITICAL(fmt, ...) LOG_CRITICAL(quill::get_logger("trackaudio_logger"), fmt, ##__VA_ARGS__) +#define TRACK_LOG_INFO(fmt, ...) \ + LOG_INFO(quill::get_logger("trackaudio_logger"), fmt, ##__VA_ARGS__) +#define TRACK_LOG_WARNING(fmt, ...) \ + LOG_WARNING(quill::get_logger("trackaudio_logger"), fmt, ##__VA_ARGS__) +#define TRACK_LOG_ERROR(fmt, ...) \ + LOG_ERROR(quill::get_logger("trackaudio_logger"), fmt, ##__VA_ARGS__) +#define TRACK_LOG_CRITICAL(fmt, ...) \ + LOG_CRITICAL(quill::get_logger("trackaudio_logger"), fmt, ##__VA_ARGS__) constexpr semver::version VERSION = semver::version { 1, 0, 2, semver::prerelease::beta, 2 }; @@ -34,9 +38,8 @@ static std::unique_ptr mClient = nullptr; #define API_SERVER_PORT 49080 -const std::vector allowedYx = { "_CTR", "_APP", "_TWR", "_GND", - "_DEP", "_DEL", "_FSS", "_SUP", - "_RDO", "_RMP", "_TMU", "_FMP" }; +const std::vector allowedYx = { "_CTR", "_APP", "_TWR", "_GND", "_DEP", "_DEL", "_FSS", + "_SUP", "_RDO", "_RMP", "_TMU", "_FMP" }; namespace UserSession { static std::string cid; diff --git a/backend/src/main.cpp b/backend/src/main.cpp index 7442f93..51bf0d4 100644 --- a/backend/src/main.cpp +++ b/backend/src/main.cpp @@ -51,8 +51,7 @@ Napi::Array GetAudioInputDevices(const Napi::CallbackInfo& info) int apiId = info[0].As().Int32Value(); Napi::Array arr = Napi::Array::New(env); - for (const auto& [deviceId, deviceName, isDefault] : - mClient->GetAudioInputDevices(apiId)) { + for (const auto& [deviceId, deviceName, isDefault] : mClient->GetAudioInputDevices(apiId)) { Napi::Object obj = Napi::Object::New(env); obj.Set("id", deviceId); obj.Set("name", deviceName); @@ -69,8 +68,7 @@ Napi::Array GetAudioOutputDevices(const Napi::CallbackInfo& info) int apiId = info[0].As().Int32Value(); Napi::Array arr = Napi::Array::New(env); - for (const auto& [deviceId, deviceName, isDefault] : - mClient->GetAudioOutputDevices(apiId)) { + for (const auto& [deviceId, deviceName, isDefault] : mClient->GetAudioOutputDevices(apiId)) { Napi::Object obj = Napi::Object::New(env); obj.Set("id", deviceId); obj.Set("name", deviceName); @@ -143,8 +141,7 @@ Napi::Boolean AddFrequency(const Napi::CallbackInfo& info) auto hasBeenAddded = mClient->AddFrequency(frequency, callsign); if (!hasBeenAddded) { Helpers::CallbackWithError("Could not add frequency: it already exists"); - TRACK_LOG_WARNING("Could not add frequency, it already exists: {} {}", - frequency, callsign); + TRACK_LOG_WARNING("Could not add frequency, it already exists: {} {}", frequency, callsign); return Napi::Boolean::New(info.Env(), false); } mClient->SetRx(frequency, false); @@ -331,8 +328,7 @@ void StartMicTest(const Napi::CallbackInfo& /*info*/) mainStaticData::runVuMeterCallback = true; mainStaticData::vuMeterThread = std::make_unique([] { - for (int i = 0; i < 2400; - i++) { // Max of 2 minutes, don't allow infinite test + for (int i = 0; i < 2400; i++) { // Max of 2 minutes, don't allow infinite test #ifndef WIN32 std::this_thread::sleep_for(std::chrono::milliseconds(50)); #else @@ -351,10 +347,9 @@ void StartMicTest(const Napi::CallbackInfo& /*info*/) callbackRef.NonBlockingCall( [vuMeter, vuMeterPeak](Napi::Env env, Napi::Function jsCallback) { - jsCallback.Call( - { Napi::String::New(env, "VuMeter"), - Napi::String::New(env, std::to_string(vuMeter)), - Napi::String::New(env, std::to_string(vuMeterPeak)) }); + jsCallback.Call({ Napi::String::New(env, "VuMeter"), + Napi::String::New(env, std::to_string(vuMeter)), + Napi::String::New(env, std::to_string(vuMeterPeak)) }); }); } }); @@ -395,8 +390,7 @@ void StopAudio(const Napi::CallbackInfo& /*info*/) mClient->StopAudio(); } -static void HandleAfvEvents(afv_native::ClientEventType eventType, void* data, - void* data2) +static void HandleAfvEvents(afv_native::ClientEventType eventType, void* data, void* data2) { if (!callbackAvailable) { return; @@ -404,8 +398,8 @@ static void HandleAfvEvents(afv_native::ClientEventType eventType, void* data, if (eventType == afv_native::ClientEventType::VoiceServerConnected) { callbackRef.NonBlockingCall([](Napi::Env env, Napi::Function jsCallback) { - jsCallback.Call({ Napi::String::New(env, "VoiceConnected"), - Napi::String::New(env, ""), Napi::String::New(env, "") }); + jsCallback.Call({ Napi::String::New(env, "VoiceConnected"), Napi::String::New(env, ""), + Napi::String::New(env, "") }); }); } @@ -426,10 +420,9 @@ static void HandleAfvEvents(afv_native::ClientEventType eventType, void* data, auto transceiverCount = mClient->GetTransceiverCountForStation(station); callbackRef.NonBlockingCall( [transceiverCount, station](Napi::Env env, Napi::Function jsCallback) { - jsCallback.Call( - { Napi::String::New(env, "StationTransceiversUpdated"), - Napi::String::New(env, station), - Napi::String::New(env, std::to_string(transceiverCount)) }); + jsCallback.Call({ Napi::String::New(env, "StationTransceiversUpdated"), + Napi::String::New(env, station), + Napi::String::New(env, std::to_string(transceiverCount)) }); }); } @@ -466,7 +459,8 @@ static void HandleAfvEvents(afv_native::ClientEventType eventType, void* data, return; } // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) - std::map stations = *reinterpret_cast*>(data2); + std::map stations + = *reinterpret_cast*>(data2); for (const auto& station : stations) { const std::string& callsign = station.first; @@ -478,10 +472,9 @@ static void HandleAfvEvents(afv_native::ClientEventType eventType, void* data, callbackRef.NonBlockingCall( [callsign, frequency](Napi::Env env, Napi::Function jsCallback) { - jsCallback.Call( - { Napi::String::New(env, "StationDataReceived"), - Napi::String::New(env, callsign), - Napi::String::New(env, std::to_string(frequency)) }); + jsCallback.Call({ Napi::String::New(env, "StationDataReceived"), + Napi::String::New(env, callsign), + Napi::String::New(env, std::to_string(frequency)) }); }); } } @@ -493,12 +486,10 @@ static void HandleAfvEvents(afv_native::ClientEventType eventType, void* data, // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) int frequency = *reinterpret_cast(data); - callbackRef.NonBlockingCall( - [frequency](Napi::Env env, Napi::Function jsCallback) { - jsCallback.Call({ Napi::String::New(env, "FrequencyRxBegin"), - Napi::String::New(env, std::to_string(frequency)), - Napi::String::New(env, "") }); - }); + callbackRef.NonBlockingCall([frequency](Napi::Env env, Napi::Function jsCallback) { + jsCallback.Call({ Napi::String::New(env, "FrequencyRxBegin"), + Napi::String::New(env, std::to_string(frequency)), Napi::String::New(env, "") }); + }); return; } @@ -510,12 +501,10 @@ static void HandleAfvEvents(afv_native::ClientEventType eventType, void* data, // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) int frequency = *reinterpret_cast(data); - callbackRef.NonBlockingCall( - [frequency](Napi::Env env, Napi::Function jsCallback) { - jsCallback.Call({ Napi::String::New(env, "FrequencyRxEnd"), - Napi::String::New(env, std::to_string(frequency)), - Napi::String::New(env, "") }); - }); + callbackRef.NonBlockingCall([frequency](Napi::Env env, Napi::Function jsCallback) { + jsCallback.Call({ Napi::String::New(env, "FrequencyRxEnd"), + Napi::String::New(env, std::to_string(frequency)), Napi::String::New(env, "") }); + }); return; } @@ -530,14 +519,15 @@ static void HandleAfvEvents(afv_native::ClientEventType eventType, void* data, std::string callsign = *reinterpret_cast(data2); callbackRef.NonBlockingCall( [frequency, callsign](Napi::Env env, Napi::Function jsCallback) { - LOG_TRACE_L1(quill::get_logger("trackaudio_logger"), "StationRxBegin to node: {} {}", frequency, callsign); + LOG_TRACE_L1(quill::get_logger("trackaudio_logger"), + "StationRxBegin to node: {} {}", frequency, callsign); jsCallback.Call({ Napi::String::New(env, "StationRxBegin"), Napi::String::New(env, std::to_string(frequency)), Napi::String::New(env, callsign) }); }); - mainStaticData::mApiServer->handleAFVEventForWebsocket(sdk::types::Event::kRxBegin, - callsign, frequency); + mainStaticData::mApiServer->handleAFVEventForWebsocket( + sdk::types::Event::kRxBegin, callsign, frequency); return; } @@ -552,30 +542,27 @@ static void HandleAfvEvents(afv_native::ClientEventType eventType, void* data, // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) std::string callsign = *reinterpret_cast(data2); - mainStaticData::mApiServer->handleAFVEventForWebsocket(sdk::types::Event::kRxEnd, callsign, - frequency); + mainStaticData::mApiServer->handleAFVEventForWebsocket( + sdk::types::Event::kRxEnd, callsign, frequency); } if (eventType == afv_native::ClientEventType::PttOpen) { callbackRef.NonBlockingCall([](Napi::Env env, Napi::Function jsCallback) { - jsCallback.Call({ Napi::String::New(env, "PttState"), - Napi::String::New(env, "1"), + jsCallback.Call({ Napi::String::New(env, "PttState"), Napi::String::New(env, "1"), Napi::String::New(env, "") }); }); } if (eventType == afv_native::ClientEventType::PttClosed) { callbackRef.NonBlockingCall([](Napi::Env env, Napi::Function jsCallback) { - jsCallback.Call({ Napi::String::New(env, "PttState"), - Napi::String::New(env, "0"), + jsCallback.Call({ Napi::String::New(env, "PttState"), Napi::String::New(env, "0"), Napi::String::New(env, "") }); }); } if (eventType == afv_native::ClientEventType::AudioError) { - Helpers::CallbackWithError( - "Error stating audio devices, check your configuration."); + Helpers::CallbackWithError("Error stating audio devices, check your configuration."); } if (eventType == afv_native::ClientEventType::APIServerError) { @@ -586,13 +573,13 @@ static void HandleAfvEvents(afv_native::ClientEventType eventType, void* data, // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) auto err = *reinterpret_cast(data); - if (err == afv_native::afv::APISessionError::BadPassword || err == afv_native::afv::APISessionError::RejectedCredentials) { + if (err == afv_native::afv::APISessionError::BadPassword + || err == afv_native::afv::APISessionError::RejectedCredentials) { Helpers::CallbackWithError("Invalid Credentials"); } if (err == afv_native::afv::APISessionError::ConnectionError) { - Helpers::CallbackWithError( - "API Connection Error, check your internet connection."); + Helpers::CallbackWithError("API Connection Error, check your internet connection."); } if (err == afv_native::afv::APISessionError::BadRequestOrClientIncompatible) { @@ -645,41 +632,39 @@ void CreateLoggers() // Starts the logging backend thread quill::start(); - std::shared_ptr trackaudio_logger = quill::rotating_file_handler( - GetStateFolderPath() / "trackaudio.log", []() { - quill::RotatingFileHandlerConfig cfg; - cfg.set_rotation_max_file_size(5e+6); // 5MB files - cfg.set_max_backup_files(2); - cfg.set_overwrite_rolled_files(true); - return cfg; - }()); + std::shared_ptr trackaudio_logger + = quill::rotating_file_handler(GetStateFolderPath() / "trackaudio.log", []() { + quill::RotatingFileHandlerConfig cfg; + cfg.set_rotation_max_file_size(5e+6); // 5MB files + cfg.set_max_backup_files(2); + cfg.set_overwrite_rolled_files(true); + return cfg; + }()); auto* logger = quill::create_logger("trackaudio_logger", std::move(trackaudio_logger)); logger->set_log_level(quill::LogLevel::Info); - std::shared_ptr afv_logger = quill::rotating_file_handler( - GetStateFolderPath() / "trackaudio-afv.log", []() { - quill::RotatingFileHandlerConfig cfg; - cfg.set_rotation_max_file_size(5e+6); // 5MB files - cfg.set_max_backup_files(2); - cfg.set_overwrite_rolled_files(true); - cfg.set_pattern("%(ascii_time) [%(thread)] %(message)"); - return cfg; - }()); + std::shared_ptr afv_logger + = quill::rotating_file_handler(GetStateFolderPath() / "trackaudio-afv.log", []() { + quill::RotatingFileHandlerConfig cfg; + cfg.set_rotation_max_file_size(5e+6); // 5MB files + cfg.set_max_backup_files(2); + cfg.set_overwrite_rolled_files(true); + cfg.set_pattern("%(ascii_time) [%(thread)] %(message)"); + return cfg; + }()); // Create a file logger auto* _ = quill::create_logger("afv_logger", std::move(afv_logger)); // NOLINTNEXTLINE this cannot be solved here but in afv - afv_native::api::setLogger([](std::string subsystem, std::string file, - int line, std::string lineOut) { - auto strippedFiledName = file.substr(file.find_last_of('/') + 1); - LOG_INFO(quill::get_logger("afv_logger"), - "[{}] [{}@{}] {}", - subsystem, strippedFiledName, line, - lineOut); - }); + afv_native::api::setLogger( + [](std::string subsystem, std::string file, int line, std::string lineOut) { + auto strippedFiledName = file.substr(file.find_last_of('/') + 1); + LOG_INFO(quill::get_logger("afv_logger"), "[{}] [{}@{}] {}", subsystem, + strippedFiledName, line, lineOut); + }); } bool CheckVersionSync(const Napi::CallbackInfo& /*info*/) @@ -701,8 +686,8 @@ bool CheckVersionSync(const Napi::CallbackInfo& /*info*/) auto mandatoryVersion = semver::version(cleanBody); if (VERSION < mandatoryVersion) { mainStaticData::ShouldRun = false; - TRACK_LOG_ERROR("Mandatory update required: {} -> {}", - VERSION.to_string(), mandatoryVersion.to_string()); + TRACK_LOG_ERROR("Mandatory update required: {} -> {}", VERSION.to_string(), + mandatoryVersion.to_string()); return false; } } catch (const std::exception& e) { @@ -728,10 +713,9 @@ Napi::Boolean Bootstrap(const Napi::CallbackInfo& info) mainStaticData::mRemoteDataHandler = std::make_unique(); // Setup afv - mClient->RaiseClientEvent( - [](afv_native::ClientEventType eventType, void* data1, void* data2) { - HandleAfvEvents(eventType, data1, data2); - }); + mClient->RaiseClientEvent([](afv_native::ClientEventType eventType, void* data1, void* data2) { + HandleAfvEvents(eventType, data1, data2); + }); mainStaticData::mApiServer = std::make_unique(); @@ -753,11 +737,9 @@ void Exit(const Napi::CallbackInfo& /*info*/) Napi::Object Init(Napi::Env env, Napi::Object exports) { - exports.Set(Napi::String::New(env, "GetVersion"), - Napi::Function::New(env, Version)); + exports.Set(Napi::String::New(env, "GetVersion"), Napi::Function::New(env, Version)); - exports.Set(Napi::String::New(env, "GetAudioApis"), - Napi::Function::New(env, GetAudioApis)); + exports.Set(Napi::String::New(env, "GetAudioApis"), Napi::Function::New(env, GetAudioApis)); exports.Set(Napi::String::New(env, "GetAudioInputDevices"), Napi::Function::New(env, GetAudioInputDevices)); @@ -765,73 +747,59 @@ Napi::Object Init(Napi::Env env, Napi::Object exports) exports.Set(Napi::String::New(env, "GetAudioOutputDevices"), Napi::Function::New(env, GetAudioOutputDevices)); - exports.Set(Napi::String::New(env, "Connect"), - Napi::Function::New(env, Connect)); + exports.Set(Napi::String::New(env, "Connect"), Napi::Function::New(env, Connect)); - exports.Set(Napi::String::New(env, "Disconnect"), - Napi::Function::New(env, Disconnect)); + exports.Set(Napi::String::New(env, "Disconnect"), Napi::Function::New(env, Disconnect)); - exports.Set(Napi::String::New(env, "SetAudioSettings"), - Napi::Function::New(env, SetAudioSettings)); + exports.Set( + Napi::String::New(env, "SetAudioSettings"), Napi::Function::New(env, SetAudioSettings)); - exports.Set(Napi::String::New(env, "AddFrequency"), - Napi::Function::New(env, AddFrequency)); + exports.Set(Napi::String::New(env, "AddFrequency"), Napi::Function::New(env, AddFrequency)); - exports.Set(Napi::String::New(env, "RemoveFrequency"), - Napi::Function::New(env, RemoveFrequency)); + exports.Set( + Napi::String::New(env, "RemoveFrequency"), Napi::Function::New(env, RemoveFrequency)); - exports.Set(Napi::String::New(env, "SetFrequencyState"), - Napi::Function::New(env, SetFrequencyState)); + exports.Set( + Napi::String::New(env, "SetFrequencyState"), Napi::Function::New(env, SetFrequencyState)); - exports.Set(Napi::String::New(env, "GetFrequencyState"), - Napi::Function::New(env, GetFrequencyState)); + exports.Set( + Napi::String::New(env, "GetFrequencyState"), Napi::Function::New(env, GetFrequencyState)); - exports.Set(Napi::String::New(env, "RegisterCallback"), - Napi::Function::New(env, RegisterCallback)); + exports.Set( + Napi::String::New(env, "RegisterCallback"), Napi::Function::New(env, RegisterCallback)); - exports.Set(Napi::String::New(env, "GetStation"), - Napi::Function::New(env, GetStation)); + exports.Set(Napi::String::New(env, "GetStation"), Napi::Function::New(env, GetStation)); - exports.Set(Napi::String::New(env, "RefreshStation"), - Napi::Function::New(env, RefreshStation)); + exports.Set(Napi::String::New(env, "RefreshStation"), Napi::Function::New(env, RefreshStation)); - exports.Set(Napi::String::New(env, "IsFrequencyActive"), - Napi::Function::New(env, IsFrequencyActive)); + exports.Set( + Napi::String::New(env, "IsFrequencyActive"), Napi::Function::New(env, IsFrequencyActive)); exports.Set(Napi::String::New(env, "Reset"), Napi::Function::New(env, Reset)); - exports.Set(Napi::String::New(env, "SetCid"), - Napi::Function::New(env, SetCid)); + exports.Set(Napi::String::New(env, "SetCid"), Napi::Function::New(env, SetCid)); - exports.Set(Napi::String::New(env, "SetPtt"), - Napi::Function::New(env, SetPtt)); + exports.Set(Napi::String::New(env, "SetPtt"), Napi::Function::New(env, SetPtt)); - exports.Set(Napi::String::New(env, "SetRadioGain"), - Napi::Function::New(env, SetRadioGain)); + exports.Set(Napi::String::New(env, "SetRadioGain"), Napi::Function::New(env, SetRadioGain)); - exports.Set(Napi::String::New(env, "SetHardwareType"), - Napi::Function::New(env, SetHardwareType)); + exports.Set( + Napi::String::New(env, "SetHardwareType"), Napi::Function::New(env, SetHardwareType)); - exports.Set(Napi::String::New(env, "Bootstrap"), - Napi::Function::New(env, Bootstrap)); + exports.Set(Napi::String::New(env, "Bootstrap"), Napi::Function::New(env, Bootstrap)); - exports.Set(Napi::String::New(env, "IsConnected"), - Napi::Function::New(env, IsConnected)); + exports.Set(Napi::String::New(env, "IsConnected"), Napi::Function::New(env, IsConnected)); - exports.Set(Napi::String::New(env, "GetStateFolder"), - Napi::Function::New(env, GetStateFolderNapi)); + exports.Set( + Napi::String::New(env, "GetStateFolder"), Napi::Function::New(env, GetStateFolderNapi)); - exports.Set(Napi::String::New(env, "StartMicTest"), - Napi::Function::New(env, StartMicTest)); + exports.Set(Napi::String::New(env, "StartMicTest"), Napi::Function::New(env, StartMicTest)); - exports.Set(Napi::String::New(env, "StopMicTest"), - Napi::Function::New(env, StopMicTest)); + exports.Set(Napi::String::New(env, "StopMicTest"), Napi::Function::New(env, StopMicTest)); - exports.Set(Napi::String::New(env, "StartAudio"), - Napi::Function::New(env, StartAudio)); + exports.Set(Napi::String::New(env, "StartAudio"), Napi::Function::New(env, StartAudio)); - exports.Set(Napi::String::New(env, "StopAudio"), - Napi::Function::New(env, StopAudio)); + exports.Set(Napi::String::New(env, "StopAudio"), Napi::Function::New(env, StopAudio)); exports.Set(Napi::String::New(env, "Exit"), Napi::Function::New(env, Exit)); diff --git a/backend/src/sdk.cpp b/backend/src/sdk.cpp index 65da009..85a1b4d 100644 --- a/backend/src/sdk.cpp +++ b/backend/src/sdk.cpp @@ -31,13 +31,12 @@ void SDK::buildServer() } void SDK::handleAFVEventForWebsocket(sdk::types::Event event, - const std::optional& callsign, - const std::optional& frequencyHz) + const std::optional& callsign, const std::optional& frequencyHz) { if (event == sdk::types::Event::kDisconnectFrequencyStateUpdate) { - nlohmann::json jsonMessage = WebsocketMessage::buildMessage( - WebsocketMessageType::kFrequencyStateUpdate); + nlohmann::json jsonMessage + = WebsocketMessage::buildMessage(WebsocketMessageType::kFrequencyStateUpdate); jsonMessage["value"]["rx"] = nlohmann::json::array(); jsonMessage["value"]["tx"] = nlohmann::json::array(); @@ -73,8 +72,8 @@ void SDK::handleAFVEventForWebsocket(sdk::types::Event event, } if (event == sdk::types::Event::kFrequencyStateUpdate) { - nlohmann::json jsonMessage = WebsocketMessage::buildMessage( - WebsocketMessageType::kFrequencyStateUpdate); + nlohmann::json jsonMessage + = WebsocketMessage::buildMessage(WebsocketMessageType::kFrequencyStateUpdate); std::vector rxBar; std::vector txBar; @@ -111,25 +110,19 @@ std::unique_ptr> SDK::buildRouter() std::unique_ptr> router; router = std::make_unique>(); router->http_get(routeMap[sdkCall::kTransmitting], - [&](auto req, auto /*params*/) { - return SDK::handleTransmittingSDKCall(req); - }); + [&](auto req, auto /*params*/) { return SDK::handleTransmittingSDKCall(req); }); - router->http_get( - routeMap[sdkCall::kRx], + router->http_get(routeMap[sdkCall::kRx], [&](auto req, auto /*params*/) { return this->handleRxSDKCall(req); }); - router->http_get( - routeMap[sdkCall::kTx], + router->http_get(routeMap[sdkCall::kTx], [&](auto req, auto /*params*/) { return this->handleTxSDKCall(req); }); - router->http_get( - routeMap[sdkCall::kWebSocket], + router->http_get(routeMap[sdkCall::kWebSocket], [&](auto req, auto /*params*/) { return handleWebSocketSDKCall(req); }); - router->non_matched_request_handler([](auto req) { - return req->create_response().set_body(CLIENT_NAME).done(); - }); + router->non_matched_request_handler( + [](auto req) { return req->create_response().set_body(CLIENT_NAME).done(); }); auto methodNotAllowed = [](const auto& req, auto) { return req->create_response(restinio::status_method_not_allowed()) @@ -138,22 +131,21 @@ std::unique_ptr> SDK::buildRouter() }; router->add_handler( - restinio::router::none_of_methods(restinio::http_method_get()), "/", - methodNotAllowed); + restinio::router::none_of_methods(restinio::http_method_get()), "/", methodNotAllowed); return std::move(router); } -restinio::request_handling_status_t -SDK::handleTransmittingSDKCall(const restinio::request_handle_t& req) +restinio::request_handling_status_t SDK::handleTransmittingSDKCall( + const restinio::request_handle_t& req) { const std::lock_guard lock(TransmittingMutex); std::string out = absl::StrJoin(CurrentlyTransmittingData, ","); return req->create_response().set_body(out).done(); }; -restinio::request_handling_status_t -SDK::handleRxSDKCall(const restinio::request_handle_t& req) +// NOLINTNEXTLINE +restinio::request_handling_status_t SDK::handleRxSDKCall(const restinio::request_handle_t& req) { if (!mClient->IsVoiceConnected()) { return req->create_response().set_body("").done(); @@ -170,8 +162,8 @@ SDK::handleRxSDKCall(const restinio::request_handle_t& req) return req->create_response().set_body(absl::StrJoin(outData, ",")).done(); }; -restinio::request_handling_status_t -SDK::handleTxSDKCall(const restinio::request_handle_t& req) +// NOLINTNEXTLINE +restinio::request_handling_status_t SDK::handleTxSDKCall(const restinio::request_handle_t& req) { if (!mClient->IsVoiceConnected()) { return req->create_response().set_body("").done(); @@ -188,24 +180,22 @@ SDK::handleTxSDKCall(const restinio::request_handle_t& req) return req->create_response().set_body(absl::StrJoin(outData, ",")).done(); } -restinio::request_handling_status_t -SDK::handleWebSocketSDKCall(const restinio::request_handle_t& req) +restinio::request_handling_status_t SDK::handleWebSocketSDKCall( + const restinio::request_handle_t& req) { if (restinio::http_connection_header_t::upgrade != req->header().connection()) { return restinio::request_rejected(); } auto wsh = restinio::websocket::basic::upgrade( - *req, restinio::websocket::basic::activation_t::immediate, - [&](auto wsh, auto m) { - if (restinio::websocket::basic::opcode_t::ping_frame == m->opcode()) { + *req, restinio::websocket::basic::activation_t::immediate, [&](auto wsh, auto message) { + if (restinio::websocket::basic::opcode_t::ping_frame == message->opcode()) { // Ping-Pong - auto resp = *m; + auto resp = *message; resp.set_opcode(restinio::websocket::basic::opcode_t::pong_frame); wsh->send_message(resp); - } else if (restinio::websocket::basic::opcode_t:: - connection_close_frame - == m->opcode()) { + } else if (restinio::websocket::basic::opcode_t::connection_close_frame + == message->opcode()) { // Close connection this->pWsRegistry.erase(wsh->connection_id()); } @@ -216,8 +206,8 @@ SDK::handleWebSocketSDKCall(const restinio::request_handle_t& req) // Upon connection, send the status of frequencies straight away { - this->handleAFVEventForWebsocket(sdk::types::Event::kFrequencyStateUpdate, - std::nullopt, std::nullopt); + this->handleAFVEventForWebsocket( + sdk::types::Event::kFrequencyStateUpdate, std::nullopt, std::nullopt); } return restinio::request_accepted(); @@ -234,8 +224,7 @@ void SDK::broadcastOnWebsocket(const std::string& data) try { ws->send_message(outgoingMessage); } catch (const std::exception& ex) { - TRACK_LOG_ERROR("Error while sending message to websocket: {}", - ex.what()); + TRACK_LOG_ERROR("Error while sending message to websocket: {}", ex.what()); } } }; diff --git a/backend/src/sdk.hpp b/backend/src/sdk.hpp index 4c2a63f..4d13d2b 100644 --- a/backend/src/sdk.hpp +++ b/backend/src/sdk.hpp @@ -25,12 +25,7 @@ using sdk::types::WebsocketMessage; using sdk::types::WebsocketMessageType; namespace sdk::types { -enum Event { - kRxBegin, - kRxEnd, - kFrequencyStateUpdate, - kDisconnectFrequencyStateUpdate -}; +enum Event { kRxBegin, kRxEnd, kFrequencyStateUpdate, kDisconnectFrequencyStateUpdate }; } class SDK { @@ -49,12 +44,10 @@ class SDK { * @param data Optional data associated with the event. */ void handleAFVEventForWebsocket(sdk::types::Event event, - const std::optional& callsign, - const std::optional& frequencyHz); + const std::optional& callsign, const std::optional& frequencyHz); private: - using serverTraits = restinio::traits_t>; restinio::running_server_handle_t pSDKServer; @@ -77,12 +70,8 @@ class SDK { inline static std::map& getSDKCallUrlMap() { - static std::map mSDKCallUrl = { - { kTransmitting, "/transmitting" }, - { kRx, "/rx" }, - { kTx, "/tx" }, - { kWebSocket, "/ws" } - }; + static std::map mSDKCallUrl = { { kTransmitting, "/transmitting" }, + { kRx, "/rx" }, { kTx, "/tx" }, { kWebSocket, "/ws" } }; return mSDKCallUrl; } @@ -115,8 +104,8 @@ class SDK { * @param req The request handle. * @return The status of request handling. */ - static restinio::request_handling_status_t - handleTransmittingSDKCall(const restinio::request_handle_t& req); + static restinio::request_handling_status_t handleTransmittingSDKCall( + const restinio::request_handle_t& req); /** * Handles the SDK call received in the request. @@ -124,16 +113,14 @@ class SDK { * @param req The request handle. * @return The status of the request handling. */ - restinio::request_handling_status_t - handleRxSDKCall(const restinio::request_handle_t& req); + restinio::request_handling_status_t handleRxSDKCall(const restinio::request_handle_t& req); /** * Handles the SDK call. * * @param req The request handle. * @return The request handling status. */ - restinio::request_handling_status_t - handleTxSDKCall(const restinio::request_handle_t& req); + restinio::request_handling_status_t handleTxSDKCall(const restinio::request_handle_t& req); /** * Handles a WebSocket SDK call. @@ -141,6 +128,6 @@ class SDK { * @param req The request handle. * @return The status of the request handling. */ - restinio::request_handling_status_t - handleWebSocketSDKCall(const restinio::request_handle_t& req); + restinio::request_handling_status_t handleWebSocketSDKCall( + const restinio::request_handle_t& req); }; diff --git a/backend/src/sdkWebsocketMessage.hpp b/backend/src/sdkWebsocketMessage.hpp index 87f2a6e..ed093dd 100644 --- a/backend/src/sdkWebsocketMessage.hpp +++ b/backend/src/sdkWebsocketMessage.hpp @@ -6,15 +6,12 @@ #include namespace sdk::types { -enum class WebsocketMessageType { kRxBegin, - kRxEnd, - kFrequencyStateUpdate }; +enum class WebsocketMessageType { kRxBegin, kRxEnd, kFrequencyStateUpdate }; inline const std::map& getWebsocketMessageTypeMap() { static const std::map kWebsocketMessageTypeMap { - { WebsocketMessageType::kRxBegin, "kRxBegin" }, - { WebsocketMessageType::kRxEnd, "kRxEnd" }, + { WebsocketMessageType::kRxBegin, "kRxBegin" }, { WebsocketMessageType::kRxEnd, "kRxEnd" }, { WebsocketMessageType::kFrequencyStateUpdate, "kFrequenciesUpdate" } }; return kWebsocketMessageTypeMap; @@ -46,23 +43,11 @@ namespace ns { class Station { public: [[nodiscard]] inline int getFrequencyHz() const { return pFrequencyHz; } - [[nodiscard]] inline const std::string& getCallsign() const - { - return pCallsign; - } - [[nodiscard]] inline const std::string& getHumanFrequency() const - { - return pHumanFreq; - } + [[nodiscard]] inline const std::string& getCallsign() const { return pCallsign; } + [[nodiscard]] inline const std::string& getHumanFrequency() const { return pHumanFreq; } - [[nodiscard]] inline int getTransceiverCount() const - { - return pTransceiverCount; - } - [[nodiscard]] inline bool hasTransceiver() const - { - return pTransceiverCount > 0; - } + [[nodiscard]] inline int getTransceiverCount() const { return pTransceiverCount; } + [[nodiscard]] inline bool hasTransceiver() const { return pTransceiverCount > 0; } inline void setTransceiverCount(int count) { pTransceiverCount = count; } inline static Station build(const std::string& callsign, int freqHz)