From aef3c2da8648b1bf8ce9cde9bdd864b5e5ddec1e Mon Sep 17 00:00:00 2001 From: Nikita Poltorapavlo Date: Thu, 23 May 2024 18:41:39 +0300 Subject: [PATCH 01/21] RDKTV-30141 : Switch for account scope feature Reason for change: Make it easy to turn off part of the functionality via cmake variable. Test Procedure: None Risks: None Signed-off-by: Nikita Poltorapavlo --- PersistentStore/CMakeLists.txt | 36 ++++++++++--------- .../PersistentStoreImplementation.cpp | 7 +++- 2 files changed, 26 insertions(+), 17 deletions(-) diff --git a/PersistentStore/CMakeLists.txt b/PersistentStore/CMakeLists.txt index a6fe7b596d..dc5c44a975 100644 --- a/PersistentStore/CMakeLists.txt +++ b/PersistentStore/CMakeLists.txt @@ -33,6 +33,7 @@ set(PLUGIN_PERSISTENTSTORE_MAXVALUE "3000" CACHE STRING "For single text data, i set(PLUGIN_PERSISTENTSTORE_LIMIT "10000" CACHE STRING "Default for all text data in namespace, in bytes") set(PLUGIN_PERSISTENTSTORE_TOKEN_COMMAND "" CACHE STRING "Shell command to get the service access token") set(PLUGIN_PERSISTENTSTORE_STARTUPORDER "" CACHE STRING "To configure startup order of PersistentStore plugin") +set(PLUGIN_PERSISTENTSTORE_WITH_ACCOUNT_SCOPE true CACHE BOOL "Enable account scope") add_library(${MODULE_NAME} SHARED PersistentStore.cpp @@ -82,26 +83,29 @@ if (IARMBUS_LIBRARIES) target_compile_definitions(${PLUGIN_IMPLEMENTATION} PRIVATE WITH_SYSMGR) endif () -find_package(Protobuf REQUIRED) -target_link_libraries(${PLUGIN_IMPLEMENTATION} PRIVATE ${Protobuf_LIBRARIES}) +if (PLUGIN_PERSISTENTSTORE_WITH_ACCOUNT_SCOPE) + find_package(Protobuf REQUIRED) + target_link_libraries(${PLUGIN_IMPLEMENTATION} PRIVATE ${Protobuf_LIBRARIES}) -add_custom_target(protoc - ${Protobuf_PROTOC_EXECUTABLE} --cpp_out ${CMAKE_CURRENT_BINARY_DIR} -I ${CMAKE_CURRENT_SOURCE_DIR}/grpc/secure_storage ${CMAKE_CURRENT_SOURCE_DIR}/grpc/secure_storage/secure_storage.proto -) -add_dependencies(${PLUGIN_IMPLEMENTATION} protoc) + add_custom_target(protoc + ${Protobuf_PROTOC_EXECUTABLE} --cpp_out ${CMAKE_CURRENT_BINARY_DIR} -I ${CMAKE_CURRENT_SOURCE_DIR}/grpc/secure_storage ${CMAKE_CURRENT_SOURCE_DIR}/grpc/secure_storage/secure_storage.proto + ) + add_dependencies(${PLUGIN_IMPLEMENTATION} protoc) -target_link_libraries(${PLUGIN_IMPLEMENTATION} PRIVATE grpc++) -find_program(GRPC_CPP_PLUGIN grpc_cpp_plugin REQUIRED) + target_link_libraries(${PLUGIN_IMPLEMENTATION} PRIVATE grpc++) + find_program(GRPC_CPP_PLUGIN grpc_cpp_plugin REQUIRED) -add_custom_target(protoc-gen-grpc - ${Protobuf_PROTOC_EXECUTABLE} --grpc_out ${CMAKE_CURRENT_BINARY_DIR} --plugin=protoc-gen-grpc=${GRPC_CPP_PLUGIN} -I ${CMAKE_CURRENT_SOURCE_DIR}/grpc/secure_storage ${CMAKE_CURRENT_SOURCE_DIR}/grpc/secure_storage/secure_storage.proto -) -add_dependencies(${PLUGIN_IMPLEMENTATION} protoc-gen-grpc) + add_custom_target(protoc-gen-grpc + ${Protobuf_PROTOC_EXECUTABLE} --grpc_out ${CMAKE_CURRENT_BINARY_DIR} --plugin=protoc-gen-grpc=${GRPC_CPP_PLUGIN} -I ${CMAKE_CURRENT_SOURCE_DIR}/grpc/secure_storage ${CMAKE_CURRENT_SOURCE_DIR}/grpc/secure_storage/secure_storage.proto + ) + add_dependencies(${PLUGIN_IMPLEMENTATION} protoc-gen-grpc) -set(PROTO_SRCS secure_storage.pb.cc secure_storage.grpc.pb.cc) -target_sources(${PLUGIN_IMPLEMENTATION} PRIVATE ${PROTO_SRCS}) -set_property(SOURCE ${PROTO_SRCS} PROPERTY GENERATED 1) -target_include_directories(${PLUGIN_IMPLEMENTATION} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}) + set(PROTO_SRCS secure_storage.pb.cc secure_storage.grpc.pb.cc) + target_sources(${PLUGIN_IMPLEMENTATION} PRIVATE ${PROTO_SRCS}) + set_property(SOURCE ${PROTO_SRCS} PROPERTY GENERATED 1) + target_include_directories(${PLUGIN_IMPLEMENTATION} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}) + target_compile_definitions(${PLUGIN_IMPLEMENTATION} PRIVATE WITH_ACCOUNT_SCOPE) +endif () install(TARGETS ${PLUGIN_IMPLEMENTATION} DESTINATION lib/${STORAGE_DIRECTORY}/plugins) diff --git a/PersistentStore/PersistentStoreImplementation.cpp b/PersistentStore/PersistentStoreImplementation.cpp index 8f93343328..f57ca52682 100644 --- a/PersistentStore/PersistentStoreImplementation.cpp +++ b/PersistentStore/PersistentStoreImplementation.cpp @@ -18,7 +18,9 @@ */ #include "PersistentStoreImplementation.h" +#ifdef WITH_ACCOUNT_SCOPE #include "grpc/Store2.h" +#endif #include "sqlite/Store2.h" namespace WPEFramework { @@ -31,7 +33,7 @@ namespace Plugin { , _deviceStoreCache(nullptr) , _deviceStoreInspector(nullptr) , _deviceStoreLimit(nullptr) - , _accountStore2(Core::Service::Create()) + , _accountStore2(nullptr) , _store2Sink(*this) { if (_deviceStore2 != nullptr) { @@ -45,7 +47,10 @@ namespace Plugin { ASSERT(_deviceStoreCache != nullptr); ASSERT(_deviceStoreInspector != nullptr); ASSERT(_deviceStoreLimit != nullptr); +#ifdef WITH_ACCOUNT_SCOPE + _accountStore2 = Core::Service::Create(); ASSERT(_accountStore2 != nullptr); +#endif } PersistentStoreImplementation::~PersistentStoreImplementation() From d94e83943fee65b0be50225af89eae9295ba100c Mon Sep 17 00:00:00 2001 From: Filipe Norte Date: Wed, 22 May 2024 16:44:05 +0000 Subject: [PATCH 02/21] RDK-48800: Add pressure settings for service worker process --- WebKitBrowser/CMakeLists.txt | 20 ++++++++++++++ WebKitBrowser/HtmlApp.conf.in | 8 ++++++ WebKitBrowser/JSPP.conf.in | 9 +++++++ WebKitBrowser/LightningApp.conf.in | 9 +++++++ WebKitBrowser/ResidentApp.conf.in | 9 +++++++ WebKitBrowser/SearchAndDiscoveryApp.conf.in | 9 +++++++ WebKitBrowser/WebKitBrowser.conf.in | 9 +++++++ WebKitBrowser/WebKitImplementation.cpp | 29 +++++++++++++++++++-- 8 files changed, 100 insertions(+), 2 deletions(-) diff --git a/WebKitBrowser/CMakeLists.txt b/WebKitBrowser/CMakeLists.txt index e6ff8f7a36..ab4f560ba8 100644 --- a/WebKitBrowser/CMakeLists.txt +++ b/WebKitBrowser/CMakeLists.txt @@ -68,6 +68,8 @@ set(PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_WEBPROCESS_SETTINGS_GPU_FILE "" CACHE ST set(PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_WEBPROCESS_SETTINGS_POLLINTERVAL "1" CACHE STRING "WebkitBrower Memory Pressure Webprocess Poll Interval") set(PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_LIMIT "100" CACHE STRING "WebkitBrower Memory Pressure Networkprocess Limit") set(PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_POLLINTERVAL "1" CACHE STRING "WebkitBrower Memory Pressure Networkprocess Poll Interval") +set(PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_LIMIT "100" CACHE STRING "WebkitBrower Memory Pressure Service Worker process Limit") +set(PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_POLLINTERVAL "1" CACHE STRING "WebkitBrower Memory Pressure Service Worker process Poll Interval") set(PLUGIN_WEBKITBROWSER_MEDIA_CONTENT_TYPES_REQUIRING_HARDWARE_SUPPORT "video/*" CACHE STRING "Media content types requiring hardware support") set(PLUGIN_WEBKITBROWSER_MEDIADISKCACHE "false" CACHE STRING "Media Disk Cache") set(PLUGIN_WEBKITBROWSER_MSEBUFFERS "audio:2m,video:15m,text:1m" CACHE STRING "MSE Buffers for WebKit") @@ -104,6 +106,8 @@ set(PLUGIN_YOUTUBE_MEMORYPRESSURE_WEBPROCESS_SETTINGS_GPU_FILE ${PLUGIN_WEBKITBR set(PLUGIN_YOUTUBE_MEMORYPRESSURE_WEBPROCESS_SETTINGS_POLLINTERVAL ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_WEBPROCESS_SETTINGS_POLLINTERVAL} CACHE STRING "YouTube Memory Pressure Webprocess Poll Interval") set(PLUGIN_YOUTUBE_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_LIMIT ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_LIMIT} CACHE STRING "YouTube Memory Pressure Networkprocess Limit") set(PLUGIN_YOUTUBE_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_POLLINTERVAL ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_POLLINTERVAL} CACHE STRING "YouTube Memory Pressure Networkprocess Poll Interval") +set(PLUGIN_YOUTUBE_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_LIMIT ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_LIMIT} CACHE STRING "YouTube Memory Pressure Service Worker kprocess Limit") +set(PLUGIN_YOUTUBE_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_POLLINTERVAL ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_POLLINTERVAL} CACHE STRING "YouTube Memory Pressure Service Worker process Poll Interval") set(PLUGIN_UX_AUTOSTART "false" CACHE STRING "Automatically start UX plugin") set(PLUGIN_UX_STARTUPORDER "" CACHE STRING "To configure startup order of UX plugin") @@ -118,6 +122,8 @@ set(PLUGIN_UX_MEMORYPRESSURE_WEBPROCESS_SETTINGS_GPU_FILE ${PLUGIN_WEBKITBROWSER set(PLUGIN_UX_MEMORYPRESSURE_WEBPROCESS_SETTINGS_POLLINTERVAL ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_WEBPROCESS_SETTINGS_POLLINTERVAL} CACHE STRING "UX Memory Pressure Webprocess Poll Interval") set(PLUGIN_UX_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_LIMIT ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_LIMIT} CACHE STRING "UX Memory Pressure Networkprocess Limit") set(PLUGIN_UX_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_POLLINTERVAL ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_POLLINTERVAL} CACHE STRING "UX Memory Pressure Networkprocess Poll Interval") +set(PLUGIN_UX_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_LIMIT ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_LIMIT} CACHE STRING "UX Memory Pressure Service Worker kprocess Limit") +set(PLUGIN_UX_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_POLLINTERVAL ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_POLLINTERVAL} CACHE STRING "UX Memory Pressure Service Worker process Poll Interval") set(PLUGIN_APPS_AUTOSTART "false" CACHE STRING "Automatically start Apps plugin") set(PLUGIN_APPS_STARTUPORDER "" CACHE STRING "To configure startup order of Apps plugin") @@ -133,6 +139,8 @@ set(PLUGIN_APPS_MEMORYPRESSURE_WEBPROCESS_SETTINGS_GPU_FILE ${PLUGIN_WEBKITBROWS set(PLUGIN_APPS_MEMORYPRESSURE_WEBPROCESS_SETTINGS_POLLINTERVAL ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_WEBPROCESS_SETTINGS_POLLINTERVAL} CACHE STRING "Apps Memory Pressure Webprocess Poll Interval") set(PLUGIN_APPS_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_LIMIT ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_LIMIT} CACHE STRING "Apps Memory Pressure Networkprocess Limit") set(PLUGIN_APPS_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_POLLINTERVAL ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_POLLINTERVAL} CACHE STRING "Apps Memory Pressure Networkprocess Poll Interval") +set(PLUGIN_APPS_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_LIMIT ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_LIMIT} CACHE STRING "Apps Memory Pressure Service Worker kprocess Limit") +set(PLUGIN_APPS_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_POLLINTERVAL ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_POLLINTERVAL} CACHE STRING "Apps Memory Pressure Service Worker process Poll Interval") set(PLUGIN_RESIDENT_APP_AUTOSTART "false" CACHE STRING "Automatically start Resident App plugin") set(PLUGIN_RESIDENT_APP_STARTUPORDER "" CACHE STRING "To configure startup order of Resident App plugin") @@ -148,6 +156,8 @@ set(PLUGIN_RESIDENT_APP_MEMORYPRESSURE_WEBPROCESS_SETTINGS_GPU_FILE ${PLUGIN_WEB set(PLUGIN_RESIDENT_APP_MEMORYPRESSURE_WEBPROCESS_SETTINGS_POLLINTERVAL ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_WEBPROCESS_SETTINGS_POLLINTERVAL} CACHE STRING "Resident App Memory Pressure Webprocess Poll Interval") set(PLUGIN_RESIDENT_APP_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_LIMIT ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_LIMIT} CACHE STRING "Resident App Memory Pressure Networkprocess Limit") set(PLUGIN_RESIDENT_APP_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_POLLINTERVAL ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_POLLINTERVAL} CACHE STRING "Resident App Memory Pressure Networkprocess Poll Interval") +set(PLUGIN_RESIDENT_APP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_LIMIT ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_LIMIT} CACHE STRING "Resident App Memory Pressure Service Worker kprocess Limit") +set(PLUGIN_RESIDENT_APP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_POLLINTERVAL ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_POLLINTERVAL} CACHE STRING "Resident App Memory Pressure Service Worker process Poll Interval") set(PLUGIN_RESIDENT_APP_COMPOSITOR "msaa" CACHE STRING "cairo compositor mode for Resident App") set(PLUGIN_SEARCH_AND_DISCOVERY_APP_AUTOSTART "false" CACHE STRING "Automatically start Search&Discovery App plugin") @@ -163,6 +173,8 @@ set(PLUGIN_SEARCH_AND_DISCOVERY_APP_MEMORYPRESSURE_WEBPROCESS_SETTINGS_GPU_FILE set(PLUGIN_SEARCH_AND_DISCOVERY_APP_MEMORYPRESSURE_WEBPROCESS_SETTINGS_POLLINTERVAL ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_WEBPROCESS_SETTINGS_POLLINTERVAL} CACHE STRING "Search and Discovery App Memory Pressure Webprocess Poll Interval") set(PLUGIN_SEARCH_AND_DISCOVERY_APP_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_LIMIT ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_LIMIT} CACHE STRING "Search and Discovery App Memory Pressure Networkprocess Limit") set(PLUGIN_SEARCH_AND_DISCOVERY_APP_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_POLLINTERVAL ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_POLLINTERVAL} CACHE STRING "Search and Discovery App Memory Pressure Networkprocess Poll Interval") +set(PLUGIN_SEARCH_AND_DISCOVERY_APP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_LIMIT ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_LIMIT} CACHE STRING "Search and Discovery App Memory Pressure Service Worker kprocess Limit") +set(PLUGIN_SEARCH_AND_DISCOVERY_APP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_POLLINTERVAL ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_POLLINTERVAL} CACHE STRING "Search and Discovery App Memory Pressure Service Worker process Poll Interval") set(PLUGIN_SEARCH_AND_DISCOVERY_APP_COMPOSITOR "msaa" CACHE STRING "cairo compositor mode for Search&Discovery App") set(PLUGIN_HTML_APP_AUTOSTART "false" CACHE STRING "Automatically start Htmp App plugin") @@ -178,6 +190,8 @@ set(PLUGIN_HTML_APP_MEMORYPRESSURE_WEBPROCESS_SETTINGS_GPU_FILE ${PLUGIN_WEBKITB set(PLUGIN_HTML_APP_MEMORYPRESSURE_WEBPROCESS_SETTINGS_POLLINTERVAL ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_WEBPROCESS_SETTINGS_POLLINTERVAL} CACHE STRING "Html App Memory Pressure Webprocess Poll Interval") set(PLUGIN_HTML_APP_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_LIMIT ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_LIMIT} CACHE STRING "Html App Memory Pressure Networkprocess Limit") set(PLUGIN_HTML_APP_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_POLLINTERVAL ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_POLLINTERVAL} CACHE STRING "Html App Memory Pressure Networkprocess Poll Interval") +set(PLUGIN_HTML_APP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_LIMIT ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_LIMIT} CACHE STRING "Html App Memory Pressure Service Worker kprocess Limit") +set(PLUGIN_HTML_APP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_POLLINTERVAL ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_POLLINTERVAL} CACHE STRING "Html App Memory Pressure Service Worker process Poll Interval") set(PLUGIN_HTML_APP_COMPOSITOR "noaa" CACHE STRING "cairo compositor mode for Html App") set(PLUGIN_LIGHTNING_APP_AUTOSTART "false" CACHE STRING "Automatically start Lightning App plugin") @@ -193,6 +207,8 @@ set(PLUGIN_LIGHTNING_APP_MEMORYPRESSURE_WEBPROCESS_SETTINGS_GPU_FILE ${PLUGIN_WE set(PLUGIN_LIGHTNING_APP_MEMORYPRESSURE_WEBPROCESS_SETTINGS_POLLINTERVAL ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_WEBPROCESS_SETTINGS_POLLINTERVAL} CACHE STRING "Lightning App Memory Pressure Webprocess Poll Interval") set(PLUGIN_LIGHTNING_APP_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_LIMIT ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_LIMIT} CACHE STRING "Lightning App Memory Pressure Networkprocess Limit") set(PLUGIN_LIGHTNING_APP_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_POLLINTERVAL ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_POLLINTERVAL} CACHE STRING "Lightning App Memory Pressure Networkprocess Poll Interval") +set(PLUGIN_LIGHTNING_APP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_LIMIT ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_LIMIT} CACHE STRING "Lightning App Memory Pressure Service Worker kprocess Limit") +set(PLUGIN_LIGHTNING_APP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_POLLINTERVAL ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_POLLINTERVAL} CACHE STRING "Lightning App Memory Pressure Service Worker process Poll Interval") set(PLUGIN_LIGHTNING_APP_COMPOSITOR "noaa" CACHE STRING "cairo compositor mode for Lightning App") set(PLUGIN_JSPP_AUTOSTART "false" CACHE STRING "Automatically start JSPP plugin") @@ -207,6 +223,8 @@ set(PLUGIN_JSPP_MEMORYPRESSURE_WEBPROCESS_SETTINGS_GPU_FILE ${PLUGIN_WEBKITBROWS set(PLUGIN_JSPP_MEMORYPRESSURE_WEBPROCESS_SETTINGS_POLLINTERVAL ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_WEBPROCESS_SETTINGS_POLLINTERVAL} CACHE STRING "JSPP App Memory Pressure Webprocess Poll Interval") set(PLUGIN_JSPP_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_LIMIT ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_LIMIT} CACHE STRING "JSPP App Memory Pressure Networkprocess Limit") set(PLUGIN_JSPP_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_POLLINTERVAL ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_POLLINTERVAL} CACHE STRING "JSPP App Memory Pressure Networkprocess Poll Interval") +set(PLUGIN_JSPP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_LIMIT ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_LIMIT} CACHE STRING "JSPP App Memory Pressure Service Worker kprocess Limit") +set(PLUGIN_JSPP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_POLLINTERVAL ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_POLLINTERVAL} CACHE STRING "JSPP App Memory Pressure Service Worker process Poll Interval") set(PLUGIN_JSPP_STARTURL "about:blank" CACHE STRING "JSPP default URL to use") set(PLUGIN_AMAZON_AUTOSTART "false" CACHE STRING "Automatically start Amazon plugin") @@ -221,6 +239,8 @@ set(PLUGIN_AMAZON_MEMORYPRESSURE_WEBPROCESS_SETTINGS_GPU_FILE ${PLUGIN_WEBKITBRO set(PLUGIN_AMAZON_MEMORYPRESSURE_WEBPROCESS_SETTINGS_POLLINTERVAL ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_WEBPROCESS_SETTINGS_POLLINTERVAL} CACHE STRING "Amazon App Memory Pressure Webprocess Poll Interval") set(PLUGIN_AMAZON_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_LIMIT ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_LIMIT} CACHE STRING "Amazon App Memory Pressure Networkprocess Limit") set(PLUGIN_AMAZON_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_POLLINTERVAL ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_POLLINTERVAL} CACHE STRING "Amazon App Memory Pressure Networkprocess Poll Interval") +set(PLUGIN_AMAZON_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_LIMIT ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_LIMIT} CACHE STRING "Amazon App Memory Pressure Service Worker kprocess Limit") +set(PLUGIN_AMAZON_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_POLLINTERVAL ${PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_POLLINTERVAL} CACHE STRING "Amazon App Memory Pressure Service Worker process Poll Interval") find_package(${NAMESPACE}Plugins REQUIRED) find_package(${NAMESPACE}Definitions REQUIRED) diff --git a/WebKitBrowser/HtmlApp.conf.in b/WebKitBrowser/HtmlApp.conf.in index abbffda7f7..678681b818 100644 --- a/WebKitBrowser/HtmlApp.conf.in +++ b/WebKitBrowser/HtmlApp.conf.in @@ -67,6 +67,7 @@ memory = JSON() webprocesssettings = JSON() networkprocesssettings = JSON() +serviceworkerprocesssettings = JSON() if ("@PLUGIN_HTML_APP_MEMORYPRESSURE_WEBPROCESS_SETTINGS_LIMIT@ OR (@PLUGIN_HTML_APP_MEMORYPRESSURE_WEBPROCESS_SETTINGS_GPU_LIMIT@ AND @PLUGIN_HTML_APP_MEMORYPRESSURE_WEBPROCESS_SETTINGS_GPU_FILE@) OR @PLUGIN_HTML_APP_MEMORYPRESSURE_WEBPROCESS_SETTINGS_POLLINTERVAL@"): @@ -89,5 +90,12 @@ if ("@PLUGIN_HTML_APP_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_LIMIT@ AND @PLUGIN_ networkprocesssettings.add("pollinterval", "@PLUGIN_HTML_APP_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_POLLINTERVAL@") memory.add("networkprocesssettings", networkprocesssettings) +if ("@PLUGIN_HTML_APP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_LIMIT@ AND @PLUGIN_HTML_APP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_POLLINTERVAL@"): + if ("@PLUGIN_HTML_APP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_LIMIT@"): + serviceworkerprocesssettings.add("limit", "@PLUGIN_HTML_APP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_LIMIT@") + if ("@PLUGIN_HTML_APP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_POLLINTERVAL@"): + serviceworkerprocesssettings.add("pollinterval", "@PLUGIN_HTML_APP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_POLLINTERVAL@") +memory.add("serviceworkerprocesssettings", serviceworkerprocesssettings) + configuration.add("memory", memory) diff --git a/WebKitBrowser/JSPP.conf.in b/WebKitBrowser/JSPP.conf.in index 58277c489a..19a2e26bd7 100644 --- a/WebKitBrowser/JSPP.conf.in +++ b/WebKitBrowser/JSPP.conf.in @@ -119,6 +119,7 @@ memory = JSON() webprocesssettings = JSON() networkprocesssettings = JSON() +serviceworkerprocesssettings = JSON() if ("@PLUGIN_JSPP_MEMORYPRESSURE_WEBPROCESS_SETTINGS_LIMIT@ OR (@PLUGIN_JSPP_MEMORYPRESSURE_WEBPROCESS_SETTINGS_GPU_LIMIT@ AND @PLUGIN_JSPP_MEMORYPRESSURE_WEBPROCESS_SETTINGS_GPU_FILE@) OR @PLUGIN_JSPP_MEMORYPRESSURE_WEBPROCESS_SETTINGS_POLLINTERVAL@"): @@ -140,5 +141,13 @@ if ("@PLUGIN_JSPP_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_LIMIT@ OR @PLUGIN_JSPP_ if ("@PLUGIN_JSPP_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_POLLINTERVAL@"): networkprocesssettings.add("pollinterval", "@PLUGIN_JSPP_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_POLLINTERVAL@") memory.add("networkprocesssettings", networkprocesssettings) + +if ("@PLUGIN_JSPP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_LIMIT@ AND @PLUGIN_JSPP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_POLLINTERVAL@"): + if ("@PLUGIN_JSPP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_LIMIT@"): + serviceworkerprocesssettings.add("limit", "@PLUGIN_JSPP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_LIMIT@") + if ("@PLUGIN_JSPP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_POLLINTERVAL@"): + serviceworkerprocesssettings.add("pollinterval", "@PLUGIN_JSPP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_POLLINTERVAL@") +memory.add("serviceworkerprocesssettings", serviceworkerprocesssettings) + configuration.add("memory", memory) diff --git a/WebKitBrowser/LightningApp.conf.in b/WebKitBrowser/LightningApp.conf.in index b7ee80352e..382f1e1c5d 100644 --- a/WebKitBrowser/LightningApp.conf.in +++ b/WebKitBrowser/LightningApp.conf.in @@ -67,6 +67,7 @@ memory = JSON() webprocesssettings = JSON() networkprocesssettings = JSON() +serviceworkerprocesssettings = JSON() if ("@PLUGIN_LIGHTNING_APP_MEMORYPRESSURE_WEBPROCESS_SETTINGS_LIMIT@ OR (@PLUGIN_LIGHTNING_APP_MEMORYPRESSURE_WEBPROCESS_SETTINGS_GPU_LIMIT@ AND @PLUGIN_LIGHTNING_APP_MEMORYPRESSURE_WEBPROCESS_SETTINGS_GPU_FILE@) OR @PLUGIN_LIGHTNING_APP_MEMORYPRESSURE_WEBPROCESS_SETTINGS_POLLINTERVAL@"): @@ -88,4 +89,12 @@ if ("@PLUGIN_LIGHTNING_APP_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_LIMIT@ AND @PL if ("@PLUGIN_LIGHTNING_APP_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_POLLINTERVAL@"): networkprocesssettings.add("pollinterval", "@PLUGIN_LIGHTNING_APP_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_POLLINTERVAL@") memory.add("networkprocesssettings", networkprocesssettings) + +if ("@PLUGIN_LIGHTNING_APP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_LIMIT@ AND @PLUGIN_LIGHTNING_APP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_POLLINTERVAL@"): + if ("@PLUGIN_LIGHTNING_APP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_LIMIT@"): + serviceworkerprocesssettings.add("limit", "@PLUGIN_LIGHTNING_APP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_LIMIT@") + if ("@PLUGIN_LIGHTNING_APP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_POLLINTERVAL@"): + serviceworkerprocesssettings.add("pollinterval", "@PLUGIN_LIGHTNING_APP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_POLLINTERVAL@") +memory.add("serviceworkerprocesssettings", serviceworkerprocesssettings) + configuration.add("memory", memory) diff --git a/WebKitBrowser/ResidentApp.conf.in b/WebKitBrowser/ResidentApp.conf.in index b10d6efa90..69208ebbc0 100644 --- a/WebKitBrowser/ResidentApp.conf.in +++ b/WebKitBrowser/ResidentApp.conf.in @@ -62,6 +62,7 @@ memory = JSON() webprocesssettings = JSON() networkprocesssettings = JSON() +serviceworkerprocesssettings = JSON() if ("@PLUGIN_RESIDENT_APP_MEMORYPRESSURE_WEBPROCESS_SETTINGS_LIMIT@ OR (@PLUGIN_RESIDENT_APP_MEMORYPRESSURE_WEBPROCESS_SETTINGS_GPU_LIMIT@ AND @PLUGIN_RESIDENT_APP_MEMORYPRESSURE_WEBPROCESS_SETTINGS_GPU_FILE@) OR @PLUGIN_RESIDENT_APP_MEMORYPRESSURE_WEBPROCESS_SETTINGS_POLLINTERVAL@"): @@ -83,4 +84,12 @@ if ("@PLUGIN_RESIDENT_APP_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_LIMIT@ AND @PLU if ("@PLUGIN_RESIDENT_APP_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_POLLINTERVAL@"): networkprocesssettings.add("pollinterval", "@PLUGIN_RESIDENT_APP_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_POLLINTERVAL@") memory.add("networkprocesssettings", networkprocesssettings) + +if ("@PLUGIN_RESIDENT_APP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_LIMIT@ AND @PLUGIN_RESIDENT_APP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_POLLINTERVAL@"): + if ("@PLUGIN_RESIDENT_APP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_LIMIT@"): + serviceworkerprocesssettings.add("limit", "@PLUGIN_RESIDENT_APP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_LIMIT@") + if ("@PLUGIN_RESIDENT_APP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_POLLINTERVAL@"): + serviceworkerprocesssettings.add("pollinterval", "@PLUGIN_RESIDENT_APP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_POLLINTERVAL@") +memory.add("serviceworkerprocesssettings", serviceworkerprocesssettings) + configuration.add("memory", memory) diff --git a/WebKitBrowser/SearchAndDiscoveryApp.conf.in b/WebKitBrowser/SearchAndDiscoveryApp.conf.in index e4e4e6fb75..cadea0216f 100644 --- a/WebKitBrowser/SearchAndDiscoveryApp.conf.in +++ b/WebKitBrowser/SearchAndDiscoveryApp.conf.in @@ -64,6 +64,7 @@ memory = JSON() webprocesssettings = JSON() networkprocesssettings = JSON() +serviceworkerprocesssettings = JSON() if ("@PLUGIN_SEARCH_AND_DISCOVERY_APP_MEMORYPRESSURE_WEBPROCESS_SETTINGS_LIMIT@ OR (@PLUGIN_SEARCH_AND_DISCOVERY_APP_MEMORYPRESSURE_WEBPROCESS_SETTINGS_GPU_LIMIT@ AND @PLUGIN_SEARCH_AND_DISCOVERY_APP_MEMORYPRESSURE_WEBPROCESS_SETTINGS_GPU_FILE@) OR @PLUGIN_SEARCH_AND_DISCOVERY_APP_MEMORYPRESSURE_WEBPROCESS_SETTINGS_POLLINTERVAL@"): if ("@PLUGIN_SEARCH_AND_DISCOVERY_APP_MEMORYPRESSURE_WEBPROCESS_SETTINGS_LIMIT@"): @@ -84,4 +85,12 @@ if ("@PLUGIN_SEARCH_AND_DISCOVERY_APP_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_LIM if ("@PLUGIN_SEARCH_AND_DISCOVERY_APP_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_POLLINTERVAL@"): networkprocesssettings.add("pollinterval", "@PLUGIN_SEARCH_AND_DISCOVERY_APP_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_POLLINTERVAL@") memory.add("networkprocesssettings", networkprocesssettings) + +if ("@PLUGIN_SEARCH_AND_DISCOVERY_APP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_LIMIT@ AND @PLUGIN_SEARCH_AND_DISCOVERY_APP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_POLLINTERVAL@"): + if ("@PLUGIN_SEARCH_AND_DISCOVERY_APP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_LIMIT@"): + serviceworkerprocesssettings.add("limit", "@PLUGIN_SEARCH_AND_DISCOVERY_APP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_LIMIT@") + if ("@PLUGIN_SEARCH_AND_DISCOVERY_APP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_POLLINTERVAL@"): + serviceworkerprocesssettings.add("pollinterval", "@PLUGIN_SEARCH_AND_DISCOVERY_APP_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_POLLINTERVAL@") +memory.add("serviceworkerprocesssettings", serviceworkerprocesssettings) + configuration.add("memory", memory) diff --git a/WebKitBrowser/WebKitBrowser.conf.in b/WebKitBrowser/WebKitBrowser.conf.in index 1c0312d66c..067cad5a60 100644 --- a/WebKitBrowser/WebKitBrowser.conf.in +++ b/WebKitBrowser/WebKitBrowser.conf.in @@ -77,6 +77,7 @@ memory = JSON() webprocesssettings = JSON() networkprocesssettings = JSON() +serviceworkerprocesssettings = JSON() if ("@PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_WEBPROCESS_SETTINGS_LIMIT@ OR (@PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_WEBPROCESS_SETTINGS_GPU_LIMIT@ AND @PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_WEBPROCESS_SETTINGS_GPU_FILE@) OR @PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_WEBPROCESS_SETTINGS_POLLINTERVAL@"): @@ -98,4 +99,12 @@ if ("@PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_LIMIT@ AND @PL if ("@PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_POLLINTERVAL@"): networkprocesssettings.add("pollinterval", "@PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_NETWORKPROCESS_SETTINGS_POLLINTERVAL@") memory.add("networkprocesssettings", networkprocesssettings) + +if ("@PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_LIMIT@ AND @PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_POLLINTERVAL@"): + if ("@PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_LIMIT@"): + serviceworkerprocesssettings.add("limit", "@PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_LIMIT@") + if ("@PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_POLLINTERVAL@"): + serviceworkerprocesssettings.add("pollinterval", "@PLUGIN_WEBKITBROWSER_MEMORYPRESSURE_SERVICEWORKERPROCESS_SETTINGS_POLLINTERVAL@") +memory.add("serviceworkerprocesssettings", serviceworkerprocesssettings) + configuration.add("memory", memory) diff --git a/WebKitBrowser/WebKitImplementation.cpp b/WebKitBrowser/WebKitImplementation.cpp index cdea9ba177..c46d3db6eb 100644 --- a/WebKitBrowser/WebKitImplementation.cpp +++ b/WebKitBrowser/WebKitImplementation.cpp @@ -543,9 +543,11 @@ static GSourceFuncs _handlerIntervention = : Core::JSON::Container() , WebProcessSettings() , NetworkProcessSettings() + , ServiceWorkerProcessSettings() { Add(_T("webprocesssettings"), &WebProcessSettings); Add(_T("networkprocesssettings"), &NetworkProcessSettings); + Add(_T("serviceworkerprocesssettings"), &ServiceWorkerProcessSettings); } ~MemorySettings() { @@ -554,6 +556,7 @@ static GSourceFuncs _handlerIntervention = public: WebProcess WebProcessSettings; Settings NetworkProcessSettings; + WebProcess ServiceWorkerProcessSettings; }; public: @@ -2855,8 +2858,30 @@ static GSourceFuncs _handlerIntervention = webkit_memory_pressure_settings_set_poll_interval(memoryPressureSettings, _config.Memory.WebProcessSettings.PollInterval.Value()); } - // Pass web process memory pressure settings to WebKitWebContext constructor - wkContext = WEBKIT_WEB_CONTEXT(g_object_new(WEBKIT_TYPE_WEB_CONTEXT, "website-data-manager", websiteDataManager, "memory-pressure-settings", memoryPressureSettings, nullptr)); + if (_config.Memory.ServiceWorkerProcessSettings.IsSet() == true) { + WebKitMemoryPressureSettings* serviceWorkerMemoryPressureSettings = webkit_memory_pressure_settings_new(); + + if (_config.Memory.ServiceWorkerProcessSettings.Limit.IsSet() == true) { + webkit_memory_pressure_settings_set_memory_limit(serviceWorkerMemoryPressureSettings, _config.Memory.ServiceWorkerProcessSettings.Limit.Value()); + } + if (_config.Memory.ServiceWorkerProcessSettings.PollInterval.IsSet() == true) { + webkit_memory_pressure_settings_set_poll_interval(serviceWorkerMemoryPressureSettings, _config.Memory.ServiceWorkerProcessSettings.PollInterval.Value()); + } + + // Pass web and service worker process memory pressure settings to WebKitWebContext constructor + wkContext = WEBKIT_WEB_CONTEXT(g_object_new(WEBKIT_TYPE_WEB_CONTEXT, + "website-data-manager", websiteDataManager, + "memory-pressure-settings", memoryPressureSettings, + "service-worker-memory-pressure-settings", serviceWorkerMemoryPressureSettings, + nullptr)); + webkit_memory_pressure_settings_free(serviceWorkerMemoryPressureSettings); + } else { + // Pass web process memory pressure settings to WebKitWebContext constructor + wkContext = WEBKIT_WEB_CONTEXT(g_object_new(WEBKIT_TYPE_WEB_CONTEXT, + "website-data-manager", websiteDataManager, + "memory-pressure-settings", memoryPressureSettings, + nullptr)); + } webkit_memory_pressure_settings_free(memoryPressureSettings); } else #endif From b57ba0078673805b5a6098591f93137ce936aa7c Mon Sep 17 00:00:00 2001 From: Karunakaran A <48997923+karuna2git@users.noreply.github.com> Date: Wed, 29 May 2024 09:24:40 -0400 Subject: [PATCH 03/21] DELIA-65343, RDK-48562 : Refactor NetworkManager Plugin (#5345) * Restructure the whole NetworkManager code to be single component & updated COMRPC Proxy Implementation Signed-off-by: Karunakaran A --- NetworkManager/CHANGELOG.md | 7 + NetworkManager/CMakeLists.txt | 124 ++- .../{interface => }/INetworkManager.h | 8 +- .../LegacyPlugin_NetworkAPIs.conf.in | 3 + .../LegacyPlugin_NetworkAPIs.config | 3 + NetworkManager/LegacyPlugin_NetworkAPIs.cpp | 908 ++++++++++++++++++ NetworkManager/LegacyPlugin_NetworkAPIs.h | 89 ++ .../LegacyPlugin_WiFiManagerAPIs.conf.in | 3 + .../LegacyPlugin_WiFiManagerAPIs.config | 3 + .../LegacyPlugin_WiFiManagerAPIs.cpp | 536 +++++++++++ NetworkManager/LegacyPlugin_WiFiManagerAPIs.h | 96 ++ NetworkManager/{service => }/Module.cpp | 0 NetworkManager/{service => }/Module.h | 0 .../{service => }/NetworkManager.conf.in | 7 +- .../{service => }/NetworkManager.config | 1 - .../{service => }/NetworkManager.cpp | 9 +- NetworkManager/{service => }/NetworkManager.h | 121 +-- .../{service => }/NetworkManager.json | 0 ...ity.cpp => NetworkManagerConnectivity.cpp} | 70 +- ...ctivity.h => NetworkManagerConnectivity.h} | 2 - .../NetworkManagerGnomeProxy.cpp | 11 +- .../{service => }/NetworkManagerGnomeWIFI.cpp | 0 .../{service => }/NetworkManagerGnomeWIFI.h | 0 .../NetworkManagerImplementation.cpp | 4 +- .../NetworkManagerImplementation.h | 15 +- .../{service => }/NetworkManagerJsonRpc.cpp | 52 +- .../{service => }/NetworkManagerLogger.cpp | 2 +- .../{service => }/NetworkManagerLogger.h | 0 .../{service => }/NetworkManagerPlugin.json | 0 .../{service => }/NetworkManagerRDKProxy.cpp | 9 +- ...lient.cpp => NetworkManagerStunClient.cpp} | 2 +- ...tunClient.h => NetworkManagerStunClient.h} | 0 ...itor.cpp => WiFiSignalStrengthMonitor.cpp} | 20 +- ...hMonitor.h => WiFiSignalStrengthMonitor.h} | 10 +- NetworkManager/cmake | 1 - NetworkManager/cmake/FindIARMBus.cmake | 46 + NetworkManager/interface/CMakeLists.txt | 48 - NetworkManager/interface/Module.cpp | 3 - NetworkManager/interface/Module.h | 8 - NetworkManager/service/CMakeLists.txt | 110 --- NetworkManager/service/Network.conf.in | 25 - NetworkManager/service/Network.config | 27 - .../service/NetworkManagerLegacy.cpp | 639 ------------ NetworkManager/service/WiFiManager.conf.in | 25 - NetworkManager/service/WiFiManager.config | 28 - 45 files changed, 1905 insertions(+), 1170 deletions(-) rename NetworkManager/{interface => }/INetworkManager.h (97%) create mode 100644 NetworkManager/LegacyPlugin_NetworkAPIs.conf.in create mode 100644 NetworkManager/LegacyPlugin_NetworkAPIs.config create mode 100644 NetworkManager/LegacyPlugin_NetworkAPIs.cpp create mode 100644 NetworkManager/LegacyPlugin_NetworkAPIs.h create mode 100644 NetworkManager/LegacyPlugin_WiFiManagerAPIs.conf.in create mode 100644 NetworkManager/LegacyPlugin_WiFiManagerAPIs.config create mode 100644 NetworkManager/LegacyPlugin_WiFiManagerAPIs.cpp create mode 100644 NetworkManager/LegacyPlugin_WiFiManagerAPIs.h rename NetworkManager/{service => }/Module.cpp (100%) rename NetworkManager/{service => }/Module.h (100%) rename NetworkManager/{service => }/NetworkManager.conf.in (86%) rename NetworkManager/{service => }/NetworkManager.config (93%) rename NetworkManager/{service => }/NetworkManager.cpp (95%) rename NetworkManager/{service => }/NetworkManager.h (67%) rename NetworkManager/{service => }/NetworkManager.json (100%) rename NetworkManager/{service/NetworkConnectivity.cpp => NetworkManagerConnectivity.cpp} (89%) rename NetworkManager/{service/NetworkConnectivity.h => NetworkManagerConnectivity.h} (97%) rename NetworkManager/{service => }/NetworkManagerGnomeProxy.cpp (98%) mode change 100755 => 100644 rename NetworkManager/{service => }/NetworkManagerGnomeWIFI.cpp (100%) rename NetworkManager/{service => }/NetworkManagerGnomeWIFI.h (100%) rename NetworkManager/{service => }/NetworkManagerImplementation.cpp (99%) rename NetworkManager/{service => }/NetworkManagerImplementation.h (95%) rename NetworkManager/{service => }/NetworkManagerJsonRpc.cpp (95%) rename NetworkManager/{service => }/NetworkManagerLogger.cpp (93%) rename NetworkManager/{service => }/NetworkManagerLogger.h (100%) rename NetworkManager/{service => }/NetworkManagerPlugin.json (100%) rename NetworkManager/{service => }/NetworkManagerRDKProxy.cpp (99%) rename NetworkManager/{service/StunClient.cpp => NetworkManagerStunClient.cpp} (99%) rename NetworkManager/{service/StunClient.h => NetworkManagerStunClient.h} (100%) rename NetworkManager/{service/WifiSignalStrengthMonitor.cpp => WiFiSignalStrengthMonitor.cpp} (90%) rename NetworkManager/{service/WifiSignalStrengthMonitor.h => WiFiSignalStrengthMonitor.h} (86%) delete mode 120000 NetworkManager/cmake create mode 100644 NetworkManager/cmake/FindIARMBus.cmake delete mode 100644 NetworkManager/interface/CMakeLists.txt delete mode 100644 NetworkManager/interface/Module.cpp delete mode 100644 NetworkManager/interface/Module.h delete mode 100644 NetworkManager/service/CMakeLists.txt delete mode 100644 NetworkManager/service/Network.conf.in delete mode 100644 NetworkManager/service/Network.config delete mode 100644 NetworkManager/service/NetworkManagerLegacy.cpp delete mode 100644 NetworkManager/service/WiFiManager.conf.in delete mode 100644 NetworkManager/service/WiFiManager.config diff --git a/NetworkManager/CHANGELOG.md b/NetworkManager/CHANGELOG.md index 2f15638f0c..f731621cfd 100644 --- a/NetworkManager/CHANGELOG.md +++ b/NetworkManager/CHANGELOG.md @@ -16,6 +16,13 @@ All notable changes to this RDK Service will be documented in this file. * For more details, refer to [versioning](https://github.com/rdkcentral/rdkservices#versioning) section under Main README. +## [0.2.0] - 2024-05-27 +### Added +- Restructured the NetworkManager folder organization +- Refactored Legacy Network & WiFiManager Plugin as JSONRPC +- Built COMRPC Proxy Implementation as part of NetworkManager Plugin itself +- Built out-of-process class as part of main library itself. + ## [0.1.0] - 2024-03-28 ### Added - Added NetworkManager plugin. A Unified `NetworkManager` plugin that allows you to manage Ethernet and Wifi interfaces on the device. diff --git a/NetworkManager/CMakeLists.txt b/NetworkManager/CMakeLists.txt index 6b88f14d42..f8016c2dd0 100644 --- a/NetworkManager/CMakeLists.txt +++ b/NetworkManager/CMakeLists.txt @@ -5,7 +5,7 @@ find_package(WPEFramework) list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/cmake") set(VERSION_MAJOR 0) -set(VERSION_MINOR 1) +set(VERSION_MINOR 2) set(VERSION_PATCH 0) add_compile_definitions(NETWORKMANAGER_MAJOR_VERSION=${VERSION_MAJOR}) @@ -20,6 +20,124 @@ include(CmakeHelperFunctions) string(TOLOWER ${NAMESPACE} STORAGE_DIRECTORY) get_directory_property(SEVICES_DEFINES COMPILE_DEFINITIONS) -add_subdirectory(interface) -add_subdirectory(service) +set(PLUGIN_NAME NetworkManager) +set(MODULE_NAME ${NAMESPACE}${PLUGIN_NAME}) +set(PLUGIN_LEGACY_DEPRECATED_NETWORK ${NAMESPACE}Network) +set(PLUGIN_LEGACY_DEPRECATED_WIFI ${NAMESPACE}WiFiManager) + +find_package(${NAMESPACE}Core REQUIRED) +find_package(${NAMESPACE}Plugins REQUIRED) +find_package(CURL) +if(ENABLE_GNOME_NETWORKMANAGER) +pkg_check_modules(GLIB REQUIRED glib-2.0) +pkg_check_modules(LIBNM REQUIRED libnm) +else() +find_package(IARMBus REQUIRED) +endif () + + +message("Setup ProxyStub for INetworkManager.h") +find_package(CompileSettingsDebug CONFIG REQUIRED) +find_package(ProxyStubGenerator REQUIRED) + +set(ProxyStubGenerator_DIR ${CMAKE_SYSROOT}${CMAKE_INSTALL_PREFIX}/tools/cmake ${ProxyStubGenerator_DIR}) + +if(NOT GENERATOR_SEARCH_PATH) + set(GENERATOR_SEARCH_PATH ${CMAKE_SYSROOT}${CMAKE_INSTALL_PREFIX}/include/${NAMESPACE}) +endif() + +message("The Search path is, ${GENERATOR_SEARCH_PATH}") +ProxyStubGenerator(INPUT "${CMAKE_CURRENT_SOURCE_DIR}" OUTDIR "${CMAKE_CURRENT_BINARY_DIR}/generated" INCLUDE_PATH ${GENERATOR_SEARCH_PATH}) + +file(GLOB PROXY_STUB_SOURCES "${CMAKE_CURRENT_BINARY_DIR}/generated/ProxyStubs*.cpp") + +message("Setup ${PROJECT_NAME} v${PROJECT_VERSION}") + +set(PLUGIN_NETWORKMANAGER_LOGLEVEL "5" CACHE STRING "To configure default loglevel NetworkManager plugin") + + +include_directories(${PROJECT_SOURCE_DIR}) +# Build the main plugin that runs inside the WPEFramework daemon +add_library(${MODULE_NAME} SHARED + NetworkManager.cpp + NetworkManagerJsonRpc.cpp + NetworkManagerLogger.cpp + NetworkManagerImplementation.cpp + NetworkManagerConnectivity.cpp + NetworkManagerStunClient.cpp + WiFiSignalStrengthMonitor.cpp + Module.cpp + ${PROXY_STUB_SOURCES}) + +target_link_libraries(${MODULE_NAME} PRIVATE + ${NAMESPACE}Core::${NAMESPACE}Core + ${NAMESPACE}Plugins::${NAMESPACE}Plugins + ) + +set_target_properties(${MODULE_NAME} PROPERTIES + CXX_STANDARD 11 + CXX_STANDARD_REQUIRED YES + FRAMEWORK FALSE) + +include_directories(${PROJECT_SOURCE_DIR}/interface) +include_directories(${PROJECT_SOURCE_DIR}/service) +include_directories(${PROJECT_SOURCE_DIR}/../helpers) + +install(TARGETS ${MODULE_NAME} DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/${STORAGE_DIRECTORY}/plugins) + + +# Build the implementation that runs out-of-process behind a COM-RPC interface + +if(ENABLE_GNOME_NETWORKMANAGER) + target_sources(${MODULE_NAME} PRIVATE NetworkManagerGnomeProxy.cpp NetworkManagerGnomeWIFI.cpp) + target_include_directories(${MODULE_NAME} PRIVATE ${GLIB_INCLUDE_DIRS} ${LIBNM_INCLUDE_DIRS}) + target_link_libraries(${MODULE_NAME} PRIVATE ${LIBNM_LIBRARIES}) +else() + target_sources(${MODULE_NAME} PRIVATE NetworkManagerRDKProxy.cpp) + target_include_directories(${MODULE_NAME} PRIVATE ${IARMBUS_INCLUDE_DIRS}) + target_link_libraries(${MODULE_NAME} PRIVATE ${IARMBUS_LIBRARIES}) +endif() + + +target_link_libraries(${MODULE_NAME} PRIVATE ${CURL_LIBRARIES}) +target_include_directories(${MODULE_NAME} PRIVATE ${CURL_INCLUDE_DIRS}) + + +add_library(${PLUGIN_LEGACY_DEPRECATED_NETWORK} SHARED + LegacyPlugin_NetworkAPIs.cpp + NetworkManagerLogger.cpp + Module.cpp +) + +target_link_libraries(${PLUGIN_LEGACY_DEPRECATED_NETWORK} PRIVATE + ${NAMESPACE}Core::${NAMESPACE}Core + ${NAMESPACE}Plugins::${NAMESPACE}Plugins + ) + +set_target_properties(${PLUGIN_LEGACY_DEPRECATED_NETWORK} PROPERTIES + CXX_STANDARD 11 + CXX_STANDARD_REQUIRED YES) + +install(TARGETS ${PLUGIN_LEGACY_DEPRECATED_NETWORK} DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/${STORAGE_DIRECTORY}/plugins) + +add_library(${PLUGIN_LEGACY_DEPRECATED_WIFI} SHARED + LegacyPlugin_WiFiManagerAPIs.cpp + NetworkManagerLogger.cpp + Module.cpp +) + +target_link_libraries(${PLUGIN_LEGACY_DEPRECATED_WIFI} PRIVATE + ${NAMESPACE}Core::${NAMESPACE}Core + ${NAMESPACE}Plugins::${NAMESPACE}Plugins + ) + +set_target_properties(${PLUGIN_LEGACY_DEPRECATED_WIFI} PROPERTIES + CXX_STANDARD 11 + CXX_STANDARD_REQUIRED YES) + +install(TARGETS ${PLUGIN_LEGACY_DEPRECATED_WIFI} DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/${STORAGE_DIRECTORY}/plugins) + +write_config() +write_config(PLUGINS LegacyPlugin_NetworkAPIs CLASSNAME Network LOCATOR lib${PLUGIN_LEGACY_DEPRECATED_NETWORK}.so) +write_config(PLUGINS LegacyPlugin_WiFiManagerAPIs CLASSNAME WiFiManager LOCATOR lib${PLUGIN_LEGACY_DEPRECATED_WIFI}.so) diff --git a/NetworkManager/interface/INetworkManager.h b/NetworkManager/INetworkManager.h similarity index 97% rename from NetworkManager/interface/INetworkManager.h rename to NetworkManager/INetworkManager.h index d51fd82e1c..ec034d219a 100644 --- a/NetworkManager/interface/INetworkManager.h +++ b/NetworkManager/INetworkManager.h @@ -211,10 +211,10 @@ namespace WPEFramework /* @brief Set the Primary Interface used for external world communication */ virtual uint32_t SetPrimaryInterface (const string& interface/* @in */) = 0; - /* @brief Enable the active Interface used for external world communication */ - virtual uint32_t EnableInterface (const string& interface/* @in */) = 0; - /* @brief Disable the Interface passed */ - virtual uint32_t DisableInterface (const string& interface/* @in */) = 0; + /* @brief Enable/Disable the given interface */ + virtual uint32_t SetInterfaceState (const string& interface /* @in */, const bool& enabled /* @in */) = 0; + /* @brief Get the state of given interface */ + virtual uint32_t GetInterfaceState (const string& interface /* @in */, bool& isEnabled /* @out */) = 0; /* @brief Get IP Address Of the Interface */ virtual uint32_t GetIPSettings(const string& interface /* @in */, const string &ipversion /* @in */, IPAddressInfo& result /* @out */) = 0; diff --git a/NetworkManager/LegacyPlugin_NetworkAPIs.conf.in b/NetworkManager/LegacyPlugin_NetworkAPIs.conf.in new file mode 100644 index 0000000000..0519daf3da --- /dev/null +++ b/NetworkManager/LegacyPlugin_NetworkAPIs.conf.in @@ -0,0 +1,3 @@ +precondition = ["Platform"] +callsign = "org.rdk.Network" +autostart = "true" diff --git a/NetworkManager/LegacyPlugin_NetworkAPIs.config b/NetworkManager/LegacyPlugin_NetworkAPIs.config new file mode 100644 index 0000000000..fcec1be201 --- /dev/null +++ b/NetworkManager/LegacyPlugin_NetworkAPIs.config @@ -0,0 +1,3 @@ +set (autostart true) +set (preconditions Platform) +set (callsign "org.rdk.Network") diff --git a/NetworkManager/LegacyPlugin_NetworkAPIs.cpp b/NetworkManager/LegacyPlugin_NetworkAPIs.cpp new file mode 100644 index 0000000000..eca0d45bad --- /dev/null +++ b/NetworkManager/LegacyPlugin_NetworkAPIs.cpp @@ -0,0 +1,908 @@ +/** +* If not stated otherwise in this file or this component's LICENSE +* file the following copyright and licenses apply: +* +* Copyright 2022 RDK Management +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +**/ +#include "LegacyPlugin_NetworkAPIs.h" +#include "NetworkManagerLogger.h" + + +using namespace std; +using namespace WPEFramework::Plugin; +#define API_VERSION_NUMBER_MAJOR 2 +#define API_VERSION_NUMBER_MINOR 0 +#define API_VERSION_NUMBER_PATCH 0 +#define NETWORK_MANAGER_CALLSIGN "org.rdk.NetworkManager.1" + +#define LOGINFOMETHOD() { string json; parameters.ToString(json); NMLOG_TRACE("Legacy params=%s", json.c_str() ); } +#define LOGTRACEMETHODFIN() { string json; response.ToString(json); NMLOG_TRACE("Legacy response=%s", json.c_str() ); } + +namespace WPEFramework +{ + class Job : public Core::IDispatch { + public: + Job(function work) + : _work(work) + { + } + void Dispatch() override + { + _work(); + } + + private: + function _work; + }; + + static Plugin::Metadata metadata( + // Version (Major, Minor, Patch) + API_VERSION_NUMBER_MAJOR, API_VERSION_NUMBER_MINOR, API_VERSION_NUMBER_PATCH, + // Preconditions + {}, + // Terminations + {}, + // Controls + {} + ); + + Network* _gNWInstance = nullptr; + namespace Plugin + { + SERVICE_REGISTRATION(Network, API_VERSION_NUMBER_MAJOR, API_VERSION_NUMBER_MINOR, API_VERSION_NUMBER_PATCH); + Network::Network() + : PluginHost::JSONRPC() + , m_service(nullptr) + { + _gNWInstance = this; + m_defaultInterface = "wlan0"; + RegisterLegacyMethods(); + } + + Network::~Network() + { + _gNWInstance = nullptr; + } + + void Network::activatePrimaryPlugin() + { + uint32_t result = Core::ERROR_ASYNC_FAILED; + string callsign(NETWORK_MANAGER_CALLSIGN); + Core::Event event(false, true); + Core::IWorkerPool::Instance().Submit(Core::ProxyType(Core::ProxyType::Create([&]() { + auto interface = m_service->QueryInterfaceByCallsign(callsign); + if (interface == nullptr) { + result = Core::ERROR_UNAVAILABLE; + NMLOG_WARNING("no IShell for %s", callsign.c_str()); + } else { + NMLOG_INFO("Activating %s", callsign.c_str()); + result = interface->Activate(PluginHost::IShell::reason::REQUESTED); + interface->Release(); + } + event.SetEvent(); + }))); + event.Lock(); + + return; + } + + const string Network::Initialize(PluginHost::IShell* service ) + { + m_service = service; + m_service->AddRef(); + + string callsign(NETWORK_MANAGER_CALLSIGN); + + auto interface = m_service->QueryInterfaceByCallsign(callsign); + if (interface != nullptr) + { + PluginHost::IShell::state state = interface->State(); + NMLOG_INFO("Current status of the %s plugin is %d", callsign.c_str(), state); + + if((PluginHost::IShell::state::ACTIVATED == state) || (PluginHost::IShell::state::ACTIVATION == state)) + { + NMLOG_INFO("Dependency Plugin '%s' Ready", callsign.c_str()); + } + else + { + activatePrimaryPlugin(); + } + interface->Release(); + } + + Core::SystemInfo::SetEnvironment(_T("THUNDER_ACCESS"), (_T("127.0.0.1:9998"))); + string query="token="; + m_networkmanager = make_shared >("org.rdk.NetworkManager", ""); + + /* Wait for Proxy stuff to be established */ + sleep(3); + + if (Core::ERROR_NONE != subscribeToEvents()) + return string("Failed to Subscribe"); + else + return string(); + } + + void Network::Deinitialize(PluginHost::IShell* /* service */) + { + UnregisterLegacyMethods(); + m_service->Release(); + m_service = nullptr; + _gNWInstance = nullptr; + } + + string Network::Information() const + { + return(string()); + } + + /** + * Hook up all our JSON RPC methods + * + * Each method definition comprises of: + * * Input parameters + * * Output parameters + * * Method name + * * Function that implements that method + */ + void Network::RegisterLegacyMethods() + { + CreateHandler({2}); + + Register("getStbIp", &Network::getStbIp, this); + Register("getSTBIPFamily", &Network::getSTBIPFamily, this); + Register("getInterfaces", &Network::getInterfaces, this); + Register("isInterfaceEnabled", &Network::isInterfaceEnabled, this); + Register("getPublicIP", &Network::getPublicIP, this); + Register("setInterfaceEnabled", &Network::setInterfaceEnabled, this); + Register("getDefaultInterface", &Network::getDefaultInterface, this); + Register("setDefaultInterface", &Network::setDefaultInterface, this); + Register("setIPSettings", &Network::setIPSettings, this); + Register("getIPSettings", &Network::getIPSettings, this); + Register("getInternetConnectionState", &Network::getInternetConnectionState, this); + Register("ping", &Network::doPing, this); + Register("isConnectedToInternet", &Network::isConnectedToInternet, this); + Register("setStunEndPoint", &Network::setStunEndPoint, this); + Register("trace", &Network::doTrace, this); + Register("setConnectivityTestEndpoints", &Network::setConnectivityTestEndpoints, this); + Register("startConnectivityMonitoring", &Network::startConnectivityMonitoring, this); + Register("getCaptivePortalURI", &Network::getCaptivePortalURI, this); + Register("stopConnectivityMonitoring", &Network::stopConnectivityMonitoring, this); + GetHandler(2)->Register("setIPSettings", &Network::setIPSettings, this); + GetHandler(2)->Register("getIPSettings", &Network::getIPSettings, this); + } + + /** + * Unregister all our JSON-RPC methods + */ + void Network::UnregisterLegacyMethods() + { + Unregister("getInterfaces"); + Unregister("isInterfaceEnabled"); + Unregister("getPublicIP"); + Unregister("setInterfaceEnabled"); + Unregister("getDefaultInterface"); + Unregister("setDefaultInterface"); + Unregister("setIPSettings"); + Unregister("getIPSettings"); + Unregister("getInternetConnectionState"); + Unregister("ping"); + Unregister("isConnectedToInternet"); + Unregister("setConnectivityTestEndpoints"); + Unregister("startConnectivityMonitoring"); + Unregister("getCaptivePortalURI"); + Unregister("stopConnectivityMonitoring"); + } + +#define CIDR_NETMASK_IP_LEN 32 +const string CIDR_PREFIXES[CIDR_NETMASK_IP_LEN] = { + "128.0.0.0", + "192.0.0.0", + "224.0.0.0", + "240.0.0.0", + "248.0.0.0", + "252.0.0.0", + "254.0.0.0", + "255.0.0.0", + "255.128.0.0", + "255.192.0.0", + "255.224.0.0", + "255.240.0.0", + "255.248.0.0", + "255.252.0.0", + "255.254.0.0", + "255.255.0.0", + "255.255.128.0", + "255.255.192.0", + "255.255.224.0", + "255.255.240.0", + "255.255.248.0", + "255.255.252.0", + "255.255.254.0", + "255.255.255.0", + "255.255.255.128", + "255.255.255.192", + "255.255.255.224", + "255.255.255.240", + "255.255.255.248", + "255.255.255.252", + "255.255.255.254", + "255.255.255.255", + }; + + uint32_t Network::getInterfaces (const JsonObject& parameters, JsonObject& response) + { + uint32_t rc = Core::ERROR_GENERAL; + JsonObject tmpResponse; + JsonArray array; + + LOGINFOMETHOD(); + + if (m_networkmanager) + rc = m_networkmanager->Invoke(5000, _T("GetAvailableInterfaces"), parameters, tmpResponse); + else + rc = Core::ERROR_UNAVAILABLE; + + if ((rc == Core::ERROR_NONE) && (tmpResponse["success"].Boolean())) + { + const JsonArray& tmpArray = tmpResponse["interfaces"].Array(); + for (int i=0; iInvoke(5000, _T("SetStunEndpoint"), parameters, response); + else + rc = Core::ERROR_UNAVAILABLE; + + LOGTRACEMETHODFIN(); + return rc; + } + + uint32_t Network::setInterfaceEnabled (const JsonObject& parameters, JsonObject& response) + { + uint32_t rc = Core::ERROR_GENERAL; + string interface; + JsonObject tmpParameters; + + LOGINFOMETHOD(); + if("WIFI" == parameters["interface"].String()) + interface = "wlan0"; + else if("ETHERNET" == parameters["interface"].String()) + interface = "eth0"; + + tmpParameters["interface"] = interface; + tmpParameters["enabled"] = parameters["enabled"]; + + if (m_networkmanager) + { + rc = m_networkmanager->Invoke(5000, _T("SetInterfaceState"), tmpParameters, response); + } + else + rc = Core::ERROR_UNAVAILABLE; + + LOGTRACEMETHODFIN(); + return rc; + } + + uint32_t Network::getDefaultInterface (const JsonObject& parameters, JsonObject& response) + { + uint32_t rc = Core::ERROR_GENERAL; + JsonObject tmpResponse; + + LOGINFOMETHOD(); + + if (m_networkmanager) + rc = m_networkmanager->Invoke(5000, _T("GetPrimaryInterface"), parameters, tmpResponse); + else + rc = Core::ERROR_UNAVAILABLE; + + if (Core::ERROR_NONE == rc) + { + if ("wlan0" == tmpResponse["interface"].String()) + response["interface"] = "WIFI"; + else if("eth0" == tmpResponse["interface"].String()) + response["interface"] = "ETHERNET"; + response["success"] = tmpResponse["success"]; + } + LOGTRACEMETHODFIN(); + return rc; + } + + uint32_t Network::setDefaultInterface(const JsonObject& parameters, JsonObject& response) + { + uint32_t rc = Core::ERROR_GENERAL; + JsonObject tmpParameters; + string interface; + LOGINFOMETHOD(); + if("WIFI" == parameters["interface"].String()) + tmpParameters["interface"] = "wlan0"; + else if("ETHERNET" == parameters["interface"].String()) + tmpParameters["interface"] = "eth0"; + + if (m_networkmanager) + rc = m_networkmanager->Invoke(5000, _T("SetPrimaryInterface"), tmpParameters, response); + else + rc = Core::ERROR_UNAVAILABLE; + + LOGTRACEMETHODFIN(); + + return rc; + } + + uint32_t Network::setIPSettings(const JsonObject& parameters, JsonObject& response) + { + uint32_t rc = Core::ERROR_GENERAL; + JsonObject tmpResponse; + JsonObject tmpParameters; + LOGINFOMETHOD(); + + if("WIFI" == parameters["interface"].String()) + tmpParameters["interface"] = "wlan0"; + else if("ETHERNET" == parameters["interface"].String()) + tmpParameters["interface"] = "eth0"; + + tmpParameters["ipversion"] = parameters["ipversion"]; + tmpParameters["autoconfig"] = parameters["autoconfig"]; + tmpParameters["ipaddress"] = parameters["ipaddr"]; + auto it = find(begin(CIDR_PREFIXES), end(CIDR_PREFIXES), parameters["netmask"].String()); + if (it == end(CIDR_PREFIXES)) + return rc; + else + tmpParameters["prefix"] = distance(begin(CIDR_PREFIXES), it); + tmpParameters["gateway"] = parameters["gateway"]; + tmpParameters["primarydns"] = parameters["primarydns"]; + tmpParameters["secondarydns"] = parameters["secondarydns"]; + + if (m_networkmanager) + rc = m_networkmanager->Invoke(5000, _T("SetIPSettings"), tmpParameters, tmpResponse); + else + rc = Core::ERROR_UNAVAILABLE; + + if (Core::ERROR_NONE == rc) + { + response["supported"] = true; + response["success"] = tmpResponse["success"]; + } + LOGTRACEMETHODFIN(); + return rc; + } + + uint32_t Network::getIPSettings (const JsonObject& parameters, JsonObject& response) + { + uint32_t rc = Core::ERROR_GENERAL; + JsonObject tmpResponse; + JsonObject tmpParameters; + size_t index; + + LOGINFOMETHOD(); + + if (parameters.HasLabel("ipversion")) + tmpParameters["ipversion"] = parameters["ipversion"]; + if (parameters.HasLabel("interface")) + { + if ("WIFI" == parameters["interface"].String()) + tmpParameters["interface"] = "wlan0"; + else if("ETHERNET" == parameters["interface"].String()) + tmpParameters["interface"] = "eth0"; + } + + if (m_networkmanager) + rc = m_networkmanager->Invoke(5000, _T("GetIPSettings"), tmpParameters, tmpResponse); + else + rc = Core::ERROR_UNAVAILABLE; + + if (Core::ERROR_NONE == rc) + { + string ipversion = tmpResponse["ipversion"].String(); + std::transform(ipversion.begin(), ipversion.end(), ipversion.begin(), ::toupper); + + if (parameters.HasLabel("interface")) + { + response["interface"] = parameters["interface"]; + } + else + { + if ("wlan0" == m_defaultInterface) + response["interface"] = "WIFI"; + else if("eth0" == m_defaultInterface) + response["interface"] = "ETHERNET"; + } + + response["ipversion"] = tmpResponse["ipversion"]; + response["autoconfig"] = tmpResponse["autoconfig"]; + response["ipaddr"] = tmpResponse["ipaddress"]; + if(tmpResponse["ipaddress"].String().empty()) + response["netmask"] = ""; + else if ("IPV4" == ipversion) + { + index = tmpResponse["prefix"].Number(); + if(CIDR_NETMASK_IP_LEN <= index) + return Core::ERROR_GENERAL; + response["netmask"] = CIDR_PREFIXES[index]; + } + else if ("IPV6" == ipversion) + { + response["netmask"] = tmpResponse["prefix"]; + } + response["gateway"] = tmpResponse["gateway"]; + response["dhcpserver"] = tmpResponse["dhcpserver"]; + response["primarydns"] = tmpResponse["primarydns"]; + response["secondarydns"] = tmpResponse["secondarydns"]; + response["success"] = tmpResponse["success"]; + } + LOGTRACEMETHODFIN(); + return rc; + } + uint32_t Network::isConnectedToInternet(const JsonObject& parameters, JsonObject& response) + { + uint32_t rc = Core::ERROR_GENERAL; + JsonObject tmpResponse; + + LOGINFOMETHOD(); + string ipversion = parameters["ipversion"].String(); + + if (m_networkmanager) + rc = m_networkmanager->Invoke(5000, _T("IsConnectedToInternet"), parameters, tmpResponse); + else + rc = Core::ERROR_UNAVAILABLE; + + if (Core::ERROR_NONE == rc) + { + response["connectedToInternet"] = tmpResponse["isConnectedToInternet"]; + if(ipversion == "IPV4" || ipversion == "IPV6") + response["ipversion"] = ipversion.c_str(); + response["success"] = true; + } + LOGTRACEMETHODFIN(); + return rc; + } + uint32_t Network::getInternetConnectionState(const JsonObject& parameters, JsonObject& response) + { + uint32_t rc = Core::ERROR_GENERAL; + uint32_t rc1 = Core::ERROR_GENERAL; + string endPoint; + JsonObject tmpResponse; + JsonObject captivePortalResponse; + JsonObject tmpParameters; + string status; + + LOGINFOMETHOD(); + string ipversion = parameters["ipversion"].String(); + + if (m_networkmanager) + rc = m_networkmanager->Invoke(5000, _T("IsConnectedToInternet"), parameters, tmpResponse); + else + rc = Core::ERROR_UNAVAILABLE; + + if (Core::ERROR_NONE == rc) + { + status = tmpResponse["status"].String(); + NMLOG_TRACE("status = %s\n", status.c_str() ); + NMLOG_TRACE("tmpResponse[status].String() = %s\n", tmpResponse["status"].String().c_str() ); + if(status == "LIMITED_INTERNET") + response["state"] = static_cast(2); + else if(status == "CAPTIVE_PORTAL") + { + response["state"] = static_cast(1); + rc1 = getCaptivePortalURI(tmpParameters, captivePortalResponse); + if (Core::ERROR_NONE == rc1) + response["uri"] = captivePortalResponse["uri"]; + } + else if(status == "FULLY_CONNECTED") + response["state"] = static_cast(3); + else + response["state"] = static_cast(0); + + if(ipversion == "IPV4" || ipversion == "IPV6") + response["ipversion"] = ipversion.c_str(); + response["success"] = true; + } + LOGTRACEMETHODFIN(); + return rc; + } + uint32_t Network::doPing(const JsonObject& parameters, JsonObject& response) + { + uint32_t rc = Core::ERROR_GENERAL; + struct in_addr ipv4address; + struct in6_addr ipv6address; + JsonObject tmpParameters; + JsonObject tmpResponse; + string endpoint{}; + + LOGINFOMETHOD(); + + endpoint = parameters["endpoint"].String(); + + if (inet_pton(AF_INET, endpoint.c_str(), &ipv4address) > 0) + tmpParameters["ipversion"] = "IPv4"; + else if (inet_pton(AF_INET6, endpoint.c_str(), &ipv6address) > 0) + tmpParameters["ipversion"] = "IPv6"; + + tmpParameters["noOfRequest"] = parameters["packets"]; + tmpParameters["endpoint"] = parameters["endpoint"]; + tmpParameters["timeout"] = 5; + tmpParameters["guid"] = parameters["guid"]; + + if (m_networkmanager) + rc = m_networkmanager->Invoke(5000, _T("Ping"), tmpParameters, response); + else + rc = Core::ERROR_UNAVAILABLE; + + if (Core::ERROR_NONE == rc) + { + response["target"] = parameters["endpoint"]; + response["guid"] = parameters["guid"]; + } + LOGTRACEMETHODFIN(); + return rc; + } + + uint32_t Network::doTrace(const JsonObject& parameters, JsonObject& response) + { + LOGINFOMETHOD(); + uint32_t rc = Core::ERROR_GENERAL; + JsonObject tmpParameters; + tmpParameters["endpoint"] = parameters["endpoint"].String(); + tmpParameters["noOfRequest"] = parameters["packets"].Number(); + tmpParameters["guid"] = ""; + + if(m_networkmanager) + rc = m_networkmanager->Invoke(5000, _T("Trace"), tmpParameters, response); + else + rc = Core::ERROR_UNAVAILABLE; + + LOGTRACEMETHODFIN(); + return rc; + } + + uint32_t Network::getPublicIP(const JsonObject& parameters, JsonObject& response) + { + uint32_t rc = Core::ERROR_GENERAL; + string interface; + string ipversion{"IPv4"}; + JsonObject tmpParameters; + JsonObject tmpResponse; + + LOGINFOMETHOD(); + if("WIFI" == parameters["iface"].String()) + interface = "wlan0"; + else if("ETHERNET" == parameters["iface"].String()) + interface = "eth0"; + + if(parameters["ipv6"].Boolean()) + ipversion = "IPv6"; + else + ipversion = "IPv4"; + + tmpParameters["interface"] = interface; + tmpParameters["ipversion"] = ipversion; + + if (m_networkmanager) + rc = m_networkmanager->Invoke(5000, _T("GetPublicIP"), tmpParameters, tmpResponse); + else + rc = Core::ERROR_UNAVAILABLE; + + if (Core::ERROR_NONE == rc) + { + response["public_ip"] = tmpResponse["publicIP"]; + response["success"] = tmpResponse["success"]; + } + LOGTRACEMETHODFIN(); + return rc; + } + + uint32_t Network::isInterfaceEnabled (const JsonObject& parameters, JsonObject& response) + { + uint32_t rc = Core::ERROR_GENERAL; + JsonObject tmpParameters; + + LOGINFOMETHOD(); + string interface = parameters["interface"].String(); + string newInterface = ""; + + if("WIFI" == interface) + newInterface = "wlan0"; + else if("ETHERNET" == interface) + newInterface = "eth0"; + + tmpParameters["interface"] = newInterface; + + if (m_networkmanager) + rc = m_networkmanager->Invoke(5000, _T("GetInterfaceState"), tmpParameters, response); + else + rc = Core::ERROR_UNAVAILABLE; + + LOGTRACEMETHODFIN(); + + return rc; + } + + uint32_t Network::setConnectivityTestEndpoints(const JsonObject& parameters, JsonObject& response) + { + LOGINFOMETHOD(); + uint32_t rc = Core::ERROR_GENERAL; + if (m_networkmanager) + rc = m_networkmanager->Invoke(5000, _T("SetConnectivityTestEndpoints"), parameters, response); + else + rc = Core::ERROR_UNAVAILABLE; + + LOGTRACEMETHODFIN(); + return rc; + } + + uint32_t Network::startConnectivityMonitoring(const JsonObject& parameters, JsonObject& response) + { + LOGINFOMETHOD(); + uint32_t rc = Core::ERROR_GENERAL; + uint32_t interval = parameters["interval"].Number(); + + NMLOG_TRACE("connectivity interval = %d", interval); + + if (m_networkmanager) + rc = m_networkmanager->Invoke(5000, _T("StartConnectivityMonitoring"), parameters, response); + else + rc = Core::ERROR_UNAVAILABLE; + + LOGTRACEMETHODFIN(); + return rc; + } + + uint32_t Network::getCaptivePortalURI(const JsonObject& parameters, JsonObject& response) + { + LOGINFOMETHOD(); + uint32_t rc = Core::ERROR_GENERAL; + string endPoint; + if (m_networkmanager) + rc = m_networkmanager->Invoke(5000, _T("GetCaptivePortalURI"), parameters, response); + else + rc = Core::ERROR_UNAVAILABLE; + + LOGTRACEMETHODFIN(); + return rc; + } + + uint32_t Network::stopConnectivityMonitoring(const JsonObject& parameters, JsonObject& response) + { + LOGINFOMETHOD(); + uint32_t rc = Core::ERROR_GENERAL; + + if (m_networkmanager) + rc = m_networkmanager->Invoke(5000, _T("StopConnectivityMonitoring"), parameters, response); + else + rc = Core::ERROR_UNAVAILABLE; + + LOGTRACEMETHODFIN(); + return rc; + } + + uint32_t Network::getStbIp(const JsonObject& parameters, JsonObject& response) + { + uint32_t rc = Core::ERROR_GENERAL; + LOGTRACEMETHODFIN(); + JsonObject tmpResponse; + + if (m_networkmanager) + rc = m_networkmanager->Invoke(5000, _T("GetIPSettings"), parameters, tmpResponse); + else + rc = Core::ERROR_UNAVAILABLE; + + if (Core::ERROR_NONE == rc) + { + response["ip"] = tmpResponse["ipaddress"]; + response["success"] = true; + } + return rc; + } + + uint32_t Network::getSTBIPFamily(const JsonObject& parameters, JsonObject& response) + { + uint32_t rc = Core::ERROR_GENERAL; + LOGTRACEMETHODFIN(); + JsonObject tmpResponse; + JsonObject tmpParameters; + + tmpParameters["ipversion"] = parameters["family"]; + + if (m_networkmanager) + rc = m_networkmanager->Invoke(5000, _T("GetIPSettings"), tmpParameters, tmpResponse); + else + rc = Core::ERROR_UNAVAILABLE; + + if (Core::ERROR_NONE == rc) + { + response["ip"] = tmpResponse["ipaddress"]; + response["success"] = true; + } + return rc; + } + + /** Private */ + uint32_t Network::subscribeToEvents(void) + { + uint32_t errCode = Core::ERROR_GENERAL; + if (m_networkmanager) + { + errCode = m_networkmanager->Subscribe(1000, _T("onInterfaceStateChange"), &Network::onInterfaceStateChange); + if (errCode != Core::ERROR_NONE) + { + NMLOG_ERROR ("Subscribe to onInterfaceStateChange failed, errCode: %u", errCode); + } + errCode = m_networkmanager->Subscribe(1000, _T("onActiveInterfaceChange"), &Network::onActiveInterfaceChange); + if (errCode != Core::ERROR_NONE) + { + NMLOG_ERROR("Subscribe to onActiveInterfaceChange failed, errCode: %u", errCode); + } + errCode = m_networkmanager->Subscribe(1000, _T("onIPAddressChange"), &Network::onIPAddressChange); + if (errCode != Core::ERROR_NONE) + { + NMLOG_ERROR("Subscribe to onIPAddressChange failed, errCode: %u", errCode); + } + + errCode = m_networkmanager->Subscribe(1000, _T("onInternetStatusChange"), &Network::onInternetStatusChange); + if (errCode != Core::ERROR_NONE) + { + NMLOG_ERROR("Subscribe to onInternetStatusChange failed, errCode: %u", errCode); + } + } + return errCode; + } + + string Network::getInterfaceMapping(const string & interface) + { + if(interface == "wlan0") + return string("WIFI"); + else if(interface == "eth0") + return string("ETHERNET"); + return string(" "); + } + + /** Event Handling and Publishing */ + void Network::ReportonInterfaceStateChange(const JsonObject& parameters) + { + LOGINFOMETHOD(); + JsonObject legacyParams; + string json; + string state = parameters["state"].String(); + + legacyParams["interface"] = getInterfaceMapping(parameters["interface"].String()); + + /* State check */ + if(state == "INTERFACE_ADDED") + legacyParams["enabled"] = true; + else if(state == "INTERFACE_REMOVED") + legacyParams["enabled"] = false; + else if(state == "INTERFACE_LINK_UP") + legacyParams["status"] = "CONNECTED"; + else if(state == "INTERFACE_LINK_DOWN") + legacyParams["status"] = "DISCONNECTED"; + + if((state == "INTERFACE_ADDED") || (state == "INTERFACE_REMOVED")) + { + Notify("onInterfaceStatusChanged", legacyParams); + } + else if((state == "INTERFACE_LINK_UP") || (state == "INTERFACE_LINK_DOWN")) + { + Notify("onConnectionStatusChanged", legacyParams); + } + + return; + } + + void Network::ReportonActiveInterfaceChange(const JsonObject& parameters) + { + LOGINFOMETHOD(); + JsonObject legacyParams; + + legacyParams["oldInterfaceName"] = getInterfaceMapping(parameters["oldInterfaceName"].String()); + legacyParams["newInterfaceName"] = getInterfaceMapping(parameters["newInterfaceName"].String()); + + m_defaultInterface = parameters["newInterfaceName"].String(); + Notify("onDefaultInterfaceChanged", legacyParams); + return; + } + + void Network::ReportonIPAddressChange(const JsonObject& parameters) + { + LOGINFOMETHOD(); + JsonObject legacyParams; + legacyParams["interface"] = getInterfaceMapping(parameters["interface"].String()); + + if (parameters["isIPv6"].Boolean()) + { + legacyParams["ip6Address"] = parameters["ipAddress"]; + legacyParams["ip4Address"] = ""; + } + else + { + legacyParams["ip4Address"] = parameters["ipAddress"]; + legacyParams["ip6Address"] = ""; + } + + legacyParams["status"] = parameters["status"]; + + if (_gNWInstance) + _gNWInstance->Notify("onIPAddressStatusChanged", legacyParams); + + if ("ACQUIRED" == parameters["status"].String()) + m_defaultInterface = parameters["interface"].String(); + + return; + } + + void Network::ReportonInternetStatusChange(const JsonObject& parameters) + { + LOGINFOMETHOD(); + Notify("onInternetStatusChange", parameters); + return; + } + + void Network::onInterfaceStateChange(const JsonObject& parameters) + { + LOGINFOMETHOD(); + if(_gNWInstance) + _gNWInstance->ReportonInterfaceStateChange(parameters); + + return; + } + + void Network::onActiveInterfaceChange(const JsonObject& parameters) + { + LOGINFOMETHOD(); + if(_gNWInstance) + _gNWInstance->ReportonActiveInterfaceChange(parameters); + return; + } + + void Network::onIPAddressChange(const JsonObject& parameters) + { + LOGINFOMETHOD(); + if(_gNWInstance) + _gNWInstance->ReportonIPAddressChange(parameters); + return; + } + + void Network::onInternetStatusChange(const JsonObject& parameters) + { + LOGINFOMETHOD(); + if(_gNWInstance) + _gNWInstance->ReportonInternetStatusChange(parameters); + } + } +} diff --git a/NetworkManager/LegacyPlugin_NetworkAPIs.h b/NetworkManager/LegacyPlugin_NetworkAPIs.h new file mode 100644 index 0000000000..107c066f91 --- /dev/null +++ b/NetworkManager/LegacyPlugin_NetworkAPIs.h @@ -0,0 +1,89 @@ +#pragma once + +#include +#include + +#include "Module.h" +#include "core/Link.h" + +namespace WPEFramework { + namespace Plugin { + + // This is a server for a JSONRPC communication channel. + // For a plugin to be capable to handle JSONRPC, inherit from PluginHost::JSONRPC. + // By inheriting from this class, the plugin realizes the interface PluginHost::IDispatcher. + // This realization of this interface implements, by default, the following methods on this plugin + // - exists + // - register + // - unregister + // Any other methood to be handled by this plugin can be added can be added by using the + // templated methods Register on the PluginHost::JSONRPC class. + // As the registration/unregistration of notifications is realized by the class PluginHost::JSONRPC, + // this class exposes a public method called, Notify(), using this methods, all subscribed clients + // will receive a JSONRPC message as a notification, in case this method is called. + class Network : public PluginHost::IPlugin, public PluginHost::JSONRPC + { + private: + // We do not allow this plugin to be copied !! + Network(const Network&) = delete; + Network& operator=(const Network&) = delete; + + void RegisterLegacyMethods(); + void UnregisterLegacyMethods(); + uint32_t subscribeToEvents(void); + static std::string getInterfaceMapping(const std::string &interface); + void activatePrimaryPlugin(); + + /* Methods */ + uint32_t getInterfaces(const JsonObject& parameters, JsonObject& response); + uint32_t isInterfaceEnabled(const JsonObject& parameters, JsonObject& response); + uint32_t setInterfaceEnabled(const JsonObject& parameters, JsonObject& response); + uint32_t getDefaultInterface(const JsonObject& parameters, JsonObject& response); + uint32_t setDefaultInterface(const JsonObject& parameters, JsonObject& response); + uint32_t doTrace(const JsonObject& parameters, JsonObject& response); + uint32_t doPing(const JsonObject& parameters, JsonObject& response); + uint32_t setIPSettings(const JsonObject& parameters, JsonObject& response); + uint32_t getIPSettings(const JsonObject& parameters, JsonObject& response); + uint32_t isConnectedToInternet(const JsonObject& parameters, JsonObject& response); + uint32_t setConnectivityTestEndpoints(const JsonObject& parameters, JsonObject& response); + uint32_t getInternetConnectionState(const JsonObject& parameters, JsonObject& response); + uint32_t startConnectivityMonitoring(const JsonObject& parameters, JsonObject& response); + uint32_t getCaptivePortalURI(const JsonObject& parameters, JsonObject& response); + uint32_t stopConnectivityMonitoring(const JsonObject& parameters, JsonObject& response); + uint32_t getPublicIP(const JsonObject& parameters, JsonObject& response); + uint32_t setStunEndPoint(const JsonObject& parameters, JsonObject& response); + uint32_t getStbIp(const JsonObject& parameters, JsonObject& response); + uint32_t getSTBIPFamily(const JsonObject& parameters, JsonObject& response); + + /* Events */ + static void onInterfaceStateChange(const JsonObject& parameters); + static void onActiveInterfaceChange(const JsonObject& parameters); + static void onIPAddressChange(const JsonObject& parameters); + static void onInternetStatusChange(const JsonObject& parameters); + + public: + Network(); + ~Network(); + //Build QueryInterface implementation, specifying all possible interfaces to be returned. + BEGIN_INTERFACE_MAP(Network) + INTERFACE_ENTRY(PluginHost::IPlugin) + INTERFACE_ENTRY(PluginHost::IDispatcher) + END_INTERFACE_MAP + + void ReportonInterfaceStateChange(const JsonObject& parameters); + void ReportonActiveInterfaceChange(const JsonObject& parameters); + void ReportonIPAddressChange(const JsonObject& parameters); + void ReportonInternetStatusChange(const JsonObject& parameters); + + //IPlugin methods + virtual const std::string Initialize(PluginHost::IShell* service) override; + virtual void Deinitialize(PluginHost::IShell* service) override; + virtual std::string Information() const override; + + private: + PluginHost::IShell* m_service; + std::shared_ptr> m_networkmanager; + string m_defaultInterface; + }; + } // namespace Plugin +} // namespace WPEFramework diff --git a/NetworkManager/LegacyPlugin_WiFiManagerAPIs.conf.in b/NetworkManager/LegacyPlugin_WiFiManagerAPIs.conf.in new file mode 100644 index 0000000000..090ef0da5a --- /dev/null +++ b/NetworkManager/LegacyPlugin_WiFiManagerAPIs.conf.in @@ -0,0 +1,3 @@ +precondition = ["Platform"] +callsign = "org.rdk.Wifi" +autostart = "true" diff --git a/NetworkManager/LegacyPlugin_WiFiManagerAPIs.config b/NetworkManager/LegacyPlugin_WiFiManagerAPIs.config new file mode 100644 index 0000000000..3428986fdf --- /dev/null +++ b/NetworkManager/LegacyPlugin_WiFiManagerAPIs.config @@ -0,0 +1,3 @@ +set (autostart true) +set (preconditions Platform) +set (callsign "org.rdk.Wifi") diff --git a/NetworkManager/LegacyPlugin_WiFiManagerAPIs.cpp b/NetworkManager/LegacyPlugin_WiFiManagerAPIs.cpp new file mode 100644 index 0000000000..f0f3395fc4 --- /dev/null +++ b/NetworkManager/LegacyPlugin_WiFiManagerAPIs.cpp @@ -0,0 +1,536 @@ +/** +* If not stated otherwise in this file or this component's LICENSE +* file the following copyright and licenses apply: +* +* Copyright 2022 RDK Management +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +**/ +#include "LegacyPlugin_WiFiManagerAPIs.h" +#include "NetworkManagerLogger.h" + + +using namespace std; +using namespace WPEFramework::Plugin; +#define API_VERSION_NUMBER_MAJOR 2 +#define API_VERSION_NUMBER_MINOR 0 +#define API_VERSION_NUMBER_PATCH 0 +#define NETWORK_MANAGER_CALLSIGN "org.rdk.NetworkManager.1" + +#define LOGINFOMETHOD() { string json; parameters.ToString(json); NMLOG_TRACE("Legacy params=%s", json.c_str() ); } +#define LOGTRACEMETHODFIN() { string json; response.ToString(json); NMLOG_TRACE("Legacy response=%s", json.c_str() ); } + +namespace WPEFramework +{ + class Job : public Core::IDispatch { + public: + Job(function work) + : _work(work) + { + } + void Dispatch() override + { + _work(); + } + + private: + function _work; + }; + + static Plugin::Metadata metadata( + // Version (Major, Minor, Patch) + API_VERSION_NUMBER_MAJOR, API_VERSION_NUMBER_MINOR, API_VERSION_NUMBER_PATCH, + // Preconditions + {}, + // Terminations + {}, + // Controls + {} + ); + + WiFiManager* _gWiFiInstance = nullptr; + namespace Plugin + { + SERVICE_REGISTRATION(WiFiManager, API_VERSION_NUMBER_MAJOR, API_VERSION_NUMBER_MINOR, API_VERSION_NUMBER_PATCH); + + WiFiManager::WiFiManager() + : PluginHost::JSONRPC() + , m_service(nullptr) + { + _gWiFiInstance = this; + RegisterLegacyMethods(); + } + + WiFiManager::~WiFiManager() + { + _gWiFiInstance = nullptr; + } + + void WiFiManager::activatePrimaryPlugin() + { + uint32_t result = Core::ERROR_ASYNC_FAILED; + string callsign(NETWORK_MANAGER_CALLSIGN); + Core::Event event(false, true); + Core::IWorkerPool::Instance().Submit(Core::ProxyType(Core::ProxyType::Create([&]() { + auto interface = m_service->QueryInterfaceByCallsign(callsign); + if (interface == nullptr) { + result = Core::ERROR_UNAVAILABLE; + NMLOG_WARNING("no IShell for %s", callsign.c_str()); + } else { + NMLOG_INFO("Activating %s", callsign.c_str()); + result = interface->Activate(PluginHost::IShell::reason::REQUESTED); + interface->Release(); + } + event.SetEvent(); + }))); + event.Lock(); + + return; + } + + const string WiFiManager::Initialize(PluginHost::IShell* service ) + { + m_service = service; + m_service->AddRef(); + + string callsign(NETWORK_MANAGER_CALLSIGN); + + auto interface = m_service->QueryInterfaceByCallsign(callsign); + if (interface != nullptr) + { + PluginHost::IShell::state state = interface->State(); + NMLOG_INFO("Current status of the %s plugin is %d", callsign.c_str(), state); + + if((PluginHost::IShell::state::ACTIVATED == state) || (PluginHost::IShell::state::ACTIVATION == state)) + { + NMLOG_INFO("Dependency Plugin '%s' Ready", callsign.c_str()); + } + else + { + activatePrimaryPlugin(); + } + interface->Release(); + } + + Core::SystemInfo::SetEnvironment(_T("THUNDER_ACCESS"), (_T("127.0.0.1:9998"))); + string query="token="; + m_networkmanager = make_shared >("org.rdk.NetworkManager", ""); + + /* Wait for Proxy stuff to be established */ + sleep(3); + + if (Core::ERROR_NONE != subscribeToEvents()) + return string("Failed to Subscribe"); + else + return string(); + } + + void WiFiManager::Deinitialize(PluginHost::IShell* /* service */) + { + UnregisterLegacyMethods(); + m_service->Release(); + m_service = nullptr; + _gWiFiInstance = nullptr; + } + + string WiFiManager::Information() const + { + return(string()); + } + + /** + * Hook up all our JSON RPC methods + * + * Each method definition comprises of: + * * Input parameters + * * Output parameters + * * Method name + * * Function that implements that method + */ + void WiFiManager::RegisterLegacyMethods() + { + CreateHandler({2}); + Register("cancelWPSPairing", &WiFiManager::cancelWPSPairing, this); + Register("clearSSID", &WiFiManager::clearSSID, this); + Register("connect", &WiFiManager::connect, this); + Register("disconnect", &WiFiManager::disconnect, this); + Register("getConnectedSSID", &WiFiManager::getConnectedSSID, this); + Register("getCurrentState", &WiFiManager::getCurrentState, this); + Register("getPairedSSID", &WiFiManager::getPairedSSID, this); + Register("getPairedSSIDInfo", &WiFiManager::getPairedSSIDInfo, this); + Register("getSupportedSecurityModes", &WiFiManager::getSupportedSecurityModes, this); + Register("initiateWPSPairing", &WiFiManager::initiateWPSPairing, this); + GetHandler(2)->Register("initiateWPSPairing", &WiFiManager::initiateWPSPairing, this); + Register("isPaired", &WiFiManager::isPaired, this); + Register("saveSSID", &WiFiManager::saveSSID, this); + Register("startScan", &WiFiManager::startScan, this); + Register("stopScan", &WiFiManager::stopScan, this); + } + + /** + * Unregister all our JSON-RPC methods + */ + void WiFiManager::UnregisterLegacyMethods() + { + Unregister("cancelWPSPairing"); + Unregister("clearSSID"); + Unregister("connect"); + Unregister("disconnect"); + Unregister("getConnectedSSID"); + Unregister("getCurrentState"); + Unregister("getPairedSSID"); + Unregister("getPairedSSIDInfo"); + Unregister("getSupportedSecurityModes"); + Unregister("initiateWPSPairing"); + Unregister("isPaired"); + Unregister("saveSSID"); + Unregister("startScan"); + Unregister("stopScan"); + } + + uint32_t WiFiManager::cancelWPSPairing (const JsonObject& parameters, JsonObject& response) + { + uint32_t rc = Core::ERROR_GENERAL; + + LOGINFOMETHOD(); + + if (m_networkmanager) + rc = m_networkmanager->Invoke(5000, _T("StopWPS"), parameters, response); + else + rc = Core::ERROR_UNAVAILABLE; + + if (Core::ERROR_NONE == rc) + { + response["result"] = string(); + } + + LOGTRACEMETHODFIN(); + return rc; + } + + uint32_t WiFiManager::clearSSID (const JsonObject& parameters, JsonObject& response) + { + uint32_t rc = Core::ERROR_GENERAL; + JsonObject tmpParameters; + + LOGINFOMETHOD(); + + if (m_networkmanager) + rc = m_networkmanager->Invoke(5000, _T("RemoveKnownSSID"), tmpParameters, response); + else + rc = Core::ERROR_UNAVAILABLE; + + if (Core::ERROR_NONE == rc) + { + response["result"] = 0; + } + + LOGTRACEMETHODFIN(); + return rc; + } + + uint32_t WiFiManager::connect(const JsonObject& parameters, JsonObject& response) + { + LOGINFOMETHOD(); + uint32_t rc = Core::ERROR_GENERAL; + + if (m_networkmanager) + rc = m_networkmanager->Invoke(5000, _T("WiFiConnect"), parameters, response); + else + rc = Core::ERROR_UNAVAILABLE; + + if (Core::ERROR_NONE == rc) + { + response["success"] = true; + } + LOGTRACEMETHODFIN(); + return rc; + } + + uint32_t WiFiManager::getConnectedSSID (const JsonObject& parameters, JsonObject& response) + { + uint32_t rc = Core::ERROR_GENERAL; + JsonObject tmpResponse; + + LOGINFOMETHOD(); + + if (m_networkmanager) + rc = m_networkmanager->Invoke(5000, _T("GetConnectedSSID"), parameters, tmpResponse); + else + rc = Core::ERROR_UNAVAILABLE; + + if (Core::ERROR_NONE == rc) + { + response["ssid"] = tmpResponse["ssid"]; + response["bssid"] = tmpResponse["bssid"]; + response["rate"] = tmpResponse["rate"]; + response["noise"] = tmpResponse["noise"]; + response["security"] = tmpResponse["securityMode"]; + response["signalStrength"] = tmpResponse["signalStrength"]; + response["frequency"] = tmpResponse["frequency"]; + response["success"] = tmpResponse["success"]; + } + LOGTRACEMETHODFIN(); + return rc; + } + + uint32_t WiFiManager::getCurrentState(const JsonObject& parameters, JsonObject& response) + { + uint32_t rc = Core::ERROR_GENERAL; + + if (m_networkmanager) + rc = m_networkmanager->Invoke(5000, _T("GetWifiState"), parameters, response); + else + rc = Core::ERROR_UNAVAILABLE; + + LOGTRACEMETHODFIN(); + return rc; + } + + uint32_t WiFiManager::getPairedSSID(const JsonObject& parameters, JsonObject& response) + { + LOGINFOMETHOD(); + uint32_t rc = Core::ERROR_GENERAL; + + if (m_networkmanager) + rc = m_networkmanager->Invoke(5000, _T("GetKnownSSIDs"), parameters, response); + else + rc = Core::ERROR_UNAVAILABLE; + + LOGTRACEMETHODFIN(); + return rc; + } + + uint32_t WiFiManager::getPairedSSIDInfo(const JsonObject& parameters, JsonObject& response) + { + LOGINFOMETHOD(); + uint32_t rc = Core::ERROR_GENERAL; + + if (m_networkmanager) + rc = m_networkmanager->Invoke(5000, _T("GetConnectedSSID"), parameters, response); + else + rc = Core::ERROR_UNAVAILABLE; + + LOGTRACEMETHODFIN(); + return rc; + } + + uint32_t WiFiManager::getSupportedSecurityModes(const JsonObject& parameters, JsonObject& response) + { + LOGINFOMETHOD(); + uint32_t rc = Core::ERROR_GENERAL; + + if (m_networkmanager) + rc = m_networkmanager->Invoke(5000, _T("GetSupportedSecurityModes"), parameters, response); + else + rc = Core::ERROR_UNAVAILABLE; + + LOGTRACEMETHODFIN(); + return rc; + } + + uint32_t WiFiManager::isPaired (const JsonObject& parameters, JsonObject& response) + { + uint32_t rc = Core::ERROR_GENERAL; + LOGINFOMETHOD(); + JsonObject tmpResponse; + + rc = getPairedSSID(parameters, tmpResponse); + + if (Core::ERROR_NONE == rc) + { + JsonArray array = tmpResponse["ssids"].Array(); + if (0 == array.Length()) + { + response["result"] = 1; + } + else + { + response["result"] = 0; + } + response["success"] = true; + } + LOGTRACEMETHODFIN(); + return rc; + } + + uint32_t WiFiManager::saveSSID (const JsonObject& parameters, JsonObject& response) + { + uint32_t rc = Core::ERROR_GENERAL; + + LOGINFOMETHOD(); + + if (m_networkmanager) + rc = m_networkmanager->Invoke(5000, _T("AddToKnownSSIDs"), parameters, response); + else + rc = Core::ERROR_UNAVAILABLE; + + if (Core::ERROR_NONE == rc) + { + response["result"] = 0; + } + + LOGTRACEMETHODFIN(); + return rc; + } + + uint32_t WiFiManager::disconnect (const JsonObject& parameters, JsonObject& response) + { + uint32_t rc = Core::ERROR_GENERAL; + + LOGINFOMETHOD(); + + if (m_networkmanager) + rc = m_networkmanager->Invoke(5000, _T("WiFiDisconnect"), parameters, response); + else + rc = Core::ERROR_UNAVAILABLE; + + if (Core::ERROR_NONE == rc) + { + response["result"] = 0; + } + + LOGTRACEMETHODFIN(); + return rc; + } + + uint32_t WiFiManager::initiateWPSPairing (const JsonObject& parameters, JsonObject& response) + { + uint32_t rc = Core::ERROR_GENERAL; + JsonObject tmpParameters; + LOGINFOMETHOD(); + if (parameters.HasLabel("method")) + { + string method = parameters["method"].String(); + if (method == "PBC") + { + tmpParameters["method"] = 0; + } + else if (method == "PIN") + { + tmpParameters["method"] = 1; + tmpParameters["wps_pin"] = parameters.HasLabel("wps_pin"); + } + else if (method == "SERIALIZED_PIN") + { + tmpParameters["method"] = 2; + } + } + else + tmpParameters["method"] = 0; + + if (m_networkmanager) + rc = m_networkmanager->Invoke(5000, _T("StartWPS"), tmpParameters, response); + else + rc = Core::ERROR_UNAVAILABLE; + + if (Core::ERROR_NONE == rc) + { + response["result"] = string(); + } + LOGTRACEMETHODFIN(); + return rc; + } + + uint32_t WiFiManager::startScan(const JsonObject& parameters, JsonObject& response) + { + LOGINFOMETHOD(); + uint32_t rc = Core::ERROR_GENERAL; + JsonObject tmpParameters; + + if (m_networkmanager) + rc = m_networkmanager->Invoke(5000, _T("StartWiFiScan"), tmpParameters, response); + else + rc = Core::ERROR_UNAVAILABLE; + + LOGTRACEMETHODFIN(); + return rc; + } + + uint32_t WiFiManager::stopScan(const JsonObject& parameters, JsonObject& response) + { + LOGINFOMETHOD(); + uint32_t rc = Core::ERROR_GENERAL; + + if (m_networkmanager) + rc = m_networkmanager->Invoke(5000, _T("StopWiFiScan"), parameters, response); + else + rc = Core::ERROR_UNAVAILABLE; + + LOGTRACEMETHODFIN(); + return rc; + } + + /** Private */ + uint32_t WiFiManager::subscribeToEvents(void) + { + uint32_t errCode = Core::ERROR_GENERAL; + if (m_networkmanager) + { + errCode = m_networkmanager->Subscribe(1000, _T("onWiFiStateChange"), &WiFiManager::onWiFiStateChange); + if (errCode != Core::ERROR_NONE) + { + NMLOG_ERROR ("Subscribe to onInterfaceStateChange failed, errCode: %u", errCode); + } + errCode = m_networkmanager->Subscribe(1000, _T("onAvailableSSIDs"), &WiFiManager::onAvailableSSIDs); + if (errCode != Core::ERROR_NONE) + { + NMLOG_ERROR("Subscribe to onIPAddressChange failed, errCode: %u", errCode); + } + errCode = m_networkmanager->Subscribe(1000, _T("onWiFiSignalStrengthChange"), &WiFiManager::onWiFiSignalStrengthChange); + if (errCode != Core::ERROR_NONE) + { + NMLOG_ERROR("Subscribe to onActiveInterfaceChange failed, errCode: %u", errCode); + } + } + return errCode; + } + + /** Event Handling and Publishing */ + void WiFiManager::onWiFiStateChange(const JsonObject& parameters) + { + LOGINFOMETHOD(); + JsonObject legacyResult; + legacyResult["state"] = parameters["state"]; + legacyResult["isLNF"] = false; + + if(_gWiFiInstance) + _gWiFiInstance->Notify("onWIFIStateChanged", legacyResult); + + return; + } + + void WiFiManager::onAvailableSSIDs(const JsonObject& parameters) + { + LOGINFOMETHOD(); + + if(_gWiFiInstance) + _gWiFiInstance->Notify("onAvailableSSIDs", parameters); + + return; + } + + void WiFiManager::onWiFiSignalStrengthChange(const JsonObject& parameters) + { + LOGINFOMETHOD(); + JsonObject legacyParams; + legacyParams["signalStrength"] = parameters["signalQuality"]; + legacyParams["strength"] = parameters["signalLevel"]; + + if (_gWiFiInstance) + _gWiFiInstance->Notify("onWifiSignalThresholdChanged", legacyParams); + + return; + } + } +} diff --git a/NetworkManager/LegacyPlugin_WiFiManagerAPIs.h b/NetworkManager/LegacyPlugin_WiFiManagerAPIs.h new file mode 100644 index 0000000000..d6155ea5ec --- /dev/null +++ b/NetworkManager/LegacyPlugin_WiFiManagerAPIs.h @@ -0,0 +1,96 @@ +/** +* If not stated otherwise in this file or this component's LICENSE +* file the following copyright and licenses apply: +* +* Copyright 2020 RDK Management +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +**/ + +#pragma once + +#include "Module.h" + +namespace WPEFramework { + + namespace Plugin { + // This is a server for a JSONRPC communication channel. + // For a plugin to be capable to handle JSONRPC, inherit from PluginHost::JSONRPC. + // By inheriting from this class, the plugin realizes the interface PluginHost::IDispatcher. + // This realization of this interface implements, by default, the following methods on this plugin + // - exists + // - register + // - unregister + // Any other methood to be handled by this plugin can be added can be added by using the + // templated methods Register on the PluginHost::JSONRPC class. + // As the registration/unregistration of notifications is realized by the class PluginHost::JSONRPC, + // this class exposes a public method called, Notify(), using this methods, all subscribed clients + // will receive a JSONRPC message as a notification, in case this method is called. + class WiFiManager : public PluginHost::IPlugin, public PluginHost::JSONRPC { + public: + WiFiManager(); + ~WiFiManager(); + WiFiManager(const WiFiManager&) = delete; + WiFiManager& operator=(const WiFiManager&) = delete; + + //Begin methods + uint32_t getCurrentState(const JsonObject& parameters, JsonObject& response); + uint32_t startScan(const JsonObject& parameters, JsonObject& response); + uint32_t stopScan(const JsonObject& parameters, JsonObject& response); + uint32_t getConnectedSSID(const JsonObject& parameters, JsonObject& response); + uint32_t setEnabled(const JsonObject& parameters, JsonObject& response); + uint32_t connect(const JsonObject& parameters, JsonObject& response); + uint32_t disconnect(const JsonObject& parameters, JsonObject& response); + uint32_t initiateWPSPairing(const JsonObject& parameters, JsonObject& response); + uint32_t cancelWPSPairing(const JsonObject& parameters, JsonObject& response); + uint32_t saveSSID(const JsonObject& parameters, JsonObject& response); + uint32_t clearSSID(const JsonObject& parameters, JsonObject& response); + uint32_t getPairedSSID(const JsonObject& parameters, JsonObject& response); + uint32_t getPairedSSIDInfo(const JsonObject& parameters, JsonObject& response); + uint32_t isPaired(const JsonObject& parameters, JsonObject& response); + uint32_t setSignalThresholdChangeEnabled(const JsonObject& parameters, JsonObject& response); + uint32_t isSignalThresholdChangeEnabled(const JsonObject& parameters, JsonObject& response); + uint32_t getSupportedSecurityModes(const JsonObject& parameters, JsonObject& response); + //End methods + + //Begin events + static void onWiFiStateChange(const JsonObject& parameters); + static void onAvailableSSIDs(const JsonObject& parameters); + static void onWiFiSignalStrengthChange(const JsonObject& parameters); + + //End events + + //Build QueryInterface implementation, specifying all possible interfaces to be returned. + BEGIN_INTERFACE_MAP(WiFiManager) + INTERFACE_ENTRY(PluginHost::IPlugin) + INTERFACE_ENTRY(PluginHost::IDispatcher) + END_INTERFACE_MAP + + //IPlugin methods + virtual const string Initialize(PluginHost::IShell* service) override; + virtual void Deinitialize(PluginHost::IShell* service) override; + virtual string Information() const override; + + private: + void RegisterLegacyMethods(); + void UnregisterLegacyMethods(); + uint32_t subscribeToEvents(void); + static std::string getInterfaceMapping(const std::string &interface); + void activatePrimaryPlugin(); + + private: + PluginHost::IShell* m_service; + std::shared_ptr> m_networkmanager; + }; + } // namespace Plugin +} // namespace WPEFramework diff --git a/NetworkManager/service/Module.cpp b/NetworkManager/Module.cpp similarity index 100% rename from NetworkManager/service/Module.cpp rename to NetworkManager/Module.cpp diff --git a/NetworkManager/service/Module.h b/NetworkManager/Module.h similarity index 100% rename from NetworkManager/service/Module.h rename to NetworkManager/Module.h diff --git a/NetworkManager/service/NetworkManager.conf.in b/NetworkManager/NetworkManager.conf.in similarity index 86% rename from NetworkManager/service/NetworkManager.conf.in rename to NetworkManager/NetworkManager.conf.in index e81798a7b1..22fca875b4 100644 --- a/NetworkManager/service/NetworkManager.conf.in +++ b/NetworkManager/NetworkManager.conf.in @@ -1,9 +1,8 @@ autostart = "true" callsign= "org.rdk.NetworkManager" -test = JSON() -test.add("locator", "lib@PLUGIN_IMPLEMENTATION@.so") -test.add("outofprocess", "true") +process= JSON() +process.add("outofprocess", "true") connectivity = JSON() connectivity.add("endpoint_1", "@PLUGIN_NETWORKMANAGER_CONN_ENDPOINT_1@") @@ -19,7 +18,7 @@ stun.add("port", "@PLUGIN_NETWORKMANAGER_STUN_PORT@") stun.add("interval", "30") configuration = JSON() -configuration.add("root", test) +configuration.add("root", process) configuration.add("connectivity", connectivity) configuration.add("stun", stun) configuration.add("loglevel", "@PLUGIN_NETWORKMANAGER_LOGLEVEL@") diff --git a/NetworkManager/service/NetworkManager.config b/NetworkManager/NetworkManager.config similarity index 93% rename from NetworkManager/service/NetworkManager.config rename to NetworkManager/NetworkManager.config index da2a22c5c2..c11c09bd36 100644 --- a/NetworkManager/service/NetworkManager.config +++ b/NetworkManager/NetworkManager.config @@ -5,7 +5,6 @@ map() key(root) map() kv(outofprocess true) - kv(locator lib${PLUGIN_IMPLEMENTATION}.so) end() key(connectivity) map() diff --git a/NetworkManager/service/NetworkManager.cpp b/NetworkManager/NetworkManager.cpp similarity index 95% rename from NetworkManager/service/NetworkManager.cpp rename to NetworkManager/NetworkManager.cpp index cb732430d7..2327815212 100644 --- a/NetworkManager/service/NetworkManager.cpp +++ b/NetworkManager/NetworkManager.cpp @@ -43,6 +43,7 @@ namespace WPEFramework _notification(this) { // Don't do any work in the constructor - all set up should be done in Initialize + m_defaultInterface = "wlan0"; } NetworkManager::~NetworkManager() @@ -90,14 +91,10 @@ namespace WPEFramework _NetworkManager->Configure(_service->ConfigLine(), _loglevel); // configure loglevel in libWPEFrameworkNetworkManager.so NetworkManagerLogger::SetLevel(static_cast (_loglevel)); - //Exchange::JNetworkManager::Register(*this, _NetworkManager); _NetworkManager->Register(&_notification); // Register all custom JSON-RPC methods RegisterAllMethods(); -#ifdef ENABLE_LEGACY_NSM_SUPPORT - RegisterLegacyMethods(); -#endif } else { @@ -133,12 +130,8 @@ namespace WPEFramework _service->Unregister(&_notification); _NetworkManager->Unregister(&_notification); - //Exchange::JNetworkManager::Unregister(*this); // Unregister all our JSON-RPC methods UnregisterAllMethods(); -#ifdef ENABLE_LEGACY_NSM_SUPPORT - UnregisterLegacyMethods(); -#endif _NetworkManager->Release(); } diff --git a/NetworkManager/service/NetworkManager.h b/NetworkManager/NetworkManager.h similarity index 67% rename from NetworkManager/service/NetworkManager.h rename to NetworkManager/NetworkManager.h index 95472b72f0..a32ed86436 100644 --- a/NetworkManager/service/NetworkManager.h +++ b/NetworkManager/NetworkManager.h @@ -117,40 +117,10 @@ namespace WPEFramework } public: - /* Only for legacy, we are posting 2 events(onInterfaceStatusChanged and onConnectionStatusChanged) - in onInterfaceStateChange() function */ void onInterfaceStateChange(const Exchange::INetworkManager::InterfaceState event, const string interface) override { NMLOG_TRACE("%s", __FUNCTION__); JsonObject params; -#ifdef ENABLE_LEGACY_NSM_SUPPORT - JsonObject legacyParams; - JsonObject onConnParams; - std::string json; - if(interface == "wlan0") - legacyParams["interface"] = "WIFI"; - else if(interface == "eth0") - legacyParams["interface"] = "ETHERNET"; - if(event == Exchange::INetworkManager::INTERFACE_ADDED) - legacyParams["enabled"] = true; - else if(event == Exchange::INetworkManager::INTERFACE_REMOVED) - legacyParams["enabled"] = false; - /* Posting the "onInterfaceStatusChanged" event only when the interface state - is either INTERFACE_REMOVED or INTERFACE_ADDED */ - if(event == Exchange::INetworkManager::INTERFACE_REMOVED || event == Exchange::INetworkManager::INTERFACE_ADDED) - _parent.Notify("onInterfaceStatusChanged", legacyParams); - if(event == Exchange::INetworkManager::INTERFACE_LINK_UP) - onConnParams["status"] = "CONNECTED"; - else if(event == Exchange::INetworkManager::INTERFACE_LINK_DOWN) - onConnParams["status"] = "DISCONNECTED"; - onConnParams["interface"] = legacyParams["interface"]; - onConnParams.ToString(json); - NMLOG_TRACE("onConnectionStatusChanged onConnParams=%s", json.c_str() ); - /* Posting the "onConnectionStatusChanged" event only when the interface state - is either INTERFACE_LINK_UP or INTERFACE_LINK_DOWN */ - if(event == Exchange::INetworkManager::INTERFACE_LINK_UP || event == Exchange::INetworkManager::INTERFACE_LINK_DOWN) - _parent.Notify("onConnectionStatusChanged", onConnParams); -#endif params["interface"] = interface; params["state"] = InterfaceStateToString(event); _parent.Notify("onInterfaceStateChange", params); @@ -160,25 +130,6 @@ namespace WPEFramework { NMLOG_TRACE("%s", __FUNCTION__); JsonObject params; -#ifdef ENABLE_LEGACY_NSM_SUPPORT - JsonObject legacyParams; - if(isIPv6) - { - legacyParams["ip6Address"] = ipAddress; - legacyParams["ip4Address"] = ""; - } - else - { - legacyParams["ip4Address"] = ipAddress; - legacyParams["ip6Address"] = ""; - } - if(interface == "wlan0") - legacyParams["interface"] = "WIFI"; - else if(interface == "eth0") - legacyParams["interface"] = "ETHERNET"; - legacyParams["status"] = string (isAcquired ? "ACQUIRED" : "LOST"); - _parent.Notify("onIPAddressStatusChanged", legacyParams); -#endif params["status"] = string (isAcquired ? "ACQUIRED" : "LOST"); params["interface"] = interface; params["ipAddress"] = ipAddress; @@ -190,26 +141,6 @@ namespace WPEFramework { NMLOG_TRACE("%s", __FUNCTION__); JsonObject params; -#ifdef ENABLE_LEGACY_NSM_SUPPORT - JsonObject legacyParams; - string oldInterface; - string newInterface; - if(prevActiveInterface == "wlan0") - oldInterface = "WIFI"; - else if(prevActiveInterface == "eth0") - oldInterface = "ETHERNET"; - else - oldInterface = prevActiveInterface; - if(currentActiveinterface == "wlan0") - newInterface = "WIFI"; - else if(currentActiveinterface == "eth0") - newInterface = "ETHERNET"; - else - newInterface = currentActiveinterface; - legacyParams["oldInterfaceName"] = oldInterface; - legacyParams["newInterfaceName"] = newInterface; - _parent.Notify("onDefaultInterfaceChanged", legacyParams); -#endif params["oldInterfaceName"] = prevActiveInterface; params["newInterfaceName"] = currentActiveinterface; _parent.Notify("onActiveInterfaceChange", params); @@ -251,12 +182,6 @@ namespace WPEFramework { NMLOG_TRACE("%s", __FUNCTION__); JsonObject result; -#ifdef ENABLE_LEGACY_NSM_SUPPORT - JsonObject legacyResult; - legacyResult["state"] = static_cast (state); - legacyResult["isLNF"] = false; - _parent.Notify("onWIFIStateChanged", legacyResult); -#endif result["state"] = static_cast (state); _parent.Notify("onWiFiStateChange", result); } @@ -265,12 +190,6 @@ namespace WPEFramework { NMLOG_TRACE("%s", __FUNCTION__); JsonObject result; -#ifdef ENABLE_LEGACY_NSM_SUPPORT - JsonObject legacyResult; - legacyResult["signalStrength"] = WiFiSignalQualityToString(signalQuality); - legacyResult["strength"] = signalLevel; - _parent.Notify("onWifiSignalThresholdChanged", legacyResult); -#endif result["ssid"] = ssid; result["signalQuality"] = WiFiSignalQualityToString(signalQuality); result["signalLevel"] = signalLevel; @@ -354,18 +273,14 @@ namespace WPEFramework // JSON-RPC setup void RegisterAllMethods(); void UnregisterAllMethods(); -#ifdef ENABLE_LEGACY_NSM_SUPPORT - void RegisterLegacyMethods(); - void UnregisterLegacyMethods(); -#endif // JSON-RPC methods (take JSON in, spit JSON back out) uint32_t SetLogLevel (const JsonObject& parameters, JsonObject& response); uint32_t GetAvailableInterfaces (const JsonObject& parameters, JsonObject& response); uint32_t GetPrimaryInterface (const JsonObject& parameters, JsonObject& response); uint32_t SetPrimaryInterface (const JsonObject& parameters, JsonObject& response); - uint32_t EnableInterface (const JsonObject& parameters, JsonObject& response); - uint32_t DisableInterface (const JsonObject& parameters, JsonObject& response); + uint32_t GetInterfaceState(const JsonObject& parameters, JsonObject& response); + uint32_t SetInterfaceState(const JsonObject& parameters, JsonObject& response); uint32_t GetIPSettings(const JsonObject& parameters, JsonObject& response); uint32_t SetIPSettings(const JsonObject& parameters, JsonObject& response); uint32_t GetStunEndpoint(const JsonObject& parameters, JsonObject& response); @@ -392,37 +307,7 @@ namespace WPEFramework uint32_t GetWifiState(const JsonObject& parameters, JsonObject& response); uint32_t GetWiFiSignalStrength(const JsonObject& parameters, JsonObject& response); uint32_t GetSupportedSecurityModes(const JsonObject& parameters, JsonObject& response); -#ifdef ENABLE_LEGACY_NSM_SUPPORT - uint32_t getInterfaces (const JsonObject& parameters, JsonObject& response); - uint32_t isInterfaceEnabled (const JsonObject& parameters, JsonObject& response); - uint32_t setInterfaceEnabled (const JsonObject& parameters, JsonObject& response); - uint32_t getPublicIP (const JsonObject& parameters, JsonObject& response); - uint32_t getDefaultInterface(const JsonObject& parameters, JsonObject& response); - uint32_t setDefaultInterface(const JsonObject& parameters, JsonObject& response); - uint32_t setIPSettings(const JsonObject& parameters, JsonObject& response); - uint32_t getIPSettings(const JsonObject& parameters, JsonObject& response); - uint32_t getInternetConnectionState(const JsonObject& parameters, JsonObject& response); - uint32_t ping(const JsonObject& parameters, JsonObject& response); - uint32_t isConnectedToInternet(const JsonObject& parameters, JsonObject& response); - uint32_t setConnectivityTestEndpoints(const JsonObject& parameters, JsonObject& response); - uint32_t startConnectivityMonitoring(const JsonObject& parameters, JsonObject& response); - uint32_t getCaptivePortalURI(const JsonObject& parameters, JsonObject& response); - uint32_t stopConnectivityMonitoring(const JsonObject& parameters, JsonObject& response); - uint32_t getPairedSSID(const JsonObject& parameters, JsonObject& response); - uint32_t getPairedSSIDInfo(const JsonObject& parameters, JsonObject& response); - uint32_t initiateWPSPairing(const JsonObject& parameters, JsonObject& response); - uint32_t isPaired(const JsonObject& parameters, JsonObject& response); - uint32_t saveSSID(const JsonObject& parameters, JsonObject& response); - uint32_t cancelWPSPairing(const JsonObject& parameters, JsonObject& response); - uint32_t clearSSID(const JsonObject& parameters, JsonObject& response); - uint32_t connect(const JsonObject& parameters, JsonObject& response); - uint32_t disconnect(const JsonObject& parameters, JsonObject& response); - uint32_t getConnectedSSID(const JsonObject& parameters, JsonObject& response); - uint32_t getSupportedSecurityModes(const JsonObject& parameters, JsonObject& response); - uint32_t startScan(const JsonObject& parameters, JsonObject& response); - uint32_t stopScan(const JsonObject& parameters, JsonObject& response); - uint32_t getCurrentState(const JsonObject& parameters, JsonObject& response); -#endif + private: uint32_t _connectionId; PluginHost::IShell *_service; diff --git a/NetworkManager/service/NetworkManager.json b/NetworkManager/NetworkManager.json similarity index 100% rename from NetworkManager/service/NetworkManager.json rename to NetworkManager/NetworkManager.json diff --git a/NetworkManager/service/NetworkConnectivity.cpp b/NetworkManager/NetworkManagerConnectivity.cpp similarity index 89% rename from NetworkManager/service/NetworkConnectivity.cpp rename to NetworkManager/NetworkManagerConnectivity.cpp index c876e97b4d..2c925b7788 100644 --- a/NetworkManager/service/NetworkConnectivity.cpp +++ b/NetworkManager/NetworkManagerConnectivity.cpp @@ -13,7 +13,7 @@ #include #include #include "Module.h" -#include "NetworkConnectivity.h" +#include "NetworkManagerConnectivity.h" #include "NetworkManagerImplementation.h" namespace WPEFramework { @@ -65,74 +65,6 @@ namespace WPEFramework { return readStrings; } - void Connectivity::loadConnectivityConfig(const std::string& configFilePath) - { - std::ifstream configFile(configFilePath); - if (!configFile.is_open()) - { - NMLOG_ERROR("Unable to open the configuration file: %s", configFilePath.c_str()); - return; - } - - bool ConnectivityConfigFound = false; - - // load connectivity endpoint configuration - std::string line; - while (std::getline(configFile, line)) - { - if (line == "[Connectivity_Config]") - { - ConnectivityConfigFound = true; - continue; - } - - if (ConnectivityConfigFound) - { - size_t equalsPos = line.find('='); - if (equalsPos != std::string::npos) - { - std::string key = line.substr(0, equalsPos); - std::string value = line.substr(equalsPos + 1); - configMap[key] = value; - } - } - } - - configFile.close(); - - /* Parse the connectivity monitor interval and enable values */ - configMonitorConnectivityEnabled = ((configMap["CONNECTIVITY_MONITOR_ENABLE"] == "1")? true:false); - std::string monitorIntervalStr = configMap["CONNECTIVITY_MONITOR_INTERVAL"]; - if (!monitorIntervalStr.empty()) - { - configMonitorInterval = std::stoi(monitorIntervalStr); - } - - m_defaultEndpoints.clear(); - for (int i = 1; i <= 5; ++i) - { - std::string endpointName = "CONNECTIVITY_ENDPOINT_" + std::to_string(i); - auto endpoint = configMap.find(endpointName); - if (endpoint != configMap.end() && endpoint->second.length() > 3) - { - m_defaultEndpoints.push_back(endpoint->second); - } - } - - if(m_defaultEndpoints.empty()) - { - NMLOG_ERROR("Default endpoints are empty !!"); - } - else - { - std::string endpoints_str; - for (const auto& endpoint : m_defaultEndpoints) - endpoints_str.append(endpoint).append(" "); - NMLOG_INFO("default endpoints count %d and endpoints:- %s", static_cast(m_defaultEndpoints.size()), endpoints_str.c_str()); - NMLOG_INFO("default monitor connectivity interval: %d and monitor connectivity auto start : %s", configMonitorInterval, configMonitorConnectivityEnabled?"true":"false"); - } - } - bool ConnectivityMonitor::isConnectivityMonitorEndpointSet() { const std::lock_guard lock(endpointMutex); diff --git a/NetworkManager/service/NetworkConnectivity.h b/NetworkManager/NetworkManagerConnectivity.h similarity index 97% rename from NetworkManager/service/NetworkConnectivity.h rename to NetworkManager/NetworkManagerConnectivity.h index 573c1ebfd9..e99c0586d5 100644 --- a/NetworkManager/service/NetworkConnectivity.h +++ b/NetworkManager/NetworkManagerConnectivity.h @@ -73,7 +73,6 @@ namespace WPEFramework { public: Connectivity(const std::string& configFilePath = "/etc/netsrvmgr.conf") { - loadConnectivityConfig(configFilePath); if(m_defaultEndpoints.empty()) { NMLOG_ERROR("NETSRVMGR CONFIGURATION ERROR: CONNECTIVITY ENDPOINT EMPTY"); @@ -89,7 +88,6 @@ namespace WPEFramework { void setCaptivePortal(const char* captivePortal) {const std::lock_guard lock(capitiveMutex); g_captivePortal = captivePortal; } private: - void loadConnectivityConfig(const std::string& configFilePath); nsm_internetState checkInternetStateFromResponseCode(const std::vector& responses); std::vector m_defaultEndpoints; diff --git a/NetworkManager/service/NetworkManagerGnomeProxy.cpp b/NetworkManager/NetworkManagerGnomeProxy.cpp old mode 100755 new mode 100644 similarity index 98% rename from NetworkManager/service/NetworkManagerGnomeProxy.cpp rename to NetworkManager/NetworkManagerGnomeProxy.cpp index 883f12dd3f..b33204d6aa --- a/NetworkManager/service/NetworkManagerGnomeProxy.cpp +++ b/NetworkManager/NetworkManagerGnomeProxy.cpp @@ -173,7 +173,7 @@ namespace WPEFramework return rc; } - uint32_t NetworkManagerImplementation::EnableInterface (const string& interface/* @in */) + uint32_t NetworkManagerImplementation::SetInterfaceState(const string& interface/* @in */, const bool& enabled /* @in */) { uint32_t rc = Core::ERROR_NONE; const GPtrArray *devices = nm_client_get_devices(client); @@ -187,10 +187,9 @@ namespace WPEFramework // Check if the device name matches if (g_strcmp0(name, interface.c_str()) == 0) { - nm_device_set_managed(device, true); + nm_device_set_managed(device, enabled); - NMLOG_TRACE("Interface %s status set to enabled\n", - interface.c_str()); + NMLOG_TRACE("Interface %s status set to %s\n", interface.c_str(), enabled ? "Enabled" : "Disabled"); } } @@ -200,9 +199,10 @@ namespace WPEFramework return rc; } - uint32_t NetworkManagerImplementation::DisableInterface (const string& interface/* @in */) + uint32_t NetworkManagerImplementation::GetInterfaceState(const string& interface/* @in */, bool& isEnabled /* @out */) { uint32_t rc = Core::ERROR_NONE; +#if 0 //FIXME const GPtrArray *devices = nm_client_get_devices(client); NMDevice *device = NULL; @@ -224,6 +224,7 @@ namespace WPEFramework // Cleanup if(device) g_clear_object(&device); +#endif return rc; } diff --git a/NetworkManager/service/NetworkManagerGnomeWIFI.cpp b/NetworkManager/NetworkManagerGnomeWIFI.cpp similarity index 100% rename from NetworkManager/service/NetworkManagerGnomeWIFI.cpp rename to NetworkManager/NetworkManagerGnomeWIFI.cpp diff --git a/NetworkManager/service/NetworkManagerGnomeWIFI.h b/NetworkManager/NetworkManagerGnomeWIFI.h similarity index 100% rename from NetworkManager/service/NetworkManagerGnomeWIFI.h rename to NetworkManager/NetworkManagerGnomeWIFI.h diff --git a/NetworkManager/service/NetworkManagerImplementation.cpp b/NetworkManager/NetworkManagerImplementation.cpp similarity index 99% rename from NetworkManager/service/NetworkManagerImplementation.cpp rename to NetworkManager/NetworkManagerImplementation.cpp index b23f1b6c89..56a7ce1b0f 100644 --- a/NetworkManager/service/NetworkManagerImplementation.cpp +++ b/NetworkManager/NetworkManagerImplementation.cpp @@ -18,8 +18,8 @@ **/ #include "NetworkManagerImplementation.h" -#include "NetworkConnectivity.h" -#include "WifiSignalStrengthMonitor.h" +#include "NetworkManagerConnectivity.h" +#include "WiFiSignalStrengthMonitor.h" using namespace WPEFramework; using namespace WPEFramework::Plugin; diff --git a/NetworkManager/service/NetworkManagerImplementation.h b/NetworkManager/NetworkManagerImplementation.h similarity index 95% rename from NetworkManager/service/NetworkManagerImplementation.h rename to NetworkManager/NetworkManagerImplementation.h index 4cc7906a58..76cbd00b5a 100644 --- a/NetworkManager/service/NetworkManagerImplementation.h +++ b/NetworkManager/NetworkManagerImplementation.h @@ -31,9 +31,9 @@ using namespace std; //#include #include "INetworkManager.h" #include "NetworkManagerLogger.h" -#include "WifiSignalStrengthMonitor.h" -#include "NetworkConnectivity.h" -#include "StunClient.h" +#include "WiFiSignalStrengthMonitor.h" +#include "NetworkManagerConnectivity.h" +#include "NetworkManagerStunClient.h" #define LOG_ENTRY_FUNCTION() { NMLOG_TRACE("Entering=%s", __FUNCTION__ ); } @@ -151,8 +151,11 @@ namespace WPEFramework /* @brief Set the active Interface used for external world communication */ uint32_t SetPrimaryInterface (const string& interface/* @in */) override; - uint32_t EnableInterface (const string& interface/* @in */) override; - uint32_t DisableInterface (const string& interface/* @in */) override; + /* @brief Enable/Disable the given interface */ + uint32_t SetInterfaceState(const string& interface/* @in */, const bool& isEnabled/* @in */) override; + /* @brief Get the state of given interface */ + uint32_t GetInterfaceState(const string& interface/* @in */, bool& isEnabled/* @out */) override; + /* @brief Get IP Address Of the Interface */ uint32_t GetIPSettings(const string& interface /* @in */, const string &ipversion /* @in */, IPAddressInfo& result /* @out */) override; /* @brief Set IP Address Of the Interface */ @@ -235,7 +238,7 @@ namespace WPEFramework uint16_t m_stunBindTimeout; uint16_t m_stunCacheTimeout; public: - WifiSignalStrengthMonitor wifiSignalStrengthMonitor; + WiFiSignalStrengthMonitor m_wifiSignalMonitor; mutable ConnectivityMonitor connectivityMonitor; }; } diff --git a/NetworkManager/service/NetworkManagerJsonRpc.cpp b/NetworkManager/NetworkManagerJsonRpc.cpp similarity index 95% rename from NetworkManager/service/NetworkManagerJsonRpc.cpp rename to NetworkManager/NetworkManagerJsonRpc.cpp index 1c960cd09c..4d39ca4b97 100644 --- a/NetworkManager/service/NetworkManagerJsonRpc.cpp +++ b/NetworkManager/NetworkManagerJsonRpc.cpp @@ -43,8 +43,8 @@ namespace WPEFramework Register("GetAvailableInterfaces", &NetworkManager::GetAvailableInterfaces, this); Register("GetPrimaryInterface", &NetworkManager::GetPrimaryInterface, this); Register("SetPrimaryInterface", &NetworkManager::SetPrimaryInterface, this); - Register("EnableInterface", &NetworkManager::EnableInterface, this); - Register("DisableInterface", &NetworkManager::DisableInterface, this); + Register("SetInterfaceState", &NetworkManager::SetInterfaceState, this); + Register("GetInterfaceState", &NetworkManager::GetInterfaceState, this); Register("GetIPSettings", &NetworkManager::GetIPSettings, this); Register("SetIPSettings", &NetworkManager::SetIPSettings, this); Register("GetStunEndpoint", &NetworkManager::GetStunEndpoint, this); @@ -82,8 +82,8 @@ namespace WPEFramework Unregister("GetAvailableInterfaces"); Unregister("GetPrimaryInterface"); Unregister("SetPrimaryInterface"); - Unregister("EnableInterface"); - Unregister("DisableInterface"); + Unregister("SetInterfaceState"); + Unregister("GetInterfaceState"); Unregister("GetIPSettings"); Unregister("SetIPSettings"); Unregister("GetStunEndpoint"); @@ -212,13 +212,14 @@ namespace WPEFramework return rc; } - uint32_t NetworkManager::EnableInterface (const JsonObject& parameters, JsonObject& response) + uint32_t NetworkManager::SetInterfaceState(const JsonObject& parameters, JsonObject& response) { LOGINFOMETHOD(); uint32_t rc = Core::ERROR_GENERAL; string interface = parameters["interface"].String(); + bool enabled = parameters["enable"].Boolean(); if (_NetworkManager) - rc = _NetworkManager->EnableInterface(interface); + rc = _NetworkManager->SetInterfaceState(interface, enabled); else rc = Core::ERROR_UNAVAILABLE; @@ -230,18 +231,21 @@ namespace WPEFramework return rc; } - uint32_t NetworkManager::DisableInterface (const JsonObject& parameters, JsonObject& response) + uint32_t NetworkManager::GetInterfaceState(const JsonObject& parameters, JsonObject& response) { LOGINFOMETHOD(); uint32_t rc = Core::ERROR_GENERAL; + bool isEnabled = false; string interface = parameters["interface"].String(); + if (_NetworkManager) - rc = _NetworkManager->DisableInterface(interface); + rc = _NetworkManager->GetInterfaceState(interface, isEnabled); else rc = Core::ERROR_UNAVAILABLE; if (Core::ERROR_NONE == rc) { + response["enabled"] = isEnabled; response["success"] = true; } LOGTRACEMETHODFIN(); @@ -553,10 +557,18 @@ namespace WPEFramework if (parameters.HasLabel("ipversion")) ipversion = parameters["ipversion"].String(); - if (_NetworkManager) - rc = _NetworkManager->GetPublicIP(ipversion, ipAddress); + if ((!m_publicIPAddress.empty()) && (m_publicIPAddressType == ipversion)) + { + rc = Core::ERROR_NONE; + ipAddress = m_publicIPAddress; + } else - rc = Core::ERROR_UNAVAILABLE; + { + if (_NetworkManager) + rc = _NetworkManager->GetPublicIP(ipversion, ipAddress); + else + rc = Core::ERROR_UNAVAILABLE; + } if (Core::ERROR_NONE == rc) { @@ -580,7 +592,23 @@ namespace WPEFramework JsonObject input, output; GetPublicIP(input, output); } - //TODO:: Report ISUBSYSTEM::Internet Ready. Get ISubsystem::Internet and if it is NULL, set it.. + + if (!m_publicIPAddress.empty()) + { + PluginHost::ISubSystem* subSystem = _service->SubSystems(); + + if (subSystem != nullptr) + { + const PluginHost::ISubSystem::IInternet* internet(subSystem->Get()); + if (nullptr == internet) + { + subSystem->Set(PluginHost::ISubSystem::INTERNET, this); + NMLOG_INFO("Set INTERNET ISubSystem"); + } + + subSystem->Release(); + } + } } uint32_t NetworkManager::Ping(const JsonObject& parameters, JsonObject& response) diff --git a/NetworkManager/service/NetworkManagerLogger.cpp b/NetworkManager/NetworkManagerLogger.cpp similarity index 93% rename from NetworkManager/service/NetworkManagerLogger.cpp rename to NetworkManager/NetworkManagerLogger.cpp index 2615eaf1f1..3432b75705 100644 --- a/NetworkManager/service/NetworkManagerLogger.cpp +++ b/NetworkManager/NetworkManagerLogger.cpp @@ -83,7 +83,7 @@ namespace NetworkManagerLogger { gettimeofday(&tv, NULL); lt = localtime(&tv.tv_sec); - printf("%.2d:%.2d:%.2d.%.6lld %-10s %s %s:%d : %s\n", lt->tm_hour, lt->tm_min, lt->tm_sec, (long long int)tv.tv_usec, levelMap[level], basename(file), func, line, formattedLog); + printf("%.2d:%.2d:%.2d.%.6lld %-10s %s:%d : %s\n", lt->tm_hour, lt->tm_min, lt->tm_sec, (long long int)tv.tv_usec, levelMap[level], func, line, formattedLog); fflush(stdout); #endif } diff --git a/NetworkManager/service/NetworkManagerLogger.h b/NetworkManager/NetworkManagerLogger.h similarity index 100% rename from NetworkManager/service/NetworkManagerLogger.h rename to NetworkManager/NetworkManagerLogger.h diff --git a/NetworkManager/service/NetworkManagerPlugin.json b/NetworkManager/NetworkManagerPlugin.json similarity index 100% rename from NetworkManager/service/NetworkManagerPlugin.json rename to NetworkManager/NetworkManagerPlugin.json diff --git a/NetworkManager/service/NetworkManagerRDKProxy.cpp b/NetworkManager/NetworkManagerRDKProxy.cpp similarity index 99% rename from NetworkManager/service/NetworkManagerRDKProxy.cpp rename to NetworkManager/NetworkManagerRDKProxy.cpp index 6f8a071d05..97bf449d3c 100644 --- a/NetworkManager/service/NetworkManagerRDKProxy.cpp +++ b/NetworkManager/NetworkManagerRDKProxy.cpp @@ -1,5 +1,5 @@ #include "NetworkManagerImplementation.h" -#include "WifiSignalStrengthMonitor.h" +#include "WiFiSignalStrengthMonitor.h" #include "libIBus.h" using namespace WPEFramework; @@ -37,7 +37,6 @@ namespace WPEJ = WPEFramework::Core::JSON; #define MAX_SSIDLIST_BUF (48*1024) #define MAX_FILE_PATH_LEN 4096 - typedef enum _NetworkManager_EventId_t { IARM_BUS_NETWORK_MANAGER_EVENT_SET_INTERFACE_ENABLED=50, IARM_BUS_NETWORK_MANAGER_EVENT_SET_INTERFACE_CONTROL_PERSISTENCE, @@ -487,7 +486,7 @@ namespace WPEFramework state = to_wifi_state(e->data.wifiStateChange.state); if(e->data.wifiStateChange.state == WIFI_CONNECTED) - ::_instance->wifiSignalStrengthMonitor.startWifiSignalStrengthMonitor(DEFAULT_WIFI_SIGNAL_TEST_INTERVAL_SEC); + ::_instance->m_wifiSignalMonitor.startWiFiSignalStrengthMonitor(DEFAULT_WIFI_SIGNAL_TEST_INTERVAL_SEC); ::_instance->ReportWiFiStateChangedEvent(state); break; } @@ -640,7 +639,7 @@ namespace WPEFramework return rc; } - uint32_t NetworkManagerImplementation::EnableInterface (const string& interface/* @in */) + uint32_t NetworkManagerImplementation::SetInterfaceState(const string& interface/* @in */, const bool& enable /* @in */) { LOG_ENTRY_FUNCTION(); uint32_t rc = Core::ERROR_RPC_CALL_FAILED; @@ -672,7 +671,7 @@ namespace WPEFramework return rc; } - uint32_t NetworkManagerImplementation::DisableInterface (const string& interface/* @in */) + uint32_t NetworkManagerImplementation::GetInterfaceState(const string& interface/* @in */, bool& isEnabled /* @out */) { LOG_ENTRY_FUNCTION(); uint32_t rc = Core::ERROR_RPC_CALL_FAILED; diff --git a/NetworkManager/service/StunClient.cpp b/NetworkManager/NetworkManagerStunClient.cpp similarity index 99% rename from NetworkManager/service/StunClient.cpp rename to NetworkManager/NetworkManagerStunClient.cpp index 7bbf01f98a..999f14e88c 100644 --- a/NetworkManager/service/StunClient.cpp +++ b/NetworkManager/NetworkManagerStunClient.cpp @@ -1,4 +1,4 @@ -#include "StunClient.h" +#include "NetworkManagerStunClient.h" #include #include #include diff --git a/NetworkManager/service/StunClient.h b/NetworkManager/NetworkManagerStunClient.h similarity index 100% rename from NetworkManager/service/StunClient.h rename to NetworkManager/NetworkManagerStunClient.h diff --git a/NetworkManager/service/WifiSignalStrengthMonitor.cpp b/NetworkManager/WiFiSignalStrengthMonitor.cpp similarity index 90% rename from NetworkManager/service/WifiSignalStrengthMonitor.cpp rename to NetworkManager/WiFiSignalStrengthMonitor.cpp index f448e00e71..501083a089 100644 --- a/NetworkManager/service/WifiSignalStrengthMonitor.cpp +++ b/NetworkManager/WiFiSignalStrengthMonitor.cpp @@ -4,7 +4,7 @@ #include #include "NetworkManagerLogger.h" #include "NetworkManagerImplementation.h" -#include "WifiSignalStrengthMonitor.h" +#include "WiFiSignalStrengthMonitor.h" #define BUFFER_SIZE 512 #define rssid_command "wpa_cli signal_poll" @@ -19,7 +19,7 @@ namespace WPEFramework static const float signalStrengthThresholdFair = -67.0f; extern NetworkManagerImplementation* _instance; - std::string WifiSignalStrengthMonitor::retrieveValues(const char *command, const char* keyword, char *output_buffer, size_t output_buffer_size) + std::string WiFiSignalStrengthMonitor::retrieveValues(const char *command, const char* keyword, char *output_buffer, size_t output_buffer_size) { std::string key, value; std::string keystr = ""; @@ -45,7 +45,7 @@ namespace WPEFramework return keystr; } - void WifiSignalStrengthMonitor::getSignalData(std::string &ssid, Exchange::INetworkManager::WiFiSignalQuality &quality, std::string &strengthOut) + void WiFiSignalStrengthMonitor::getSignalData(std::string &ssid, Exchange::INetworkManager::WiFiSignalQuality &quality, std::string &strengthOut) { float signalStrengthOut = 0.0f; char buff[BUFFER_SIZE] = {'\0'}; @@ -92,24 +92,24 @@ namespace WPEFramework }; } - void WifiSignalStrengthMonitor::startWifiSignalStrengthMonitor(int interval) + void WiFiSignalStrengthMonitor::startWiFiSignalStrengthMonitor(int interval) { stopThread = false; if (isRunning) { - NMLOG_INFO("WifiSignalStrengthMonitor Thread is already running."); + NMLOG_INFO("WiFiSignalStrengthMonitor Thread is already running."); return; } isRunning = true; - monitorThread = std::thread(&WifiSignalStrengthMonitor::monitorThreadFunction, this, interval); + monitorThread = std::thread(&WiFiSignalStrengthMonitor::monitorThreadFunction, this, interval); monitorThread.detach(); std::thread::id threadId = monitorThread.get_id(); NMLOG_INFO("Thread started with interval: %d seconds. Thread ID: %lu", interval); } - void WifiSignalStrengthMonitor::monitorThreadFunction(int interval) + void WiFiSignalStrengthMonitor::monitorThreadFunction(int interval) { static Exchange::INetworkManager::WiFiSignalQuality oldSignalQuality = Exchange::INetworkManager::WIFI_SIGNAL_DISCONNECTED; - NMLOG_INFO("WifiSignalStrengthMonitor thread started !"); + NMLOG_INFO("WiFiSignalStrengthMonitor thread started !"); while (!stopThread) { string ssid = ""; @@ -128,7 +128,7 @@ namespace WPEFramework if(newSignalQuality == Exchange::INetworkManager::WIFI_SIGNAL_DISCONNECTED) { - NMLOG_WARNING("WiFiSignalStrengthChanged to disconnect - WifiSignalStrengthMonitor exiting"); + NMLOG_WARNING("WiFiSignalStrengthChanged to disconnect - WiFiSignalStrengthMonitor exiting"); stopThread= false; break; // Let the thread exit naturally } @@ -141,4 +141,4 @@ namespace WPEFramework isRunning = false; } } -} \ No newline at end of file +} diff --git a/NetworkManager/service/WifiSignalStrengthMonitor.h b/NetworkManager/WiFiSignalStrengthMonitor.h similarity index 86% rename from NetworkManager/service/WifiSignalStrengthMonitor.h rename to NetworkManager/WiFiSignalStrengthMonitor.h index 19f757b49a..56929aaeb2 100644 --- a/NetworkManager/service/WifiSignalStrengthMonitor.h +++ b/NetworkManager/WiFiSignalStrengthMonitor.h @@ -32,12 +32,12 @@ namespace WPEFramework { namespace Plugin { - class WifiSignalStrengthMonitor + class WiFiSignalStrengthMonitor { public: - WifiSignalStrengthMonitor():isRunning(false) {} - ~WifiSignalStrengthMonitor(){ NMLOG_INFO("~WifiSignalStrengthMonitor"); } - void startWifiSignalStrengthMonitor(int interval); + WiFiSignalStrengthMonitor():isRunning(false) {} + ~WiFiSignalStrengthMonitor(){ NMLOG_INFO("~WiFiSignalStrengthMonitor"); } + void startWiFiSignalStrengthMonitor(int interval); void getSignalData(std::string &ssid, Exchange::INetworkManager::WiFiSignalQuality &quality, std::string &strengthOut); private: std::string retrieveValues(const char *command, const char* keyword, char *output_buffer, size_t output_buffer_size); @@ -47,4 +47,4 @@ namespace WPEFramework void monitorThreadFunction(int interval); }; } -} \ No newline at end of file +} diff --git a/NetworkManager/cmake b/NetworkManager/cmake deleted file mode 120000 index 8e8a460f74..0000000000 --- a/NetworkManager/cmake +++ /dev/null @@ -1 +0,0 @@ -../cmake/ \ No newline at end of file diff --git a/NetworkManager/cmake/FindIARMBus.cmake b/NetworkManager/cmake/FindIARMBus.cmake new file mode 100644 index 0000000000..cad92b7305 --- /dev/null +++ b/NetworkManager/cmake/FindIARMBus.cmake @@ -0,0 +1,46 @@ +# If not stated otherwise in this file or this component's license file the +# following copyright and licenses apply: +# +# Copyright 2020 RDK Management +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# - Try to find IARMBus +# Once done this will define +# IARMBUS_FOUND - System has IARMBus +# IARMBUS_INCLUDE_DIRS - The IARMBus include directories +# IARMBUS_LIBRARIES - The libraries needed to use IARMBus +# IARMBUS_FLAGS - The flags needed to use IARMBus +# + +find_package(PkgConfig) + +find_library(IARMBUS_LIBRARIES NAMES IARMBus) +find_path(IARMBUS_INCLUDE_DIRS NAMES libIARM.h PATH_SUFFIXES rdk/iarmbus) +find_path(IARMIR_INCLUDE_DIRS NAMES irMgr.h PATH_SUFFIXES rdk/iarmmgrs/ir) +find_path(IARMRECEIVER_INCLUDE_DIRS NAMES receiverMgr.h PATH_SUFFIXES rdk/iarmmgrs/receiver) +find_path(IARMPWR_INCLUDE_DIRS NAMES pwrMgr.h PATH_SUFFIXES rdk/iarmmgrs-hal) + +set(IARMBUS_LIBRARIES ${IARMBUS_LIBRARIES} CACHE PATH "Path to IARMBus library") +set(IARMBUS_INCLUDE_DIRS ${IARMBUS_INCLUDE_DIRS} ${IARMIR_INCLUDE_DIRS} ${IARMRECEIVER_INCLUDE_DIRS} ${IARMPWR_INCLUDE_DIRS}) +set(IARMBUS_INCLUDE_DIRS ${IARMBUS_INCLUDE_DIRS} ${IARMIR_INCLUDE_DIRS} ${IARMRECEIVER_INCLUDE_DIRS} ${IARMPWR_INCLUDE_DIRS} CACHE PATH "Path to IARMBus include") + +include(FindPackageHandleStandardArgs) +FIND_PACKAGE_HANDLE_STANDARD_ARGS(IARMBUS DEFAULT_MSG IARMBUS_INCLUDE_DIRS IARMBUS_LIBRARIES) + +mark_as_advanced( + IARMBUS_FOUND + IARMBUS_INCLUDE_DIRS + IARMBUS_LIBRARIES + IARMBUS_LIBRARY_DIRS + IARMBUS_FLAGS) diff --git a/NetworkManager/interface/CMakeLists.txt b/NetworkManager/interface/CMakeLists.txt deleted file mode 100644 index 78e85eb410..0000000000 --- a/NetworkManager/interface/CMakeLists.txt +++ /dev/null @@ -1,48 +0,0 @@ -project(NetworkManagerInterface) -find_package(WPEFramework REQUIRED) -find_package(${NAMESPACE}Core REQUIRED) -find_package(CompileSettingsDebug CONFIG REQUIRED) -find_package(ProxyStubGenerator REQUIRED) - -set(ProxyStubGenerator_DIR ${CMAKE_SYSROOT}${CMAKE_INSTALL_PREFIX}/tools/cmake ${ProxyStubGenerator_DIR}) - -if(NOT GENERATOR_SEARCH_PATH) - set(GENERATOR_SEARCH_PATH ${CMAKE_SYSROOT}${CMAKE_INSTALL_PREFIX}/include/${NAMESPACE}) -endif() - -ProxyStubGenerator(INPUT "${CMAKE_CURRENT_SOURCE_DIR}" OUTDIR "${CMAKE_CURRENT_BINARY_DIR}/generated" INCLUDE_PATH ${GENERATOR_SEARCH_PATH}) - -file(GLOB INTERFACES_HEADERS I*.h) -list(APPEND INTERFACES_HEADERS Module.h) - -file(GLOB PROXY_STUB_SOURCES "${CMAKE_CURRENT_BINARY_DIR}/generated/ProxyStubs*.cpp") - -set(TARGET ${NAMESPACE}NetworkManagerInterface) -string(TOLOWER ${NAMESPACE} NAMESPACE_LIB) - -add_library(${TARGET} SHARED ${PROXY_STUB_SOURCES} Module.cpp) - -target_include_directories( ${TARGET} PUBLIC $) - -target_link_libraries(${TARGET} PRIVATE ${NAMESPACE}Core::${NAMESPACE}Core) -target_link_libraries(${TARGET} PRIVATE CompileSettingsDebug::CompileSettingsDebug) - -set_target_properties(${TargetMarshalling} PROPERTIES - CXX_STANDARD 11 - CXX_STANDARD_REQUIRED YES - FRAMEWORK FALSE - VERSION ${PROJECT_VERSION} - SOVERSION ${PROJECT_VERSION_MAJOR} - ) - -install( - TARGETS ${TARGET} EXPORT ${TARGET}Targets # for downstream dependencies - ARCHIVE DESTINATION lib/${NAMESPACE_LIB}/proxystubs COMPONENT libs # static lib - LIBRARY DESTINATION lib/${NAMESPACE_LIB}/proxystubs COMPONENT libs # shared lib - RUNTIME DESTINATION bin COMPONENT libs # binaries - FRAMEWORK DESTINATION bin/${NAMESPACE_LIB}/proxystubs COMPONENT libs # for mac - PUBLIC_HEADER DESTINATION include/${NAMESPACE}/proxystubs COMPONENT devel # headers for mac (note the different component -> different package) - INCLUDES DESTINATION include/${NAMESPACE}/proxystubs # headers -) - -InstallCMakeConfig(TARGETS ${TARGET}) diff --git a/NetworkManager/interface/Module.cpp b/NetworkManager/interface/Module.cpp deleted file mode 100644 index 2d85ed902b..0000000000 --- a/NetworkManager/interface/Module.cpp +++ /dev/null @@ -1,3 +0,0 @@ -#include "Module.h" - -MODULE_NAME_DECLARATION(BUILD_REFERENCE) diff --git a/NetworkManager/interface/Module.h b/NetworkManager/interface/Module.h deleted file mode 100644 index aa41a21789..0000000000 --- a/NetworkManager/interface/Module.h +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once - -#ifndef MODULE_NAME -#define MODULE_NAME INetworkManager -#endif - -#include -#include diff --git a/NetworkManager/service/CMakeLists.txt b/NetworkManager/service/CMakeLists.txt deleted file mode 100644 index f7a37d1fdb..0000000000 --- a/NetworkManager/service/CMakeLists.txt +++ /dev/null @@ -1,110 +0,0 @@ -# If not stated otherwise in this file or this component's LICENSE -# file the following copyright and licenses apply: -# -# Copyright 2022 RDK Management -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -set(PLUGIN_NAME NetworkManager) -set(MODULE_NAME ${NAMESPACE}${PLUGIN_NAME}) -set(PLUGIN_IMPLEMENTATION ${MODULE_NAME}Implementation) - -find_package(${NAMESPACE}Core REQUIRED) -find_package(${NAMESPACE}Plugins REQUIRED) -find_package(${NAMESPACE}Definitions REQUIRED) -find_package(CURL) -if(ENABLE_GNOME_NETWORKMANAGER) -pkg_check_modules(GLIB REQUIRED glib-2.0) -pkg_check_modules(LIBNM REQUIRED libnm) -else() -find_package(IARMBus REQUIRED) -endif () - -message("Setup ${PROJECT_NAME} v${PROJECT_VERSION}") - -set(PLUGIN_NETWORKMANAGER_LOGLEVEL "5" CACHE STRING "To configure default loglevel NetworkManager plugin") - -# Build the main plugin that runs inside the WPEFramework daemon -add_library(${MODULE_NAME} SHARED - NetworkManager.cpp - NetworkManagerJsonRpc.cpp - NetworkManagerLogger.cpp - Module.cpp -) - -if(ENABLE_LEGACY_NSM_SUPPORT) -target_sources(${MODULE_NAME} PRIVATE NetworkManagerLegacy.cpp) -endif () - -if(ENABLE_LEGACY_NSM_SUPPORT) -add_definitions(-DENABLE_LEGACY_NSM_SUPPORT) -endif () - -target_link_libraries(${MODULE_NAME} PRIVATE - ${NAMESPACE}Core::${NAMESPACE}Core - ${NAMESPACE}Plugins::${NAMESPACE}Plugins - ${NAMESPACE}Definitions::${NAMESPACE}Definitions) - -set_target_properties(${MODULE_NAME} PROPERTIES - CXX_STANDARD 11 - CXX_STANDARD_REQUIRED YES) - -include_directories(${PROJECT_SOURCE_DIR}/interface) -include_directories(${PROJECT_SOURCE_DIR}/service) -include_directories(${PROJECT_SOURCE_DIR}/../helpers) - -install(TARGETS ${MODULE_NAME} DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/${STORAGE_DIRECTORY}/plugins) - - -# Build the implementation that runs out-of-process behind a COM-RPC interface -add_library(${PLUGIN_IMPLEMENTATION} SHARED - NetworkManagerImplementation.cpp - NetworkConnectivity.cpp - NetworkManagerLogger.cpp - StunClient.cpp - WifiSignalStrengthMonitor.cpp - Module.cpp - ${PUBLIC_HEADERS} -) - -if(ENABLE_GNOME_NETWORKMANAGER) - target_sources(${PLUGIN_IMPLEMENTATION} PRIVATE NetworkManagerGnomeProxy.cpp NetworkManagerGnomeWIFI.cpp) - target_include_directories(${PLUGIN_IMPLEMENTATION} PRIVATE ${GLIB_INCLUDE_DIRS} ${LIBNM_INCLUDE_DIRS}) - target_link_libraries(${PLUGIN_IMPLEMENTATION} PRIVATE ${LIBNM_LIBRARIES}) -else() - target_sources(${PLUGIN_IMPLEMENTATION} PRIVATE NetworkManagerRDKProxy.cpp) - target_include_directories(${PLUGIN_IMPLEMENTATION} PRIVATE ${IARMBUS_INCLUDE_DIRS}) - target_link_libraries(${PLUGIN_IMPLEMENTATION} PRIVATE ${IARMBUS_LIBRARIES}) -endif() - -target_link_libraries(${PLUGIN_IMPLEMENTATION} PRIVATE - ${NAMESPACE}Plugins::${NAMESPACE}Plugins - ${NAMESPACE}Definitions::${NAMESPACE}Definitions) - -set_target_properties(${PLUGIN_IMPLEMENTATION} PROPERTIES - CXX_STANDARD 11 - CXX_STANDARD_REQUIRED YES - FRAMEWORK FALSE) - -target_link_libraries(${PLUGIN_IMPLEMENTATION} PRIVATE ${CURL_LIBRARIES}) -target_include_directories(${PLUGIN_IMPLEMENTATION} PRIVATE ${CURL_INCLUDE_DIRS}) - -install(TARGETS ${PLUGIN_IMPLEMENTATION} DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/${STORAGE_DIRECTORY}/plugins) - -write_config() - -if(ENABLE_LEGACY_NSM_SUPPORT) -add_definitions(-DENABLE_LEGACY_NSM_SUPPORT) -write_config(Network) -write_config(WiFiManager) -endif () diff --git a/NetworkManager/service/Network.conf.in b/NetworkManager/service/Network.conf.in deleted file mode 100644 index 74bb46f4b3..0000000000 --- a/NetworkManager/service/Network.conf.in +++ /dev/null @@ -1,25 +0,0 @@ -autostart = "true" -callsign= "org.rdk.Network" - -test = JSON() -test.add("locator", "lib@PLUGIN_IMPLEMENTATION@.so") -test.add("outofprocess", "true") - -connectivity = JSON() -connectivity.add("endpoint_1", "@PLUGIN_NETWORKMANAGER_CONN_ENDPOINT_1@") -connectivity.add("endpoint_2", "@PLUGIN_NETWORKMANAGER_CONN_ENDPOINT_2@") -connectivity.add("endpoint_3", "@PLUGIN_NETWORKMANAGER_CONN_ENDPOINT_3@") -connectivity.add("endpoint_4", "@PLUGIN_NETWORKMANAGER_CONN_ENDPOINT_4@") -connectivity.add("endpoint_5", "@PLUGIN_NETWORKMANAGER_CONN_ENDPOINT_5@") -connectivity.add("interval", "@PLUGIN_NETWORKMANAGER_CONN_MONITOR_INTERVAL@") - -stun = JSON() -stun.add("endpoint", "@PLUGIN_NETWORKMANAGER_STUN_ENDPOINT@") -stun.add("port", "@PLUGIN_NETWORKMANAGER_STUN_PORT@") -stun.add("interval", "30") - -configuration = JSON() -configuration.add("root", test) -configuration.add("connectivity", connectivity) -configuration.add("stun", stun) -configuration.add("loglevel", "@PLUGIN_NETWORKMANAGER_LOGLEVEL@") diff --git a/NetworkManager/service/Network.config b/NetworkManager/service/Network.config deleted file mode 100644 index 5cb22809f2..0000000000 --- a/NetworkManager/service/Network.config +++ /dev/null @@ -1,27 +0,0 @@ -set(autostart true) -set(callsign "org.rdk.Network") - -map() - key(root) - map() - kv(outofprocess true) - kv(locator lib${PLUGIN_IMPLEMENTATION}.so) - end() - key(connectivity) - map() - kv(endpoint_1 ${PLUGIN_NETWORKMANAGER_CONN_ENDPOINT_1}) - kv(endpoint_2 ${PLUGIN_NETWORKMANAGER_CONN_ENDPOINT_2}) - kv(endpoint_3 ${PLUGIN_NETWORKMANAGER_CONN_ENDPOINT_3}) - kv(endpoint_4 ${PLUGIN_NETWORKMANAGER_CONN_ENDPOINT_4}) - kv(endpoint_5 ${PLUGIN_NETWORKMANAGER_CONN_ENDPOINT_5}) - kv(interval, @PLUGIN_NETWORKMANAGER_CONN_MONITOR_INTERVAL@) - end() - key(stun) - map() - kv(endpoint, ${PLUGIN_NETWORKMANAGER_STUN_ENDPOINT}) - kv(port, PLUGIN_NETWORKMANAGER_STUN_PORT) - kv(interval, 30) - end() - kv(loglevel, 3) -end() -ans(configuration) diff --git a/NetworkManager/service/NetworkManagerLegacy.cpp b/NetworkManager/service/NetworkManagerLegacy.cpp deleted file mode 100644 index eada776e10..0000000000 --- a/NetworkManager/service/NetworkManagerLegacy.cpp +++ /dev/null @@ -1,639 +0,0 @@ -/** -* If not stated otherwise in this file or this component's LICENSE -* file the following copyright and licenses apply: -* -* Copyright 2022 RDK Management -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -**/ - -#include "NetworkManager.h" -#include "NetworkConnectivity.h" -#include - -#define LOGINFOMETHOD() { std::string json; parameters.ToString(json); NMLOG_TRACE("Legacy params=%s", json.c_str() ); } -#define LOGTRACEMETHODFIN() { std::string json; response.ToString(json); NMLOG_TRACE("Legacy response=%s", json.c_str() ); } - -using namespace std; -using namespace WPEFramework::Plugin; - -namespace WPEFramework -{ - namespace Plugin - { - /** - * Hook up all our JSON RPC methods - * - * Each method definition comprises of: - * * Input parameters - * * Output parameters - * * Method name - * * Function that implements that method - */ - void NetworkManager::RegisterLegacyMethods() - { - CreateHandler({2}); - Register("getInterfaces", &NetworkManager::getInterfaces, this); - Register("isInterfaceEnabled", &NetworkManager::isInterfaceEnabled, this); - Register("getPublicIP", &NetworkManager::getPublicIP, this); - Register("setInterfaceEnabled", &NetworkManager::setInterfaceEnabled, this); - Register("getDefaultInterface", &NetworkManager::getDefaultInterface, this); - Register("setDefaultInterface", &NetworkManager::setDefaultInterface, this); - Register("setIPSettings", &NetworkManager::setIPSettings, this); - Register("getIPSettings", &NetworkManager::getIPSettings, this); - Register("getInternetConnectionState", &NetworkManager::getInternetConnectionState, this); - Register("ping", &NetworkManager::ping, this); - Register("isConnectedToInternet", &NetworkManager::isConnectedToInternet, this); - Register("setConnectivityTestEndpoints", &NetworkManager::SetConnectivityTestEndpoints, this); - Register("startConnectivityMonitoring", &NetworkManager::StartConnectivityMonitoring, this); - Register("getCaptivePortalURI", &NetworkManager::GetCaptivePortalURI, this); - Register("stopConnectivityMonitoring", &NetworkManager::StopConnectivityMonitoring, this); - Register("cancelWPSPairing", &NetworkManager::cancelWPSPairing, this); - Register("clearSSID", &NetworkManager::clearSSID, this); - Register("connect", &NetworkManager::WiFiConnect, this); - Register("disconnect", &NetworkManager::disconnect, this); - Register("getConnectedSSID", &NetworkManager::getConnectedSSID, this); - Register("startScan", &NetworkManager::StartWiFiScan, this); - Register("stopScan", &NetworkManager::StopWiFiScan, this); - Register("getPairedSSID", &NetworkManager::GetKnownSSIDs, this); - Register("getPairedSSIDInfo", &NetworkManager::GetConnectedSSID, this); - Register("initiateWPSPairing", &NetworkManager::initiateWPSPairing, this); - Register("isPaired", &NetworkManager::isPaired, this); - Register("saveSSID", &NetworkManager::saveSSID, this); - Register("getSupportedSecurityModes", &NetworkManager::GetSupportedSecurityModes, this); - Register("getCurrentState", &NetworkManager::GetWifiState, this); - GetHandler(2)->Register("setIPSettings", &NetworkManager::setIPSettings, this); - GetHandler(2)->Register("getIPSettings", &NetworkManager::getIPSettings, this); - GetHandler(2)->Register("initiateWPSPairing", &NetworkManager::initiateWPSPairing, this); - } - - /** - * Unregister all our JSON-RPC methods - */ - void NetworkManager::UnregisterLegacyMethods() - { - Unregister("getInterfaces"); - Unregister("isInterfaceEnabled"); - Unregister("getPublicIP"); - Unregister("setInterfaceEnabled"); - Unregister("getDefaultInterface"); - Unregister("setDefaultInterface"); - Unregister("setIPSettings"); - Unregister("getIPSettings"); - Unregister("getInternetConnectionState"); - Unregister("ping"); - Unregister("isConnectedToInternet"); - Unregister("setConnectivityTestEndpoints"); - Unregister("startConnectivityMonitoring"); - Unregister("getCaptivePortalURI"); - Unregister("stopConnectivityMonitoring"); - Unregister("cancelWPSPairing"); - Unregister("clearSSID"); - Unregister("connect"); - Unregister("disconnect"); - Unregister("getConnectedSSID"); - Unregister("startScan"); - Unregister("stopScan"); - Unregister("getPairedSSID"); - Unregister("getPairedSSIDInfo"); - Unregister("initiateWPSPairing"); - Unregister("isPaired"); - Unregister("saveSSID"); - Unregister("getSupportedSecurityModes"); - Unregister("getCurrentState"); - } - -#define CIDR_NETMASK_IP_LEN 32 -const string CIDR_PREFIXES[CIDR_NETMASK_IP_LEN] = { - "128.0.0.0", - "192.0.0.0", - "224.0.0.0", - "240.0.0.0", - "248.0.0.0", - "252.0.0.0", - "254.0.0.0", - "255.0.0.0", - "255.128.0.0", - "255.192.0.0", - "255.224.0.0", - "255.240.0.0", - "255.248.0.0", - "255.252.0.0", - "255.254.0.0", - "255.255.0.0", - "255.255.128.0", - "255.255.192.0", - "255.255.224.0", - "255.255.240.0", - "255.255.248.0", - "255.255.252.0", - "255.255.254.0", - "255.255.255.0", - "255.255.255.128", - "255.255.255.192", - "255.255.255.224", - "255.255.255.240", - "255.255.255.248", - "255.255.255.252", - "255.255.255.254", - "255.255.255.255", - }; - - uint32_t NetworkManager::getInterfaces (const JsonObject& parameters, JsonObject& response) - { - uint32_t rc = Core::ERROR_GENERAL; - JsonObject tmpResponse; - JsonArray array; - - LOGINFOMETHOD(); - rc = GetAvailableInterfaces(parameters, tmpResponse); - - const JsonArray& tmpArray = tmpResponse["interfaces"].Array(); - for (int i=0; iStartWPS(wpsmethod, wps_pin); - else - rc = Core::ERROR_UNAVAILABLE; - - if (Core::ERROR_NONE == rc) - { - response["result"] = string(); - response["success"] = true; - } - LOGTRACEMETHODFIN(); - return rc; - } - uint32_t NetworkManager::getDefaultInterface (const JsonObject& parameters, JsonObject& response) - { - uint32_t rc = Core::ERROR_GENERAL; - JsonObject tmpResponse; - - LOGINFOMETHOD(); - rc = GetPrimaryInterface(parameters, tmpResponse); - - if (Core::ERROR_NONE == rc) - { - if ("wlan0" == tmpResponse["interface"].String()) - response["interface"] = "WIFI"; - else if("eth0" == tmpResponse["interface"].String()) - response["interface"] = "ETHERNET"; - response["success"] = tmpResponse["success"]; - } - LOGTRACEMETHODFIN(); - return rc; - } - uint32_t NetworkManager::setDefaultInterface(const JsonObject& parameters, JsonObject& response) - { - uint32_t rc = Core::ERROR_GENERAL; - JsonObject tmpParameters; - string interface; - LOGINFOMETHOD(); - if("WIFI" == parameters["interface"].String()) - tmpParameters["interface"] = "wlan0"; - else if("ETHERNET" == parameters["interface"].String()) - tmpParameters["interface"] = "eth0"; - - rc = SetPrimaryInterface(tmpParameters, response); - LOGTRACEMETHODFIN(); - - return rc; - } - uint32_t NetworkManager::setIPSettings(const JsonObject& parameters, JsonObject& response) - { - uint32_t rc = Core::ERROR_GENERAL; - JsonObject tmpResponse; - JsonObject tmpParameters; - Exchange::INetworkManager::IPAddressInfo result{}; - - LOGINFOMETHOD(); - - if("WIFI" == parameters["interface"].String()) - tmpParameters["interface"] = "wlan0"; - else if("ETHERNET" == parameters["interface"].String()) - tmpParameters["interface"] = "eth0"; - - tmpParameters["ipversion"] = parameters["ipversion"]; - tmpParameters["autoconfig"] = parameters["autoconfig"]; - tmpParameters["ipaddress"] = parameters["ipaddr"]; - auto it = std::find(std::begin(CIDR_PREFIXES), std::end(CIDR_PREFIXES), parameters["netmask"].String()); - if (it == std::end(CIDR_PREFIXES)) - return rc; - else - tmpParameters["prefix"] = std::distance(std::begin(CIDR_PREFIXES), it); - tmpParameters["gateway"] = parameters["gateway"]; - tmpParameters["primarydns"] = parameters["primarydns"]; - tmpParameters["secondarydns"] = parameters["secondarydns"]; - - rc = SetIPSettings(tmpParameters, tmpResponse); - - if (Core::ERROR_NONE == rc) - { - response["supported"] = true; - response["success"] = tmpResponse["success"]; - } - LOGTRACEMETHODFIN(); - return rc; - } - uint32_t NetworkManager::getIPSettings (const JsonObject& parameters, JsonObject& response) - { - uint32_t rc = Core::ERROR_GENERAL; - JsonObject tmpResponse; - JsonObject tmpParameters; - size_t index; - - LOGINFOMETHOD(); - - if (parameters.HasLabel("ipversion")) - { - tmpParameters["ipversion"] = parameters["ipversion"]; - } - if (parameters.HasLabel("interface")) - { - if ("WIFI" == parameters["interface"].String()) - tmpParameters["interface"] = "wlan0"; - else if("ETHERNET" == parameters["interface"].String()) - tmpParameters["interface"] = "eth0"; - } - - rc = GetIPSettings(tmpParameters, tmpResponse); - - if (Core::ERROR_NONE == rc) - { - string ipversion = tmpResponse["ipversion"].String(); - std::transform(ipversion.begin(), ipversion.end(), ipversion.begin(), ::toupper); - - if (parameters.HasLabel("interface")) - { - response["interface"] = parameters["interface"]; - } - else - { - if ("wlan0" == m_defaultInterface) - response["interface"] = "WIFI"; - else if("eth0" == m_defaultInterface) - response["interface"] = "ETHERNET"; - } - response["ipversion"] = tmpResponse["ipversion"]; - response["autoconfig"] = tmpResponse["autoconfig"]; - response["ipaddr"] = tmpResponse["ipaddress"]; - if(tmpResponse["ipaddress"].String().empty()) - response["netmask"] = ""; - else if ("IPV4" == ipversion) - { - index = tmpResponse["prefix"].Number(); - if(CIDR_NETMASK_IP_LEN <= index) - return Core::ERROR_GENERAL; - response["netmask"] = CIDR_PREFIXES[index]; - } - else if ("IPV6" == ipversion) - { - response["netmask"] = tmpResponse["prefix"]; - } - response["gateway"] = tmpResponse["gateway"]; - response["dhcpserver"] = tmpResponse["dhcpserver"]; - response["primarydns"] = tmpResponse["primarydns"]; - response["secondarydns"] = tmpResponse["secondarydns"]; - response["success"] = tmpResponse["success"]; - } - LOGTRACEMETHODFIN(); - return rc; - } - uint32_t NetworkManager::isConnectedToInternet(const JsonObject& parameters, JsonObject& response) - { - uint32_t rc = Core::ERROR_GENERAL; - JsonObject tmpResponse; - - LOGINFOMETHOD(); - string ipversion = parameters["ipversion"].String(); - rc = IsConnectedToInternet(parameters, tmpResponse); - - if (Core::ERROR_NONE == rc) - { - response["connectedToInternet"] = tmpResponse["isConnectedToInternet"]; - if(ipversion == "IPV4" || ipversion == "IPV6") - response["ipversion"] = ipversion.c_str(); - response["success"] = true; - } - LOGTRACEMETHODFIN(); - return rc; - } - uint32_t NetworkManager::getInternetConnectionState(const JsonObject& parameters, JsonObject& response) - { - uint32_t rc = Core::ERROR_GENERAL; - uint32_t rc1 = Core::ERROR_GENERAL; - string endPoint; - JsonObject tmpResponse; - JsonObject captivePortalResponse; - JsonObject tmpParameters; - string status; - - LOGINFOMETHOD(); - string ipversion = parameters["ipversion"].String(); - rc = IsConnectedToInternet(parameters, tmpResponse); - if (Core::ERROR_NONE == rc) - { - status = tmpResponse["status"].String(); - NMLOG_TRACE("status = %s\n", status ); - NMLOG_TRACE("tmpResponse[status].String() = %s\n", tmpResponse["status"].String() ); - if(status == "LIMITED_INTERNET") - response["state"] = static_cast(nsm_internetState::LIMITED_INTERNET); - else if(status == "CAPTIVE_PORTAL") - { - response["state"] = static_cast(nsm_internetState::CAPTIVE_PORTAL); - rc1 = getCaptivePortalURI(tmpParameters, captivePortalResponse); - if (Core::ERROR_NONE == rc1) - response["uri"] = captivePortalResponse["uri"]; - } - else if(status == "FULLY_CONNECTED") - response["state"] = static_cast(nsm_internetState::FULLY_CONNECTED); - else - response["state"] = static_cast(nsm_internetState::NO_INTERNET); - - if(ipversion == "IPV4" || ipversion == "IPV6") - response["ipversion"] = ipversion.c_str(); - response["success"] = true; - } - LOGTRACEMETHODFIN(); - return rc; - } - uint32_t NetworkManager::ping(const JsonObject& parameters, JsonObject& response) - { - uint32_t rc = Core::ERROR_GENERAL; - struct in_addr ipv4address; - struct in6_addr ipv6address; - JsonObject tmpParameters; - JsonObject tmpResponse; - string endpoint{}; - - LOGINFOMETHOD(); - - endpoint = parameters["endpoint"].String(); - - if (inet_pton(AF_INET, endpoint.c_str(), &ipv4address) > 0) - tmpParameters["ipversion"] = "IPv4"; - else if (inet_pton(AF_INET6, endpoint.c_str(), &ipv6address) > 0) - tmpParameters["ipversion"] = "IPv6"; - - tmpParameters["noOfRequest"] = parameters["packets"]; - tmpParameters["endpoint"] = parameters["endpoint"]; - tmpParameters["timeout"] = 5; - tmpParameters["guid"] = parameters["guid"]; - - rc = Ping(tmpParameters, response); - - if (Core::ERROR_NONE == rc) - { - response["target"] = parameters["endpoint"]; - response["guid"] = parameters["guid"]; - } - LOGTRACEMETHODFIN(); - return rc; - } - uint32_t NetworkManager::getPublicIP(const JsonObject& parameters, JsonObject& response) - { - uint32_t rc = Core::ERROR_GENERAL; - string interface; - string ipversion{"IPv4"}; - JsonObject tmpParameters; - JsonObject tmpResponse; - - LOGINFOMETHOD(); - if("WIFI" == parameters["iface"].String()) - interface = "wlan0"; - else if("ETHERNET" == parameters["iface"].String()) - interface = "eth0"; - - if(parameters["ipv6"].Boolean()) - ipversion = "IPv6"; - else - ipversion = "IPv4"; - - tmpParameters["interface"] = interface; - tmpParameters["ipversion"] = ipversion; - rc = GetPublicIP(tmpParameters, tmpResponse); - - if (Core::ERROR_NONE == rc) - { - response["public_ip"] = tmpResponse["publicIP"]; - response["success"] = tmpResponse["success"]; - } - LOGTRACEMETHODFIN(); - return rc; - } - - uint32_t NetworkManager::isInterfaceEnabled (const JsonObject& parameters, JsonObject& response) - { - uint32_t rc = Core::ERROR_GENERAL; - JsonObject tmpResponse; - - LOGINFOMETHOD(); - rc = GetAvailableInterfaces(parameters, tmpResponse); - - const JsonArray& tmpArray = tmpResponse["interfaces"].Array(); - for (int i=0; i Date: Wed, 29 May 2024 16:52:43 +0000 Subject: [PATCH 04/21] RDKTV-30678: Two TV fails to boot up on AC power cut in PP build. Reason for change: To fix file corruption. Test Procedure: Refer JIRA. Risks: low Priority: P0 Signed-off-by: nanimatta --- MaintenanceManager/MaintenanceManager.cpp | 14 ++++++++++++++ SystemServices/SystemServices.cpp | 14 ++++++++++++++ helpers/UtilsfileExists.h | 5 +++++ 3 files changed, 33 insertions(+) diff --git a/MaintenanceManager/MaintenanceManager.cpp b/MaintenanceManager/MaintenanceManager.cpp index 7ab9db78a2..f86ab8edbb 100644 --- a/MaintenanceManager/MaintenanceManager.cpp +++ b/MaintenanceManager/MaintenanceManager.cpp @@ -37,6 +37,7 @@ #include #include #include +#include #include "MaintenanceManager.h" @@ -251,6 +252,19 @@ namespace WPEFramework { :PluginHost::JSONRPC() { MaintenanceManager::_instance = this; + if (Utils::directoryExists(MAINTENANCE_MGR_RECORD_FILE)) + { + std::cout << "File " << MAINTENANCE_MGR_RECORD_FILE << " detected as folder, deleting.." << std::endl; + if (rmdir(MAINTENANCE_MGR_RECORD_FILE) == 0) + { + cSettings mtemp(MAINTENANCE_MGR_RECORD_FILE); + MaintenanceManager::m_setting = mtemp; + } + else + { + std::cout << "Unable to delete folder: " << MAINTENANCE_MGR_RECORD_FILE << std::endl; + } + } /** * @brief Invoking Plugin API register to WPEFRAMEWORK. diff --git a/SystemServices/SystemServices.cpp b/SystemServices/SystemServices.cpp index 6a5d55e65d..336d074fd4 100644 --- a/SystemServices/SystemServices.cpp +++ b/SystemServices/SystemServices.cpp @@ -349,6 +349,20 @@ namespace WPEFramework { , m_cacheService(SYSTEM_SERVICE_SETTINGS_FILE) { SystemServices::_instance = this; + if (Utils::directoryExists(SYSTEM_SERVICE_SETTINGS_FILE)) + { + std::cout << "File " << SYSTEM_SERVICE_SETTINGS_FILE << " detected as folder, deleting.." << std::endl; + if (rmdir(SYSTEM_SERVICE_SETTINGS_FILE) == 0) + { + cSettings stemp(SYSTEM_SERVICE_SETTINGS_FILE); + SystemServices::m_cacheService = stemp; + } + else + { + std::cout << "Unable to delete folder: " << SYSTEM_SERVICE_SETTINGS_FILE << std::endl; + } + } + //Updating the standard territory m_strStandardTerritoryList = "ABW AFG AGO AIA ALA ALB AND ARE ARG ARM ASM ATA ATF ATG AUS AUT AZE BDI BEL BEN BES BFA BGD BGR BHR BHS BIH BLM BLR BLZ BMU BOL BRA BRB BRN BTN BVT BWA CAF CAN CCK CHE CHL CHN CIV CMR COD COG COK COL COM CPV CRI CUB Cuba CUW CXR CYM CYP CZE DEU DJI DMA DNK DOM DZA ECU EGY ERI ESH ESP EST ETH FIN FJI FLK FRA FRO FSM GAB GBR GEO GGY GHA GIB GIN GLP GMB GNB GNQ GRC GRD GRL GTM GUF GUM GUY HKG HMD HND HRV HTI HUN IDN IMN IND IOT IRL IRN IRQ ISL ISR ITA JAM JEY JOR JPN KAZ KEN KGZ KHM KIR KNA KOR KWT LAO LBN LBR LBY LCA LIE LKA LSO LTU LUX LVA MAC MAF MAR MCO MDA MDG MDV MEX MHL MKD MLI MLT MMR MNE MNG MNP MOZ MRT MSR MTQ MUS MWI MYS MYT NAM NCL NER NFK NGA NIC NIU NLD NOR NPL NRU NZL OMN PAK PAN PCN PER PHL PLW PNG POL PRI PRK PRT PRY PSE PYF QAT REU ROU RUS RWA SAU SDN SEN SGP SGS SHN SJM SLB SLE SLV SMR SOM SPM SRB SSD STP SUR SVK SVN SWE SWZ SXM SYC SYR TCA TCD TGO THA TJK TKL TKM TLS TON TTO TUN TUR TUV TWN TZA UGA UKR UMI URY USA UZB VAT VCT VEN VGB VIR VNM VUT WLF WSM YEM ZAF ZMB ZWE"; diff --git a/helpers/UtilsfileExists.h b/helpers/UtilsfileExists.h index 13fc840c8f..a3ac5b1727 100644 --- a/helpers/UtilsfileExists.h +++ b/helpers/UtilsfileExists.h @@ -8,4 +8,9 @@ inline bool fileExists(const char* pFileName) struct stat fileStat; return 0 == stat(pFileName, &fileStat) && S_IFREG == (fileStat.st_mode & S_IFMT); } +inline bool directoryExists(const char* pDirName) +{ + struct stat dirStat; + return 0 == stat(pDirName, &dirStat) && S_ISDIR(dirStat.st_mode); +} } From d5dcd2b7b424461ba79ecb01b66d5350e8b34302 Mon Sep 17 00:00:00 2001 From: Vishnu Dinakaran <59993407+vdinak240@users.noreply.github.com> Date: Fri, 31 May 2024 16:10:39 +0530 Subject: [PATCH 05/21] DELIA-65299: TTS using offline engine for VG even with Device Online (#5357) Reason for change: Increase Network plugin access Timeout from 1 sec to 3 sec Test Procedure: Mentioned in ticket Risks: Low Signed-off-by: vdinak240 --- TextToSpeech/impl/NetworkStatusObserver.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/TextToSpeech/impl/NetworkStatusObserver.cpp b/TextToSpeech/impl/NetworkStatusObserver.cpp index 3a6c0d4fe1..914866175d 100644 --- a/TextToSpeech/impl/NetworkStatusObserver.cpp +++ b/TextToSpeech/impl/NetworkStatusObserver.cpp @@ -82,7 +82,7 @@ bool NetworkStatusObserver::isConnected() { } JsonObject joGetParams, joGetResult; - auto status = m_networkService->Invoke(1000, "isConnectedToInternet", joGetParams, joGetResult); + auto status = m_networkService->Invoke(3000, "isConnectedToInternet", joGetParams, joGetResult); if (status == Core::ERROR_NONE && joGetResult.HasLabel("connectedToInternet")) { m_isConnected = joGetResult["connectedToInternet"].Boolean(); } else { @@ -92,7 +92,7 @@ bool NetworkStatusObserver::isConnected() { } if (!m_eventRegistered) { - if (m_networkService->Subscribe(1000, "onInternetStatusChange", + if (m_networkService->Subscribe(3000, "onInternetStatusChange", &NetworkStatusObserver::onConnectionStatusChangedEventHandler, this) == Core::ERROR_NONE) { m_eventRegistered = true; TTSLOG_INFO("Subscribed to notification handler : onInternetStatusChange"); From 2bda9e6f5cefe927551fa7f0805777c68bb155d1 Mon Sep 17 00:00:00 2001 From: gururaajar <83449026+gururaajar@users.noreply.github.com> Date: Fri, 31 May 2024 22:20:14 -0400 Subject: [PATCH 06/21] RDKTV-30981 - Devices went to offline plui state (#5366) * RDKTV-30981 - Devices went to offline plui state Reason for change: Created authorization token and passed the same for json RPC call to networkmanager from network plugin. Also added timer logic to subscribe for events. Corrected SetInterfaceState and GetInterfaceState function calls. Updated logger to print file name instead of function name. Test Procedure: Do CDL and confirm the device boots up in online state Risks: Low Priority: P1 Signed-off-by: Gururaaja ESR * Update NetworkManagerPlugin.md Co-authored-by: Karunakaran A <48997923+karuna2git@users.noreply.github.com> --- NetworkManager/LegacyPlugin_NetworkAPIs.cpp | 42 +++- NetworkManager/LegacyPlugin_NetworkAPIs.h | 5 +- .../LegacyPlugin_WiFiManagerAPIs.cpp | 40 +++- NetworkManager/LegacyPlugin_WiFiManagerAPIs.h | 4 +- NetworkManager/NetworkManagerJsonRpc.cpp | 2 +- NetworkManager/NetworkManagerLogger.cpp | 2 +- NetworkManager/NetworkManagerRDKProxy.cpp | 11 +- NetworkManager/NetworkManagerTimer.h | 132 +++++++++++ docs/api/NetworkManagerPlugin.md | 216 +++++++++--------- 9 files changed, 312 insertions(+), 142 deletions(-) create mode 100644 NetworkManager/NetworkManagerTimer.h diff --git a/NetworkManager/LegacyPlugin_NetworkAPIs.cpp b/NetworkManager/LegacyPlugin_NetworkAPIs.cpp index eca0d45bad..153857c09b 100644 --- a/NetworkManager/LegacyPlugin_NetworkAPIs.cpp +++ b/NetworkManager/LegacyPlugin_NetworkAPIs.cpp @@ -68,6 +68,7 @@ namespace WPEFramework { _gNWInstance = this; m_defaultInterface = "wlan0"; + m_timer.connect(std::bind(&Network::subscribeToEvents, this)); RegisterLegacyMethods(); } @@ -105,6 +106,28 @@ namespace WPEFramework string callsign(NETWORK_MANAGER_CALLSIGN); + string token = ""; + + // TODO: use interfaces and remove token + auto security = m_service->QueryInterfaceByCallsign("SecurityAgent"); + if (security != nullptr) { + string payload = "http://localhost"; + if (security->CreateToken( + static_cast(payload.length()), + reinterpret_cast(payload.c_str()), + token) + == Core::ERROR_NONE) { + std::cout << "DisplaySettings got security token" << std::endl; + } else { + std::cout << "DisplaySettings failed to get security token" << std::endl; + } + security->Release(); + } else { + std::cout << "No security agent" << std::endl; + } + + string query = "token=" + token; + auto interface = m_service->QueryInterfaceByCallsign(callsign); if (interface != nullptr) { @@ -123,16 +146,10 @@ namespace WPEFramework } Core::SystemInfo::SetEnvironment(_T("THUNDER_ACCESS"), (_T("127.0.0.1:9998"))); - string query="token="; - m_networkmanager = make_shared >("org.rdk.NetworkManager", ""); - - /* Wait for Proxy stuff to be established */ - sleep(3); - - if (Core::ERROR_NONE != subscribeToEvents()) - return string("Failed to Subscribe"); - else - return string(); + m_networkmanager = make_shared >(_T(NETWORK_MANAGER_CALLSIGN), _T(NETWORK_MANAGER_CALLSIGN), false, query); + + m_timer.start(5000); + return string(); } void Network::Deinitialize(PluginHost::IShell* /* service */) @@ -754,7 +771,7 @@ const string CIDR_PREFIXES[CIDR_NETMASK_IP_LEN] = { } /** Private */ - uint32_t Network::subscribeToEvents(void) + void Network::subscribeToEvents(void) { uint32_t errCode = Core::ERROR_GENERAL; if (m_networkmanager) @@ -781,7 +798,8 @@ const string CIDR_PREFIXES[CIDR_NETMASK_IP_LEN] = { NMLOG_ERROR("Subscribe to onInternetStatusChange failed, errCode: %u", errCode); } } - return errCode; + if (errCode == Core::ERROR_NONE) + m_timer.stop(); } string Network::getInterfaceMapping(const string & interface) diff --git a/NetworkManager/LegacyPlugin_NetworkAPIs.h b/NetworkManager/LegacyPlugin_NetworkAPIs.h index 107c066f91..f4bd0c6da2 100644 --- a/NetworkManager/LegacyPlugin_NetworkAPIs.h +++ b/NetworkManager/LegacyPlugin_NetworkAPIs.h @@ -5,10 +5,10 @@ #include "Module.h" #include "core/Link.h" +#include "NetworkManagerTimer.h" namespace WPEFramework { namespace Plugin { - // This is a server for a JSONRPC communication channel. // For a plugin to be capable to handle JSONRPC, inherit from PluginHost::JSONRPC. // By inheriting from this class, the plugin realizes the interface PluginHost::IDispatcher. @@ -30,7 +30,7 @@ namespace WPEFramework { void RegisterLegacyMethods(); void UnregisterLegacyMethods(); - uint32_t subscribeToEvents(void); + void subscribeToEvents(void); static std::string getInterfaceMapping(const std::string &interface); void activatePrimaryPlugin(); @@ -84,6 +84,7 @@ namespace WPEFramework { PluginHost::IShell* m_service; std::shared_ptr> m_networkmanager; string m_defaultInterface; + NetworkManagerTimer m_timer; }; } // namespace Plugin } // namespace WPEFramework diff --git a/NetworkManager/LegacyPlugin_WiFiManagerAPIs.cpp b/NetworkManager/LegacyPlugin_WiFiManagerAPIs.cpp index f0f3395fc4..0ab3abac67 100644 --- a/NetworkManager/LegacyPlugin_WiFiManagerAPIs.cpp +++ b/NetworkManager/LegacyPlugin_WiFiManagerAPIs.cpp @@ -68,6 +68,7 @@ namespace WPEFramework , m_service(nullptr) { _gWiFiInstance = this; + m_timer.connect(std::bind(&WiFiManager::subscribeToEvents, this)); RegisterLegacyMethods(); } @@ -104,7 +105,27 @@ namespace WPEFramework m_service->AddRef(); string callsign(NETWORK_MANAGER_CALLSIGN); + string token = ""; + + // TODO: use interfaces and remove token + auto security = m_service->QueryInterfaceByCallsign("SecurityAgent"); + if (security != nullptr) { + string payload = "http://localhost"; + if (security->CreateToken( + static_cast(payload.length()), + reinterpret_cast(payload.c_str()), + token) + == Core::ERROR_NONE) { + std::cout << "DisplaySettings got security token" << std::endl; + } else { + std::cout << "DisplaySettings failed to get security token" << std::endl; + } + security->Release(); + } else { + std::cout << "No security agent" << std::endl; + } + string query = "token=" + token; auto interface = m_service->QueryInterfaceByCallsign(callsign); if (interface != nullptr) { @@ -123,16 +144,10 @@ namespace WPEFramework } Core::SystemInfo::SetEnvironment(_T("THUNDER_ACCESS"), (_T("127.0.0.1:9998"))); - string query="token="; - m_networkmanager = make_shared >("org.rdk.NetworkManager", ""); - - /* Wait for Proxy stuff to be established */ - sleep(3); - - if (Core::ERROR_NONE != subscribeToEvents()) - return string("Failed to Subscribe"); - else - return string(); + m_networkmanager = make_shared >(_T(NETWORK_MANAGER_CALLSIGN), _T(NETWORK_MANAGER_CALLSIGN), false, query); + + m_timer.start(5000); + return string(); } void WiFiManager::Deinitialize(PluginHost::IShell* /* service */) @@ -472,7 +487,7 @@ namespace WPEFramework } /** Private */ - uint32_t WiFiManager::subscribeToEvents(void) + void WiFiManager::subscribeToEvents(void) { uint32_t errCode = Core::ERROR_GENERAL; if (m_networkmanager) @@ -493,7 +508,8 @@ namespace WPEFramework NMLOG_ERROR("Subscribe to onActiveInterfaceChange failed, errCode: %u", errCode); } } - return errCode; + if (errCode == Core::ERROR_NONE) + m_timer.stop(); } /** Event Handling and Publishing */ diff --git a/NetworkManager/LegacyPlugin_WiFiManagerAPIs.h b/NetworkManager/LegacyPlugin_WiFiManagerAPIs.h index d6155ea5ec..300ca767b2 100644 --- a/NetworkManager/LegacyPlugin_WiFiManagerAPIs.h +++ b/NetworkManager/LegacyPlugin_WiFiManagerAPIs.h @@ -20,6 +20,7 @@ #pragma once #include "Module.h" +#include "NetworkManagerTimer.h" namespace WPEFramework { @@ -84,13 +85,14 @@ namespace WPEFramework { private: void RegisterLegacyMethods(); void UnregisterLegacyMethods(); - uint32_t subscribeToEvents(void); + void subscribeToEvents(void); static std::string getInterfaceMapping(const std::string &interface); void activatePrimaryPlugin(); private: PluginHost::IShell* m_service; std::shared_ptr> m_networkmanager; + NetworkManagerTimer m_timer; }; } // namespace Plugin } // namespace WPEFramework diff --git a/NetworkManager/NetworkManagerJsonRpc.cpp b/NetworkManager/NetworkManagerJsonRpc.cpp index 4d39ca4b97..0271ccf789 100644 --- a/NetworkManager/NetworkManagerJsonRpc.cpp +++ b/NetworkManager/NetworkManagerJsonRpc.cpp @@ -217,7 +217,7 @@ namespace WPEFramework LOGINFOMETHOD(); uint32_t rc = Core::ERROR_GENERAL; string interface = parameters["interface"].String(); - bool enabled = parameters["enable"].Boolean(); + bool enabled = parameters["enabled"].Boolean(); if (_NetworkManager) rc = _NetworkManager->SetInterfaceState(interface, enabled); else diff --git a/NetworkManager/NetworkManagerLogger.cpp b/NetworkManager/NetworkManagerLogger.cpp index 3432b75705..9ea3b9d534 100644 --- a/NetworkManager/NetworkManagerLogger.cpp +++ b/NetworkManager/NetworkManagerLogger.cpp @@ -83,7 +83,7 @@ namespace NetworkManagerLogger { gettimeofday(&tv, NULL); lt = localtime(&tv.tv_sec); - printf("%.2d:%.2d:%.2d.%.6lld %-10s %s:%d : %s\n", lt->tm_hour, lt->tm_min, lt->tm_sec, (long long int)tv.tv_usec, levelMap[level], func, line, formattedLog); + printf("%.2d:%.2d:%.2d.%.6lld %-10s %s:%d : %s\n", lt->tm_hour, lt->tm_min, lt->tm_sec, (long long int)tv.tv_usec, levelMap[level], basename(file), line, formattedLog); fflush(stdout); #endif } diff --git a/NetworkManager/NetworkManagerRDKProxy.cpp b/NetworkManager/NetworkManagerRDKProxy.cpp index 97bf449d3c..b98d99cc1e 100644 --- a/NetworkManager/NetworkManagerRDKProxy.cpp +++ b/NetworkManager/NetworkManagerRDKProxy.cpp @@ -657,7 +657,7 @@ namespace WPEFramework return rc; } - iarmData.isInterfaceEnabled = true; + iarmData.isInterfaceEnabled = enable; iarmData.persist = true; if (IARM_RESULT_SUCCESS == IARM_Bus_Call (IARM_BUS_NM_SRV_MGR_NAME, IARM_BUS_NETSRVMGR_API_setInterfaceEnabled, (void *)&iarmData, sizeof(iarmData))) { @@ -671,7 +671,7 @@ namespace WPEFramework return rc; } - uint32_t NetworkManagerImplementation::GetInterfaceState(const string& interface/* @in */, bool& isEnabled /* @out */) + uint32_t NetworkManagerImplementation::GetInterfaceState(const string& interface/* @in */, bool &isEnabled /* @out */) { LOG_ENTRY_FUNCTION(); uint32_t rc = Core::ERROR_RPC_CALL_FAILED; @@ -689,11 +689,10 @@ namespace WPEFramework return rc; } - iarmData.isInterfaceEnabled = false; - iarmData.persist = true; - if (IARM_RESULT_SUCCESS == IARM_Bus_Call (IARM_BUS_NM_SRV_MGR_NAME, IARM_BUS_NETSRVMGR_API_setInterfaceEnabled, (void *)&iarmData, sizeof(iarmData))) + if (IARM_RESULT_SUCCESS == IARM_Bus_Call (IARM_BUS_NM_SRV_MGR_NAME, IARM_BUS_NETSRVMGR_API_isInterfaceEnabled, (void *)&iarmData, sizeof(iarmData))) { - NMLOG_INFO ("Call to %s for %s success", IARM_BUS_NM_SRV_MGR_NAME, IARM_BUS_NETSRVMGR_API_setInterfaceEnabled); + NMLOG_TRACE("Call to %s for %s success", IARM_BUS_NM_SRV_MGR_NAME, IARM_BUS_NETSRVMGR_API_isInterfaceEnabled); + isEnabled = iarmData.isInterfaceEnabled; rc = Core::ERROR_NONE; } else diff --git a/NetworkManager/NetworkManagerTimer.h b/NetworkManager/NetworkManagerTimer.h new file mode 100644 index 0000000000..5fbeea3524 --- /dev/null +++ b/NetworkManager/NetworkManagerTimer.h @@ -0,0 +1,132 @@ +/** +* If not stated otherwise in this file or this component's LICENSE +* file the following copyright and licenses apply: +* +* Copyright 2020 RDK Management +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +**/ + +namespace WPEFramework { + + namespace Plugin { + class NetworkManagerTimer { + private: + class NetworkManagerTimerJob { + private: + NetworkManagerTimerJob() = delete; + NetworkManagerTimerJob& operator=(const NetworkManagerTimerJob& RHS) = delete; + + public: + NetworkManagerTimerJob(NetworkManagerTimer* tpt) + : m_tptimer(tpt) + { + } + NetworkManagerTimerJob(const NetworkManagerTimerJob& copy) + : m_tptimer(copy.m_tptimer) + { + } + ~NetworkManagerTimerJob() {} + + inline bool operator==(const NetworkManagerTimerJob& RHS) const + { + return (m_tptimer == RHS.m_tptimer); + } + + public: + uint64_t Timed(const uint64_t scheduledTime) + { + if (m_tptimer) { + m_tptimer->Timed(); + } + return 0; + } + + private: + NetworkManagerTimer* m_tptimer; + }; + + public: + NetworkManagerTimer() + : baseTimer(64 * 1024, "TimerUtility") + , m_timerJob(this) + , m_isActive(false) + , m_isSingleShot(false) + , m_intervalInMs(-1) + { + } + ~NetworkManagerTimer() + { + stop(); + } + + bool isActive() + { + return m_isActive; + } + void stop() + { + baseTimer.Revoke(m_timerJob); + m_isActive = false; + } + void start() + { + baseTimer.Revoke(m_timerJob); + baseTimer.Schedule(Core::Time::Now().Add(m_intervalInMs), m_timerJob); + m_isActive = true; + } + void start(int msec) + { + setInterval(msec); + start(); + } + void setSingleShot(bool val) + { + m_isSingleShot = val; + } + void setInterval(int msec) + { + m_intervalInMs = msec; + } + + void connect(std::function callback) + { + onTimeoutCallback = callback; + } + + private: + void Timed() + { + if (onTimeoutCallback != nullptr) { + onTimeoutCallback(); + } + + if (m_isActive) { + if (m_isSingleShot) { + stop(); + } else { + start(); + } + } + } + + WPEFramework::Core::TimerType baseTimer; + NetworkManagerTimerJob m_timerJob; + bool m_isActive; + bool m_isSingleShot; + int m_intervalInMs; + + std::function onTimeoutCallback; + }; + } +} diff --git a/docs/api/NetworkManagerPlugin.md b/docs/api/NetworkManagerPlugin.md index 88b30ccfe1..e924017e39 100644 --- a/docs/api/NetworkManagerPlugin.md +++ b/docs/api/NetworkManagerPlugin.md @@ -2,7 +2,7 @@ # NetworkManager Plugin -**Version: [0.1.0]()** +**Version: [0.2.0]()** A NetworkManager plugin for Thunder framework. @@ -58,6 +58,8 @@ NetworkManager interface methods: | [GetAvailableInterfaces](#method.GetAvailableInterfaces) | Get device supported list of available interface including their state | | [GetPrimaryInterface](#method.GetPrimaryInterface) | Gets the primary/default network interface for the device | | [SetPrimaryInterface](#method.SetPrimaryInterface) | Sets the primary/default interface for the device | +| [SetInterfaceState](#method.SetInterfaceState) | Enable the interface | +| [GetInterfaceState](#method.GetInterfaceState) | Disable the interface | | [GetIPSettings](#method.GetIPSettings) | Gets the IP setting for the given interface | | [SetIPSettings](#method.SetIPSettings) | Sets the IP settings for the given interface | | [GetStunEndpoint](#method.GetStunEndpoint) | Get the STUN Endpoint that is used to identify public IP of the device | @@ -84,8 +86,6 @@ NetworkManager interface methods: | [GetWiFiSignalStrength](#method.GetWiFiSignalStrength) | Get WiFiSignalStrength of connected SSID | | [GetSupportedSecurityModes](#method.GetSupportedSecurityModes) | Returns the Wifi security modes that the device supports | | [SetLogLevel](#method.SetLogLevel) | Set Log level for more information | -| [EnableInterface](#method.EnableInterface) | Enable the interface | -| [DisableInterface](#method.DisableInterface) | Disable the interface | | [GetWifiState](#method.GetWifiState) | Returns the current Wifi State | @@ -247,6 +247,112 @@ Sets the primary/default interface for the device. This call fails if the interf } ``` + +## *SetInterfaceState [method](#head.Methods)* + +Enable or Disable the specified interface. + +### Events + +| Event | Description | +| :-------- | :-------- | +| [onInterfaceStateChange](#event.onInterfaceStateChange) | Triggered when interface’s status changes to enabled or disabled. | + +### Parameters + +| Name | Type | Description | +| :-------- | :-------- | :-------- | +| params | object | | +| params.interface | string | An interface, such as `eth0` or `wlan0`, depending upon availability of the given interface in `GetAvailableInterfaces` | +| params.enabled | boolean | Set the state of the interface to be Enabled or Disabled | + +### Result + +| Name | Type | Description | +| :-------- | :-------- | :-------- | +| result | object | | +| result.success | boolean | Whether the request succeeded | + +### Example + +#### Request + +```json +{ + "jsonrpc": "2.0", + "id": 42, + "method": "org.rdk.NetworkManager.SetInterfaceState", + "params": { + "interface": "wlan0", + "enabled": true + } +} +``` + +#### Response + +```json +{ + "jsonrpc": "2.0", + "id": 42, + "result": { + "success": true + } +} +``` + + +## *GetInterfaceState [method](#head.Methods)* + +Disable the specified interface. + +### Events + +No Events + +### Parameters + +| Name | Type | Description | +| :-------- | :-------- | :-------- | +| params | object | | +| params.interface | string | An interface, such as `eth0` or `wlan0`, depending upon availability of the given interface in `GetAvailableInterfaces` | + +### Result + +| Name | Type | Description | +| :-------- | :-------- | :-------- | +| result | object | | +| result.isEnabled | boolean | Whether the Interface is enabled or disabled | +| result.success | boolean | Whether the request succeeded | + +### Example + +#### Request + +```json +{ + "jsonrpc": "2.0", + "id": 42, + "method": "org.rdk.NetworkManager.GetInterfaceState", + "params": { + "interface": "wlan0" + } +} +``` + +#### Response + +```json +{ + "jsonrpc": "2.0", + "id": 42, + "result": { + "isEnabled": true, + "success": true + } +} +``` + ## *GetIPSettings [method](#head.Methods)* @@ -1696,110 +1802,6 @@ No Events } ``` - -## *EnableInterface [method](#head.Methods)* - -Enable the specified interface. - -### Events - -| Event | Description | -| :-------- | :-------- | -| [onInterfaceStateChange](#event.onInterfaceStateChange) | Triggered when interface’s status changes to enabled. | - -### Parameters - -| Name | Type | Description | -| :-------- | :-------- | :-------- | -| params | object | | -| params.interface | string | An interface, such as `eth0` or `wlan0`, depending upon availability of the given interface in `GetAvailableInterfaces` | - -### Result - -| Name | Type | Description | -| :-------- | :-------- | :-------- | -| result | object | | -| result.success | boolean | Whether the request succeeded | - -### Example - -#### Request - -```json -{ - "jsonrpc": "2.0", - "id": 42, - "method": "org.rdk.NetworkManager.EnableInterface", - "params": { - "interface": "wlan0" - } -} -``` - -#### Response - -```json -{ - "jsonrpc": "2.0", - "id": 42, - "result": { - "success": true - } -} -``` - - -## *DisableInterface [method](#head.Methods)* - -Disable the specified interface. - -### Events - -| Event | Description | -| :-------- | :-------- | -| [onInterfaceStateChange](#event.onInterfaceStateChange) | Triggered when interface’s status changes to disabled. | - -### Parameters - -| Name | Type | Description | -| :-------- | :-------- | :-------- | -| params | object | | -| params.interface | string | An interface, such as `eth0` or `wlan0`, depending upon availability of the given interface in `GetAvailableInterfaces` | - -### Result - -| Name | Type | Description | -| :-------- | :-------- | :-------- | -| result | object | | -| result.success | boolean | Whether the request succeeded | - -### Example - -#### Request - -```json -{ - "jsonrpc": "2.0", - "id": 42, - "method": "org.rdk.NetworkManager.DisableInterface", - "params": { - "interface": "wlan0" - } -} -``` - -#### Response - -```json -{ - "jsonrpc": "2.0", - "id": 42, - "result": { - "success": true - } -} -``` - ## *GetWifiState [method](#head.Methods)* From 98c29845b59d59280d62a9c2fa840cdfec11607f Mon Sep 17 00:00:00 2001 From: gururaajar <83449026+gururaajar@users.noreply.github.com> Date: Mon, 3 Jun 2024 14:36:41 -0400 Subject: [PATCH 07/21] DELIA-65343 : Devices went to offline plui state after the initial change (#5375) * DELIA-65343 : Devices went to offline plui state after the initial change Reason for change: Updated with review comments Test Procedure: Do CDL and confirm the device boots up in online state Risks: Low Priority: P1 Signed-off-by: Gururaaja ESR --- NetworkManager/LegacyPlugin_NetworkAPIs.cpp | 10 ++++++---- NetworkManager/LegacyPlugin_WiFiManagerAPIs.cpp | 10 ++++++---- docs/api/NetworkPlugin.md | 2 +- docs/api/WifiPlugin.md | 2 +- 4 files changed, 14 insertions(+), 10 deletions(-) diff --git a/NetworkManager/LegacyPlugin_NetworkAPIs.cpp b/NetworkManager/LegacyPlugin_NetworkAPIs.cpp index 153857c09b..71dd8f33e6 100644 --- a/NetworkManager/LegacyPlugin_NetworkAPIs.cpp +++ b/NetworkManager/LegacyPlugin_NetworkAPIs.cpp @@ -26,6 +26,7 @@ using namespace WPEFramework::Plugin; #define API_VERSION_NUMBER_MINOR 0 #define API_VERSION_NUMBER_PATCH 0 #define NETWORK_MANAGER_CALLSIGN "org.rdk.NetworkManager.1" +#define SUBSCRIPTION_TIMEOUT_IN_MILLISECONDS 5000 #define LOGINFOMETHOD() { string json; parameters.ToString(json); NMLOG_TRACE("Legacy params=%s", json.c_str() ); } #define LOGTRACEMETHODFIN() { string json; response.ToString(json); NMLOG_TRACE("Legacy response=%s", json.c_str() ); } @@ -117,13 +118,13 @@ namespace WPEFramework reinterpret_cast(payload.c_str()), token) == Core::ERROR_NONE) { - std::cout << "DisplaySettings got security token" << std::endl; + NMLOG_TRACE("Network plugin got security token"); } else { - std::cout << "DisplaySettings failed to get security token" << std::endl; + NMLOG_WARNING("Network plugin failed to get security token"); } security->Release(); } else { - std::cout << "No security agent" << std::endl; + NMLOG_INFO("Network plugin: No security agent"); } string query = "token=" + token; @@ -148,7 +149,7 @@ namespace WPEFramework Core::SystemInfo::SetEnvironment(_T("THUNDER_ACCESS"), (_T("127.0.0.1:9998"))); m_networkmanager = make_shared >(_T(NETWORK_MANAGER_CALLSIGN), _T(NETWORK_MANAGER_CALLSIGN), false, query); - m_timer.start(5000); + m_timer.start(SUBSCRIPTION_TIMEOUT_IN_MILLISECONDS); return string(); } @@ -776,6 +777,7 @@ const string CIDR_PREFIXES[CIDR_NETMASK_IP_LEN] = { uint32_t errCode = Core::ERROR_GENERAL; if (m_networkmanager) { + /** ToDo: Don't subscribe for other events when one of the event subscription fails **/ errCode = m_networkmanager->Subscribe(1000, _T("onInterfaceStateChange"), &Network::onInterfaceStateChange); if (errCode != Core::ERROR_NONE) { diff --git a/NetworkManager/LegacyPlugin_WiFiManagerAPIs.cpp b/NetworkManager/LegacyPlugin_WiFiManagerAPIs.cpp index 0ab3abac67..7c6a7c044f 100644 --- a/NetworkManager/LegacyPlugin_WiFiManagerAPIs.cpp +++ b/NetworkManager/LegacyPlugin_WiFiManagerAPIs.cpp @@ -26,6 +26,7 @@ using namespace WPEFramework::Plugin; #define API_VERSION_NUMBER_MINOR 0 #define API_VERSION_NUMBER_PATCH 0 #define NETWORK_MANAGER_CALLSIGN "org.rdk.NetworkManager.1" +#define SUBSCRIPTION_TIMEOUT_IN_MILLISECONDS 5000 #define LOGINFOMETHOD() { string json; parameters.ToString(json); NMLOG_TRACE("Legacy params=%s", json.c_str() ); } #define LOGTRACEMETHODFIN() { string json; response.ToString(json); NMLOG_TRACE("Legacy response=%s", json.c_str() ); } @@ -116,13 +117,13 @@ namespace WPEFramework reinterpret_cast(payload.c_str()), token) == Core::ERROR_NONE) { - std::cout << "DisplaySettings got security token" << std::endl; + NMLOG_TRACE("WiFi manager plugin got security token"); } else { - std::cout << "DisplaySettings failed to get security token" << std::endl; + NMLOG_WARNING("WiFi manager plugin failed to get security token"); } security->Release(); } else { - std::cout << "No security agent" << std::endl; + NMLOG_INFO("WiFi manager plugin: No security agent"); } string query = "token=" + token; @@ -146,7 +147,7 @@ namespace WPEFramework Core::SystemInfo::SetEnvironment(_T("THUNDER_ACCESS"), (_T("127.0.0.1:9998"))); m_networkmanager = make_shared >(_T(NETWORK_MANAGER_CALLSIGN), _T(NETWORK_MANAGER_CALLSIGN), false, query); - m_timer.start(5000); + m_timer.start(SUBSCRIPTION_TIMEOUT_IN_MILLISECONDS); return string(); } @@ -490,6 +491,7 @@ namespace WPEFramework void WiFiManager::subscribeToEvents(void) { uint32_t errCode = Core::ERROR_GENERAL; + /** ToDo: Don't subscribe for other events when one of the event subscription fails **/ if (m_networkmanager) { errCode = m_networkmanager->Subscribe(1000, _T("onWiFiStateChange"), &WiFiManager::onWiFiStateChange); diff --git a/docs/api/NetworkPlugin.md b/docs/api/NetworkPlugin.md index 712d656fdc..fb1f572372 100644 --- a/docs/api/NetworkPlugin.md +++ b/docs/api/NetworkPlugin.md @@ -1,5 +1,5 @@ - +(Deprecated) # NetworkPlugin **Version: [1.3.9](https://github.com/rdkcentral/rdkservices/blob/main/Network/CHANGELOG.md)** diff --git a/docs/api/WifiPlugin.md b/docs/api/WifiPlugin.md index 5fc91c5afa..4ff21e0162 100644 --- a/docs/api/WifiPlugin.md +++ b/docs/api/WifiPlugin.md @@ -1,5 +1,5 @@ - +(Deprecated) # Wifi Plugin **Version: [1.0.9](https://github.com/rdkcentral/rdkservices/blob/main/WifiManager/CHANGELOG.md)** From 0d84c36f63213299d0b1d6316b2a0ef911817a65 Mon Sep 17 00:00:00 2001 From: Mateusz Daniluk <121170681+VeithMetro@users.noreply.github.com> Date: Tue, 4 Jun 2024 15:48:36 +0200 Subject: [PATCH 08/21] [WebKitBrowser] CookieJar updated to 2.42 WebKit API (#5326) Co-authored-by: emutavchi --- WebKitBrowser/WebKitImplementation.cpp | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/WebKitBrowser/WebKitImplementation.cpp b/WebKitBrowser/WebKitImplementation.cpp index c46d3db6eb..c21337fa64 100644 --- a/WebKitBrowser/WebKitImplementation.cpp +++ b/WebKitBrowser/WebKitImplementation.cpp @@ -1466,9 +1466,13 @@ static GSourceFuncs _handlerIntervention = #ifdef WEBKIT_GLIB_API WebKitWebContext* context = webkit_web_view_get_context(_view); WebKitCookieManager* manager = webkit_web_context_get_cookie_manager(context); +#if WEBKIT_CHECK_VERSION(2, 42, 0) + webkit_cookie_manager_get_all_cookies(manager, NULL, [](GObject* object, GAsyncResult* result, gpointer user_data) { + GList* cookies_list = webkit_cookie_manager_get_all_cookies_finish(WEBKIT_COOKIE_MANAGER(object), result, nullptr); +#else webkit_cookie_manager_get_cookie_jar(manager, NULL, [](GObject* object, GAsyncResult* result, gpointer user_data) { GList* cookies_list = webkit_cookie_manager_get_cookie_jar_finish(WEBKIT_COOKIE_MANAGER(object), result, nullptr); - +#endif std::vector cookieVector; cookieVector.reserve(g_list_length(cookies_list)); for (GList* it = cookies_list; it != NULL; it = g_list_next(it)) { @@ -1584,8 +1588,11 @@ static GSourceFuncs _handlerIntervention = WebKitWebContext* context = webkit_web_view_get_context(_view); WebKitCookieManager* manager = webkit_web_context_get_cookie_manager(context); +#if WEBKIT_CHECK_VERSION(2, 42, 0) + webkit_cookie_manager_replace_cookies(manager, g_list_reverse(cookies_list), nullptr, nullptr, nullptr); +#else webkit_cookie_manager_set_cookie_jar(manager, g_list_reverse(cookies_list), nullptr, nullptr, nullptr); - +#endif g_list_free_full(cookies_list, reinterpret_cast(soup_cookie_free)); #else auto toWKCookie = [](SoupCookie* cookie) -> WKCookieRef From 3237958d5fdeda4ea721605ba7f5691a6379cb8e Mon Sep 17 00:00:00 2001 From: RAFI <103924677+cmuhammedrafi@users.noreply.github.com> Date: Tue, 4 Jun 2024 20:25:16 +0530 Subject: [PATCH 09/21] DELIA-65419: Delay in providing 'oninternetstatuschange' event from Network Thunder Plugin (#5374) DELIA-65419: Update no internet event logic in both Network and NetworkManager --- Network/NetworkConnectivity.cpp | 3 ++- NetworkManager/NetworkManagerConnectivity.cpp | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/Network/NetworkConnectivity.cpp b/Network/NetworkConnectivity.cpp index 4ebf0b03df..58effcb677 100644 --- a/Network/NetworkConnectivity.cpp +++ b/Network/NetworkConnectivity.cpp @@ -577,7 +577,8 @@ namespace WPEFramework { if(g_internetState.load() != InternetConnectionState) { LOGINFO("notification count %d ...", notifyWaitCount); - if(InternetConnectionState == nsm_internetState::NO_INTERNET && notifyWaitCount > 0) + /* Retry logic only need when continuous monitor is running, otherwise post notification immediately */ + if(InternetConnectionState == nsm_internetState::NO_INTERNET && isContinuesMonitoringNeeded && notifyWaitCount > 0) { /* Decrease the notification count to create a delay in posting the 'no internet' state. */ notifyWaitCount--; diff --git a/NetworkManager/NetworkManagerConnectivity.cpp b/NetworkManager/NetworkManagerConnectivity.cpp index 2c925b7788..12713f47cd 100644 --- a/NetworkManager/NetworkManagerConnectivity.cpp +++ b/NetworkManager/NetworkManagerConnectivity.cpp @@ -509,7 +509,7 @@ namespace WPEFramework { if(g_internetState.load() != InternetConnectionState) { NMLOG_TRACE("notification count %d ", notifyWaitCount); - if(InternetConnectionState == nsm_internetState::NO_INTERNET && notifyWaitCount > 0) + if(InternetConnectionState == nsm_internetState::NO_INTERNET && isContinuesMonitoringNeeded && notifyWaitCount > 0) { /* Decrease the notification count to create a delay in posting the 'no internet' state. */ notifyWaitCount--; From 6ce5f785a46bb6b7461f326f75e01e2ebd501ad3 Mon Sep 17 00:00:00 2001 From: smohap466 Date: Wed, 5 Jun 2024 13:07:50 +0530 Subject: [PATCH 10/21] Warehouse L2Test Usecase Scenarios --- .github/workflows/L2-tests.yml | 5 +- Tests/L2Tests/L2TestsPlugin/CMakeLists.txt | 1 + .../L2TestsPlugin/tests/Telemetry_L2Test.cpp | 9 - .../L2TestsPlugin/tests/UsbAccess_L2Test.cpp | 12 +- .../L2TestsPlugin/tests/Warehouse_L2Test.cpp | 1055 +++++++++++++++++ Warehouse/CMakeLists.txt | 10 + l2tests.cmake | 5 +- 7 files changed, 1080 insertions(+), 17 deletions(-) create mode 100644 Tests/L2Tests/L2TestsPlugin/tests/Warehouse_L2Test.cpp diff --git a/.github/workflows/L2-tests.yml b/.github/workflows/L2-tests.yml index 17fe99466d..2692c5c702 100755 --- a/.github/workflows/L2-tests.yml +++ b/.github/workflows/L2-tests.yml @@ -229,6 +229,7 @@ jobs: -DCMAKE_DISABLE_FIND_PACKAGE_RBus=ON -DPLUGIN_SYSTEMSERVICES=ON -DPLUGIN_TELEMETRY=ON + -DPLUGIN_WAREHOUSE=ON -DPLUGIN_HDCPPROFILE=ON -DPLUGIN_NETWORK=ON -DPLUGIN_TEXTTOSPEECH=ON @@ -256,6 +257,7 @@ jobs: /run/media/sda2/logs/PreviousLogs /run/sda1/UsbTestFWUpdate /run/sda1/UsbProdFWUpdate + /run/media/sda1/Logs /run/sda2 && sudo touch @@ -272,7 +274,8 @@ jobs: /run/media/sda1/logs/test.png /run/media/sda1/logs/test.docx /run/media/sda2/logs/test.txt - /run/media/sda2/logs/test.png + /run/media/sda2/logs/test.png + /run/media/sda1/Logs/5C3400F15492_Logs_12-05-22-10-41PM.tgz /run/sda1/HSTP11MWR_5.11p5s1_VBN_sdy.bin /run/sda1/UsbTestFWUpdate/HSTP11MWR_3.11p5s1_VBN_sdy.bin /run/sda1/UsbProdFWUpdate/HSTP11MWR_4.11p5s1_VBN_sdy.bin diff --git a/Tests/L2Tests/L2TestsPlugin/CMakeLists.txt b/Tests/L2Tests/L2TestsPlugin/CMakeLists.txt index a7150f382b..bd64143f80 100755 --- a/Tests/L2Tests/L2TestsPlugin/CMakeLists.txt +++ b/Tests/L2Tests/L2TestsPlugin/CMakeLists.txt @@ -28,6 +28,7 @@ add_library(${MODULE_NAME} SHARED tests/SystemService_L2Test.cpp tests/UsbAccess_L2Test.cpp tests/Telemetry_L2Test.cpp + tests/Warehouse_L2Test.cpp tests/VerifyContracts.cpp) set_target_properties(${MODULE_NAME} PROPERTIES diff --git a/Tests/L2Tests/L2TestsPlugin/tests/Telemetry_L2Test.cpp b/Tests/L2Tests/L2TestsPlugin/tests/Telemetry_L2Test.cpp index db54a3afd2..9e6456ed4b 100644 --- a/Tests/L2Tests/L2TestsPlugin/tests/Telemetry_L2Test.cpp +++ b/Tests/L2Tests/L2TestsPlugin/tests/Telemetry_L2Test.cpp @@ -285,7 +285,6 @@ JSONRPC::LinkType jsonrpc(TELEMETRY_CALLSIGN, TELEMETRYL2T JsonObject result; std::string message; JsonObject expected_status; - uint32_t signalled = TELEMETRYL2TEST_STATE_INVALID; /* Without params and with Params as "No status" expecting Fail case*/ status = InvokeServiceMethod("org.rdk.Telemetry.1", "setReportProfileStatus", params, result); @@ -343,7 +342,6 @@ TEST_F(Telemetry_L2test, TelemetrylogApplicationEvent){ JsonObject result; std::string message; JsonObject expected_status; - uint32_t signalled = TELEMETRYL2TEST_STATE_INVALID; /* Without params expecting Fail case*/ status = InvokeServiceMethod("org.rdk.Telemetry.1", "logApplicationEvent", params, result); @@ -384,7 +382,6 @@ TEST_F(Telemetry_L2test, TelemetryAbortReport){ JsonObject result; std::string message; JsonObject expected_status; - uint32_t signalled = TELEMETRYL2TEST_STATE_INVALID; struct _rbusObject rbObject; status = InvokeServiceMethod("org.rdk.Telemetry.1", "abortReport", params, result); @@ -451,8 +448,6 @@ TEST_F(Telemetry_L2test, TelemetryImplementationMock){ JsonObject result; std::string message; JsonObject expected_status; - uint32_t signalled = TELEMETRYL2TEST_STATE_INVALID; - struct _rbusObject rbObject; EXPECT_CALL(*p_telemetryApiImplMock, t2_init(::testing::_)) @@ -520,8 +515,6 @@ TEST_F(Telemetry_L2test, TelemetryRbusOpeningErrorCheck){ JsonObject result; std::string message; JsonObject expected_status; - uint32_t signalled = TELEMETRYL2TEST_STATE_INVALID; - struct _rbusObject rbObject; EXPECT_CALL(*p_rBusApiImplMock, rbus_open(::testing::_, ::testing::_)) .Times(2) @@ -563,9 +556,7 @@ TEST_F(Telemetry_L2test, TelemetryReportUploadErrorCheck){ JsonObject result; std::string message; JsonObject expected_status; - uint32_t signalled = TELEMETRYL2TEST_STATE_INVALID; struct _rbusObject rbObject; - struct _rbusValue rbValue; ON_CALL(*p_rBusApiImplMock, rbus_open(::testing::_, ::testing::_)) .WillByDefault( diff --git a/Tests/L2Tests/L2TestsPlugin/tests/UsbAccess_L2Test.cpp b/Tests/L2Tests/L2TestsPlugin/tests/UsbAccess_L2Test.cpp index f5feb519af..5763671c6c 100755 --- a/Tests/L2Tests/L2TestsPlugin/tests/UsbAccess_L2Test.cpp +++ b/Tests/L2Tests/L2TestsPlugin/tests/UsbAccess_L2Test.cpp @@ -577,7 +577,7 @@ TEST_F(UsbAccess_L2test,UsbAccessArchiveLogs) static struct mntent entry1; entry1.mnt_fsname = const_cast("/dev/sda1"); - entry1.mnt_dir = const_cast("/run/media/sda1"); + entry1.mnt_dir = const_cast("/run/media/sda1/Logs"); static int callCount = 0; if (callCount == 0) { @@ -596,9 +596,9 @@ TEST_F(UsbAccess_L2test,UsbAccessArchiveLogs) va_copy(args2, args); char strFmt[256]; vsnprintf(strFmt, sizeof(strFmt), command, args2); - va_end(args2); - if (strcmp(strFmt, "/lib/rdk/usbLogUpload.sh /run/media/sda1") == 0) { - valueToReturn = "/run/media/sda1/5C3400F15492_Logs_12-05-22-10-41PM.tgz"; + va_end(args2); + if (strcmp(strFmt, "/lib/rdk/usbLogUpload.sh /run/media/sda1/Logs") == 0) { + valueToReturn = "/run/media/sda1/Logs/5C3400F15492_Logs_12-05-22-10-41PM.tgz"; } if (valueToReturn != NULL) { char buffer[1024]; @@ -626,7 +626,7 @@ TEST_F(UsbAccess_L2test,UsbAccessArchiveLogs) /* Compresses and uploads device logs into attached USB drive */ - params["path"] = "/run/media/sda1"; + params["path"] = "/run/media/sda1/Logs"; params["error"] = "none"; params["success"] = "true"; status = InvokeServiceMethod("org.rdk.UsbAccess.1", "ArchiveLogs", params, result); @@ -635,7 +635,7 @@ TEST_F(UsbAccess_L2test,UsbAccessArchiveLogs) /* Request status for onArchive. */ - message = "{\"error\":\"none\",\"success\":true,\"path\":\"\\/run\\/media\\/sda1\\/5C3400F15492_Logs_12-05-22-10-41PM.tgz\"}"; + message = "{\"error\":\"none\",\"success\":true,\"path\":\"\\/run\\/media\\/sda1\\/Logs\\/5C3400F15492_Logs_12-05-22-10-41PM.tgz\"}"; expected_status.FromString(message); EXPECT_CALL(async_handler, onArchiveLogs(MatchRequestStatus(expected_status))) .WillOnce(Invoke(this, &UsbAccess_L2test::onArchiveLogs)); diff --git a/Tests/L2Tests/L2TestsPlugin/tests/Warehouse_L2Test.cpp b/Tests/L2Tests/L2TestsPlugin/tests/Warehouse_L2Test.cpp new file mode 100644 index 0000000000..2b3984b114 --- /dev/null +++ b/Tests/L2Tests/L2TestsPlugin/tests/Warehouse_L2Test.cpp @@ -0,0 +1,1055 @@ +#include +#include +#include "L2Tests.h" +#include "L2TestsMock.h" +#include +#include +#include + +#define JSON_TIMEOUT (1000) +#define TEST_LOG(x, ...) fprintf(stderr, "\033[1;32m[%s:%d](%s)" x "\n\033[0m", __FILE__, __LINE__, __FUNCTION__, getpid(), gettid(), ##__VA_ARGS__); fflush(stderr); +#define WAREHOUSE_CALLSIGN _T("org.rdk.Warehouse.1") +#define WAREHOUSEL2TEST_CALLSIGN _T("L2tests.1") + +using ::testing::NiceMock; +using namespace WPEFramework; +using testing::StrictMock; + +typedef enum : uint32_t { + WAREHOUSEL2TEST_RESETDONE= 0x00000001, + WAREHOUSEL2TEST_STATE_INVALID = 0x00000000 +}WarehouseL2test_async_events_t; + +/** + * @brief Internal test mock class + * + * Note that this is for internal test use only and doesn't mock any actual + * concrete interface. + */ + +class AsyncHandlerMock_Warehouse +{ + public: + AsyncHandlerMock_Warehouse () + { + } + + MOCK_METHOD(void, resetDone, (const JsonObject &message)); +}; + +/* WareHouse L2 test class declaration */ +class Warehouse_L2Test : public L2TestMocks { + protected: + Core::JSONRPC::Message message; + string response; + IARM_EventHandler_t whMgrStatusChangeEventsHandler = nullptr; + + virtual ~Warehouse_L2Test() override; + + public: + Warehouse_L2Test(); + void resetDone(const JsonObject &message); + /** + * @brief waits for various status change on asynchronous calls + */ + uint32_t WaitForRequestStatus(uint32_t timeout_ms,WarehouseL2test_async_events_t expected_status); + + private: + /** @brief Mutex */ + std::mutex m_mutex; + + /** @brief Condition variable */ + std::condition_variable m_condition_variable; + + /** @brief Event signalled flag */ + uint32_t m_event_signalled; +}; + +/** + * @brief Constructor for WareHouse L2 test class + */ +Warehouse_L2Test::Warehouse_L2Test() + : L2TestMocks() +{ + uint32_t status = Core::ERROR_GENERAL; + m_event_signalled = WAREHOUSEL2TEST_STATE_INVALID; + + ON_CALL(*p_iarmBusImplMock, IARM_Bus_RegisterEventHandler(::testing::_, ::testing::_, ::testing::_)) + .WillByDefault(::testing::Invoke( + [&](const char* ownerName, IARM_EventId_t eventId, IARM_EventHandler_t handler) { + if ((string(IARM_BUS_PWRMGR_NAME) == string(ownerName)) && (eventId == IARM_BUS_PWRMGR_EVENT_WAREHOUSEOPS_STATUSCHANGED)) { + whMgrStatusChangeEventsHandler = handler; + } + return IARM_RESULT_SUCCESS; + })); + + /* Activate plugin in constructor */ + status = ActivateService("org.rdk.Warehouse"); + EXPECT_EQ(Core::ERROR_NONE, status); +} + +/** + * @brief Destructor for WareHouse L2 test class + */ +Warehouse_L2Test:: ~Warehouse_L2Test() +{ + uint32_t status = Core::ERROR_GENERAL; + m_event_signalled = WAREHOUSEL2TEST_STATE_INVALID; + + /* Deactivate plugin in destructor */ + status = DeactivateService("org.rdk.Warehouse"); + EXPECT_EQ(Core::ERROR_NONE, status); +} + +/** + * @brief called when resetDone + * notification received from IARM + * + * @param[in] message from WareHouse on the change + */ +void Warehouse_L2Test::resetDone(const JsonObject &message) +{ + TEST_LOG("resetDone event triggered ***\n"); + std::unique_lock lock(m_mutex); + + std::string str; + message.ToString(str); + + TEST_LOG("resetDone received: %s\n", str.c_str()); + + /* Notify the requester thread. */ + m_event_signalled |= WAREHOUSEL2TEST_RESETDONE; + m_condition_variable.notify_one(); +} + +/** + * @brief waits for various status change on asynchronous calls + * + * @param[in] timeout_ms timeout for waiting + */ +uint32_t Warehouse_L2Test::WaitForRequestStatus(uint32_t timeout_ms,WarehouseL2test_async_events_t expected_status) +{ + std::unique_lock lock(m_mutex); + auto now = std::chrono::system_clock::now(); + std::chrono::milliseconds timeout(timeout_ms); + uint32_t signalled = WAREHOUSEL2TEST_STATE_INVALID; + + while (!(expected_status & m_event_signalled)) + { + if (m_condition_variable.wait_until(lock, now + timeout) == std::cv_status::timeout) + { + TEST_LOG("Timeout waiting for request status event"); + break; + } + } + + signalled = m_event_signalled; + + return signalled; +} + +/** + * @brief Compare two request status objects + * + * @param[in] data Expected value + * @return true if the argument and data match, false otherwise + */ +MATCHER_P(MatchRequestStatus, data, "") +{ + bool match = true; + std::string expected; + std::string actual; + + data.ToString(expected); + arg.ToString(actual); + TEST_LOG(" rec = %s, arg = %s",expected.c_str(),actual.c_str()); + EXPECT_STREQ(expected.c_str(),actual.c_str()); + + return match; +} + +/******************************************************** +************Test case Details ************************** +** 1. Triggered resetDevice Method +** 2. Verify the response of resetDevice Method +** 3. Subscribe and Triggered resetDone Event +** 3. Verify the event resetDone getting triggered +*******************************************************/ + +TEST_F(Warehouse_L2Test,Warehouse_ResetDone) +{ + JSONRPC::LinkType jsonrpc(WAREHOUSE_CALLSIGN,WAREHOUSEL2TEST_CALLSIGN ); + StrictMock async_handler; + uint32_t status = Core::ERROR_GENERAL; + JsonObject params; + JsonObject result; + uint32_t signalled = WAREHOUSEL2TEST_STATE_INVALID; + std::string message; + JsonObject expected_status; + + status = InvokeServiceMethod("org.rdk.Warehouse.1", "resetDevice", params, result); + EXPECT_EQ(Core::ERROR_NONE, status); + EXPECT_TRUE(result["success"].Boolean()); + + EXPECT_CALL(*p_iarmBusImplMock, IARM_Bus_Call) + .Times(6) + .WillOnce( + [](const char* ownerName, const char* methodName, void* arg, size_t argLen) { + EXPECT_EQ(string(ownerName), string(_T(IARM_BUS_PWRMGR_NAME))); + EXPECT_EQ(string(methodName), string(IARM_BUS_PWRMGR_API_WareHouseClear)); + return IARM_RESULT_SUCCESS; + }) + .WillOnce( + [](const char* ownerName, const char* methodName, void* arg, size_t argLen) { + EXPECT_EQ(string(ownerName), string(_T(IARM_BUS_PWRMGR_NAME))); + EXPECT_EQ(string(methodName), string(IARM_BUS_PWRMGR_API_FactoryReset)); + return IARM_RESULT_SUCCESS; + }) + .WillOnce( + [](const char* ownerName, const char* methodName, void* arg, size_t argLen) { + EXPECT_EQ(string(ownerName), string(_T(IARM_BUS_PWRMGR_NAME))); + EXPECT_EQ(string(methodName), string(IARM_BUS_PWRMGR_API_WareHouseClear)); + return IARM_RESULT_SUCCESS; + }) + .WillOnce( + [](const char* ownerName, const char* methodName, void* arg, size_t argLen) { + EXPECT_EQ(string(ownerName), string(_T(IARM_BUS_PWRMGR_NAME))); + EXPECT_EQ(string(methodName), string(IARM_BUS_PWRMGR_API_ColdFactoryReset)); + return IARM_RESULT_SUCCESS; + }) + .WillOnce( + [](const char* ownerName, const char* methodName, void* arg, size_t argLen) { + EXPECT_EQ(string(ownerName), string(_T(IARM_BUS_PWRMGR_NAME))); + EXPECT_EQ(string(methodName), string(IARM_BUS_PWRMGR_API_UserFactoryReset)); + return IARM_RESULT_SUCCESS; + }) + .WillOnce( + [](const char* ownerName, const char* methodName, void* arg, size_t argLen) { + EXPECT_EQ(string(ownerName), string(_T(IARM_BUS_PWRMGR_NAME))); + EXPECT_EQ(string(methodName), string(IARM_BUS_PWRMGR_API_UserFactoryReset)); + //Return error for the Negative test case + return IARM_RESULT_INVALID_PARAM; + }); + + /* errorCode and errorDescription should not be set */ + EXPECT_FALSE(result.HasLabel("errorCode")); + EXPECT_FALSE(result.HasLabel("errorDescription")); + + /* Register for resetDone event. */ + status = jsonrpc.Subscribe(JSON_TIMEOUT, + _T("resetDone"), + &AsyncHandlerMock_Warehouse::resetDone, + &async_handler); + EXPECT_EQ(Core::ERROR_NONE, status); + + message = "{\"success\":true}"; + expected_status.FromString(message); + EXPECT_CALL(async_handler, resetDone(MatchRequestStatus(expected_status))) + .WillOnce(Invoke(this, &Warehouse_L2Test::resetDone)); + + IARM_BUS_PWRMgr_WareHouseOpn_EventData_t eventData = {IARM_BUS_PWRMGR_WAREHOUSE_RESET, IARM_BUS_PWRMGR_WAREHOUSE_COMPLETED}; + whMgrStatusChangeEventsHandler(IARM_BUS_PWRMGR_NAME, IARM_BUS_PWRMGR_EVENT_WAREHOUSEOPS_STATUSCHANGED, &eventData, 0); + + /* resetDevice method takes 2 parameters with different Inputs as + * "suppressReboot = true" & "resetType = WAREHOUSE_CLEAR" + * WareHouseResetIARM: WAREHOUSE_CLEAR reset... + * resetDeviceWrapper: response={"success":true} + */ + params["suppressReboot"] = "true"; + params["resetType"] = "WAREHOUSE_CLEAR"; + status = InvokeServiceMethod("org.rdk.Warehouse.1", "resetDevice", params, result); + EXPECT_EQ(Core::ERROR_NONE, status); + EXPECT_TRUE(result["success"].Boolean()); + + /* "suppressReboot = true" & "resetType = FACTORY" + * resetDeviceWrapper: response={"success":true} + * WareHouseResetIARM: FACTORY reset... + * WareHouseResetIARM: Notify resetDone {"success":true} + */ + params["suppressReboot"] = "true"; + params["resetType"] = "FACTORY"; + status = InvokeServiceMethod("org.rdk.Warehouse.1", "resetDevice", params, result); + EXPECT_EQ(Core::ERROR_NONE, status); + EXPECT_TRUE(result["success"].Boolean()); + + message = "{\"success\":true}"; + expected_status.FromString(message); + EXPECT_CALL(async_handler, resetDone(MatchRequestStatus(expected_status))) + .WillOnce(Invoke(this, &Warehouse_L2Test::resetDone)) + .WillOnce(Invoke(this, &Warehouse_L2Test::resetDone)); + + /* suppressReboot = "false" & "resetType = "WAREHOUSE_CLEAR" + * WareHouseResetIARM: WAREHOUSE_CLEAR reset... + * resetDeviceWrapper: response={"success":true} + * WareHouseResetIARM: Notify resetDone {"success":true} + */ + + params["suppressReboot"] = "false"; + params["resetType"] = "WAREHOUSE_CLEAR"; + status = InvokeServiceMethod("org.rdk.Warehouse.1", "resetDevice", params, result); + EXPECT_EQ(Core::ERROR_NONE, status); + EXPECT_TRUE(result["success"].Boolean()); + + /* suppressReboot = "true" & "resetType = "COLD" + * WareHouseResetIARM: COLD reset... + * resetDeviceWrapper: response={"success":true} + * WareHouseResetIARM: Notify resetDone {"success":true} + */ + params["suppressReboot"] = "true"; + params["resetType"] = "COLD"; + status = InvokeServiceMethod("org.rdk.Warehouse.1", "resetDevice", params, result); + EXPECT_EQ(Core::ERROR_NONE, status); + EXPECT_TRUE(result["success"].Boolean()); + + message = "{\"success\":true}"; + expected_status.FromString(message); + EXPECT_CALL(async_handler, resetDone(MatchRequestStatus(expected_status))) + .WillOnce(Invoke(this, &Warehouse_L2Test::resetDone)) + .WillOnce(Invoke(this, &Warehouse_L2Test::resetDone)); + + /* suppressReboot = "true" & "resetType = "USERFACTORY" + * WareHouseResetIARM: USERFACTORY reset... + * resetDeviceWrapper: response={"success":true} + * WareHouseResetIARM: Notify resetDone {"success":true} + */ + params["suppressReboot"] = "true"; + params["resetType"] = "USERFACTORY"; + status = InvokeServiceMethod("org.rdk.Warehouse.1", "resetDevice", params, result); + EXPECT_EQ(Core::ERROR_NONE, status); + EXPECT_TRUE(result["success"].Boolean()); + + message = "{\"success\":false,\"error\":\"Reset failed\"}"; + expected_status.FromString(message); + EXPECT_CALL(async_handler, resetDone(MatchRequestStatus(expected_status))) + .WillOnce(Invoke(this, &Warehouse_L2Test::resetDone)); + + /* suppressReboot = "true" & resetType = "USERFACTORY" + * WareHouseResetIARM: USERFACTORY reset... + * WareHouseResetIARM: IARM_RESULT_INVALID_PARAM [invalid input parameter] + * Notify resetDone {"success":false,"error":"Reset failed"} + */ + params["suppressReboot"] = "true"; + params["resetType"] = "USERFACTORY"; + status = InvokeServiceMethod("org.rdk.Warehouse.1", "resetDevice", params, result); + EXPECT_EQ(Core::ERROR_NONE, status); + EXPECT_TRUE(result["success"].Boolean()); + + signalled = WaitForRequestStatus(JSON_TIMEOUT,WAREHOUSEL2TEST_RESETDONE); + EXPECT_TRUE(signalled & WAREHOUSEL2TEST_RESETDONE); + + /* Unregister for events. */ + jsonrpc.Unsubscribe(JSON_TIMEOUT, _T("resetDone")); +} + + +/******************************************************** +************Test case Details ************************** +** 1. Triggered lightReset Method +** 2. Verify the response of lightReset Method +*******************************************************/ + +TEST_F(Warehouse_L2Test,Warehouse_LightReset) +{ + JSONRPC::LinkType jsonrpc(WAREHOUSE_CALLSIGN,WAREHOUSEL2TEST_CALLSIGN ); + StrictMock async_handler; + uint32_t status = Core::ERROR_GENERAL; + JsonObject params; + JsonObject result; + std::string message; + JsonObject expected_status; + + status = InvokeServiceMethod("org.rdk.Warehouse.1", "lightReset", params, result); + EXPECT_EQ(Core::ERROR_NONE, status); + EXPECT_FALSE(result["success"].Boolean()); + + EXPECT_CALL(*p_iarmBusImplMock, IARM_Bus_Call) + .Times(2) + .WillOnce( + [](const char* ownerName, const char* methodName, void* arg, size_t argLen) { + EXPECT_EQ(string(ownerName), string(_T(IARM_BUS_SYSMGR_NAME))); + if (string(methodName) == string(_T(IARM_BUS_SYSMGR_API_RunScript))) + { + auto* runScriptParam = static_cast(arg); + runScriptParam->return_value = -1; + } + return IARM_RESULT_SUCCESS; + }) + .WillOnce( + [](const char* ownerName, const char* methodName, void* arg, size_t argLen) { + EXPECT_EQ(string(ownerName), string(_T(IARM_BUS_SYSMGR_NAME))); + if (string(methodName) == string(_T(IARM_BUS_SYSMGR_API_RunScript))) + { + auto* runScriptParam = static_cast(arg); + runScriptParam->return_value = 0; + EXPECT_EQ(string(runScriptParam->script_path), string("rm -rf /opt/netflix/* /opt/QT/home/data/* /opt/hn_service_settings.conf /opt/apps/common/proxies.conf /opt/lib/bluetooth /opt/persistent/rdkservicestore")); + } + return IARM_RESULT_SUCCESS; + }); + + /* errorCode and errorDescription should not be set */ + EXPECT_FALSE(result.HasLabel("errorCode")); + EXPECT_FALSE(result.HasLabel("errorDescription")); + + /* lightReset method takes no parameters + lightReset: lightReset failed. script returned: -1 */ + status = InvokeServiceMethod("org.rdk.Warehouse.1", "lightReset", params, result); + EXPECT_EQ(Core::ERROR_NONE, status); + EXPECT_FALSE(result["success"].Boolean()); + + // lightReset: lightReset succeeded + status = InvokeServiceMethod("org.rdk.Warehouse.1", "lightReset", params, result); + EXPECT_EQ(Core::ERROR_NONE, status); + EXPECT_TRUE(result["success"].Boolean()); +} + +/******************************************************** +************Test case Details ************************** +** 1. Triggered getHardwareTestResults Method +** 2. Verify the response of getHardwareTestResults Method +** 3. Triggered executeHardwareTest Method +** 4. Verify the response of executeHardwareTest Method +*******************************************************/ + +TEST_F(Warehouse_L2Test,Warehouse_getHardwareTestResults_executeHardwareTest) +{ + JSONRPC::LinkType jsonrpc(WAREHOUSE_CALLSIGN,WAREHOUSEL2TEST_CALLSIGN ); + StrictMock async_handler; + uint32_t status = Core::ERROR_GENERAL; + JsonObject params; + JsonObject result; + std::string message; + JsonObject expected_status; + + EXPECT_CALL(*p_rfcApiImplMock, getRFCParameter(::testing::_, ::testing::_, ::testing::_)) + .Times(1) + .WillOnce(::testing::Invoke( + [](char* pcCallerID, const char* pcParameterName, RFC_ParamData_t* pstParamData) { + EXPECT_EQ(string(pcCallerID), string("Warehouse")); + EXPECT_EQ(string(pcParameterName), string("Device.DeviceInfo.X_RDKCENTRAL-COM_xOpsDeviceMgmt.hwHealthTest.Results")); + strncpy(pstParamData->value, "test", sizeof(pstParamData->value)); + return WDMP_SUCCESS; + })); + + EXPECT_CALL(*p_rfcApiImplMock, setRFCParameter(::testing::_, ::testing::_, ::testing::_, ::testing::_)) + .Times(1) + .WillOnce(::testing::Invoke( + [](char* pcCallerID, const char* pcParameterName, const char* pcParameterValue, DATA_TYPE eDataType) { + EXPECT_EQ(string(pcCallerID), _T("Warehouse")); + EXPECT_EQ(string(pcParameterName), _T("Device.DeviceInfo.X_RDKCENTRAL-COM_RFC.Feature.hwHealthTest.Enable")); + EXPECT_EQ(string(pcParameterValue), _T("false")); + EXPECT_EQ(eDataType, WDMP_BOOLEAN); + return WDMP_SUCCESS; + })); + + //getHardwareTestResultsWrapper: response={"testResults":"test","success":true} + params["testResults"] = ""; + status = InvokeServiceMethod("org.rdk.Warehouse.1", "getHardwareTestResults", params, result); + EXPECT_EQ(Core::ERROR_NONE, status); + EXPECT_TRUE(result["success"].Boolean()); + EXPECT_STREQ("test", result["testResults"].String().c_str()); + + EXPECT_CALL(*p_rfcApiImplMock, setRFCParameter(::testing::_, ::testing::_, ::testing::_, ::testing::_)) + .Times(2) + .WillOnce(::testing::Invoke( + [](char* pcCallerID, const char* pcParameterName, const char* pcParameterValue, DATA_TYPE eDataType) { + EXPECT_EQ(string(pcCallerID), _T("Warehouse")); + EXPECT_EQ(string(pcParameterName), _T("Device.DeviceInfo.X_RDKCENTRAL-COM_RFC.Feature.hwHealthTest.Enable")); + EXPECT_EQ(string(pcParameterValue), _T("true")); + EXPECT_EQ(eDataType, WDMP_BOOLEAN); + return WDMP_SUCCESS; + })) + .WillOnce(::testing::Invoke( + [](char* pcCallerID, const char* pcParameterName, const char* pcParameterValue, DATA_TYPE eDataType) { + EXPECT_EQ(string(pcCallerID), _T("Warehouse")); + EXPECT_EQ(string(pcParameterName), _T("Device.DeviceInfo.X_RDKCENTRAL-COM_xOpsDeviceMgmt.hwHealthTest.ExecuteTest")); + EXPECT_EQ(string(pcParameterValue), _T("1")); + EXPECT_EQ(eDataType, WDMP_INT); + return WDMP_SUCCESS; + })); + + //executeHardwareTestWrapper: response={"success":true} + params["testResults"] = ""; + status = InvokeServiceMethod("org.rdk.Warehouse.1", "executeHardwareTest", params, result); + EXPECT_EQ(Core::ERROR_NONE, status); + EXPECT_TRUE(result["success"].Boolean()); + EXPECT_STREQ("true", result["success"].String().c_str()); + + EXPECT_CALL(*p_rfcApiImplMock, getRFCParameter(::testing::_, ::testing::_, ::testing::_)) + .Times(1) + .WillOnce(::testing::Invoke( + [](char* pcCallerID, const char* pcParameterName, RFC_ParamData_t* pstParamData) { + EXPECT_EQ(string(pcCallerID), string("Warehouse")); + EXPECT_EQ(string(pcParameterName), string("Device.DeviceInfo.X_RDKCENTRAL-COM_xOpsDeviceMgmt.hwHealthTest.Results")); + strncpy(pstParamData->value, "test", sizeof(pstParamData->value)); + return WDMP_SUCCESS; + })); + EXPECT_CALL(*p_rfcApiImplMock, setRFCParameter(::testing::_, ::testing::_, ::testing::_, ::testing::_)) + .Times(1) + .WillOnce(::testing::Invoke( + [](char* pcCallerID, const char* pcParameterName, const char* pcParameterValue, DATA_TYPE eDataType) { + EXPECT_EQ(string(pcCallerID), _T("Warehouse")); + EXPECT_EQ(string(pcParameterName), _T("Device.DeviceInfo.X_RDKCENTRAL-COM_RFC.Feature.hwHealthTest.Enable")); + EXPECT_EQ(string(pcParameterValue), _T("false")); + EXPECT_EQ(eDataType, WDMP_BOOLEAN); + return WDMP_SUCCESS; + })); + + //getHardwareTestResultsWrapper: response={"testResults":"test","success":true} + params["testResults"] = "Timezone: NA 2021-04-15 10:35:06 Test execution start, remote trigger ver. 0011 2021-04-15 10:35:10 Test result: Audio/Video Decoder:PASSED 2021-04-15 10:35:06 Test result: Dynamic RAM:PASSED 2021-04-15 10:35:06 Test result: Flash Memory:PASSED 2021-04-15 10:35:06 Test result: HDMI Output:PASSED 2021-04-15 10:35:38 Test result: IR Remote Interface:WARNING_IR_Not_Detected 2021-04-15 10:35:06 Test result: Bluetooth:PASSED 2021-04-15 10:35:06 Test result: SD Card:PASSED 2021-04-15 10:35:06 Test result: WAN:PASSED 2021-04-15 10:35:38 Test execution completed:PASSED"; + status = InvokeServiceMethod("org.rdk.Warehouse.1", "getHardwareTestResults", params, result); + EXPECT_EQ(Core::ERROR_NONE, status); + EXPECT_TRUE(result["success"].Boolean()); + EXPECT_STREQ("test", result["testResults"].String().c_str()); + +} + +/******************************************************** +************Test case Details ************************** +** 1. Triggered getDeviceInfo Method +** 2. Verify the response of getDeviceInfo Method +*******************************************************/ + +// To access this below Declared functions "__real_popen" & "__real_pclose "from other files +extern "C" FILE* __real_popen(const char* command, const char* type); +extern "C" int __real_pclose(FILE* pipe); + +TEST_F(Warehouse_L2Test,Warehouse_getdeviceInfo) +{ + JSONRPC::LinkType jsonrpc(WAREHOUSE_CALLSIGN,WAREHOUSEL2TEST_CALLSIGN ); + StrictMock async_handler; + uint32_t status = Core::ERROR_GENERAL; + JsonObject params; + JsonObject result; + std::string message; + JsonObject expected_status; + + + status = InvokeServiceMethod("org.rdk.Warehouse.1", "getDeviceInfo", params, result); + EXPECT_EQ(Core::ERROR_NONE, status); + EXPECT_TRUE(result["success"].Boolean()); + + const string deviceInfoScript = _T("/lib/rdk/getDeviceDetails.sh"); + const uint8_t deviceInfoContent[] = "echo \"bluetooth_mac=12:34:56:78:90:AB\n" + "boxIP=192.168.1.0\n" + "build_type=VBN\n" + "estb_mac=12:34:56:78:90:AB\n" + "eth_mac=12:34:56:78:90:AB\n" + "friendly_id=Abc XYZ\n" + "imageVersion=ABCADS_VBN_2022010101sdy__MH_SPLASH_TEST_2\n" + "model_number=ABC123ADS\n" + "wifi_mac=12:34:56:78:90:AB\"\n"; + + ON_CALL(*p_wrapsImplMock, popen(::testing::_, ::testing::_)) + .WillByDefault(::testing::Invoke( + [&](const char* command, const char* type) -> FILE* { + EXPECT_EQ(string(command), string(_T("sh /lib/rdk/getDeviceDetails.sh read"))); + return __real_popen(command, type); + })); + ON_CALL(*p_wrapsImplMock, pclose(::testing::_)) + .WillByDefault(::testing::Invoke( + [&](FILE* pipe){ + return __real_pclose(pipe); + })); + + //Create fake device info script & Invoke getDeviceInfo + Core::File file(deviceInfoScript); + file.Create(); + //file.Open(false); + file.Write(deviceInfoContent, sizeof(deviceInfoContent)); + + status = InvokeServiceMethod("org.rdk.Warehouse.1", "getDeviceInfo", params, result); + EXPECT_EQ(Core::ERROR_NONE, status); + EXPECT_TRUE(result["success"].Boolean()); + + file.Destroy(); + +} + +/******************************************************** +************Test case Details ************************** +** 1. Triggered internalReset Method +** 2. Verify the response of internalReset Method +*******************************************************/ + +TEST_F(Warehouse_L2Test, Warehouse_internalReset) +{ + JSONRPC::LinkType jsonrpc(WAREHOUSE_CALLSIGN,WAREHOUSEL2TEST_CALLSIGN ); + StrictMock async_handler; + uint32_t status = Core::ERROR_GENERAL; + JsonObject params; + JsonObject result; + std::string message; + JsonObject expected_status; + + //Invoke internalReset - No pass phrase + status = InvokeServiceMethod("org.rdk.Warehouse.1", "internalReset", params, result); + EXPECT_EQ(Core::ERROR_GENERAL, status); + EXPECT_FALSE(result["success"].Boolean()); + + //Invoke internalReset - Incorrect pass phrase + params["passPhrase"] = "Incorrect pass phrase"; + status = InvokeServiceMethod("org.rdk.Warehouse.1", "internalReset", params, result); + EXPECT_EQ(Core::ERROR_GENERAL, status); + EXPECT_FALSE(result["success"].Boolean()); + + EXPECT_CALL(*p_iarmBusImplMock, IARM_Bus_Call) + .Times(2) + .WillOnce( + [](const char* ownerName, const char* methodName, void* arg, size_t argLen) { + EXPECT_EQ(string(ownerName), string(_T(IARM_BUS_SYSMGR_NAME))); + if (string(methodName) == string(_T(IARM_BUS_SYSMGR_API_RunScript))) + { + auto* runScriptParam = static_cast(arg); + runScriptParam->return_value = -1; + } + return IARM_RESULT_SUCCESS; + }) + .WillOnce( + [](const char* ownerName, const char* methodName, void* arg, size_t argLen) { + EXPECT_EQ(string(ownerName), string(_T(IARM_BUS_SYSMGR_NAME))); + if (string(methodName) == string(_T(IARM_BUS_SYSMGR_API_RunScript))) + { + auto* runScriptParam = static_cast(arg); + runScriptParam->return_value = 0; + EXPECT_EQ(string(runScriptParam->script_path), string("rm -rf /opt/drm /opt/www/whitebox /opt/www/authService && /rebootNow.sh -s WarehouseService &")); + } + return IARM_RESULT_SUCCESS; + }); + + //Invoke internalReset - correct pass phrase - script Failure + params["passPhrase"] = "FOR TEST PURPOSES ONLY"; + status = InvokeServiceMethod("org.rdk.Warehouse.1", "internalReset", params, result); + EXPECT_EQ(Core::ERROR_NONE, status); + EXPECT_FALSE(result["success"].Boolean()); + EXPECT_STREQ("script returned: -1", result["error"].String().c_str()); + + //Invoke internalReset - Correct pass phrase - Return success + params["passPhrase"] = "FOR TEST PURPOSES ONLY"; + status = InvokeServiceMethod("org.rdk.Warehouse.1", "internalReset", params, result); + EXPECT_EQ(Core::ERROR_NONE, status); + EXPECT_TRUE(result["success"].Boolean()); +} + +/******************************************************** +************Test case Details ************************** +** 1. Triggered isClean Method +** 2. Verify the response of isClean Method +*******************************************************/ + +TEST_F(Warehouse_L2Test,Warehouse_iscleanTest) +{ + JSONRPC::LinkType jsonrpc(WAREHOUSE_CALLSIGN,WAREHOUSEL2TEST_CALLSIGN ); + StrictMock async_handler; + uint32_t status = Core::ERROR_GENERAL; + JsonObject params; + JsonObject result; + std::string message; + JsonObject expected_status; + + const string userPrefFile = _T("/opt/user_preferences.conf"); + const uint8_t userPrefLang[] = "[General]\nui_language=US_en\n"; + const string customDataFile = _T("/lib/rdk/wh_api_5.conf"); + const uint8_t customDataFileContent[] = "[files]\n/opt/user_preferences.conf\n"; + + //No conf file + status = InvokeServiceMethod("org.rdk.Warehouse.1", "isClean", params, result); + EXPECT_EQ(Core::ERROR_NONE, status); + EXPECT_FALSE(result["success"].Boolean()); + EXPECT_FALSE(result["clean"].Boolean()); + EXPECT_STREQ("[]", result["files"].String().c_str()); + + //Empty conf file + Core::File fileConf(customDataFile); + Core::Directory(fileConf.PathName().c_str()).CreatePath(); + fileConf.Create(); + + params["age"]=300; + status = InvokeServiceMethod("org.rdk.Warehouse.1", "isClean", params, result); + EXPECT_EQ(Core::ERROR_NONE, status); + EXPECT_FALSE(result["success"].Boolean()); + EXPECT_FALSE(result["clean"].Boolean()); + EXPECT_STREQ("[]", result["files"].String().c_str()); + + //Create empty conf file + fileConf.Write(customDataFileContent, sizeof(customDataFileContent)); + + params["age"]=300; + status = InvokeServiceMethod("org.rdk.Warehouse.1", "isClean", params, result); + EXPECT_EQ(Core::ERROR_NONE, status); + EXPECT_TRUE(result["success"].Boolean()); + EXPECT_TRUE(result["clean"].Boolean()); + EXPECT_STREQ("[]", result["files"].String().c_str()); + + //Add test data to conf file + Core::File filePref(userPrefFile); + Core::Directory(filePref.PathName().c_str()).CreatePath(); + filePref.Create(); + filePref.Open(); + filePref.Write(userPrefLang, sizeof(userPrefLang)); + + params["age"]=-4; + status = InvokeServiceMethod("org.rdk.Warehouse.1", "isClean", params, result); + EXPECT_EQ(Core::ERROR_NONE, status); + EXPECT_TRUE(result["success"].Boolean()); + EXPECT_FALSE(result["clean"].Boolean()); + EXPECT_STREQ("[\"\\/opt\\/user_preferences.conf\"]", result["files"].String().c_str()); + + fileConf.Destroy(); + filePref.Destroy(); +} + +/******************************************************** +************Test case Details ************************** +** 1. TEST_F to achieve max. Lcov +** 2. Used p_rfcApiImplMock To enable RFC_PWRMGR2 & p_wrapsImplMock for systemcall +** 3. Triggered & Verify the resetDevice Method with params (suppressReboot=TRUE, resetType=COLD) +*******************************************************/ +TEST_F(Warehouse_L2Test,Warehouse_Cold_Factory_PwrMgr2RFCEnabled) +{ + JSONRPC::LinkType jsonrpc(WAREHOUSE_CALLSIGN,WAREHOUSEL2TEST_CALLSIGN ); + StrictMock async_handler; + uint32_t status = Core::ERROR_GENERAL; + JsonObject params; + JsonObject result; + std::string message; + JsonObject expected_status; + + + /* Deactivate plugin in TEST_F*/ + status = DeactivateService("org.rdk.Warehouse"); + EXPECT_EQ(Core::ERROR_NONE, status); + + ON_CALL(*p_rfcApiImplMock, getRFCParameter(::testing::_, ::testing::_, ::testing::_)) + .WillByDefault(::testing::Invoke( + [](char* pcCallerID, const char* pcParameterName, RFC_ParamData_t* pstParamData) { + pstParamData->type = WDMP_BOOLEAN; + strncpy(pstParamData->value, "true", sizeof((pstParamData->value))); + //strncpy(pstParamData->value, "true", 4); + EXPECT_EQ(string(pstParamData->value), _T("true")); + return WDMP_SUCCESS; + })); + + /* Activate plugin in TEST_F*/ + status = ActivateService("org.rdk.Warehouse"); + EXPECT_EQ(Core::ERROR_NONE, status); + + EXPECT_CALL(*p_wrapsImplMock, system(::testing::_)) + .Times(4) + .WillOnce(::testing::Invoke( + [](const char* command) { + EXPECT_EQ(string(command), string("sh /lib/rdk/deviceReset.sh coldfactory")); + return Core::ERROR_NONE; + })) + .WillRepeatedly(::testing::Return(Core::ERROR_NONE)); + + params["suppressReboot"] = "true"; + params["resetType"] = "COLD"; + status = InvokeServiceMethod("org.rdk.Warehouse.1", "resetDevice", params, result); + EXPECT_EQ(Core::ERROR_NONE, status); + EXPECT_TRUE(result["success"].Boolean()); +} + +/******************************************************** +************Test case Details ************************** +** 1. TEST_F to achieve max. Lcov +** 2. Used p_rfcApiImplMock To enable RFC_PWRMGR2 & p_wrapsImplMock for systemcall +** 3. Triggered & Verify the resetDevice Method with params (suppressReboot=TRUE, resetType=FACTORY) +*******************************************************/ +TEST_F(Warehouse_L2Test,Warehouse_Factory_ResetDevice_PwrMgr2RFCEnabled) +{ + JSONRPC::LinkType jsonrpc(WAREHOUSE_CALLSIGN,WAREHOUSEL2TEST_CALLSIGN ); + StrictMock async_handler; + uint32_t status = Core::ERROR_GENERAL; + JsonObject params; + JsonObject result; + std::string message; + JsonObject expected_status; + + /* Deactivate plugin in TEST_F*/ + status = DeactivateService("org.rdk.Warehouse"); + EXPECT_EQ(Core::ERROR_NONE, status); + + ON_CALL(*p_rfcApiImplMock, getRFCParameter(::testing::_, ::testing::_, ::testing::_)) + .WillByDefault(::testing::Invoke( + [](char* pcCallerID, const char* pcParameterName, RFC_ParamData_t* pstParamData) { + pstParamData->type = WDMP_BOOLEAN; + strncpy(pstParamData->value, "true", sizeof((pstParamData->value))); + EXPECT_EQ(string(pstParamData->value), _T("true")); + return WDMP_SUCCESS; + })); + + /* Activate plugin in TEST_F*/ + status = ActivateService("org.rdk.Warehouse"); + EXPECT_EQ(Core::ERROR_NONE, status); + + EXPECT_CALL(*p_wrapsImplMock, system(::testing::_)) + .Times(3) + .WillOnce(::testing::Invoke( + [](const char* command) { + EXPECT_EQ(string(command), string("sh /lib/rdk/deviceReset.sh factory")); + return Core::ERROR_NONE; + })) + .WillRepeatedly(::testing::Return(Core::ERROR_NONE)); + + params["suppressReboot"] = "true"; + params["resetType"] = "FACTORY"; + status = InvokeServiceMethod("org.rdk.Warehouse.1", "resetDevice", params, result); + EXPECT_EQ(Core::ERROR_NONE, status); + EXPECT_TRUE(result["success"].Boolean()); +} + +/******************************************************** +************Test case Details ************************** +** 1. TEST_F to achieve max. Lcov +** 2. Used p_rfcApiImplMock To enable RFC_PWRMGR2 & p_wrapsImplMock for systemcall +** 3. Triggered & Verify the resetDevice Method with params (suppressReboot=TRUE, resetType=USERFACTORY) +*******************************************************/ + +TEST_F(Warehouse_L2Test,Warehouse_UserFactory_ResetDevice_PwrMgr2RFCEnabled) +{ + JSONRPC::LinkType jsonrpc(WAREHOUSE_CALLSIGN,WAREHOUSEL2TEST_CALLSIGN ); + StrictMock async_handler; + uint32_t status = Core::ERROR_GENERAL; + JsonObject params; + JsonObject result; + std::string message; + JsonObject expected_status; + + /* Deactivate plugin in TEST_F*/ + status = DeactivateService("org.rdk.Warehouse"); + EXPECT_EQ(Core::ERROR_NONE, status); + + ON_CALL(*p_rfcApiImplMock, getRFCParameter(::testing::_, ::testing::_, ::testing::_)) + .WillByDefault(::testing::Invoke( + [](char* pcCallerID, const char* pcParameterName, RFC_ParamData_t* pstParamData) { + pstParamData->type = WDMP_BOOLEAN; + strncpy(pstParamData->value, "true", sizeof((pstParamData->value))); + EXPECT_EQ(string(pstParamData->value), _T("true")); + return WDMP_SUCCESS; + })); + + /* Activate plugin in TEST_F*/ + status = ActivateService("org.rdk.Warehouse"); + EXPECT_EQ(Core::ERROR_NONE, status); + + EXPECT_CALL(*p_wrapsImplMock, system(::testing::_)) + .Times(3) + .WillOnce(::testing::Return(Core::ERROR_NONE)) + .WillOnce(::testing::Return(Core::ERROR_NONE)) + .WillOnce(::testing::Invoke( + [](const char* command) { + EXPECT_EQ(string(command), string("sh /lib/rdk/deviceReset.sh userfactory")); + return Core::ERROR_NONE; + })); + + params["suppressReboot"] = "true"; + params["resetType"] = "USERFACTORY"; + status = InvokeServiceMethod("org.rdk.Warehouse.1", "resetDevice", params, result); + EXPECT_EQ(Core::ERROR_NONE, status); + EXPECT_TRUE(result["success"].Boolean()); +} + +/******************************************************** +************Test case Details ************************** +** 1. TEST_F to achieve max. Lcov +** 2. Used p_rfcApiImplMock To enable RFC_PWRMGR2 & p_wrapsImplMock for systemcall +** 3. Triggered & Verify the resetDevice Method with params (suppressReboot=FALSE, resetType=WAREHOUSE_CLEAR) +*******************************************************/ + +TEST_F(Warehouse_L2Test,Warehouse_False_Clear_ResetDevice_PwrMgr2RFCEnabled) +{ + JSONRPC::LinkType jsonrpc(WAREHOUSE_CALLSIGN,WAREHOUSEL2TEST_CALLSIGN ); + StrictMock async_handler; + uint32_t status = Core::ERROR_GENERAL; + JsonObject params; + JsonObject result; + std::string message; + JsonObject expected_status; + + /* Deactivate plugin in TEST_F*/ + status = DeactivateService("org.rdk.Warehouse"); + EXPECT_EQ(Core::ERROR_NONE, status); + + ON_CALL(*p_rfcApiImplMock, getRFCParameter(::testing::_, ::testing::_, ::testing::_)) + .WillByDefault(::testing::Invoke( + [](char* pcCallerID, const char* pcParameterName, RFC_ParamData_t* pstParamData) { + pstParamData->type = WDMP_BOOLEAN; + strncpy(pstParamData->value, "true", sizeof((pstParamData->value))); + //strncpy(pst ParamData->value, "true", 4); + EXPECT_EQ(string(pstParamData->value), _T("true")); + return WDMP_SUCCESS; + })); + + /* Activate plugin in TEST_F*/ + status = ActivateService("org.rdk.Warehouse"); + EXPECT_EQ(Core::ERROR_NONE, status); + + EXPECT_CALL(*p_wrapsImplMock, system(::testing::_)) + .Times(4) + .WillOnce(::testing::Return(Core::ERROR_NONE)) + .WillOnce(::testing::Return(Core::ERROR_NONE)) + .WillOnce(::testing::Return(Core::ERROR_NONE)) + .WillOnce(::testing::Invoke( + [](const char* command) { + EXPECT_EQ(string(command), string("sh /lib/rdk/deviceReset.sh WAREHOUSE_CLEAR")); + return Core::ERROR_NONE; + })); + + params["suppressReboot"] = "false"; + params["resetType"] = "WAREHOUSE_CLEAR"; + status = InvokeServiceMethod("org.rdk.Warehouse.1", "resetDevice", params, result); + EXPECT_EQ(Core::ERROR_NONE, status); + EXPECT_TRUE(result["success"].Boolean()); +} + +/******************************************************** +************Test case Details ************************** +** 1. TEST_F to achieve max. Lcov +** 2. Used p_rfcApiImplMock To enable RFC_PWRMGR2 & p_wrapsImplMock for systemcall +** 3. Triggered & Verify the resetDevice Method with params (suppressReboot=TRUE, resetType=WAREHOUSE_CLEAR) +*******************************************************/ + +TEST_F(Warehouse_L2Test,Warehouse_Clear_ResetDevice_PwrMgr2RFCEnabled) +{ + JSONRPC::LinkType jsonrpc(WAREHOUSE_CALLSIGN,WAREHOUSEL2TEST_CALLSIGN ); + StrictMock async_handler; + uint32_t status = Core::ERROR_GENERAL; + JsonObject params; + JsonObject result; + std::string message; + JsonObject expected_status; + + /* Deactivate plugin in TEST_F*/ + status = DeactivateService("org.rdk.Warehouse"); + EXPECT_EQ(Core::ERROR_NONE, status); + + ON_CALL(*p_rfcApiImplMock, getRFCParameter(::testing::_, ::testing::_, ::testing::_)) + .WillByDefault(::testing::Invoke( + [](char* pcCallerID, const char* pcParameterName, RFC_ParamData_t* pstParamData) { + pstParamData->type = WDMP_BOOLEAN; + strncpy(pstParamData->value, "true", sizeof((pstParamData->value))); + EXPECT_EQ(string(pstParamData->value), _T("true")); + return WDMP_SUCCESS; + })); + + /* Activate plugin in TEST_F*/ + status = ActivateService("org.rdk.Warehouse"); + EXPECT_EQ(Core::ERROR_NONE, status); + + EXPECT_CALL(*p_wrapsImplMock, system(::testing::_)) + .Times(2) + .WillOnce(::testing::Return(Core::ERROR_NONE)) + .WillOnce(::testing::Invoke( + [&](const char* command) { + EXPECT_EQ(string(command), string("sh /lib/rdk/deviceReset.sh WAREHOUSE_CLEAR --suppressReboot")); + return Core::ERROR_NONE; + })); + + params["suppressReboot"] = "true"; + params["resetType"] = "WAREHOUSE_CLEAR"; + status = InvokeServiceMethod("org.rdk.Warehouse.1", "resetDevice", params, result); + EXPECT_TRUE(result["success"].Boolean()); +} + +/******************************************************** +************Test case Details ************************** +** 1. TEST_F to achieve max. Lcov +** 2. Used p_rfcApiImplMock To enable RFC_PWRMGR2 & p_wrapsImplMock for systemcall +** 3. Triggered & Verify the resetDevice Method with params (suppressReboot=false, resetType="") +*******************************************************/ + +TEST_F(Warehouse_L2Test,Warehouse_Generic_ResetDevice_PwrMgr2RFCEnabled) +{ + JSONRPC::LinkType jsonrpc(WAREHOUSE_CALLSIGN,WAREHOUSEL2TEST_CALLSIGN ); + StrictMock async_handler; + uint32_t status = Core::ERROR_GENERAL; + JsonObject params; + JsonObject result; + std::string message; + JsonObject expected_status; + + /* Deactivate plugin in TEST_F*/ + status = DeactivateService("org.rdk.Warehouse"); + EXPECT_EQ(Core::ERROR_NONE, status); + + + ON_CALL(*p_rfcApiImplMock, getRFCParameter(::testing::_, ::testing::_, ::testing::_)) + .WillByDefault(::testing::Invoke( + [](char* pcCallerID, const char* pcParameterName, RFC_ParamData_t* pstParamData) { + pstParamData->type = WDMP_BOOLEAN; + strncpy(pstParamData->value, "true", sizeof((pstParamData->value))); + EXPECT_EQ(string(pstParamData->value), _T("true")); + return WDMP_SUCCESS; + })); + + /* Activate plugin in TEST_F*/ + status = ActivateService("org.rdk.Warehouse"); + EXPECT_EQ(Core::ERROR_NONE, status); + + EXPECT_CALL(*p_wrapsImplMock, system(::testing::_)) + .Times(4) + .WillOnce(::testing::Return(Core::ERROR_NONE)) + .WillOnce(::testing::Invoke( + [](const char* command) { + EXPECT_EQ(string(command), string("touch /tmp/.warehouse-reset")); + return Core::ERROR_GENERAL; + })) + .WillOnce(::testing::Return(Core::ERROR_NONE)) + .WillOnce(::testing::Invoke( + [](const char* command) { + EXPECT_EQ(string(command), string("sh /lib/rdk/deviceReset.sh warehouse")); + return Core::ERROR_GENERAL; + })); + params["suppressReboot"] = "false"; + params["resetType"] = ""; + status = InvokeServiceMethod("org.rdk.Warehouse.1", "resetDevice", params, result); + EXPECT_TRUE(result["success"].Boolean()); +} + +/******************************************************** +************Test case Details ************************** +** 1. TEST_F to achieve max. Lcov +** 2. Used p_rfcApiImplMock To enable RFC_PWRMGR2 & p_wrapsImplMock for systemcall +** 3. Triggered & Verify the resetDevice Method with params (suppressReboot=true, resetType="") +*******************************************************/ + +TEST_F(Warehouse_L2Test,Warehouse_UserFactory_ResetDevice_FailurePwrMgr2RFCEnabled) +{ + JSONRPC::LinkType jsonrpc(WAREHOUSE_CALLSIGN,WAREHOUSEL2TEST_CALLSIGN ); + StrictMock async_handler; + uint32_t status = Core::ERROR_GENERAL; + JsonObject params; + JsonObject result; + std::string message; + JsonObject expected_status; + + /* Deactivate plugin in TEST_F*/ + status = DeactivateService("org.rdk.Warehouse"); + EXPECT_EQ(Core::ERROR_NONE, status); + + ON_CALL(*p_rfcApiImplMock, getRFCParameter(::testing::_, ::testing::_, ::testing::_)) + .WillByDefault(::testing::Invoke( + [](char* pcCallerID, const char* pcParameterName, RFC_ParamData_t* pstParamData) { + pstParamData->type = WDMP_BOOLEAN; + strncpy(pstParamData->value, "true", sizeof((pstParamData->value))); + EXPECT_EQ(string(pstParamData->value), _T("true")); + return WDMP_SUCCESS; + })); + + /* Activate plugin in TEST_F*/ + status = ActivateService("org.rdk.Warehouse"); + EXPECT_EQ(Core::ERROR_NONE, status); + + EXPECT_CALL(*p_wrapsImplMock, system(::testing::_)) + .Times(2) + .WillOnce(::testing::Return(Core::ERROR_NONE)) + .WillOnce(::testing::Invoke( + [&](const char* command) { + EXPECT_EQ(string(command), string("sh /lib/rdk/deviceReset.sh warehouse --suppressReboot &")); + return Core::ERROR_NONE; + })); + params["suppressReboot"] = "true"; + params["resetType"] = ""; + status = InvokeServiceMethod("org.rdk.Warehouse.1", "resetDevice", params, result); + EXPECT_TRUE(result["success"].Boolean()); +} \ No newline at end of file diff --git a/Warehouse/CMakeLists.txt b/Warehouse/CMakeLists.txt index 14b7684cd6..64d47ecf43 100644 --- a/Warehouse/CMakeLists.txt +++ b/Warehouse/CMakeLists.txt @@ -33,6 +33,16 @@ set_target_properties(${MODULE_NAME} PROPERTIES CXX_STANDARD 11 CXX_STANDARD_REQUIRED YES) +if (RDK_SERVICE_L2_TEST) + find_library(TESTMOCKLIB_LIBRARIES NAMES TestMocklib) + if (TESTMOCKLIB_LIBRARIES) + message ("linking mock libraries ${TESTMOCKLIB_LIBRARIES} library") + target_link_libraries(${MODULE_NAME} PRIVATE ${TESTMOCKLIB_LIBRARIES}) + else (TESTMOCKLIB_LIBRARIES) + message ("Require ${TESTMOCKLIB_LIBRARIES} library") + endif (TESTMOCKLIB_LIBRARIES) +endif (RDK_SERVICES_L2_TEST) + target_compile_definitions(${MODULE_NAME} PRIVATE MODULE_NAME=Plugin_${PLUGIN_NAME}) set_source_files_properties(Warehouse.cpp ../helpers/frontpanel.cpp PROPERTIES COMPILE_FLAGS "-fexceptions") diff --git a/l2tests.cmake b/l2tests.cmake index ea8a14f699..ad6d11044e 100755 --- a/l2tests.cmake +++ b/l2tests.cmake @@ -45,6 +45,8 @@ set(EMPTY_HEADERS ${BASEDIR}/rdk/iarmmgrs-hal/sysMgr.h ${BASEDIR}/rdk/ds/videoOutputPortConfig.hpp ${BASEDIR}/rdk/ds/sleepMode.hpp + ${BASEDIR}/rdk/ds/frontPanelConfig.hpp + ${BASEDIR}/rdk/ds/frontPanelTextDisplay.hpp ${BASEDIR}/rfcapi.h ${BASEDIR}/rbus.h ${BASEDIR}/systemservices/proc/readproc.h @@ -83,7 +85,7 @@ endforeach () add_compile_options(-Wall -Werror) -add_link_options(-Wl,-wrap,setmntent -Wl,-wrap,getmntent -Wl,-wrap,v_secure_popen -Wl,-wrap,v_secure_pclose -Wl,-wrap,v_secure_system -Wl,-wrap,readlink) +add_link_options(-Wl,-wrap,system -Wl,-wrap,setmntent -Wl,-wrap,getmntent -Wl,-wrap,v_secure_popen -Wl,-wrap,v_secure_pclose -Wl,-wrap,v_secure_system -Wl,-wrap,readlink) add_definitions( -DUSE_IARMBUS @@ -107,6 +109,7 @@ set(CMAKE_DISABLE_FIND_PACKAGE_CEC ON) set(CMAKE_DISABLE_FIND_PACKAGE_Dobby ON) set(CMAKE_DISABLE_FIND_PACKAGE_CEC ON) set(PLUGIN_SYSTEMSERVICES ON) +set(PLUGIN_WAREHOUSE ON) set(PLUGIN_TELEMETRY ON) set(PLUGIN_HDCPPROFILE ON) set(PLUGIN_NETWORK ON) From 128578767459a82d5408a74bbbbcf8d63840411b Mon Sep 17 00:00:00 2001 From: srinibas104 <127204524+srinibas104@users.noreply.github.com> Date: Wed, 5 Jun 2024 14:42:51 +0530 Subject: [PATCH 11/21] Update Warehouse_L2Test.cpp --- Tests/L2Tests/L2TestsPlugin/tests/Warehouse_L2Test.cpp | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/Tests/L2Tests/L2TestsPlugin/tests/Warehouse_L2Test.cpp b/Tests/L2Tests/L2TestsPlugin/tests/Warehouse_L2Test.cpp index 2b3984b114..4e12c39044 100644 --- a/Tests/L2Tests/L2TestsPlugin/tests/Warehouse_L2Test.cpp +++ b/Tests/L2Tests/L2TestsPlugin/tests/Warehouse_L2Test.cpp @@ -318,11 +318,6 @@ TEST_F(Warehouse_L2Test,Warehouse_ResetDone) EXPECT_EQ(Core::ERROR_NONE, status); EXPECT_TRUE(result["success"].Boolean()); - message = "{\"success\":false,\"error\":\"Reset failed\"}"; - expected_status.FromString(message); - EXPECT_CALL(async_handler, resetDone(MatchRequestStatus(expected_status))) - .WillOnce(Invoke(this, &Warehouse_L2Test::resetDone)); - /* suppressReboot = "true" & resetType = "USERFACTORY" * WareHouseResetIARM: USERFACTORY reset... * WareHouseResetIARM: IARM_RESULT_INVALID_PARAM [invalid input parameter] @@ -1052,4 +1047,4 @@ TEST_F(Warehouse_L2Test,Warehouse_UserFactory_ResetDevice_FailurePwrMgr2RFCEnabl params["resetType"] = ""; status = InvokeServiceMethod("org.rdk.Warehouse.1", "resetDevice", params, result); EXPECT_TRUE(result["success"].Boolean()); -} \ No newline at end of file +} From 488a94e80011f2f222fda29ccdfea7a0b93a8fe6 Mon Sep 17 00:00:00 2001 From: srinibas104 <127204524+srinibas104@users.noreply.github.com> Date: Wed, 5 Jun 2024 15:02:42 +0530 Subject: [PATCH 12/21] Warehouse_L2Test.cpp --- Tests/L2Tests/L2TestsPlugin/tests/Warehouse_L2Test.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Tests/L2Tests/L2TestsPlugin/tests/Warehouse_L2Test.cpp b/Tests/L2Tests/L2TestsPlugin/tests/Warehouse_L2Test.cpp index 4e12c39044..f0aed4b8da 100644 --- a/Tests/L2Tests/L2TestsPlugin/tests/Warehouse_L2Test.cpp +++ b/Tests/L2Tests/L2TestsPlugin/tests/Warehouse_L2Test.cpp @@ -318,6 +318,11 @@ TEST_F(Warehouse_L2Test,Warehouse_ResetDone) EXPECT_EQ(Core::ERROR_NONE, status); EXPECT_TRUE(result["success"].Boolean()); + message = "{\"success\":false,\"error\":\"Reset failed\"}"; + expected_status.FromString(message); + EXPECT_CALL(async_handler, resetDone(MatchRequestStatus(expected_status))) + .WillOnce(Invoke(this, &Warehouse_L2Test::resetDone)); + /* suppressReboot = "true" & resetType = "USERFACTORY" * WareHouseResetIARM: USERFACTORY reset... * WareHouseResetIARM: IARM_RESULT_INVALID_PARAM [invalid input parameter] From 3d2b6b63b446fa1ec3ddcc071e176cf266a3897e Mon Sep 17 00:00:00 2001 From: gururaajar <83449026+gururaajar@users.noreply.github.com> Date: Wed, 5 Jun 2024 16:32:02 -0400 Subject: [PATCH 13/21] DELIA-65343 - Fixing the trace method of network manager (#5383) Reason for change: Added the trace ouput details in the Json response object Test Procedure: Run Trace method curl and check Risks: Low Priority: P1 Signed-off-by: Gururaaja ESR --- NetworkManager/NetworkManagerJsonRpc.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/NetworkManager/NetworkManagerJsonRpc.cpp b/NetworkManager/NetworkManagerJsonRpc.cpp index 0271ccf789..9b7ebad3b9 100644 --- a/NetworkManager/NetworkManagerJsonRpc.cpp +++ b/NetworkManager/NetworkManagerJsonRpc.cpp @@ -671,7 +671,10 @@ namespace WPEFramework if (Core::ERROR_NONE == rc) { - response["success"] = true; + JsonObject reply; + reply.FromString(result); + reply["success"] = true; + response = reply; } LOGTRACEMETHODFIN(); return rc; From 24ef215e593ef233b4bcb72303c6421ba685df54 Mon Sep 17 00:00:00 2001 From: Chris Buchter Date: Thu, 6 Jun 2024 18:13:50 -0400 Subject: [PATCH 14/21] SERXIONE-5242: After CDL, reboot device and stuck Reason for change: Crash on init due to ASSERT and uninitialized variable Test Procedure: Test latest and reboot Risks: Low Signed-off-by: Chris Buchter --- MaintenanceManager/CHANGELOG.md | 4 ++++ MaintenanceManager/MaintenanceManager.h | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/MaintenanceManager/CHANGELOG.md b/MaintenanceManager/CHANGELOG.md index 75e24b4c90..08ee56c10c 100644 --- a/MaintenanceManager/CHANGELOG.md +++ b/MaintenanceManager/CHANGELOG.md @@ -16,6 +16,10 @@ All notable changes to this RDK Service will be documented in this file. * For more details, refer to [versioning](https://github.com/rdkcentral/rdkservices#versioning) section under Main README. +## [1.0.36] - 2024-06-06 +### Fixed +- Potential initialization assert due to uninitialized variable + ## [1.0.35] - 2024-05-27 ### Fixed - Delay Unsolicited Maintenance start event in WAI-enabled case diff --git a/MaintenanceManager/MaintenanceManager.h b/MaintenanceManager/MaintenanceManager.h index 5928998e58..f7d5fe8bcb 100644 --- a/MaintenanceManager/MaintenanceManager.h +++ b/MaintenanceManager/MaintenanceManager.h @@ -148,7 +148,7 @@ namespace WPEFramework { std::map m_param_map; std::map m_paramType_map; - PluginHost::IShell* m_service; + PluginHost::IShell* m_service = nullptr; bool isDeviceOnline(); void task_execution_thread(); From b3b14ea7b658c6635006cdd978a9d2cface81929 Mon Sep 17 00:00:00 2001 From: apatel859 Date: Fri, 7 Jun 2024 08:51:17 -0400 Subject: [PATCH 15/21] RDKTV-30790 added retry logic for IARM connect failure Signed-off-by: apatel859 --- helpers/UtilsIarm.h | 33 +++++++++++++++++++++------------ 1 file changed, 21 insertions(+), 12 deletions(-) diff --git a/helpers/UtilsIarm.h b/helpers/UtilsIarm.h index 1d50acafe0..213d6fb8bd 100644 --- a/helpers/UtilsIarm.h +++ b/helpers/UtilsIarm.h @@ -3,6 +3,7 @@ #include "UtilsLogging.h" #include "libIBus.h" +#include #define IARM_CHECK(FUNC) { \ if ((res = FUNC) != IARM_RESULT_SUCCESS) { \ @@ -29,19 +30,27 @@ struct IARM { LOGINFO("IARM already connected"); result = true; } else { - res = IARM_Bus_Init(NAME); - LOGINFO("IARM_Bus_Init: %d", res); - if (res == IARM_RESULT_SUCCESS || res == IARM_RESULT_INVALID_STATE /* already inited or connected */) { - res = IARM_Bus_Connect(); - LOGINFO("IARM_Bus_Connect: %d", res); - if (res == IARM_RESULT_SUCCESS || res == IARM_RESULT_INVALID_STATE /* already connected or not inited */) { - result = isConnected(); + unsigned int retryCount = 0; + do + { + res = IARM_Bus_Init(NAME); + LOGINFO("IARM_Bus_Init: %d", res); + if (res == IARM_RESULT_SUCCESS || res == IARM_RESULT_INVALID_STATE /* already inited or connected */) { + res = IARM_Bus_Connect(); + LOGINFO("IARM_Bus_Connect: %d", res); + if (res == IARM_RESULT_SUCCESS || res == IARM_RESULT_INVALID_STATE /* already connected or not inited */) { + result = isConnected(); + LOGERR("ARM_Bus_Connect result: %d res: %d retryCount :%d ",result, res, retryCount); + } else { + LOGERR("IARM_Bus_Connect failure:result :%d res: %d retryCount :%d ",result, res, retryCount); + } } else { - LOGERR("IARM_Bus_Connect failure: %d", res); + LOGERR("IARM_Bus_Init failure: result :%d res: %d retryCount :%d",result, res,retryCount); } - } else { - LOGERR("IARM_Bus_Init failure: %d", res); - } + + if(result == false) usleep(100000); + + }while((result == false) && (retryCount++ < 20)); } return result; @@ -52,7 +61,7 @@ struct IARM { IARM_Result_t res; int isRegistered = 0; res = IARM_Bus_IsConnected(NAME, &isRegistered); - LOGINFO("IARM_Bus_IsConnected: %d (%d)", res, isRegistered); + LOGINFO("IARM_Bus_IsConnected: res:%d isRegistered (%d)", res, isRegistered); return (isRegistered == 1); } From b9354e163398744d062447d97a3532ad09193f63 Mon Sep 17 00:00:00 2001 From: tabbas651 <74683978+tabbas651@users.noreply.github.com> Date: Mon, 10 Jun 2024 16:37:20 -0400 Subject: [PATCH 16/21] RDK-45352: Upgrade Xumo TV to use Thunder R4.4.1 (#5396) * RDK-45352: Upgrade Xumo TV to use Thunder R4.4.1 Reason for change: ResidentApp plugin unable to activate due to unable to get the Initialize/activating Notification from Thunder(R4.4.1) Test Procedure: Verify in Jenkin Build Risks: High Signed-off-by: Thamim Razith tabbas651@cable.comcast.com * Update RDKShell.h --- RDKShell/RDKShell.cpp | 8 ++++---- RDKShell/RDKShell.h | 14 +++++++++++--- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/RDKShell/RDKShell.cpp b/RDKShell/RDKShell.cpp index a36ac4c078..a23782e5df 100755 --- a/RDKShell/RDKShell.cpp +++ b/RDKShell/RDKShell.cpp @@ -1455,7 +1455,7 @@ namespace WPEFramework { } #ifdef USE_THUNDER_R4 - void RDKShell::MonitorClients::Initialize(VARIABLE_IS_NOT_USED const string& callsign, VARIABLE_IS_NOT_USED PluginHost::IShell* service) + void RDKShell::MonitorClients::Initialize(const string& callsign, PluginHost::IShell* service) { handleInitialize(service); } @@ -1472,10 +1472,10 @@ namespace WPEFramework { //StateChange(service); handleDeactivated(service); } - void RDKShell::MonitorClients::Deinitialized(VARIABLE_IS_NOT_USED const string& callsign, VARIABLE_IS_NOT_USED PluginHost::IShell* service) - { + void RDKShell::MonitorClients::Deinitialized(const string& callsign, PluginHost::IShell* service) + { handleDeinitialized(service); - } + } void RDKShell::MonitorClients::Unavailable(const string& callsign, PluginHost::IShell* service) {} #endif /* USE_THUNDER_R4 */ diff --git a/RDKShell/RDKShell.h b/RDKShell/RDKShell.h index b46e1f8d77..0a6c0c9513 100755 --- a/RDKShell/RDKShell.h +++ b/RDKShell/RDKShell.h @@ -401,7 +401,11 @@ namespace WPEFramework { RDKShell& mShell; }; - class MonitorClients : public PluginHost::IPlugin::INotification { + class MonitorClients : public PluginHost::IPlugin::INotification +#if ((THUNDER_VERSION >= 4) && (THUNDER_VERSION_MINOR >= 4)) + , public PluginHost::IPlugin::ILifeTime +#endif + { private: MonitorClients() = delete; MonitorClients(const MonitorClients&) = delete; @@ -419,6 +423,9 @@ namespace WPEFramework { public: BEGIN_INTERFACE_MAP(MonitorClients) INTERFACE_ENTRY(PluginHost::IPlugin::INotification) +#if ((THUNDER_VERSION >= 4) && (THUNDER_VERSION_MINOR >= 4)) + INTERFACE_ENTRY(PluginHost::IPlugin::ILifeTime) +#endif END_INTERFACE_MAP private: @@ -427,13 +434,14 @@ namespace WPEFramework { void handleActivated(PluginHost::IShell* shell); void handleDeactivated(PluginHost::IShell* shell); void handleDeinitialized(PluginHost::IShell* shell); + #ifdef USE_THUNDER_R4 - virtual void Initialize(VARIABLE_IS_NOT_USED const string& callsign, VARIABLE_IS_NOT_USED PluginHost::IShell* plugin); + virtual void Initialize(const string& callsign, PluginHost::IShell* plugin); virtual void Activation(const string& name, PluginHost::IShell* plugin); virtual void Deactivation(const string& name, PluginHost::IShell* plugin); virtual void Activated(const string& callSign, PluginHost::IShell* plugin); virtual void Deactivated(const string& callSign, PluginHost::IShell* plugin); - virtual void Deinitialized(VARIABLE_IS_NOT_USED const string& callsign, VARIABLE_IS_NOT_USED PluginHost::IShell* plugin); + virtual void Deinitialized(const string& callsign, PluginHost::IShell* plugin); virtual void Unavailable(const string& callSign, PluginHost::IShell* plugin); #endif /* USE_THUNDER_R4 */ private: From 13a755a9fe6ac8d4745c02e6ef6a15d3d123ff4e Mon Sep 17 00:00:00 2001 From: viveksinghnarwaria Date: Wed, 12 Jun 2024 16:59:32 +0000 Subject: [PATCH 17/21] RDKCOM-4633 RDKDEV-990 - Upstream onApplicationFocusChanged event change handling --- RDKShell/RDKShell.json | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/RDKShell/RDKShell.json b/RDKShell/RDKShell.json index c4faad29f5..57b03fbda8 100755 --- a/RDKShell/RDKShell.json +++ b/RDKShell/RDKShell.json @@ -1253,6 +1253,28 @@ ] } }, + "getFocus": { + "summary": "Gets focus to the specified client.", + "params": { + "type":"object", + "properties": { + "client": { + "$ref": "#/definitions/client" + }, + "callsign": { + "summary": "The application callsign", + "type": "string", + "example": "org.rdk.Netflix" + } + }, + "required": [ + "client" + ] + }, + "result": { + "$ref": "#/common/result" + } + }, "hideAllClients": { "summary": "Hides/Unhides all the clients.", "params": { @@ -2370,6 +2392,20 @@ ] } }, + "onApplicationFocusChanged":{ + "summary": "Triggered when an application focus is changed", + "params": { + "type": "object", + "properties": { + "client":{ + "$ref": "#/definitions/client" + } + }, + "required": [ + "client" + ] + } + }, "onApplicationConnected":{ "summary": "Triggered when a connection to an application succeeds", "params": { From 2296b05146841bb1f454d6fcd87907a82f971471 Mon Sep 17 00:00:00 2001 From: Anju Raveendran Date: Thu, 13 Jun 2024 14:52:55 +0100 Subject: [PATCH 18/21] RDKTV-29770: AVOutput plugin code clean-up Reason for change: code clean-up Test Procedure: refer ticket Risks: Low Priority: P2 Signed-off-by: Anju Raveendran anju.raveendran@sky.uk --- AVOutput/AVOutputTV.cpp | 3524 +++++++-------------------------- AVOutput/AVOutputTV.h | 45 +- AVOutput/AVOutputTVHelper.cpp | 1701 ++++++++++++++++ AVOutput/CMakeLists.txt | 3 +- 4 files changed, 2416 insertions(+), 2857 deletions(-) create mode 100644 AVOutput/AVOutputTVHelper.cpp diff --git a/AVOutput/AVOutputTV.cpp b/AVOutput/AVOutputTV.cpp index e5f453710a..2ed615ecc5 100644 --- a/AVOutput/AVOutputTV.cpp +++ b/AVOutput/AVOutputTV.cpp @@ -27,9 +27,6 @@ #define registerMethod(...) for (uint8_t i = 1; GetHandler(i); i++) GetHandler(i)->Register(__VA_ARGS__) static bool filmMakerMode= false; -static std::map supportedSourcemap; -static std::map supportedPictureModemap; -static std::map supportedFormatmap; static bool m_isDalsEnabled = false; namespace WPEFramework { @@ -41,35 +38,42 @@ namespace Plugin { { LOGINFO("tvVideoFormatChangeHandler format:%d \n",format); AVOutputTV *obj = (AVOutputTV *)userData; - if(obj)obj->NotifyVideoFormatChange(format); + if(obj) { + obj->NotifyVideoFormatChange(format); + } } static void tvFilmMakerModeChangeHandler(tvContentType_t mode, void *userData) { LOGINFO("tvFilmMakerModeChangeHandler content:%d \n",mode); AVOutputTV *obj = (AVOutputTV *)userData; - if(obj)obj->NotifyFilmMakerModeChange(mode); + if(obj) { + obj->NotifyFilmMakerModeChange(mode); + } } static void tvVideoResolutionChangeHandler(tvResolutionParam_t resolution, void *userData) { LOGINFO("tvVideoResolutionChangeHandler resolution:%d\n",resolution.resolutionValue); AVOutputTV *obj = (AVOutputTV *)userData; - if(obj)obj->NotifyVideoResolutionChange(resolution); + if(obj) { + obj->NotifyVideoResolutionChange(resolution); + } } static void tvVideoFrameRateChangeHandler(tvVideoFrameRate_t frameRate, void *userData) { LOGINFO("tvVideoFrameRateChangeHandler format:%d \n",frameRate); AVOutputTV *obj = (AVOutputTV *)userData; - if(obj)obj->NotifyVideoFrameRateChange(frameRate); + if(obj) { + obj->NotifyVideoFrameRateChange(frameRate); + } } static bool getVideoContentTypeToString(tvContentType_t content) { bool fmmMode = false; - switch(content) - { + switch(content) { case tvContentType_FMM: LOGINFO("Content Type: FMM\n"); fmmMode = true; @@ -85,8 +89,7 @@ namespace Plugin { static const char *getVideoFormatTypeToString(tvVideoFormatType_t format) { const char *strValue = "NONE"; - switch(format) - { + switch(format) { case VIDEO_FORMAT_SDR: strValue = "SDR"; break; @@ -114,8 +117,7 @@ namespace Plugin { { std::string strValue = "NONE"; std::string interlaceValue = (resolution.isInterlaced) ? "i" : "p"; - if ( resolution.resolutionValue != tvVideoResolution_NONE ) - { + if ( resolution.resolutionValue != tvVideoResolution_NONE ) { strValue = std::to_string(resolution.frameWidth) + "*" + std::to_string(resolution.frameHeight) + interlaceValue; } LOGINFO("Video Resolution:[%s]\n", strValue.c_str()); @@ -125,8 +127,7 @@ namespace Plugin { static const char *getVideoFrameRateTypeToString(tvVideoFrameRate_t frameRate) { const char *strValue = "NONE"; - switch(frameRate) - { + switch(frameRate) { case tvVideoFrameRate_24: strValue = "24"; break; @@ -175,12 +176,11 @@ namespace Plugin { fmmMode = getVideoContentTypeToString(mode); response["filmMakerMode"] = fmmMode; - if (getCapabilitySource(rangeArray) == 0) - { + if (getCapabilitySource(rangeArray) == 0) { response["filmMakerModeSources"] = rangeArray; } // cache for latest fmm mode - filmMakerMode = fmmMode; + filmMakerMode = fmmMode; sendNotify("onVideoContentChanged", response); } @@ -201,41 +201,38 @@ namespace Plugin { //Event void AVOutputTV::dsHdmiStatusEventHandler(const char *owner, IARM_EventId_t eventId, void *data, size_t len) { - if(!AVOutputTV::instance) + if(!AVOutputTV::instance) { return; + } - if (IARM_BUS_DSMGR_EVENT_HDMI_IN_STATUS == eventId) - { - IARM_Bus_DSMgr_EventData_t *eventData = (IARM_Bus_DSMgr_EventData_t *)data; - int hdmi_in_port = eventData->data.hdmi_in_status.port; - bool hdmi_in_status = eventData->data.hdmi_in_status.isPresented; - LOGWARN("AVOutputPlugins: Received IARM_BUS_DSMGR_EVENT_HDMI_IN_STATUS event port: %d, started: %d", hdmi_in_port,hdmi_in_status); - if (!hdmi_in_status) - { - tvError_t ret = tvERROR_NONE; - AVOutputTV::instance->m_isDisabledHdmiIn4KZoom = false; - LOGWARN("AVOutputPlugins: Hdmi streaming stopped here reapply the global zoom settings:%d here. m_isDisabledHdmiIn4KZoom: %d", AVOutputTV::instance->m_videoZoomMode, AVOutputTV::instance->m_isDisabledHdmiIn4KZoom); - ret = SetAspectRatio((tvDisplayMode_t)AVOutputTV::instance->m_videoZoomMode); - if (ret != tvERROR_NONE) - { - LOGWARN("SetAspectRatio set Failed"); - } - } - else - { - AVOutputTV::instance->m_isDisabledHdmiIn4KZoom = true; - LOGWARN("AVOutputPlugins: m_isDisabledHdmiIn4KZoom: %d", AVOutputTV::instance->m_isDisabledHdmiIn4KZoom); - } - } + if (IARM_BUS_DSMGR_EVENT_HDMI_IN_STATUS == eventId) { + IARM_Bus_DSMgr_EventData_t *eventData = (IARM_Bus_DSMgr_EventData_t *)data; + int hdmi_in_port = eventData->data.hdmi_in_status.port; + bool hdmi_in_status = eventData->data.hdmi_in_status.isPresented; + LOGWARN("AVOutputPlugins: Received IARM_BUS_DSMGR_EVENT_HDMI_IN_STATUS event port: %d, started: %d", hdmi_in_port,hdmi_in_status); + if (!hdmi_in_status) { + tvError_t ret = tvERROR_NONE; + AVOutputTV::instance->m_isDisabledHdmiIn4KZoom = false; + LOGWARN("AVOutputPlugins: Hdmi streaming stopped here reapply the global zoom settings:%d here. m_isDisabledHdmiIn4KZoom: %d", AVOutputTV::instance->m_videoZoomMode, AVOutputTV::instance->m_isDisabledHdmiIn4KZoom); + ret = SetAspectRatio((tvDisplayMode_t)AVOutputTV::instance->m_videoZoomMode); + if (ret != tvERROR_NONE) { + LOGWARN("SetAspectRatio set Failed"); + } + } + else { + AVOutputTV::instance->m_isDisabledHdmiIn4KZoom = true; + LOGWARN("AVOutputPlugins: m_isDisabledHdmiIn4KZoom: %d", AVOutputTV::instance->m_isDisabledHdmiIn4KZoom); + } + } } void AVOutputTV::dsHdmiVideoModeEventHandler(const char *owner, IARM_EventId_t eventId, void *data, size_t len) { - if(!AVOutputTV::instance) + if(!AVOutputTV::instance) { return; + } - if (IARM_BUS_DSMGR_EVENT_HDMI_IN_VIDEO_MODE_UPDATE == eventId) - { + if (IARM_BUS_DSMGR_EVENT_HDMI_IN_VIDEO_MODE_UPDATE == eventId) { IARM_Bus_DSMgr_EventData_t *eventData = (IARM_Bus_DSMgr_EventData_t *)data; int hdmi_in_port = eventData->data.hdmi_in_video_mode.port; dsVideoPortResolution_t resolution; @@ -244,27 +241,22 @@ namespace Plugin { resolution.interlaced = eventData->data.hdmi_in_video_mode.resolution.interlaced; resolution.frameRate = eventData->data.hdmi_in_video_mode.resolution.frameRate; LOGWARN("AVOutputPlugins: Received IARM_BUS_DSMGR_EVENT_HDMI_IN_VIDEO_MODE_UPDATE event port: %d, pixelResolution: %d, interlaced : %d, frameRate: %d \n", hdmi_in_port,resolution.pixelResolution, resolution.interlaced, resolution.frameRate); - if (AVOutputTV::instance->m_isDisabledHdmiIn4KZoom) - { + if (AVOutputTV::instance->m_isDisabledHdmiIn4KZoom) { tvError_t ret = tvERROR_NONE; if (AVOutputTV::instance->m_currentHdmiInResolutonm_currentHdmiInResoluton)) - { + (dsVIDEO_PIXELRES_MAX == AVOutputTV::instance->m_currentHdmiInResoluton)) { LOGWARN("AVOutputPlugins: Setting %d zoom mode for below 4K", AVOutputTV::instance->m_videoZoomMode); ret = SetAspectRatio((tvDisplayMode_t)AVOutputTV::instance->m_videoZoomMode); } - else - { + else { LOGWARN("AVOutputPlugins: Setting auto zoom mode for 4K and above"); ret = SetAspectRatio(tvDisplayMode_AUTO); } - if (ret != tvERROR_NONE) - { + if (ret != tvERROR_NONE) { LOGWARN("SetAspectRatio set Failed"); } } - else - { + else { LOGWARN("AVOutputPlugins: %s: HdmiInput is not started yet. m_isDisabledHdmiIn4KZoom: %d", __FUNCTION__, AVOutputTV::instance->m_isDisabledHdmiIn4KZoom); } } @@ -278,74 +270,73 @@ namespace Plugin { LOGINFO("CTOR\n"); AVOutputTV::instance = this; - InitializeIARM(); - - registerMethod("getBacklight", &AVOutputTV::getBacklight, this); - registerMethod("setBacklight", &AVOutputTV::setBacklight, this); - registerMethod("resetBacklight", &AVOutputTV::resetBacklight, this); - registerMethod("getBacklightCaps", &AVOutputTV::getBacklightCaps, this); - registerMethod("getBrightnessCaps", &AVOutputTV::getBrightnessCaps, this); - registerMethod("getBrightness", &AVOutputTV::getBrightness, this); - registerMethod("setBrightness", &AVOutputTV::setBrightness, this); - registerMethod("resetBrightness", &AVOutputTV::resetBrightness, this); - registerMethod("getContrast", &AVOutputTV::getContrast, this); - registerMethod("setContrast", &AVOutputTV::setContrast, this); - registerMethod("resetContrast", &AVOutputTV::resetContrast, this); - registerMethod("getContrastCaps", &AVOutputTV::getContrastCaps, this); - registerMethod("getSharpness", &AVOutputTV::getSharpness, this); - registerMethod("setSharpness", &AVOutputTV::setSharpness, this); - registerMethod("resetSharpness", &AVOutputTV::resetSharpness, this); - registerMethod("getSharpnessCaps", &AVOutputTV::getSharpnessCaps, this); - registerMethod("getSaturation", &AVOutputTV::getSaturation, this); - registerMethod("setSaturation", &AVOutputTV::setSaturation, this); - registerMethod("resetSaturation", &AVOutputTV::resetSaturation, this); - registerMethod("getSaturationCaps", &AVOutputTV::getSaturationCaps, this); - registerMethod("getHue", &AVOutputTV::getHue, this); - registerMethod("setHue", &AVOutputTV::setHue, this); - registerMethod("resetHue", &AVOutputTV::resetHue, this); - registerMethod("getHueCaps", &AVOutputTV::getHueCaps, this); - registerMethod("getColorTemperature", &AVOutputTV::getColorTemperature, this); - registerMethod("setColorTemperature", &AVOutputTV::setColorTemperature, this); - registerMethod("resetColorTemperature", &AVOutputTV::resetColorTemperature, this); - registerMethod("getColorTemperatureCaps", &AVOutputTV::getColorTemperatureCaps, this); - - registerMethod("getBacklightDimmingMode", &AVOutputTV::getBacklightDimmingMode, this); - registerMethod("setBacklightDimmingMode", &AVOutputTV::setBacklightDimmingMode, this); - registerMethod("resetBacklightDimmingMode", &AVOutputTV::resetBacklightDimmingMode, this); - registerMethod("getBacklightDimmingModeCaps", &AVOutputTV::getBacklightDimmingModeCaps, this); - - registerMethod("getSupportedDolbyVisionModes", &AVOutputTV::getSupportedDolbyVisionModes, this); - registerMethod("getDolbyVisionMode", &AVOutputTV::getDolbyVisionMode, this); - registerMethod("setDolbyVisionMode", &AVOutputTV::setDolbyVisionMode, this); - registerMethod("resetDolbyVisionMode", &AVOutputTV::resetDolbyVisionMode, this); - registerMethod("getDolbyVisionModeCaps", &AVOutputTV::getDolbyVisionModeCaps, this); - registerMethod("getVideoFormat", &AVOutputTV::getVideoFormat, this); - registerMethod("getVideoSource", &AVOutputTV::getVideoSource, this); - registerMethod("getVideoFrameRate", &AVOutputTV::getVideoFrameRate, this); - registerMethod("getVideoResolution", &AVOutputTV::getVideoResolution, this); - registerMethod("getVideoContentType", &AVOutputTV::getVideoContentType, this); - - registerMethod("getZoomMode", &AVOutputTV::getZoomMode, this); - registerMethod("setZoomMode", &AVOutputTV::setZoomMode, this); - registerMethod("resetZoomMode", &AVOutputTV::resetZoomMode, this); - registerMethod("getZoomModeCaps", &AVOutputTV::getZoomModeCaps, this); - - - registerMethod("getPictureMode", &AVOutputTV::getPictureMode, this); - registerMethod("setPictureMode", &AVOutputTV::setPictureMode, this); - registerMethod("signalFilmMakerMode", &AVOutputTV::signalFilmMakerMode, this); - registerMethod("resetPictureMode", &AVOutputTV::resetPictureMode, this); - registerMethod("getPictureModeCaps", &AVOutputTV::getPictureModeCaps, this); - registerMethod("getSupportedPictureModes", &AVOutputTV::getSupportedPictureModes, this); - registerMethod("getVideoSourceCaps", &AVOutputTV::getVideoSourceCaps, this); - registerMethod("getVideoFormatCaps", &AVOutputTV::getVideoFormatCaps, this); - registerMethod("getVideoFrameRateCaps", &AVOutputTV::getVideoFrameRateCaps, this); - registerMethod("getVideoResolutionCaps", &AVOutputTV::getVideoResolutionCaps, this); - - registerMethod("getLowLatencyState", &AVOutputTV::getLowLatencyState, this); - registerMethod("setLowLatencyState", &AVOutputTV::setLowLatencyState, this); - registerMethod("resetLowLatencyState", &AVOutputTV::resetLowLatencyState, this); - registerMethod("getLowLatencyStateCaps", &AVOutputTV::getLowLatencyStateCaps, this); + InitializeIARM(); + + registerMethod("getBacklight", &AVOutputTV::getBacklight, this); + registerMethod("setBacklight", &AVOutputTV::setBacklight, this); + registerMethod("resetBacklight", &AVOutputTV::resetBacklight, this); + registerMethod("getBacklightCaps", &AVOutputTV::getBacklightCaps, this); + registerMethod("getBrightnessCaps", &AVOutputTV::getBrightnessCaps, this); + registerMethod("getBrightness", &AVOutputTV::getBrightness, this); + registerMethod("setBrightness", &AVOutputTV::setBrightness, this); + registerMethod("resetBrightness", &AVOutputTV::resetBrightness, this); + registerMethod("getContrast", &AVOutputTV::getContrast, this); + registerMethod("setContrast", &AVOutputTV::setContrast, this); + registerMethod("resetContrast", &AVOutputTV::resetContrast, this); + registerMethod("getContrastCaps", &AVOutputTV::getContrastCaps, this); + registerMethod("getSharpness", &AVOutputTV::getSharpness, this); + registerMethod("setSharpness", &AVOutputTV::setSharpness, this); + registerMethod("resetSharpness", &AVOutputTV::resetSharpness, this); + registerMethod("getSharpnessCaps", &AVOutputTV::getSharpnessCaps, this); + registerMethod("getSaturation", &AVOutputTV::getSaturation, this); + registerMethod("setSaturation", &AVOutputTV::setSaturation, this); + registerMethod("resetSaturation", &AVOutputTV::resetSaturation, this); + registerMethod("getSaturationCaps", &AVOutputTV::getSaturationCaps, this); + registerMethod("getHue", &AVOutputTV::getHue, this); + registerMethod("setHue", &AVOutputTV::setHue, this); + registerMethod("resetHue", &AVOutputTV::resetHue, this); + registerMethod("getHueCaps", &AVOutputTV::getHueCaps, this); + registerMethod("getColorTemperature", &AVOutputTV::getColorTemperature, this); + registerMethod("setColorTemperature", &AVOutputTV::setColorTemperature, this); + registerMethod("resetColorTemperature", &AVOutputTV::resetColorTemperature, this); + registerMethod("getColorTemperatureCaps", &AVOutputTV::getColorTemperatureCaps, this); + + registerMethod("getBacklightDimmingMode", &AVOutputTV::getBacklightDimmingMode, this); + registerMethod("setBacklightDimmingMode", &AVOutputTV::setBacklightDimmingMode, this); + registerMethod("resetBacklightDimmingMode", &AVOutputTV::resetBacklightDimmingMode, this); + registerMethod("getBacklightDimmingModeCaps", &AVOutputTV::getBacklightDimmingModeCaps, this); + + registerMethod("getSupportedDolbyVisionModes", &AVOutputTV::getSupportedDolbyVisionModes, this); + registerMethod("getDolbyVisionMode", &AVOutputTV::getDolbyVisionMode, this); + registerMethod("setDolbyVisionMode", &AVOutputTV::setDolbyVisionMode, this); + registerMethod("resetDolbyVisionMode", &AVOutputTV::resetDolbyVisionMode, this); + registerMethod("getDolbyVisionModeCaps", &AVOutputTV::getDolbyVisionModeCaps, this); + registerMethod("getVideoFormat", &AVOutputTV::getVideoFormat, this); + registerMethod("getVideoSource", &AVOutputTV::getVideoSource, this); + registerMethod("getVideoFrameRate", &AVOutputTV::getVideoFrameRate, this); + registerMethod("getVideoResolution", &AVOutputTV::getVideoResolution, this); + registerMethod("getVideoContentType", &AVOutputTV::getVideoContentType, this); + + registerMethod("getZoomMode", &AVOutputTV::getZoomMode, this); + registerMethod("setZoomMode", &AVOutputTV::setZoomMode, this); + registerMethod("resetZoomMode", &AVOutputTV::resetZoomMode, this); + registerMethod("getZoomModeCaps", &AVOutputTV::getZoomModeCaps, this); + + registerMethod("getPictureMode", &AVOutputTV::getPictureMode, this); + registerMethod("setPictureMode", &AVOutputTV::setPictureMode, this); + registerMethod("signalFilmMakerMode", &AVOutputTV::signalFilmMakerMode, this); + registerMethod("resetPictureMode", &AVOutputTV::resetPictureMode, this); + registerMethod("getPictureModeCaps", &AVOutputTV::getPictureModeCaps, this); + registerMethod("getSupportedPictureModes", &AVOutputTV::getSupportedPictureModes, this); + registerMethod("getVideoSourceCaps", &AVOutputTV::getVideoSourceCaps, this); + registerMethod("getVideoFormatCaps", &AVOutputTV::getVideoFormatCaps, this); + registerMethod("getVideoFrameRateCaps", &AVOutputTV::getVideoFrameRateCaps, this); + registerMethod("getVideoResolutionCaps", &AVOutputTV::getVideoResolutionCaps, this); + + registerMethod("getLowLatencyState", &AVOutputTV::getLowLatencyState, this); + registerMethod("setLowLatencyState", &AVOutputTV::setLowLatencyState, this); + registerMethod("resetLowLatencyState", &AVOutputTV::resetLowLatencyState, this); + registerMethod("getLowLatencyStateCaps", &AVOutputTV::getLowLatencyStateCaps, this); LOGINFO("Exit\n"); } @@ -379,20 +370,16 @@ namespace Plugin { ret = TvInit(); - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { LOGERR("Platform Init failed, ret: %s \n", getErrorString(ret).c_str()); } - else - { + else { LOGINFO("Platform Init successful...\n"); ret = TvSyncCalibrationInfoODM(); - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { LOGERR(" SD3 <->cri_data sync failed, ret: %s \n", getErrorString(ret).c_str()); } - else - { + else { LOGERR(" SD3 <->cri_data sync success, ret: %s \n", getErrorString(ret).c_str()); } } @@ -421,24 +408,23 @@ namespace Plugin { LOGWARN("RegisterVideoFrameRateChangeCB failed"); } - LocatePQSettingsFile(); + locatePQSettingsFile(); // Get Index from PQ capabailites - if (getPqParamIndex() != 0) - { + if (getPqParamIndex() != 0) { LOGWARN("Failed to get the supported index from capability \n"); } - SyncAvoutputTVParamsToHAL("none","none","none"); + syncAvoutputTVParamsToHAL("none","none","none"); setDefaultAspectRatio(); // source format specific sync to ssm data - SyncAvoutputTVPQModeParamsToHAL("Current", "none", "none"); + syncAvoutputTVPQModeParamsToHAL("Current", "none", "none"); // As we have source to picture mode mapping, get current source and // setting those picture mode - InitializePictureMode(); + initializePictureMode(); LOGINFO("Exit\n" ); } @@ -450,12 +436,10 @@ namespace Plugin { tvError_t ret = tvERROR_NONE; ret = TvTerm(); - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { LOGERR("Platform De-Init failed"); } - else - { + else { LOGINFO("Platform De-Init successful... \n"); } @@ -479,37 +463,30 @@ namespace Plugin { tvError_t ret = getParamsCaps(range,pqmode,source,format,"AspectRatio"); - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { returnResponse(false); } - else - { - for (index = 0; index < range.size(); index++) + else { + for (index = 0; index < range.size(); index++) { rangeArray.Add(range[index]); + } response["options"]=rangeArray; - if (pqmode.front().compare("none") != 0) - { - for (index = 0; index < pqmode.size(); index++) - { + if (pqmode.front().compare("none") != 0) { + for (index = 0; index < pqmode.size(); index++) { pqmodeArray.Add(pqmode[index]); } response["pictureModeInfo"]=pqmodeArray; } - if ((source.front()).compare("none") != 0) - { - for (index = 0; index < source.size(); index++) - { + if ((source.front()).compare("none") != 0) { + for (index = 0; index < source.size(); index++) { sourceArray.Add(source[index]); } response["videoSourceInfo"]=sourceArray; } - if ((format.front()).compare("none") != 0) - { - for (index = 0; index < format.size(); index++) - { + if ((format.front()).compare("none") != 0) { + for (index = 0; index < format.size(); index++) { formatArray.Add(format[index]); } response["videoFormatInfo"]=formatArray; @@ -532,80 +509,65 @@ namespace Plugin { value = parameters.HasLabel("zoomMode") ? parameters["zoomMode"].String() : ""; returnIfParamNotFound(parameters,"zoomMode"); - if (validateInputParameter("AspectRatio",value) != 0) - { + if (validateInputParameter("AspectRatio",value) != 0) { LOGERR("%s: Range validation failed for AspectRatio\n", __FUNCTION__); returnResponse(false); } - if (parsingSetInputArgument(parameters, "AspectRatio",source, pqmode, format) != 0) - { + if (parsingSetInputArgument(parameters, "AspectRatio",source, pqmode, format) != 0) { LOGERR("%s: Failed to parse the input arguments \n", __FUNCTION__); returnResponse(false); } - if( !isCapablityCheckPassed( pqmode, source, format, "AspectRatio" )) - { + if( !isCapablityCheckPassed( pqmode, source, format, "AspectRatio" )) { LOGERR("%s: CapablityCheck failed for AspectRatio\n", __FUNCTION__); returnResponse(false); } - if(!value.compare("TV 16X9 STRETCH")) - { + if(!value.compare("TV 16X9 STRETCH")) { mode = tvDisplayMode_16x9; } - else if (!value.compare("TV 4X3 PILLARBOX")) - { + else if (!value.compare("TV 4X3 PILLARBOX")) { mode = tvDisplayMode_4x3; } - else if (!value.compare("TV NORMAL")) - { + else if (!value.compare("TV NORMAL")) { mode = tvDisplayMode_NORMAL; } - else if (!value.compare("TV DIRECT")) - { + else if (!value.compare("TV DIRECT")) { mode = tvDisplayMode_DIRECT; } - else if (!value.compare("TV AUTO")) - { + else if (!value.compare("TV AUTO")) { mode = tvDisplayMode_AUTO; } - else if (!value.compare("TV ZOOM")) - { + else if (!value.compare("TV ZOOM")) { mode = tvDisplayMode_ZOOM; } - else - { + else { returnResponse(false); } m_videoZoomMode = mode; tvError_t ret = setAspectRatioZoomSettings (mode); - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { returnResponse(false); } - else - { + else { //Save DisplayMode to localstore and ssm_data int params[3]={0}; params[0]=mode; - int retval=UpdateAVoutputTVParam("set","AspectRatio",pqmode,source,format,PQ_PARAM_ASPECT_RATIO,params);; + int retval=updateAVoutputTVParam("set","AspectRatio",pqmode,source,format,PQ_PARAM_ASPECT_RATIO,params); - if(retval != 0) - { + if(retval != 0) { LOGERR("Failed to Save DisplayMode to ssm_data\n"); returnResponse(false); } tr181ErrorCode_t err = setLocalParam(rfc_caller_id, AVOUTPUT_ASPECTRATIO_RFC_PARAM, value.c_str()); - if ( err != tr181Success ) - { + if ( err != tr181Success ) { LOGERR("setLocalParam for %s Failed : %s\n", AVOUTPUT_ASPECTRATIO_RFC_PARAM, getTR181ErrorString(err)); returnResponse(false); } - else - { + else { LOGINFO("setLocalParam for %s Successful, Value: %s\n", AVOUTPUT_ASPECTRATIO_RFC_PARAM, value.c_str()); } LOGINFO("Exit : SetAspectRatio() value : %s\n",value.c_str()); @@ -621,14 +583,11 @@ namespace Plugin { tvError_t ret = getUserSelectedAspectRatio (&mode); - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { returnResponse(false); } - else - { - switch(mode) - { + else { + switch(mode) { case tvDisplayMode_16x9: LOGINFO("Aspect Ratio: TV 16X9 STRETCH\n"); response["zoomMode"] = "TV 16X9 STRETCH"; @@ -676,137 +635,43 @@ namespace Plugin { std::string format; tvError_t ret = tvERROR_NONE; - if (parsingSetInputArgument(parameters, "AspectRatio",source, pqmode, format) != 0) - { + if (parsingSetInputArgument(parameters, "AspectRatio",source, pqmode, format) != 0) { LOGERR("%s: Failed to parse the input arguments \n", __FUNCTION__); returnResponse(false); } - if( !isCapablityCheckPassed( pqmode, source, format, "AspectRatio" )) - { + if( !isCapablityCheckPassed( pqmode, source, format, "AspectRatio" )) { LOGERR("%s: CapablityCheck failed for AspectRatio\n", __FUNCTION__); returnResponse(false); } tr181ErrorCode_t err = clearLocalParam(rfc_caller_id,AVOUTPUT_ASPECTRATIO_RFC_PARAM); - if ( err != tr181Success ) - { + if ( err != tr181Success ) { LOGERR("clearLocalParam for %s Failed : %s\n", AVOUTPUT_ASPECTRATIO_RFC_PARAM, getTR181ErrorString(err)); ret = tvERROR_GENERAL; } - else - { + else { ret = setDefaultAspectRatio(pqmode,source,format); } - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { returnResponse(false); } - else - { + else { LOGINFO("Exit : resetDefaultAspectRatio()\n"); returnResponse(true); } } - tvError_t AVOutputTV::setDefaultAspectRatio(std::string pqmode,std::string format,std::string source) - { - tvDisplayMode_t mode = tvDisplayMode_MAX; - TR181_ParamData_t param; - tvError_t ret = tvERROR_NONE; - - memset(¶m, 0, sizeof(param)); - tr181ErrorCode_t err = getLocalParam(rfc_caller_id, AVOUTPUT_ASPECTRATIO_RFC_PARAM, ¶m); - if ( tr181Success == err ) - { - if(!std::string(param.value).compare("16:9")) - { - mode = tvDisplayMode_16x9; - } - else if (!std::string(param.value).compare("4:3")) - { - mode = tvDisplayMode_4x3; - } - else if (!std::string(param.value).compare("Full")) - { - mode = tvDisplayMode_FULL; - } - else if (!std::string(param.value).compare("Normal")) - { - mode = tvDisplayMode_NORMAL; - } - else if (!std::string(param.value).compare("TV AUTO")) - { - mode = tvDisplayMode_AUTO; - } - else if (!std::string(param.value).compare("TV DIRECT")) - { - mode = tvDisplayMode_DIRECT; - } - else if (!std::string(param.value).compare("TV NORMAL")) - { - mode = tvDisplayMode_NORMAL; - } - else if (!std::string(param.value).compare("TV ZOOM")) - { - mode = tvDisplayMode_ZOOM; - } - else if (!std::string(param.value).compare("TV 16X9 STRETCH")) - { - mode = tvDisplayMode_16x9; - } - else if (!std::string(param.value).compare("TV 4X3 PILLARBOX")) - { - mode = tvDisplayMode_4x3; - } - else - { - mode = tvDisplayMode_AUTO; - } - - m_videoZoomMode = mode; - tvError_t ret = setAspectRatioZoomSettings (mode); - - if(ret != tvERROR_NONE) - { - LOGERR("AspectRatio set failed: %s\n",getErrorString(ret).c_str()); - } - else - { - //Save DisplayMode to ssm_data - int params[3]={0}; - params[0]=mode; - int retval=UpdateAVoutputTVParam("set","AspectRatio",pqmode,source,format,PQ_PARAM_ASPECT_RATIO,params); - - if(retval != 0) - { - LOGERR("Failed to Save DisplayMode to ssm_data\n"); - ret = tvERROR_GENERAL; - } - LOGINFO("Aspect Ratio initialized successfully, value: %s\n", param.value); - } - - } - else - { - LOGERR("getLocalParam for %s Failed : %s\n", AVOUTPUT_ASPECTRATIO_RFC_PARAM, getTR181ErrorString(err)); - ret = tvERROR_GENERAL; - } - return ret; - } - uint32_t AVOutputTV::getVideoFormat(const JsonObject& parameters, JsonObject& response) { LOGINFO("Entry\n"); tvVideoFormatType_t videoFormat; tvError_t ret = GetCurrentVideoFormat(&videoFormat); - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { response["currentVideoFormat"] = "NONE"; returnResponse(false); } - else - { + else { response["currentVideoFormat"] = getVideoFormatTypeToString(videoFormat); LOGINFO("Exit: getVideoFormat :%d success \n",videoFormat); returnResponse(true); @@ -818,13 +683,11 @@ namespace Plugin { LOGINFO("Entry\n"); tvResolutionParam_t videoResolution; tvError_t ret = GetCurrentVideoResolution(&videoResolution); - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { response["currentVideoResolution"] = "NONE"; returnResponse(false); } - else - { + else { response["currentVideoResolution"] = getVideoResolutionTypeToString(videoResolution); LOGINFO("Exit: getVideoResolution :%d success \n",videoResolution.resolutionValue); returnResponse(true); @@ -836,13 +699,11 @@ namespace Plugin { LOGINFO("Entry\n"); tvVideoFrameRate_t videoFramerate; tvError_t ret = GetCurrentVideoFrameRate(&videoFramerate); - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { response["currentVideoFrameRate"] = "NONE"; returnResponse(false); } - else - { + else { response["currentVideoFrameRate"] = getVideoFrameRateTypeToString(videoFramerate); LOGINFO("Exit: videoFramerate :%d success \n",videoFramerate); returnResponse(true); @@ -857,33 +718,31 @@ namespace Plugin { std::string source; std::string format; std::string key; - - int sourceIndex=0,pqIndex=0,formatIndex=0; + + int sourceIndex=0,pqIndex=0,formatIndex=0; int backlight = 0,err = 0; - if (parsingGetInputArgument(parameters, "Backlight",source, pqmode, format) != 0) - { + if (parsingGetInputArgument(parameters, "Backlight",source, pqmode, format) != 0) { LOGINFO("%s: Failed to parse argument\n", __FUNCTION__); returnResponse(false); } - - if (isPlatformSupport("Backlight") != 0) returnResponse(false); - if (getParamIndex(source,pqmode,format,sourceIndex,pqIndex,formatIndex) == -1) - { + if (isPlatformSupport("Backlight") != 0) { + returnResponse(false); + } + + if (getParamIndex(source,pqmode,format,sourceIndex,pqIndex,formatIndex) == -1) { LOGERR("%s: getParamIndex failed to get \n", __FUNCTION__); returnResponse(false); } err = getLocalparam("Backlight",formatIndex,pqIndex,sourceIndex,backlight, PQ_PARAM_BACKLIGHT); - if( err == 0 ) - { + if( err == 0 ) { response["backlight"] = backlight; LOGINFO("Exit : Backlight Value: %d \n", backlight); returnResponse(true); } - else - { + else { returnResponse(false); } } @@ -891,8 +750,8 @@ namespace Plugin { uint32_t AVOutputTV::setBacklight(const JsonObject& parameters, JsonObject& response) { LOGINFO("Entry\n"); - - std::string value; + + std::string value; std::string pqmode; std::string source; std::string format; @@ -903,52 +762,48 @@ namespace Plugin { returnIfParamNotFound(parameters,"backlight"); backlight = std::stoi(value); - if (validateIntegerInputParameter("Backlight",backlight) != 0) - { + if (validateIntegerInputParameter("Backlight",backlight) != 0) { LOGERR("Failed in Backlight range validation:%s", __FUNCTION__); returnResponse(false); } - if (parsingSetInputArgument(parameters, "Backlight",source, pqmode, format) != 0) - { + if (parsingSetInputArgument(parameters, "Backlight",source, pqmode, format) != 0) { LOGERR("%s: Failed to parse the input arguments \n", __FUNCTION__); returnResponse(false); } - if (isPlatformSupport("Backlight") != 0 ) returnResponse(false); + if (isPlatformSupport("Backlight") != 0 ) { + returnResponse(false); + } - if( !isCapablityCheckPassed( pqmode, source, format, "Backlight" )) - { + if( !isCapablityCheckPassed( pqmode, source, format, "Backlight" )) { LOGERR("%s: CapablityCheck failed for Backlight\n", __FUNCTION__); returnResponse(false); } - if( isSetRequired(pqmode,source,format) ) - { + if( isSetRequired(pqmode,source,format) ) { LOGINFO("Proceed with setBacklight\n"); ret = SetBacklight(backlight); } - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { LOGERR("Failed to set Backlight\n"); returnResponse(false); } - else - { + else { int params[3]={0}; params[0]=backlight; - int retval= UpdateAVoutputTVParam("set","Backlight",pqmode,source,format,PQ_PARAM_BACKLIGHT,params); - if(retval != 0 ) - { + int retval= updateAVoutputTVParam("set","Backlight",pqmode,source,format,PQ_PARAM_BACKLIGHT,params); + if(retval != 0 ) { LOGERR("Failed to Save Backlight to ssm_data\n"); - returnResponse(false); + returnResponse(false); } LOGINFO("Exit : setBacklight successful to value: %d\n", backlight); returnResponse(true); } } + uint32_t AVOutputTV::resetBacklight(const JsonObject& parameters, JsonObject& response) { LOGINFO("Entry\n"); @@ -960,51 +815,44 @@ namespace Plugin { int params[3]={0}; tvError_t ret = tvERROR_NONE; - if (parsingSetInputArgument(parameters, "Backlight",source, pqmode, format) != 0) - { + if (parsingSetInputArgument(parameters, "Backlight",source, pqmode, format) != 0) { LOGERR("%s: Failed to parse the input arguments \n", __FUNCTION__); returnResponse(false); } - if (isPlatformSupport("Backlight") != 0) returnResponse(false); + if (isPlatformSupport("Backlight") != 0) { + returnResponse(false); + } - if( !isCapablityCheckPassed( pqmode, source, format, "Backlight" )) - { + if( !isCapablityCheckPassed( pqmode, source, format, "Backlight" )) { LOGERR("%s: CapablityCheck failed for Backlight\n", __FUNCTION__); returnResponse(false); } - int retval= UpdateAVoutputTVParam("reset","Backlight",pqmode,source,format,PQ_PARAM_BACKLIGHT,params); - if(retval != 0 ) - { + int retval= updateAVoutputTVParam("reset","Backlight",pqmode,source,format,PQ_PARAM_BACKLIGHT,params); + if(retval != 0 ) { LOGERR("Failed to reset Backlight\n"); returnResponse(false); } - else - { - if (isSetRequired(pqmode,source,format)) - { + else { + if (isSetRequired(pqmode,source,format)) { getParamIndex("Current","Current", "Current",sourceIndex,pqIndex,formatIndex); int err = getLocalparam("Backlight",formatIndex,pqIndex,sourceIndex,backlight, PQ_PARAM_BACKLIGHT); - if( err == 0 ) - { + if( err == 0 ) { LOGINFO("%s : getLocalparam success format :%d source : %d format : %d value : %d\n",__FUNCTION__,formatIndex, sourceIndex, pqIndex,backlight); ret = SetBacklight(backlight); } - else - { + else { LOGERR("%s : GetLocalParam Failed \n",__FUNCTION__); - ret = tvERROR_GENERAL; - } - } + ret = tvERROR_GENERAL; + } + } } - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { returnResponse(false); } - else - { + else { LOGINFO("Exit : resetBacklight Successful to value : %d \n",backlight); returnResponse(true); } @@ -1017,11 +865,11 @@ namespace Plugin { std::vector pqmode; std::vector source; std::vector format; - + std::string isPlatformSupport; std::vector indexInfo; - JsonObject rangeObj; + JsonObject rangeObj; JsonArray pqmodeArray; JsonArray formatArray; JsonArray sourceArray; @@ -1030,37 +878,30 @@ namespace Plugin { tvError_t ret = getParamsCaps(range,pqmode,source,format,"Backlight", isPlatformSupport, indexInfo); - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { returnResponse(false); } - else - { - response["platformSupport"] = (isPlatformSupport.compare("true") == 0) ? true : false; + else { + response["platformSupport"] = (isPlatformSupport.compare("true") == 0) ? true : false; rangeObj["from"] = stoi(range[0]); rangeObj["to"] = stoi(range[1]); response["rangeInfo"]=rangeObj; if ((pqmode.front()).compare("none") != 0) { - for (index = 0; index < pqmode.size(); index++) - { + for (index = 0; index < pqmode.size(); index++) { pqmodeArray.Add(pqmode[index]); } response["pictureModeInfo"]=pqmodeArray; } - if ((source.front()).compare("none") != 0) - { - for (index = 0; index < source.size(); index++) - { + if ((source.front()).compare("none") != 0) { + for (index = 0; index < source.size(); index++) { sourceArray.Add(source[index]); } response["videoSourceInfo"]=sourceArray; } - if ((format.front()).compare("none") != 0) - { - for (index = 0; index < format.size(); index++) - { + if ((format.front()).compare("none") != 0) { + for (index = 0; index < format.size(); index++) { formatArray.Add(format[index]); } response["videoFormatInfo"]=formatArray; @@ -1081,27 +922,23 @@ namespace Plugin { int sourceIndex=0,pqIndex=0,formatIndex=0; int brightness = 0; - if (parsingGetInputArgument(parameters, "Brightness",source, pqmode, format) != 0) - { + if (parsingGetInputArgument(parameters, "Brightness",source, pqmode, format) != 0) { LOGERR("%s: Failed to parse argument\n", __FUNCTION__); returnResponse(false); } - if (getParamIndex(source,pqmode,format,sourceIndex,pqIndex,formatIndex) == -1) - { + if (getParamIndex(source,pqmode,format,sourceIndex,pqIndex,formatIndex) == -1) { LOGERR("%s: getParamIndex failed to get \n", __FUNCTION__); returnResponse(false); } int err = getLocalparam("Brightness",formatIndex,pqIndex,sourceIndex,brightness, PQ_PARAM_BRIGHTNESS); - if( err == 0 ) - { + if( err == 0 ) { response["brightness"] = brightness; LOGINFO("Exit : Brightness Value: %d \n", brightness); returnResponse(true); } - else - { + else { returnResponse(false); } } @@ -1115,50 +952,43 @@ namespace Plugin { std::string source; std::string format; int brightness = 0; - tvError_t ret = tvERROR_NONE; + tvError_t ret = tvERROR_NONE; value = parameters.HasLabel("brightness") ? parameters["brightness"].String() : ""; returnIfParamNotFound(parameters,"brightness"); brightness = stoi(value); - if (validateIntegerInputParameter("Brightness",brightness) != 0) - { + if (validateIntegerInputParameter("Brightness",brightness) != 0) { LOGERR("Failed in Brightness range validation:%s", __FUNCTION__); returnResponse(false); } - if (parsingSetInputArgument(parameters, "Brightness",source, pqmode, format) != 0) - { + if (parsingSetInputArgument(parameters, "Brightness",source, pqmode, format) != 0) { LOGERR("%s: Failed to parse the input arguments \n", __FUNCTION__); returnResponse(false); } - if( !isCapablityCheckPassed( pqmode, source, format, "Brightness" )) - { + if( !isCapablityCheckPassed( pqmode, source, format, "Brightness" )) { LOGERR("%s: CapablityCheck failed for Brightness\n", __FUNCTION__); returnResponse(false); } - if( isSetRequired(pqmode,source,format) ) - { + if( isSetRequired(pqmode,source,format) ) { LOGINFO("Proceed with %s \n",__FUNCTION__); ret = SetBrightness(brightness); } - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { LOGERR("Failed to set Brightness\n"); returnResponse(false); } - else - { + else { int params[3]={0}; params[0]=brightness; - int retval= UpdateAVoutputTVParam("set","Brightness",pqmode,source,format,PQ_PARAM_BRIGHTNESS,params); - if(retval != 0 ) - { + int retval= updateAVoutputTVParam("set","Brightness",pqmode,source,format,PQ_PARAM_BRIGHTNESS,params); + if(retval != 0 ) { LOGERR("Failed to Save Brightness to ssm_data\n"); - returnResponse(false); + returnResponse(false); } LOGINFO("Exit : setBrightness successful to value: %d\n", brightness); returnResponse(true); @@ -1166,6 +996,7 @@ namespace Plugin { } + uint32_t AVOutputTV::resetBrightness(const JsonObject& parameters, JsonObject& response) { @@ -1179,49 +1010,40 @@ namespace Plugin { int params[3]={0}; tvError_t ret = tvERROR_NONE; - if (parsingSetInputArgument(parameters, "Brightness",source, pqmode, format) != 0) - { + if (parsingSetInputArgument(parameters, "Brightness",source, pqmode, format) != 0) { LOGERR("%s: Failed to parse the input arguments \n", __FUNCTION__); returnResponse(false); } - if( !isCapablityCheckPassed( pqmode, source, format, "Brightness" )) - { + if( !isCapablityCheckPassed( pqmode, source, format, "Brightness" )) { LOGERR("%s: CapablityCheck failed for Brightness\n", __FUNCTION__); returnResponse(false); } - int retval= UpdateAVoutputTVParam("reset","Brightness",pqmode,source,format,PQ_PARAM_BRIGHTNESS,params); - if(retval != 0 ) - { + int retval= updateAVoutputTVParam("reset","Brightness",pqmode,source,format,PQ_PARAM_BRIGHTNESS,params); + if(retval != 0 ) { LOGWARN("Failed to reset Brightness\n"); returnResponse(false); } - else - { - if (isSetRequired(pqmode,source,format)) - { + else { + if (isSetRequired(pqmode,source,format)) { getParamIndex("Current","Current", "Current",sourceIndex,pqIndex,formatIndex); int err = getLocalparam("Brightness",formatIndex,pqIndex,sourceIndex,brightness, PQ_PARAM_BRIGHTNESS); - if( err == 0 ) - { + if( err == 0 ) { LOGINFO("%s : getLocalparam success format :%d source : %d format : %d value : %d\n",__FUNCTION__,formatIndex, sourceIndex, pqIndex,brightness); ret = SetBrightness(brightness); } - else - { + else { LOGERR("%s : GetLocalParam Failed \n",__FUNCTION__); - ret = tvERROR_GENERAL; + ret = tvERROR_GENERAL; } } } - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { returnResponse(false); } - else - { + else { LOGINFO("Exit : resetBrightness Successful to value : %d \n",brightness); returnResponse(true); } @@ -1231,57 +1053,49 @@ namespace Plugin { uint32_t AVOutputTV::getBrightnessCaps(const JsonObject& parameters, JsonObject& response) { LOGINFO("Entry"); - std::vector range; + std::vector range; std::vector pqmode; std::vector source; std::vector format; - + JsonArray pqmodeArray; JsonArray formatArray; JsonArray sourceArray; JsonObject rangeObj; - unsigned int index = 0; + unsigned int index = 0; - tvError_t ret = getParamsCaps(range,pqmode,source,format,"Brightness"); + tvError_t ret = getParamsCaps(range,pqmode,source,format,"Brightness"); - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { returnResponse(false); } - else - { + else { rangeObj["from"] = stoi(range[0]); rangeObj["to"] = stoi(range[1]); response["rangeInfo"]=rangeObj; - if ((pqmode.front()).compare("none") != 0) - { - for (index = 0; index < pqmode.size(); index++) - { + if ((pqmode.front()).compare("none") != 0) { + for (index = 0; index < pqmode.size(); index++) { pqmodeArray.Add(pqmode[index]); } response["pictureModeInfo"]=pqmodeArray; } - if ((source.front()).compare("none") != 0) - { - for (index = 0; index < source.size(); index++) - { + if ((source.front()).compare("none") != 0) { + for (index = 0; index < source.size(); index++) { sourceArray.Add(source[index]); } response["videoSourceInfo"]=sourceArray; } - if ((format.front()).compare("none") != 0) - { - for (index = 0; index < format.size(); index++) - { + if ((format.front()).compare("none") != 0) { + for (index = 0; index < format.size(); index++) { formatArray.Add(format[index]); } - response["videoFormatInfo"]=formatArray; + response["videoFormatInfo"]=formatArray; } LOGINFO("Exit\n"); returnResponse(true); - } + } } uint32_t AVOutputTV::getContrast(const JsonObject& parameters, JsonObject& response) @@ -1295,27 +1109,23 @@ namespace Plugin { int sourceIndex=0,pqIndex=0,formatIndex=0; int contrast = 0; - if (parsingGetInputArgument(parameters, "Contrast",source, pqmode, format) != 0) - { + if (parsingGetInputArgument(parameters, "Contrast",source, pqmode, format) != 0) { LOGINFO("%s: Failed to parse argument\n", __FUNCTION__); returnResponse(false); } - if (getParamIndex(source,pqmode,format,sourceIndex,pqIndex,formatIndex) == -1) - { + if (getParamIndex(source,pqmode,format,sourceIndex,pqIndex,formatIndex) == -1) { LOGERR("%s: getParamIndex failed to get \n", __FUNCTION__); returnResponse(false); } int err = getLocalparam("Contrast",formatIndex,pqIndex,sourceIndex,contrast, PQ_PARAM_CONTRAST); - if( err == 0 ) - { + if( err == 0 ) { response["contrast"] = contrast; LOGINFO("Exit : Contrast Value: %d \n", contrast); returnResponse(true); } - else - { + else { returnResponse(false); } } @@ -1329,50 +1139,43 @@ namespace Plugin { std::string source; std::string format; int contrast = 0; - tvError_t ret = tvERROR_NONE; + tvError_t ret = tvERROR_NONE; value = parameters.HasLabel("contrast") ? parameters["contrast"].String() : ""; returnIfParamNotFound(parameters,"contrast"); contrast = stoi(value); - if (validateIntegerInputParameter("Contrast", contrast) != 0) - { + if (validateIntegerInputParameter("Contrast", contrast) != 0) { LOGERR("Failed in contrast range validation:%s", __FUNCTION__); returnResponse(false); } - if (parsingSetInputArgument(parameters, "Contrast",source, pqmode, format) != 0) - { + if (parsingSetInputArgument(parameters, "Contrast",source, pqmode, format) != 0) { LOGERR("%s: Failed to parse the input arguments \n", __FUNCTION__); returnResponse(false); } - if( !isCapablityCheckPassed( pqmode, source, format, "Contrast" )) - { + if( !isCapablityCheckPassed( pqmode, source, format, "Contrast" )) { LOGERR("%s: CapablityCheck failed for Contrast\n", __FUNCTION__); returnResponse(false); } - if( isSetRequired(pqmode,source,format) ) - { + if( isSetRequired(pqmode,source,format) ) { LOGINFO("Proceed with %s \n",__FUNCTION__); ret = SetContrast(contrast); } - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { LOGERR("Failed to set Contrast\n"); returnResponse(false); } - else - { + else { int params[3]={0}; params[0]=contrast; - int retval= UpdateAVoutputTVParam("set","Contrast",pqmode,source,format,PQ_PARAM_CONTRAST,params); - if(retval != 0 ) - { + int retval= updateAVoutputTVParam("set","Contrast",pqmode,source,format,PQ_PARAM_CONTRAST,params); + if(retval != 0 ) { LOGERR("Failed to Save Contrast to ssm_data\n"); - returnResponse(false); + returnResponse(false); } LOGINFO("Exit : setContrast successful to value: %d\n", contrast); returnResponse(true); @@ -1393,50 +1196,41 @@ namespace Plugin { int params[3]={0}; tvError_t ret = tvERROR_NONE; - if (parsingSetInputArgument(parameters, "Contrast",source, pqmode, format) != 0) - { + if (parsingSetInputArgument(parameters, "Contrast",source, pqmode, format) != 0) { LOGERR("%s: Failed to parse the input arguments \n", __FUNCTION__); returnResponse(false); } - if( !isCapablityCheckPassed( pqmode, source, format, "Contrast" )) - { + if( !isCapablityCheckPassed( pqmode, source, format, "Contrast" )) { LOGERR("%s: CapablityCheck failed for Contrast\n", __FUNCTION__); returnResponse(false); } - int retval= UpdateAVoutputTVParam("reset","Contrast",pqmode,source,format,PQ_PARAM_CONTRAST,params); + int retval= updateAVoutputTVParam("reset","Contrast",pqmode,source,format,PQ_PARAM_CONTRAST,params); - if(retval != 0 ) - { + if(retval != 0 ) { LOGWARN("Failed to reset Contrast\n"); returnResponse(false); } - else - { - if (isSetRequired(pqmode,source,format)) - { + else { + if (isSetRequired(pqmode,source,format)) { getParamIndex("Current","Current", "Current",sourceIndex,pqIndex,formatIndex); int err = getLocalparam("Contrast",formatIndex,pqIndex,sourceIndex,contrast, PQ_PARAM_CONTRAST); - if( err == 0 ) - { + if( err == 0 ) { LOGINFO("%s : getLocalparam success format :%d source : %d format : %d value : %d\n",__FUNCTION__,formatIndex, sourceIndex, pqIndex,contrast); ret = SetContrast(contrast); } - else - { + else { LOGERR("%s : GetLocalParam Failed \n",__FUNCTION__); - ret = tvERROR_GENERAL; + ret = tvERROR_GENERAL; } } } - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { returnResponse(false); } - else - { + else { LOGINFO("Exit : resetContrast Successful to value : %d \n",contrast); returnResponse(true); } @@ -1456,40 +1250,33 @@ namespace Plugin { JsonArray formatArray; JsonArray sourceArray; - JsonObject rangeObj; + JsonObject rangeObj; unsigned int index = 0; tvError_t ret = getParamsCaps(range,pqmode,source,format,"Contrast"); - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { returnResponse(false); } - else - { + else { rangeObj["from"] = stoi(range[0]); rangeObj["to"] = stoi(range[1]); response["rangeInfo"]=rangeObj; - - if ((pqmode.front()).compare("none") != 0) - { - for (index = 0; index < pqmode.size(); index++) - { + + if ((pqmode.front()).compare("none") != 0) { + for (index = 0; index < pqmode.size(); index++) { pqmodeArray.Add(pqmode[index]); } response["pictureModeInfo"]=pqmodeArray; } if ((source.front()).compare("none") != 0) { - for (index = 0; index < source.size(); index++) - { + for (index = 0; index < source.size(); index++) { sourceArray.Add(source[index]); } response["videoSourceInfo"]=sourceArray; } - if ((format.front()).compare("none") != 0) - { - for (index = 0; index < format.size(); index++) - { + if ((format.front()).compare("none") != 0) { + for (index = 0; index < format.size(); index++) { formatArray.Add(format[index]); } response["videoFormatInfo"]=formatArray; @@ -1510,27 +1297,23 @@ namespace Plugin { int sourceIndex=0,pqIndex=0,formatIndex=0; int saturation = 0; - if (parsingGetInputArgument(parameters, "Saturation",source, pqmode, format) != 0) - { + if (parsingGetInputArgument(parameters, "Saturation",source, pqmode, format) != 0) { LOGINFO("%s: Failed to parse argument\n", __FUNCTION__); returnResponse(false); } - if (getParamIndex(source,pqmode,format,sourceIndex,pqIndex,formatIndex) == -1) - { + if (getParamIndex(source,pqmode,format,sourceIndex,pqIndex,formatIndex) == -1) { LOGERR("%s: getParamIndex failed to get \n", __FUNCTION__); returnResponse(false); } int err = getLocalparam("Saturation",formatIndex,pqIndex,sourceIndex,saturation, PQ_PARAM_SATURATION); - if( err == 0 ) - { + if( err == 0 ) { response["saturation"] = saturation; LOGINFO("Exit : Saturation Value: %d \n", saturation); returnResponse(true); } - else - { + else { returnResponse(false); } } @@ -1550,44 +1333,37 @@ namespace Plugin { returnIfParamNotFound(parameters,"saturation"); saturation = stoi(value); - if (validateIntegerInputParameter("Saturation",saturation) != 0) - { + if (validateIntegerInputParameter("Saturation",saturation) != 0) { LOGERR("Failed in saturation range validation:%s", __FUNCTION__); returnResponse(false); } - if (parsingSetInputArgument(parameters, "Saturation",source, pqmode, format) != 0) - { + if (parsingSetInputArgument(parameters, "Saturation",source, pqmode, format) != 0) { LOGERR("%s: Failed to parse the input arguments \n", __FUNCTION__); returnResponse(false); } - - if( !isCapablityCheckPassed( pqmode, source, format, "Saturation" )) - { + + if( !isCapablityCheckPassed( pqmode, source, format, "Saturation" )) { LOGERR("%s: CapablityCheck failed for Saturation\n", __FUNCTION__); returnResponse(false); } - if( isSetRequired(pqmode,source,format) ) - { + if( isSetRequired(pqmode,source,format) ) { LOGINFO("Proceed with %s\n",__FUNCTION__); ret = SetSaturation(saturation); } - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { LOGERR("Failed to set Saturation\n"); returnResponse(false); } - else - { + else { int params[3]={0}; params[0]=saturation; - int retval= UpdateAVoutputTVParam("set","Saturation",pqmode,source,format,PQ_PARAM_SATURATION,params); - if(retval != 0 ) - { + int retval= updateAVoutputTVParam("set","Saturation",pqmode,source,format,PQ_PARAM_SATURATION,params); + if(retval != 0 ) { LOGERR("Failed to Save Saturation to ssm_data\n"); - returnResponse(false); + returnResponse(false); } LOGINFO("Exit : setSaturation successful to value: %d\n", saturation); returnResponse(true); @@ -1608,50 +1384,41 @@ namespace Plugin { int params[3]={0}; tvError_t ret = tvERROR_NONE; - if (parsingSetInputArgument(parameters, "Saturation",source, pqmode, format) != 0) - { + if (parsingSetInputArgument(parameters, "Saturation",source, pqmode, format) != 0) { LOGERR("%s: Failed to parse the input arguments \n", __FUNCTION__); returnResponse(false); } - if( !isCapablityCheckPassed( pqmode, source, format, "Saturation" )) - { + if( !isCapablityCheckPassed( pqmode, source, format, "Saturation" )) { LOGERR("%s: CapablityCheck failed for Saturation\n", __FUNCTION__); returnResponse(false); } - int retval= UpdateAVoutputTVParam("reset","Saturation",pqmode,source,format,PQ_PARAM_SATURATION,params); + int retval= updateAVoutputTVParam("reset","Saturation",pqmode,source,format,PQ_PARAM_SATURATION,params); - if(retval != 0 ) - { + if(retval != 0 ) { LOGERR("Failed to reset Saturation\n"); returnResponse(false); } - else - { - if (isSetRequired(pqmode,source,format)) - { + else { + if (isSetRequired(pqmode,source,format)) { getParamIndex("Current","Current", "Current",sourceIndex,pqIndex,formatIndex); int err = getLocalparam("Saturation",formatIndex,pqIndex,sourceIndex, saturation, PQ_PARAM_SATURATION); - if( err == 0 ) - { + if( err == 0 ) { LOGINFO("%s : getLocalparam success format :%d source : %d format : %d value : %d\n",__FUNCTION__,formatIndex, sourceIndex, pqIndex,saturation); ret = SetSaturation(saturation); } - else - { + else { LOGERR("%s : GetLocalParam Failed \n",__FUNCTION__); - ret = tvERROR_GENERAL; + ret = tvERROR_GENERAL; } } } - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { returnResponse(false); } - else - { + else { LOGINFO("Exit : resetSaturation Successful to value : %d \n",saturation); returnResponse(true); } @@ -1676,37 +1443,29 @@ namespace Plugin { tvError_t ret = getParamsCaps(range,pqmode,source,format,"Saturation"); - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { returnResponse(false); } - else - { + else { rangeObj["from"] = stoi(range[0]); rangeObj["to"] = stoi(range[1]); response["rangeInfo"]=rangeObj; - - if ((pqmode.front()).compare("none") != 0) - { - for (index = 0; index < pqmode.size(); index++) - { + + if ((pqmode.front()).compare("none") != 0) { + for (index = 0; index < pqmode.size(); index++) { pqmodeArray.Add(pqmode[index]); } response["pictureModeInfo"]=pqmodeArray; } - if ((source.front()).compare("none") != 0) - { - for (index = 0; index < source.size(); index++) - { + if ((source.front()).compare("none") != 0) { + for (index = 0; index < source.size(); index++) { sourceArray.Add(source[index]); } response["videoSourceInfo"]=sourceArray; } - if ((format.front()).compare("none") != 0) - { - for (index = 0; index < format.size(); index++) - { + if ((format.front()).compare("none") != 0) { + for (index = 0; index < format.size(); index++) { formatArray.Add(format[index]); } response["videoFormatInfo"]=formatArray; @@ -1727,27 +1486,23 @@ namespace Plugin { int sourceIndex=0,pqIndex=0,formatIndex=0; int sharpness = 0; - if (parsingGetInputArgument(parameters, "Sharpness",source, pqmode, format) != 0) - { + if (parsingGetInputArgument(parameters, "Sharpness",source, pqmode, format) != 0) { LOGINFO("%s: Failed to parse argument\n", __FUNCTION__); returnResponse(false); } - if (getParamIndex(source,pqmode,format,sourceIndex,pqIndex,formatIndex) == -1) - { + if (getParamIndex(source,pqmode,format,sourceIndex,pqIndex,formatIndex) == -1) { LOGERR("%s: getParamIndex failed to get \n", __FUNCTION__); returnResponse(false); } int err = getLocalparam("Sharpness",formatIndex,pqIndex,sourceIndex,sharpness, PQ_PARAM_SHARPNESS); - if( err == 0 ) - { + if( err == 0 ) { response["sharpness"] = sharpness; LOGINFO("Exit : Sharpness Value: %d \n", sharpness); returnResponse(true); } - else - { + else { returnResponse(false); } } @@ -1767,44 +1522,37 @@ namespace Plugin { returnIfParamNotFound(parameters,"sharpness"); sharpness = stoi(value); - if (validateIntegerInputParameter("Sharpness",sharpness) != 0) - { + if (validateIntegerInputParameter("Sharpness",sharpness) != 0) { LOGERR("Failed in sharpness range validation:%s", __FUNCTION__); returnResponse(false); } - if (parsingSetInputArgument(parameters, "Sharpness",source, pqmode, format) != 0) - { + if (parsingSetInputArgument(parameters, "Sharpness",source, pqmode, format) != 0) { LOGERR("%s: Failed to parse the input arguments \n", __FUNCTION__); returnResponse(false); } - - if( !isCapablityCheckPassed( pqmode, source, format, "Sharpness" )) - { + + if( !isCapablityCheckPassed( pqmode, source, format, "Sharpness" )) { LOGERR("%s: CapablityCheck failed for Sharpness\n", __FUNCTION__); returnResponse(false); } - if( isSetRequired(pqmode,source,format) ) - { + if( isSetRequired(pqmode,source,format) ) { LOGINFO("Proceed with %s\n",__FUNCTION__); ret = SetSharpness(sharpness); } - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { LOGERR("Failed to set Sharpness\n"); returnResponse(false); } - else - { + else { int params[3]={0}; params[0]=sharpness; - int retval= UpdateAVoutputTVParam("set","Sharpness",pqmode,source,format,PQ_PARAM_SHARPNESS,params); - if(retval != 0 ) - { + int retval= updateAVoutputTVParam("set","Sharpness",pqmode,source,format,PQ_PARAM_SHARPNESS,params); + if(retval != 0 ) { LOGERR("Failed to Save Sharpness to ssm_data\n"); - returnResponse(false); + returnResponse(false); } LOGINFO("Exit : setSharpness successful to value: %d\n", sharpness); returnResponse(true); @@ -1825,50 +1573,41 @@ namespace Plugin { int params[3]={0}; tvError_t ret = tvERROR_NONE; - if (parsingSetInputArgument(parameters, "Sharpness",source, pqmode, format) != 0) - { + if (parsingSetInputArgument(parameters, "Sharpness",source, pqmode, format) != 0) { LOGERR("%s: Failed to parse the input arguments \n", __FUNCTION__); returnResponse(false); } - if( !isCapablityCheckPassed( pqmode, source, format, "Sharpness" )) - { + if( !isCapablityCheckPassed( pqmode, source, format, "Sharpness" )) { LOGERR("%s: CapablityCheck failed for Sharpness\n", __FUNCTION__); returnResponse(false); } - int retval= UpdateAVoutputTVParam("reset","Sharpness",pqmode,source,format,PQ_PARAM_SHARPNESS,params); + int retval= updateAVoutputTVParam("reset","Sharpness",pqmode,source,format,PQ_PARAM_SHARPNESS,params); - if(retval != 0 ) - { + if(retval != 0 ) { LOGERR("Failed to reset Sharpness\n"); returnResponse(false); } - else - { - if (isSetRequired(pqmode,source,format)) - { + else { + if (isSetRequired(pqmode,source,format)) { getParamIndex("Current","Current", "Current",sourceIndex,pqIndex,formatIndex); int err = getLocalparam("Sharpness",formatIndex,pqIndex,sourceIndex, sharpness, PQ_PARAM_SHARPNESS); - if( err == 0 ) - { + if( err == 0 ) { LOGINFO("%s : getLocalparam success format :%d source : %d format : %d value : %d\n",__FUNCTION__,formatIndex, sourceIndex, pqIndex,sharpness); ret = SetSharpness(sharpness); } - else - { + else { LOGERR("%s : GetLocalParam Failed \n",__FUNCTION__); - ret = tvERROR_GENERAL; + ret = tvERROR_GENERAL; } } } - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { returnResponse(false); } - else - { + else { LOGINFO("Exit : resetSharpness Successful to value : %d \n",sharpness); returnResponse(true); } @@ -1893,36 +1632,28 @@ namespace Plugin { tvError_t ret = getParamsCaps(range,pqmode,source,format,"Sharpness"); - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { returnResponse(false); } - else - { + else { rangeObj["from"] = stoi(range[0]); rangeObj["to"] = stoi(range[1]); response["rangeInfo"]=rangeObj; - - if ((pqmode.front()).compare("none") != 0) - { - for (index = 0; index < pqmode.size(); index++) - { + + if ((pqmode.front()).compare("none") != 0) { + for (index = 0; index < pqmode.size(); index++) { pqmodeArray.Add(pqmode[index]); } response["pictureModeInfo"]=pqmodeArray; } - if ((source.front()).compare("none") != 0) - { - for (index = 0; index < source.size(); index++) - { + if ((source.front()).compare("none") != 0) { + for (index = 0; index < source.size(); index++) { sourceArray.Add(source[index]); } response["videoSourceInfo"]=sourceArray; } - if ((format.front()).compare("none") != 0) - { - for (index = 0; index < format.size(); index++) - { + if ((format.front()).compare("none") != 0) { + for (index = 0; index < format.size(); index++) { formatArray.Add(format[index]); } response["videoFormatInfo"]=formatArray; @@ -1943,27 +1674,23 @@ namespace Plugin { int sourceIndex=0,pqIndex=0,formatIndex=0; int hue = 0; - if (parsingGetInputArgument(parameters, "Hue",source, pqmode, format) != 0) - { + if (parsingGetInputArgument(parameters, "Hue",source, pqmode, format) != 0) { LOGINFO("%s: Failed to parse argument\n", __FUNCTION__); returnResponse(false); } - if (getParamIndex(source,pqmode,format,sourceIndex,pqIndex,formatIndex) == -1) - { + if (getParamIndex(source,pqmode,format,sourceIndex,pqIndex,formatIndex) == -1) { LOGERR("%s: getParamIndex failed to get \n", __FUNCTION__); returnResponse(false); } int err = getLocalparam("Hue",formatIndex,pqIndex,sourceIndex,hue, PQ_PARAM_HUE); - if( err == 0 ) - { + if( err == 0 ) { response["hue"] = hue; LOGINFO("Exit : Hue Value: %d \n", hue); returnResponse(true); } - else - { + else { returnResponse(false); } } @@ -1983,44 +1710,37 @@ namespace Plugin { returnIfParamNotFound(parameters,"hue"); hue = stoi(value); - if (validateIntegerInputParameter("Hue",hue) != 0) - { + if (validateIntegerInputParameter("Hue",hue) != 0) { LOGERR("Failed in hue range validation:%s", __FUNCTION__); returnResponse(false); } - if (parsingSetInputArgument(parameters, "Hue",source, pqmode, format) != 0) - { + if (parsingSetInputArgument(parameters, "Hue",source, pqmode, format) != 0) { LOGERR("%s: Failed to parse the input arguments \n", __FUNCTION__); returnResponse(false); } - if( !isCapablityCheckPassed( pqmode, source, format, "Hue" )) - { + if( !isCapablityCheckPassed( pqmode, source, format, "Hue" )) { LOGERR("%s: CapablityCheck failed for Hue\n", __FUNCTION__); returnResponse(false); } - if( isSetRequired(pqmode,source,format) ) - { + if( isSetRequired(pqmode,source,format) ) { LOGINFO("Proceed with %s\n",__FUNCTION__); ret = SetHue(hue); } - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { LOGERR("Failed to set Hue\n"); returnResponse(false); } - else - { + else { int params[3]={0}; params[0]=hue; - int retval= UpdateAVoutputTVParam("set","Hue",pqmode,source,format,PQ_PARAM_HUE,params); - if(retval != 0 ) - { + int retval= updateAVoutputTVParam("set","Hue",pqmode,source,format,PQ_PARAM_HUE,params); + if(retval != 0 ) { LOGERR("Failed to Save Hue to ssm_data\n"); - returnResponse(false); + returnResponse(false); } LOGINFO("Exit : setHue successful to value: %d\n", hue); returnResponse(true); @@ -2041,50 +1761,41 @@ namespace Plugin { int params[3]={0}; tvError_t ret = tvERROR_NONE; - if (parsingSetInputArgument(parameters, "Hue",source, pqmode, format) != 0) - { + if (parsingSetInputArgument(parameters, "Hue",source, pqmode, format) != 0) { LOGERR("%s: Failed to parse the input arguments \n", __FUNCTION__); returnResponse(false); } - if( !isCapablityCheckPassed( pqmode, source, format, "Hue" )) - { + if( !isCapablityCheckPassed( pqmode, source, format, "Hue" )) { LOGERR("%s: CapablityCheck failed for Hue\n", __FUNCTION__); returnResponse(false); } - int retval= UpdateAVoutputTVParam("reset","Hue",pqmode,source,format,PQ_PARAM_HUE,params); + int retval= updateAVoutputTVParam("reset","Hue",pqmode,source,format,PQ_PARAM_HUE,params); - if(retval != 0 ) - { + if(retval != 0 ) { LOGERR("Failed to reset Hue\n"); returnResponse(false); } - else - { - if (isSetRequired(pqmode,source,format)) - { + else { + if (isSetRequired(pqmode,source,format)) { getParamIndex("Current","Current", "Current",sourceIndex,pqIndex,formatIndex); int err = getLocalparam("Hue",formatIndex,pqIndex,sourceIndex, hue, PQ_PARAM_HUE); - if( err == 0 ) - { + if( err == 0 ) { LOGINFO("%s : getLocalparam success format :%d source : %d format : %d value : %d\n",__FUNCTION__,formatIndex, sourceIndex, pqIndex,hue); ret = SetHue(hue); } - else - { + else { LOGERR("%s : GetLocalParam Failed \n",__FUNCTION__); - ret = tvERROR_GENERAL; + ret = tvERROR_GENERAL; } } } - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { returnResponse(false); } - else - { + else { LOGINFO("Exit : resetHue Successful to value : %d \n",hue); returnResponse(true); } @@ -2109,36 +1820,28 @@ namespace Plugin { tvError_t ret = getParamsCaps(range,pqmode,source,format,"Hue"); - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { returnResponse(false); } - else - { + else { rangeObj["from"] = stoi(range[0]); rangeObj["to"] = stoi(range[1]); - response["rangeInfo"]=rangeObj; + response["rangeInfo"]=rangeObj; - if ((pqmode.front()).compare("none") != 0) - { - for (index = 0; index < pqmode.size(); index++) - { + if ((pqmode.front()).compare("none") != 0) { + for (index = 0; index < pqmode.size(); index++) { pqmodeArray.Add(pqmode[index]); } response["pictureModeInfo"]=pqmodeArray; } - if ((source.front()).compare("none") != 0) - { - for (index = 0; index < source.size(); index++) - { + if ((source.front()).compare("none") != 0) { + for (index = 0; index < source.size(); index++) { sourceArray.Add(source[index]); } response["videoSourceInfo"]=sourceArray; } - if ((format.front()).compare("none") != 0) - { - for (index = 0; index < format.size(); index++) - { + if ((format.front()).compare("none") != 0) { + for (index = 0; index < format.size(); index++) { formatArray.Add(format[index]); } response["videoFormatInfo"]=formatArray; @@ -2159,23 +1862,19 @@ namespace Plugin { int sourceIndex=0,pqIndex=0,formatIndex=0; int colortemp = 0; - if (parsingGetInputArgument(parameters, "ColorTemperature",source, pqmode, format) != 0) - { + if (parsingGetInputArgument(parameters, "ColorTemperature",source, pqmode, format) != 0) { LOGINFO("%s: Failed to parse argument\n", __FUNCTION__); returnResponse(false); } - if (getParamIndex(source,pqmode,format,sourceIndex,pqIndex,formatIndex) == -1) - { + if (getParamIndex(source,pqmode,format,sourceIndex,pqIndex,formatIndex) == -1) { LOGERR("%s: getParamIndex failed to get \n", __FUNCTION__); returnResponse(false); } int err = getLocalparam("ColorTemp",formatIndex,pqIndex,sourceIndex,colortemp,PQ_PARAM_COLOR_TEMPERATURE); - if( err == 0 ) - { - switch(colortemp) - { + if( err == 0 ) { + switch(colortemp) { case tvColorTemp_STANDARD: LOGINFO("Color Temp Value: Standard\n"); response["colorTemperature"] = "Standard"; @@ -2222,58 +1921,48 @@ namespace Plugin { value = parameters.HasLabel("colorTemperature") ? parameters["colorTemperature"].String() : ""; returnIfParamNotFound(parameters,"colorTemperature"); - if(!value.compare("Standard")) - { + if(!value.compare("Standard")) { colortemp = tvColorTemp_STANDARD; } - else if (!value.compare("Warm")) - { + else if (!value.compare("Warm")) { colortemp = tvColorTemp_WARM; } - else if (!value.compare("Cold")) - { + else if (!value.compare("Cold")) { colortemp = tvColorTemp_COLD; } - else if (!value.compare("User Defined")) - { + else if (!value.compare("User Defined")) { colortemp = tvColorTemp_USER; } - else - { + else { returnResponse(false); } - if (parsingSetInputArgument(parameters, "ColorTemperature",source, pqmode, format) != 0) - { + if (parsingSetInputArgument(parameters, "ColorTemperature",source, pqmode, format) != 0) { LOGERR("%s: Failed to parse the input arguments \n", __FUNCTION__); returnResponse(false); } - if( !isCapablityCheckPassed( pqmode, source, format, "ColorTemperature" )) - { + if( !isCapablityCheckPassed( pqmode, source, format, "ColorTemperature" )) { LOGERR("%s: CapablityCheck failed for colorTemperature\n", __FUNCTION__); returnResponse(false); } - if( isSetRequired(pqmode,source,format) ) - { + if( isSetRequired(pqmode,source,format) ) { LOGINFO("Proceed with %s\n",__FUNCTION__); ret = SetColorTemperature((tvColorTemp_t)colortemp); } - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { LOGERR("Failed to set ColorTemperature\n"); returnResponse(false); } else { int params[3]={0}; params[0]=(int)colortemp; - int retval= UpdateAVoutputTVParam("set","ColorTemp",pqmode,source,format,PQ_PARAM_COLOR_TEMPERATURE,params); - if(retval != 0 ) - { + int retval= updateAVoutputTVParam("set","ColorTemp",pqmode,source,format,PQ_PARAM_COLOR_TEMPERATURE,params); + if(retval != 0 ) { LOGERR("Failed to Save ColorTemperature to ssm_data\n"); - returnResponse(false); + returnResponse(false); } LOGINFO("Exit : setColorTemperature successful to value: %d\n", colortemp); returnResponse(true); @@ -2293,50 +1982,41 @@ namespace Plugin { int params[3]={0}; tvError_t ret = tvERROR_NONE; - if (parsingSetInputArgument(parameters, "ColorTemperature",source, pqmode, format) != 0) - { + if (parsingSetInputArgument(parameters, "ColorTemperature",source, pqmode, format) != 0) { LOGERR("%s: Failed to parse the input arguments \n", __FUNCTION__); returnResponse(false); } - if( !isCapablityCheckPassed( pqmode, source, format, "ColorTemperature" )) - { + if( !isCapablityCheckPassed( pqmode, source, format, "ColorTemperature" )) { LOGERR("%s: CapablityCheck failed for colorTemperature\n", __FUNCTION__); returnResponse(false); } - int retval= UpdateAVoutputTVParam("reset","ColorTemp",pqmode,source,format,PQ_PARAM_COLOR_TEMPERATURE,params); + int retval= updateAVoutputTVParam("reset","ColorTemp",pqmode,source,format,PQ_PARAM_COLOR_TEMPERATURE,params); - if(retval != 0 ) - { + if(retval != 0 ) { LOGERR("Failed to reset ColorTemperature\n"); returnResponse(false); } - else - { - if (isSetRequired(pqmode,source,format)) - { + else { + if (isSetRequired(pqmode,source,format)) { getParamIndex("Current","Current", "Current",sourceIndex,pqIndex,formatIndex); int err = getLocalparam("ColorTemp",formatIndex,pqIndex,sourceIndex, colortemp, PQ_PARAM_COLOR_TEMPERATURE); - if( err == 0 ) - { + if( err == 0 ) { LOGINFO("%s : getLocalparam success format :%d source : %d format : %d value : %d\n",__FUNCTION__,formatIndex, sourceIndex, pqIndex, colortemp); ret = SetColorTemperature((tvColorTemp_t)colortemp); } - else - { + else { LOGERR("%s : GetLocalParam Failed \n",__FUNCTION__); - ret = tvERROR_GENERAL; + ret = tvERROR_GENERAL; } } } - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { returnResponse(false); } - else - { + else { LOGINFO("Exit : resetColorTemperature Successful to value : %d \n",colortemp); returnResponse(true); } @@ -2362,33 +2042,27 @@ namespace Plugin { if(ret != tvERROR_NONE) { returnResponse(false); } - else - { - for (index = 0; index < range.size(); index++) + else { + for (index = 0; index < range.size(); index++) { rangeArray.Add(range[index]); + } response["options"]=rangeArray; - if (((pqmode.front()).compare("none") != 0)) - { - for (index = 0; index < pqmode.size(); index++) - { + if (((pqmode.front()).compare("none") != 0)) { + for (index = 0; index < pqmode.size(); index++) { pqmodeArray.Add(pqmode[index]); } response["pictureModeInfo"]=pqmodeArray; } - if ((source.front()).compare("none") != 0) - { - for (index = 0; index < source.size(); index++) - { + if ((source.front()).compare("none") != 0) { + for (index = 0; index < source.size(); index++) { sourceArray.Add(source[index]); } response["videoSourceInfo"]=sourceArray; } - if ((format.front()).compare("none") != 0) - { - for (index = 0; index < format.size(); index++) - { + if ((format.front()).compare("none") != 0) { + for (index = 0; index < format.size(); index++) { formatArray.Add(format[index]); } response["videoFormatInfo"]=formatArray; @@ -2405,34 +2079,30 @@ namespace Plugin { std::string pqmode; std::string source; std::string format; - std::string key; - int sourceIndex=0,pqIndex=0,formatIndex=0; + std::string key; + int sourceIndex=0,pqIndex=0,formatIndex=0; int dimmingMode = 0; - if (parsingGetInputArgument(parameters, "DimmingMode",source, pqmode, format) != 0) - { + if (parsingGetInputArgument(parameters, "DimmingMode",source, pqmode, format) != 0) { LOGINFO("%s: Failed to parse argument\n", __FUNCTION__); returnResponse(false); } - if (getParamIndex(source,pqmode,format,sourceIndex,pqIndex,formatIndex) == -1) - { + if (getParamIndex(source,pqmode,format,sourceIndex,pqIndex,formatIndex) == -1) { LOGERR("%s: getParamIndex failed to get \n", __FUNCTION__); returnResponse(false); } int err = getLocalparam("DimmingMode",formatIndex,pqIndex,sourceIndex,dimmingMode, PQ_PARAM_DIMMINGMODE); - if( err == 0 ) - { - switch(dimmingMode) - { + if( err == 0 ) { + switch(dimmingMode) { case tvDimmingMode_Fixed: LOGINFO("DimmingMode Value: Fixed\n"); response["DimmingMode"] = "fixed"; break; - case tvDimmingMode_Local: + case tvDimmingMode_Local: LOGINFO("DimmingMode Value: Local\n"); response["DimmingMode"] = "local"; break; @@ -2441,13 +2111,12 @@ namespace Plugin { LOGINFO("DimmingMode Value: Global\n"); response["DimmingMode"] = "global"; break; - + } LOGINFO("Exit : DimmingMode Value: %d \n", dimmingMode); returnResponse(true); } - else - { + else { returnResponse(false); } } @@ -2461,48 +2130,41 @@ namespace Plugin { std::string source; std::string format; int dimmingMode = 0; - tvError_t ret = tvERROR_NONE; + tvError_t ret = tvERROR_NONE; value = parameters.HasLabel("DimmingMode") ? parameters["DimmingMode"].String() : ""; returnIfParamNotFound(parameters,"DimmingMode"); - - if (validateInputParameter("DimmingMode",value) != 0) - { + + if (validateInputParameter("DimmingMode",value) != 0) { LOGERR("%s: Range validation failed for DimmingMode\n", __FUNCTION__); returnResponse(false); } dimmingMode = getDimmingModeIndex(value); - if (parsingSetInputArgument(parameters, "DimmingMode",source, pqmode, format) != 0) - { + if (parsingSetInputArgument(parameters, "DimmingMode",source, pqmode, format) != 0) { LOGERR("%s: Failed to parse the input arguments \n", __FUNCTION__); returnResponse(false); } - if( !isCapablityCheckPassed( pqmode, source, format, "DimmingMode" )) - { + if( !isCapablityCheckPassed( pqmode, source, format, "DimmingMode" )) { LOGERR("%s: CapablityCheck failed for DimmingMode\n", __FUNCTION__); returnResponse(false); } - if( isSetRequired(pqmode,source,format) ) - { + if( isSetRequired(pqmode,source,format) ) { LOGINFO("Proceed with %s\n",__FUNCTION__); ret = SetTVDimmingMode(value.c_str()); } - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { LOGERR("Failed to set DimmingMode\n"); returnResponse(false); } - else - { + else { int params[3]={0}; params[0]=(int)dimmingMode; - int retval= UpdateAVoutputTVParam("set","DimmingMode",pqmode,source,format,PQ_PARAM_DIMMINGMODE,params); - if(retval != 0 ) - { + int retval= updateAVoutputTVParam("set","DimmingMode",pqmode,source,format,PQ_PARAM_DIMMINGMODE,params); + if(retval != 0 ) { LOGERR("Failed to Save DimmingMode to ssm_data\n"); returnResponse(false); } @@ -2524,52 +2186,43 @@ namespace Plugin { int params[3]={0}; tvError_t ret = tvERROR_NONE; - if (parsingSetInputArgument(parameters, "DimmingMode",source, pqmode, format) != 0) - { + if (parsingSetInputArgument(parameters, "DimmingMode",source, pqmode, format) != 0) { LOGERR("%s: Failed to parse the input arguments \n", __FUNCTION__); returnResponse(false); } - if( !isCapablityCheckPassed( pqmode, source, format, "DimmingMode" )) - { + if( !isCapablityCheckPassed( pqmode, source, format, "DimmingMode" )) { LOGERR("%s: CapablityCheck failed for DimmingMode\n", __FUNCTION__); returnResponse(false); } - int retval= UpdateAVoutputTVParam("reset","DimmingMode",pqmode,source,format,PQ_PARAM_DIMMINGMODE,params); + int retval= updateAVoutputTVParam("reset","DimmingMode",pqmode,source,format,PQ_PARAM_DIMMINGMODE,params); - if(retval != 0 ) - { + if(retval != 0 ) { LOGERR("Failed to reset ldim\n"); returnResponse(false); } - else - { - if (isSetRequired(pqmode,source,format)) - { + else { + if (isSetRequired(pqmode,source,format)) { getParamIndex("Current","Current", "Current",sourceIndex,pqIndex,formatIndex); int err = getLocalparam("DimmingMode",formatIndex,pqIndex,sourceIndex, dMode, PQ_PARAM_DIMMINGMODE); - if( err == 0 ) - { + if( err == 0 ) { LOGINFO("%s : getLocalparam success format :%d source : %d format : %d value : %d\n",__FUNCTION__,formatIndex, sourceIndex, pqIndex, dMode); getDimmingModeStringFromEnum(dMode,dimmingMode); ret = SetTVDimmingMode(dimmingMode.c_str()); } - else - { + else { LOGERR("%s : GetLocalParam Failed \n",__FUNCTION__); - ret = tvERROR_GENERAL; + ret = tvERROR_GENERAL; } } } - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { returnResponse(false); } - else - { + else { LOGINFO("Exit : resetBacklightDimmingMode Successful to value : %s \n",dimmingMode.c_str()); returnResponse(true); } @@ -2592,37 +2245,30 @@ namespace Plugin { tvError_t ret = getParamsCaps(supportedDimmingMode,pqmode,source,format,"DimmingMode"); - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { returnResponse(false); } - else - { - for (index = 0; index < supportedDimmingMode.size(); index++) + else { + for (index = 0; index < supportedDimmingMode.size(); index++) { supportedDimmingModeArray.Add(supportedDimmingMode[index]); + } response["options"]=supportedDimmingModeArray; - - if (((pqmode.front()).compare("none") != 0)) - { - for (index = 0; index < pqmode.size(); index++) - { + + if (((pqmode.front()).compare("none") != 0)) { + for (index = 0; index < pqmode.size(); index++) { pqmodeArray.Add(pqmode[index]); } response["pictureModeInfo"]=pqmodeArray; } - if ((source.front()).compare("none") != 0) - { - for (index = 0; index < source.size(); index++) - { + if ((source.front()).compare("none") != 0) { + for (index = 0; index < source.size(); index++) { sourceArray.Add(source[index]); } response["videoSourceInfo"]=sourceArray; } - if ((format.front()).compare("none") != 0) - { - for (index = 0; index < format.size(); index++) - { + if ((format.front()).compare("none") != 0) { + for (index = 0; index < format.size(); index++) { formatArray.Add(format[index]); } response["videoFormatInfo"]=formatArray; @@ -2639,16 +2285,13 @@ namespace Plugin { pic_modes_t *dvModes; unsigned short totalAvailable = 0; tvError_t ret = GetTVSupportedDolbyVisionModesODM(&dvModes,&totalAvailable); - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { returnResponse(false); } - else - { + else { JsonArray SupportedDVModes; - for(int count = 0;count range,pqmode,source,format; - - tvError_t ret = getParamsCaps(range,pqmode,source,format,"VideoSource"); - - if(ret != tvERROR_NONE) - { - return -1; - } - else - { - if ((range.front()).compare("none") != 0) { - for (unsigned int index = 0; index < range.size(); index++) - { - rangeArray.Add(range[index]); - } - } - } - return 0; - } - - int AVOutputTV::getRangeCapability(std::string param, std::vector & rangeInfo) - { - std::vector range,pqmode,source,format; - - tvError_t ret = getParamsCaps(range,pqmode,source,format, param); - - if(ret != tvERROR_NONE) - { - return -1; - } - else - { - if ((range.front()).compare("none") != 0) - { - rangeInfo = range; - } - } - return 0; - } - - uint32_t AVOutputTV::getVideoSourceCaps(const JsonObject& parameters, JsonObject& response) + uint32_t AVOutputTV::getVideoSourceCaps(const JsonObject& parameters, JsonObject& response) { JsonArray rangeArray; @@ -2989,8 +2542,7 @@ namespace Plugin { std::vector source; std::vector format; - if (getCapabilitySource(rangeArray) != 0) - { + if (getCapabilitySource(rangeArray) != 0) { returnResponse(false); } response["options"]=rangeArray; @@ -2998,7 +2550,7 @@ namespace Plugin { returnResponse(true); } - uint32_t AVOutputTV::getVideoFormatCaps(const JsonObject& parameters, JsonObject& response) + uint32_t AVOutputTV::getVideoFormatCaps(const JsonObject& parameters, JsonObject& response) { JsonArray rangeArray; @@ -3010,16 +2562,12 @@ namespace Plugin { tvError_t ret = getParamsCaps(range,pqmode,source,format,"VideoFormat"); - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { returnResponse(false); } - else - { - if ((range.front()).compare("none") != 0) - { - for (unsigned int index = 0; index < range.size(); index++) - { + else { + if ((range.front()).compare("none") != 0) { + for (unsigned int index = 0; index < range.size(); index++) { rangeArray.Add(range[index]); } response["options"]=rangeArray; @@ -3029,20 +2577,18 @@ namespace Plugin { returnResponse(true); } - uint32_t AVOutputTV::getVideoFrameRateCaps(const JsonObject& parameters, JsonObject& response) + uint32_t AVOutputTV::getVideoFrameRateCaps(const JsonObject& parameters, JsonObject& response) { LOGINFO("Entry\n"); - + std::vector rangeInfo; JsonArray rangeArray; - - if ( getRangeCapability("VideoFrameRate", rangeInfo) != 0 ) - { + + if ( getRangeCapability("VideoFrameRate", rangeInfo) != 0 ) { returnResponse(false); - } - - for (unsigned int index = 0; index < rangeInfo.size(); index++) - { + } + + for (unsigned int index = 0; index < rangeInfo.size(); index++) { rangeArray.Add(std::stof(rangeInfo[index])); } @@ -3050,56 +2596,48 @@ namespace Plugin { returnResponse(true); } - uint32_t AVOutputTV::getVideoResolutionCaps(const JsonObject& parameters, JsonObject& response) + uint32_t AVOutputTV::getVideoResolutionCaps(const JsonObject& parameters, JsonObject& response) { LOGINFO("Entry\n"); response["maxResolution"] = "4096*2160p"; returnResponse(true); } - uint32_t AVOutputTV::getPictureModeCaps(const JsonObject& parameters, JsonObject& response) + uint32_t AVOutputTV::getPictureModeCaps(const JsonObject& parameters, JsonObject& response) { JsonArray sourceArray; JsonArray formatArray; JsonArray rangeArray; - - std::vector range; - std::vector source; - std::vector pqmode; - std::vector format; - unsigned int index = 0; + std::vector range; + std::vector source; + std::vector pqmode; + std::vector format; + + unsigned int index = 0; tvError_t ret = getParamsCaps(range,pqmode,source,format,"PictureMode"); - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { returnResponse(false); } - else - { - - if ((range.front()).compare("none") != 0) - { - for (index = 0; index < range.size(); index++) - { + else { + + if ((range.front()).compare("none") != 0) { + for (index = 0; index < range.size(); index++) { rangeArray.Add(range[index]); } response["options"]=rangeArray; } - - if ((source.front()).compare("none") != 0) - { - for (index = 0; index < source.size(); index++) - { + + if ((source.front()).compare("none") != 0) { + for (index = 0; index < source.size(); index++) { sourceArray.Add(source[index]); } response["videoSourceInfo"]=sourceArray; } - if ((format.front()).compare("none") != 0) - { - for (index = 0; index < format.size(); index++) - { + if ((format.front()).compare("none") != 0) { + for (index = 0; index < format.size(); index++) { formatArray.Add(format[index]); } response["videoFormatInfo"]=formatArray; @@ -3123,28 +2661,24 @@ namespace Plugin { TR181_ParamData_t param = {0}; tr181ErrorCode_t err = tr181Success; - if (parsingGetInputArgument(parameters, "PictureMode",source, dummyPqmode, format) != 0) - { + if (parsingGetInputArgument(parameters, "PictureMode",source, dummyPqmode, format) != 0) { LOGINFO("%s: Failed to parse argument\n", __FUNCTION__); returnResponse(false); } - if (getParamIndex(source,dummyPqmode,format,current_source,pqIndex,current_format) == -1) - { + if (getParamIndex(source,dummyPqmode,format,current_source,pqIndex,current_format) == -1) { LOGERR("%s: getParamIndex failed to get \n", __FUNCTION__); returnResponse(false); } tr181_param_name += std::string(AVOUTPUT_SOURCE_PICTUREMODE_STRING_RFC_PARAM); tr181_param_name += "." + convertSourceIndexToString(current_source) + "." + "Format."+convertVideoFormatToString(current_format)+"."+"PictureModeString"; - err = getLocalParam(rfc_caller_id, tr181_param_name.c_str(), ¶m); + err = getLocalParam(rfc_caller_id, tr181_param_name.c_str(), ¶m); - if ( tr181Success != err ) - { + if ( tr181Success != err ) { returnResponse(false); } - else - { + else { std::string s; s+=param.value; response["pictureMode"] = s; @@ -3168,84 +2702,77 @@ namespace Plugin { returnIfParamNotFound(parameters,"pictureMode"); // As only source need to validate, so pqmode and formate passing as currrent - if (parsingSetInputArgument(parameters, "PictureMode",source, dummyPqmode, format) != 0) - { + if (parsingSetInputArgument(parameters, "PictureMode",source, dummyPqmode, format) != 0) { LOGERR("%s: Failed to parse the input arguments \n", __FUNCTION__); returnResponse(false); } - if (validateInputParameter("PictureMode",value) != 0) - { + if (validateInputParameter("PictureMode",value) != 0) { LOGERR("%s: Range validation failed for PictureMode\n", __FUNCTION__); returnResponse(false); } - if( !isCapablityCheckPassed( dummyPqmode, source,format, "PictureMode" )) - { + if( !isCapablityCheckPassed( dummyPqmode, source,format, "PictureMode" )) { LOGERR("%s: CapablityCheck failed for PictureMode\n", __FUNCTION__); returnResponse(false); } - std::string local = value; - transform(local.begin(), local.end(), local.begin(), ::tolower); - if( isSetRequired("Current",source,format) ) - { + std::string local = value; + transform(local.begin(), local.end(), local.begin(), ::tolower); + if( isSetRequired("Current",source,format) ) { LOGINFO("Proceed with SetTVPictureMode\n"); ret = SetTVPictureMode(local.c_str()); } - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { returnResponse(false); } - else - { - std::vector pq_mode_vec; - std::vector source_vec; - std::vector format_vec; - - getSaveConfig("Current", source.c_str(), format.c_str(), source_vec, pq_mode_vec, format_vec); - - for (int sourceType : source_vec) - { + else { + std::vector pq_mode_vec; + std::vector source_vec; + std::vector format_vec; + + getSaveConfig("Current", source.c_str(), format.c_str(), source_vec, pq_mode_vec, format_vec); + + for (int sourceType : source_vec) { tvVideoSrcType_t source = (tvVideoSrcType_t)sourceType; - for (int formatType : format_vec) - { + for (int formatType : format_vec) { tvVideoFormatType_t format = (tvVideoFormatType_t)formatType; std::string tr181_param_name = ""; tr181_param_name += std::string(AVOUTPUT_SOURCE_PICTUREMODE_STRING_RFC_PARAM); // framing Device.DeviceInfo.X_RDKCENTRAL-COM_RFC.AVOutput.Source.source_index[x].Format.format_index[x].PictureModeString.value tr181_param_name += "."+convertSourceIndexToString(source)+"."+"Format."+ - convertVideoFormatToString(format)+"."+"PictureModeString"; + convertVideoFormatToString(format)+"."+"PictureModeString"; tr181ErrorCode_t err = setLocalParam(rfc_caller_id, tr181_param_name.c_str(), value.c_str()); - if ( err != tr181Success ) - { + if ( err != tr181Success ) { LOGERR("setLocalParam for %s Failed : %s\n", AVOUTPUT_SOURCE_PICTUREMODE_STRING_RFC_PARAM, getTR181ErrorString(err)); - returnResponse(false); + returnResponse(false); } - else - { + else { LOGINFO("setLocalParam for %s Successful, Value: %s\n", AVOUTPUT_SOURCE_PICTUREMODE_STRING_RFC_PARAM, value.c_str()); - int pqmodeindex = (int)getPictureModeIndex(value); + int pqmodeindex = (int)getPictureModeIndex(value); SaveSourcePictureMode(source, format, pqmodeindex); - } + } } } - //Filmmaker mode telemetry - if(!strncmp(value.c_str(),"filmmaker",strlen(value.c_str())) && strncmp(prevmode,"filmmaker",strlen(prevmode))) + //Filmmaker mode telemetry + if(!strncmp(value.c_str(),"filmmaker",strlen(value.c_str())) && strncmp(prevmode,"filmmaker",strlen(prevmode))) { LOGINFO("%s mode has been enabled",value.c_str()); - else if(!strncmp(prevmode,"filmmaker",strlen(prevmode)) && strncmp(value.c_str(),"filmmaker",strlen(value.c_str()))) + } + else if(!strncmp(prevmode,"filmmaker",strlen(prevmode)) && strncmp(value.c_str(),"filmmaker",strlen(value.c_str()))) { LOGINFO("%s mode has been disabled",prevmode); + } LOGINFO("Broadcasting the low latency change event \n"); - if(m_isDalsEnabled) - { + if(m_isDalsEnabled) { //GameModebroadcast - if(!strncmp(value.c_str(),"game",strlen(value.c_str())) && strncmp(prevmode,"game",strlen(prevmode))) - BroadcastLowLatencyModeChangeEvent(1); - else if(!strncmp(prevmode,"game",strlen(prevmode)) && strncmp(value.c_str(),"game",strlen(value.c_str()))) - BroadcastLowLatencyModeChangeEvent(0); - } + if(!strncmp(value.c_str(),"game",strlen(value.c_str())) && strncmp(prevmode,"game",strlen(prevmode))) { + broadcastLowLatencyModeChangeEvent(1); + } + else if(!strncmp(prevmode,"game",strlen(prevmode)) && strncmp(value.c_str(),"game",strlen(value.c_str()))) { + broadcastLowLatencyModeChangeEvent(0); + } + } LOGINFO("Exit : Value : %s \n",value.c_str()); returnResponse(true); @@ -3257,7 +2784,7 @@ namespace Plugin { LOGINFO("Entry\n"); tr181ErrorCode_t err = tr181Success; TR181_ParamData_t param = {0}; - + std::vector pq_mode_vec; std::vector source_vec; std::vector format_vec; @@ -3266,83 +2793,71 @@ namespace Plugin { std::string format; // As only source need to validate, so pqmode and formate passing as currrent - if (parsingSetInputArgument(parameters, "PictureMode",source, dummyPqmode, format) != 0) - { + if (parsingSetInputArgument(parameters, "PictureMode",source, dummyPqmode, format) != 0) { LOGERR("%s: Failed to parse the input arguments \n", __FUNCTION__); returnResponse(false); } - if( !isCapablityCheckPassed( dummyPqmode, source,format, "PictureMode" )) - { + if( !isCapablityCheckPassed( dummyPqmode, source,format, "PictureMode" )) { LOGERR("%s: CapablityCheck failed for PictureMode\n", __FUNCTION__); returnResponse(false); } getSaveConfig("Current", source, format, source_vec, pq_mode_vec, format_vec); - - for (int source : source_vec) - { + + for (int source : source_vec) { tvVideoSrcType_t sourceType = (tvVideoSrcType_t)source; - for (int format : format_vec) - { + for (int format : format_vec) { tvVideoFormatType_t formatType = (tvVideoFormatType_t)format; std::string tr181_param_name = ""; tr181_param_name += std::string(AVOUTPUT_SOURCE_PICTUREMODE_STRING_RFC_PARAM); - tr181_param_name += "."+convertSourceIndexToString(sourceType)+"."+"Format."+ - convertVideoFormatToString(formatType)+"."+"PictureModeString"; + tr181_param_name += "."+convertSourceIndexToString(sourceType)+"."+"Format."+ + convertVideoFormatToString(formatType)+"."+"PictureModeString"; - err = clearLocalParam(rfc_caller_id, tr181_param_name.c_str()); - if ( err != tr181Success ) - { + err = clearLocalParam(rfc_caller_id, tr181_param_name.c_str()); + if ( err != tr181Success ) { LOGWARN("clearLocalParam for %s Failed : %s\n", tr181_param_name.c_str(), getTR181ErrorString(err)); returnResponse(false); } - else - { + else { err = getLocalParam(rfc_caller_id, tr181_param_name.c_str(), ¶m); - if ( tr181Success == err ) - { + if ( tr181Success == err ) { //get curren source and if matches save for that alone - tvVideoSrcType_t current_source = VIDEO_SOURCE_IP; - GetCurrentSource(¤t_source); + tvVideoSrcType_t current_source = VIDEO_SOURCE_IP; + GetCurrentSource(¤t_source); - tvVideoFormatType_t current_format = VIDEO_FORMAT_NONE; - GetCurrentVideoFormat(¤t_format); - if( current_format == VIDEO_FORMAT_NONE) - { + tvVideoFormatType_t current_format = VIDEO_FORMAT_NONE; + GetCurrentVideoFormat(¤t_format); + if( current_format == VIDEO_FORMAT_NONE) { current_format = VIDEO_FORMAT_SDR; - } + } - //as hal using lower across converting to lower - std::string setparam = param.value; - transform(setparam.begin(), setparam.end(), setparam.begin(), ::tolower); + //as hal using lower across converting to lower + std::string setparam = param.value; + transform(setparam.begin(), setparam.end(), setparam.begin(), ::tolower); - if (current_source == sourceType && current_format == formatType) - { + if (current_source == sourceType && current_format == formatType) { tvError_t ret = SetTVPictureMode(setparam.c_str()); - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { LOGWARN("Picture Mode set failed: %s\n",getErrorString(ret).c_str()); returnResponse(false); } - else - { + else { LOGINFO("Exit : Picture Mode reset successfully, value: %s\n", param.value); } - } + } int pqmodeindex = (int)getPictureModeIndex(param.value); SaveSourcePictureMode(sourceType, formatType, pqmodeindex); } - else - { + else { LOGWARN("getLocalParam for %s failed\n", AVOUTPUT_SOURCE_PICTUREMODE_STRING_RFC_PARAM); returnResponse(false); } } - } + } } - returnResponse(true) + returnResponse(true) } uint32_t AVOutputTV::signalFilmMakerMode(const JsonObject& parameters, JsonObject& response) @@ -3354,18 +2869,16 @@ namespace Plugin { value = parameters.HasLabel("signalFilmMakerMode") ? parameters["signalFilmMakerMode"].String() : ""; returnIfParamNotFound(parameters, "signalFilmMakerMode"); - - if(strncmp(value.c_str(),"ON",strlen(value.c_str())) == 0) - { - NotifyFilmMakerModeChange(tvContentType_FMM); - LOGINFO(" enabling Film makermode \n"); - } - else - { - LOGINFO(" disabling Film makermode \n"); - NotifyFilmMakerModeChange(tvContentType_NONE); - } - returnResponse(true); + + if(strncmp(value.c_str(),"ON",strlen(value.c_str())) == 0) { + NotifyFilmMakerModeChange(tvContentType_FMM); + LOGINFO(" enabling Film makermode \n"); + } + else { + LOGINFO(" disabling Film makermode \n"); + NotifyFilmMakerModeChange(tvContentType_NONE); + } + returnResponse(true); } uint32_t AVOutputTV::setLowLatencyState(const JsonObject& parameters, JsonObject& response) @@ -3383,50 +2896,43 @@ namespace Plugin { returnIfParamNotFound(parameters,"LowLatencyState"); lowLatencyIndex = stoi(value); - if (validateIntegerInputParameter("LowLatencyState",lowLatencyIndex) != 0) - { + if (validateIntegerInputParameter("LowLatencyState",lowLatencyIndex) != 0) { LOGERR("Failed in Brightness range validation:%s", __FUNCTION__); returnResponse(false); } - if (parsingSetInputArgument(parameters, "LowLatencyState",source, pqmode, format) != 0) - { + if (parsingSetInputArgument(parameters, "LowLatencyState",source, pqmode, format) != 0) { LOGERR("%s: Failed to parse the input arguments \n", __FUNCTION__); returnResponse(false); } - if( !isCapablityCheckPassed(pqmode, source, format, "LowLatencyState" )) - { + if( !isCapablityCheckPassed(pqmode, source, format, "LowLatencyState" )) { LOGERR("%s: CapablityCheck failed for LowLatencyState\n", __FUNCTION__); returnResponse(false); } - if( isSetRequired(pqmode,source,format) ) - { + if( isSetRequired(pqmode,source,format) ) { LOGINFO("Proceed with setLowLatencyState\n"); ret = SetLowLatencyState( lowLatencyIndex ); } - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { LOGERR("Failed to setLowLatency\n"); returnResponse(false); } - else - { + else { int params[3]={0}; params[0]=lowLatencyIndex; - int retval= UpdateAVoutputTVParam("set","LowLatencyState",pqmode,source,format,PQ_PARAM_LOWLATENCY_STATE,params); - if(retval != 0 ) - { + int retval= updateAVoutputTVParam("set","LowLatencyState",pqmode,source,format,PQ_PARAM_LOWLATENCY_STATE,params); + if(retval != 0 ) { LOGERR("Failed to SaveLowLatency to ssm_data\n"); - returnResponse(false); + returnResponse(false); } LOGINFO("Exit : setLowLatency successful to value: %d\n", lowLatencyIndex); returnResponse(true); } } - + uint32_t AVOutputTV::getLowLatencyState(const JsonObject& parameters, JsonObject& response) { LOGINFO("Entry"); @@ -3438,26 +2944,22 @@ namespace Plugin { int sourceIndex=0,pqIndex=0,formatIndex=0; int lowlatencystate = 0; - if (parsingGetInputArgument(parameters, "LowLatencyState",source, pqmode, format) != 0) - { + if (parsingGetInputArgument(parameters, "LowLatencyState",source, pqmode, format) != 0) { LOGINFO("%s: Failed to parse argument\n", __FUNCTION__); returnResponse(false); } - if (getParamIndex(source,pqmode,format,sourceIndex,pqIndex,formatIndex) == -1) - { + if (getParamIndex(source,pqmode,format,sourceIndex,pqIndex,formatIndex) == -1) { LOGERR("%s: getParamIndex failed to get \n", __FUNCTION__); returnResponse(false); } int err = getLocalparam("LowLatencyState",formatIndex,pqIndex,sourceIndex,lowlatencystate, PQ_PARAM_LOWLATENCY_STATE); - if( err == 0 ) - { + if( err == 0 ) { response["lowLatencyState"] = std::to_string(lowlatencystate); LOGINFO("Exit : LowLatencyState Value: %d \n", lowlatencystate); returnResponse(true); } - else - { + else { returnResponse(false); } } @@ -3474,49 +2976,40 @@ namespace Plugin { int params[3]={0}; tvError_t ret = tvERROR_NONE; - if (parsingSetInputArgument(parameters, "LowLatencyState",source, pqmode, format) != 0) - { + if (parsingSetInputArgument(parameters, "LowLatencyState",source, pqmode, format) != 0) { LOGERR("%s: Failed to parse the input arguments \n", __FUNCTION__); returnResponse(false); } - if( !isCapablityCheckPassed( pqmode, source, format, "LowLatencyState" )) - { + if( !isCapablityCheckPassed( pqmode, source, format, "LowLatencyState" )) { LOGERR("%s: CapablityCheck failed for LowLatencyState\n", __FUNCTION__); returnResponse(false); } - int retval= UpdateAVoutputTVParam("reset","LowLatencyState",pqmode,source,format,PQ_PARAM_LOWLATENCY_STATE,params); - if(retval != 0 ) - { + int retval= updateAVoutputTVParam("reset","LowLatencyState",pqmode,source,format,PQ_PARAM_LOWLATENCY_STATE,params); + if(retval != 0 ) { LOGERR("Failed to clear Lowlatency from ssmdata and localstore\n"); returnResponse(false); } - else - { - if (isSetRequired(pqmode,source,format)) - { + else { + if (isSetRequired(pqmode,source,format)) { getParamIndex("Current","Current", "Current",sourceIndex,pqIndex,formatIndex); int err = getLocalparam("LowLatencyState",formatIndex,pqIndex,sourceIndex, lowlatencystate, PQ_PARAM_LOWLATENCY_STATE); - if( err == 0 ) - { + if( err == 0 ) { LOGINFO("%s : getLocalparam success format :%d source : %d format : %d value : %d\n",__FUNCTION__,formatIndex, sourceIndex, pqIndex, lowlatencystate); ret = SetLowLatencyState(lowlatencystate); } - else - { + else { LOGERR("%s : GetLocalParam Failed \n",__FUNCTION__); - ret = tvERROR_GENERAL; + ret = tvERROR_GENERAL; } } } - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { returnResponse(false); } - else - { + else { LOGINFO("Exit : resetLowLatency Successful to value : %d \n",lowlatencystate); returnResponse(true); } @@ -3539,36 +3032,29 @@ namespace Plugin { tvError_t ret = getParamsCaps(range,pqmode,source,format,"LowLatencyState"); - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { returnResponse(false); } - else - { - for (index = 0; index < range.size(); index++) + else { + for (index = 0; index < range.size(); index++) { rangeArray.Add(stoi(range[index])); + } response["LowLatencyInfo"]=rangeArray; - if ((pqmode.front()).compare("none") != 0) - { - for (index = 0; index < pqmode.size(); index++) - { + if ((pqmode.front()).compare("none") != 0) { + for (index = 0; index < pqmode.size(); index++) { pqmodeArray.Add(pqmode[index]); } response["pictureModeInfo"]=pqmodeArray; } - if ((source.front()).compare("none") != 0) - { - for (index = 0; index < source.size(); index++) - { + if ((source.front()).compare("none") != 0) { + for (index = 0; index < source.size(); index++) { sourceArray.Add(source[index]); } response["videoSourceInfo"]=sourceArray; } - if ((format.front()).compare("none") != 0) - { - for (index = 0; index < format.size(); index++) - { + if ((format.front()).compare("none") != 0) { + for (index = 0; index < format.size(); index++) { formatArray.Add(format[index]); } response["videoFormatInfo"]=formatArray; @@ -3577,20 +3063,18 @@ namespace Plugin { returnResponse(true); } } - + uint32_t AVOutputTV::getVideoSource(const JsonObject& parameters,JsonObject& response) { LOGINFO("Entry\n"); tvVideoSrcType_t currentSource = VIDEO_SOURCE_IP; tvError_t ret = GetCurrentSource(¤tSource); - if(ret != tvERROR_NONE) - { + if(ret != tvERROR_NONE) { response["currentVideoSource"] = "NONE"; returnResponse(false); } - else - { + else { response["currentVideoSource"] = convertSourceIndexToString(currentSource); LOGINFO("Exit: getVideoSource :%d success \n", currentSource); returnResponse(true); @@ -3598,1670 +3082,42 @@ namespace Plugin { } - uint32_t AVOutputTV::getVideoContentType(const JsonObject & parameters, JsonObject & response) + uint32_t AVOutputTV::getVideoContentType(const JsonObject & parameters, JsonObject & response) { JsonArray rangeArray; - response["currentFilmMakerMode"] = filmMakerMode; + response["currentFilmMakerMode"] = filmMakerMode; - if (getCapabilitySource(rangeArray) == 0) - { + if (getCapabilitySource(rangeArray) == 0) { response["currentFilmMakerModeSources"] = rangeArray; } - returnResponse(true); - } - - /*********************************************************************************************************/ -//Helper Function - - void AVOutputTV::LocatePQSettingsFile() - { - LOGINFO("Entry\n"); - char panelId[20] = {0}; - std::string PQFileName = AVOUTPUT_RFC_CALLERID; - std::string FilePath = "/etc/rfcdefaults/"; - - /* The if condition is to override the tvsettings ini file so it helps the PQ tuning process for new panels */ - if(access(AVOUTPUT_OVERRIDE_PATH, F_OK) == 0) - { - PQFileName = std::string(AVOUTPUT_RFC_CALLERID_OVERRIDE); - } - else - { - int val=GetPanelIDODM(panelId); - if(val==0) - { - LOGINFO("%s : panel id read is : %s\n",__FUNCTION__,panelId); - if(strncmp(panelId,AVOUTPUT_CONVERTERBOARD_PANELID,strlen(AVOUTPUT_CONVERTERBOARD_PANELID))!=0) - { - PQFileName+=std::string("_")+panelId; - struct stat tmp_st; - - LOGINFO("%s: Looking for %s.ini \n",__FUNCTION__,PQFileName.c_str()); - if(stat((FilePath+PQFileName+std::string(".ini")).c_str(), &tmp_st)!=0) - { - //fall back - LOGINFO("%s not available in %s Fall back to default\n",PQFileName.c_str(),FilePath.c_str()); - PQFileName =std::string(AVOUTPUT_RFC_CALLERID); - } - } - } - else - { - LOGINFO("%s : GetPanelID failed : %d\n",__FUNCTION__,val); - } - } - strncpy(rfc_caller_id,PQFileName.c_str(),PQFileName.size()); - LOGINFO("%s : Default tvsettings file : %s\n",__FUNCTION__,rfc_caller_id); - } - - tvContentFormatType_t AVOutputTV::getContentFormatIndex(tvVideoHDRFormat_t formatToConvert) - { - /* default to SDR always*/ - tvContentFormatType_t ret = tvContentFormatType_NONE; - switch(formatToConvert) - { - case tvVideoHDRFormat_HLG: - ret = tvContentFormatType_HLG; - break; - - case tvVideoHDRFormat_HDR10: - ret = tvContentFormatType_HDR10; - break; - - case tvVideoHDRFormat_HDR10PLUS: - ret = tvContentFormatType_HDR10PLUS; - break; - - case tvVideoHDRFormat_DV: - ret = tvContentFormatType_DOVI; - break; - - case tvVideoHDRFormat_SDR: - case tvVideoHDRFormat_NONE: - default: - ret = tvContentFormatType_SDR; - break; - } - return ret; - } - - tvError_t AVOutputTV::SyncAvoutputTVParamsToHAL(std::string pqmode,std::string source,std::string format) - { - int params[3]={0}; - - LOGINFO("Entry %s : pqmode : %s source : %s format : %s\n",__FUNCTION__,pqmode.c_str(),source.c_str(),format.c_str()); - - if( !UpdateAVoutputTVParam("sync","Brightness",pqmode,source,format,PQ_PARAM_BRIGHTNESS,params)) - LOGINFO("Brightness Successfully sync to Drive Cache\n"); - else - LOGERR("Brightness Sync to cache Failed !!!\n"); - - if( !UpdateAVoutputTVParam("sync","Contrast",pqmode,source,format,PQ_PARAM_CONTRAST,params)) - LOGINFO("Contrast Successfully Synced to Drive Cache\n"); - else - LOGERR("Contrast Sync to cache Failed !!!\n"); - - if( !UpdateAVoutputTVParam("sync","Sharpness",pqmode,source,format,PQ_PARAM_SHARPNESS,params)) - LOGINFO("Sharpness Successfully Synced to Drive Cache\n"); - else - LOGERR("Sharpness Sync to cache Failed !!!\n"); - - if( !UpdateAVoutputTVParam("sync","Saturation",pqmode,source,format,PQ_PARAM_SATURATION,params)) - LOGINFO("Saturation Successfully Synced to Drive Cache\n"); - else - LOGERR("Saturation Sync to cache Failed !!!\n"); - - if( !UpdateAVoutputTVParam("sync","Hue",pqmode,source,format,PQ_PARAM_HUE,params)) - LOGINFO("Hue Successfully Synced to Drive Cache\n"); - else - LOGERR("Hue Sync to cache Failed !!!\n"); - - if( !UpdateAVoutputTVParam("sync","ColorTemp",pqmode,source,format,PQ_PARAM_COLOR_TEMPERATURE,params)) - LOGINFO("ColorTemp Successfully Synced to Drive Cache\n"); - else - LOGERR("ColorTemp Sync to cache Failed !!!\n"); - - if( !UpdateAVoutputTVParam("sync","DolbyVisionMode",pqmode,source,"DV",PQ_PARAM_DOLBY_MODE,params)) - LOGINFO("dvmode Successfully Synced to Drive Cache\n"); - else - LOGERR("dvmode Sync to cache Failed !!!\n"); - - if( !UpdateAVoutputTVParam("sync","DimmingMode",pqmode,source,format,PQ_PARAM_DIMMINGMODE,params)) - LOGINFO("dimmingmode Successfully Synced to Drive Cache\n"); - else - LOGERR("dimmingmode Sync to cache Failed !!!\n"); - - if( !UpdateAVoutputTVParam("sync","Backlight",pqmode,source,format,PQ_PARAM_BACKLIGHT,params) ) - LOGINFO("Backlight Successfully Synced to Drive Cache\n"); - else - LOGERR("Backlight Sync to cache Failed !!!\n"); - - LOGINFO("Exit %s : pqmode : %s source : %s format : %s\n",__FUNCTION__,pqmode.c_str(),source.c_str(),format.c_str()); - return tvERROR_NONE; - } - - int AVOutputTV::SyncAvoutputTVPQModeParamsToHAL(std::string pqmode, std::string source, std::string format) - { - std::vector sources; - std::vector pictureModes; - std::vector formats; - tr181ErrorCode_t err = tr181Success; - TR181_ParamData_t param = {0}; - int ret = 0; - - ret = getSaveConfig(pqmode, source, format, sources, pictureModes, formats); - - if (ret == 0 ) - { - for (int source : sources) - { - tvVideoSrcType_t sourceType = (tvVideoSrcType_t)source; - for (int format : formats) - { - tvVideoFormatType_t formatType = (tvVideoFormatType_t)format; - std::string tr181_param_name = ""; - tr181_param_name += std::string(AVOUTPUT_SOURCE_PICTUREMODE_STRING_RFC_PARAM); - tr181_param_name += "."+convertSourceIndexToString(sourceType)+"."+"Format."+ - convertVideoFormatToString(formatType)+"."+"PictureModeString"; - - err = getLocalParam(rfc_caller_id, tr181_param_name.c_str(), ¶m); - if ( tr181Success == err ) - { - std::string local = param.value; - int pqmodeindex = (int)getPictureModeIndex(local); - - tvError_t tv_err = SaveSourcePictureMode(sourceType, formatType, pqmodeindex); - if (tv_err != tvERROR_NONE) - { - LOGWARN("failed to SaveSourcePictureMode \n"); - return -1; - } - } - else - { - LOGWARN("Failed to get the getLocalParam \n"); - return -1; - } - } - } - } - return ret; - } - - std::string AVOutputTV::convertToString(std::vector vec_strings) - { - std::string result = std::accumulate(vec_strings.begin(), vec_strings.end(), std::string(), - [](const std::string& a, const std::string& b) -> std::string { - return a.empty() ? b : a + "," + b; - }); - return result; - } - - int AVOutputTV::convertToValidInputParameter(std::string pqparam, std::string & source, std::string & pqmode, std::string & format) - { - - LOGINFO("Entry %s source %s pqmode %s format %s \n", __FUNCTION__, source.c_str(), pqmode.c_str(), format.c_str()); - - // converting pq to valid paramter format - if (pqmode == "Global") - { - std::string localSource; - std::string localPqmode; - std::string localFormat; - if (FetchCapablities(pqparam, localSource, localPqmode, localFormat) == 0) { - pqmode = localPqmode; - //if pqmode none from capabilty then lets keep pqmode as global to fail the capabilty - } - else - { - LOGINFO("%s, Failed to get picturemode capability\n", __FUNCTION__); - return -1; - } - } - else if (pqmode == "Current") - { - char picMode[PIC_MODE_NAME_MAX]={0}; - if(!getCurrentPictureMode(picMode)) - { - LOGINFO("Failed to get the Current picture mode\n"); - return -1; - } - else - { - pqmode = picMode; - } - } - - if (source == "Global") - { - std::string localSource; - std::string localPqmode; - std::string localFormat; - if (FetchCapablities(pqparam, localSource, localPqmode, localFormat) == 0) - { - source = localSource; - } - else - { - LOGINFO("%s, Failed to get source capability\n", __FUNCTION__); - return -1; - } - } - else if (source == "Current") - { - tvVideoSrcType_t currentSource = VIDEO_SOURCE_IP; - tvError_t ret = GetCurrentSource(¤tSource); - - if(ret != tvERROR_NONE) - { - LOGWARN("%s: GetCurrentSource( ) Failed \n",__FUNCTION__); - return -1; - } - source = convertSourceIndexToString(currentSource); - } - - //convert format into valid parameter - if (format == "Global") - { - std::string localSource; - std::string localPqmode; - std::string localFormat; - if (FetchCapablities(pqparam, localSource, localPqmode, localFormat) == 0) - { - format = localFormat; - } - else - { - LOGINFO("%s, Failed to get format capability\n", __FUNCTION__); - return -1; - } - } - else if (format == "Current") - { - tvVideoFormatType_t formatIndex = VIDEO_FORMAT_NONE; - GetCurrentVideoFormat(&formatIndex); - if ( formatIndex == VIDEO_FORMAT_NONE) formatIndex = VIDEO_FORMAT_SDR; - format = convertVideoFormatToString(formatIndex); - } - - LOGINFO("Exit %s source %s pqmode %s format %s \n", __FUNCTION__, source.c_str(), pqmode.c_str(), format.c_str()); - return 0; - } - - tvError_t AVOutputTV::getParamsCaps(std::vector &range - , std::vector &pqmode, std::vector &source, std::vector &format,std::string param ) - { - tvError_t ret = tvERROR_NONE; - - std::string rangeInfo; - std::string sourceInfo; - std::string formatInfo; - std::string pqmodeInfo; - - std::string platformsupport; - std::string indexInfo; - std::vector localIndex; - - if( ReadCapablitiesFromConfODM( rangeInfo, pqmodeInfo, formatInfo ,sourceInfo,param, platformsupport, indexInfo)) - { - LOGERR( "%s: ReadCapablitiesFromConf Failed !!!\n",__FUNCTION__); - return tvERROR_GENERAL; - } - else - { - spliltCapablities( range, pqmode, format, source, localIndex,rangeInfo, pqmodeInfo, formatInfo, sourceInfo , indexInfo); - } - - return ret; - } - - tvError_t AVOutputTV::getParamsCaps(std::vector &range - , std::vector &pqmode, std::vector &source, std::vector &format,std::string param, - std::string & isPlatformSupport, std::vector & index) - { - tvError_t ret = tvERROR_NONE; - - std::string rangeInfo; - std::string sourceInfo; - std::string formatInfo; - std::string pqmodeInfo; - std::string indexInfo; - - if( ReadCapablitiesFromConfODM( rangeInfo, pqmodeInfo, formatInfo ,sourceInfo,param, isPlatformSupport, indexInfo)) - { - LOGERR( "%s: ReadCapablitiesFromConf Failed !!!\n",__FUNCTION__); - return tvERROR_GENERAL; - } - else - { - spliltCapablities( range, pqmode, format, source, index,rangeInfo, pqmodeInfo, formatInfo, sourceInfo, indexInfo); - } - - return ret; - } - - void AVOutputTV::spliltCapablities( std::vector &range,std::vector &pqmode,std::vector &format, - std::vector &source, std::vector &index, std::string rangeInfo, - std::string pqmodeInfo, std::string formatInfo, std::string sourceInfo, std::string indexInfo) - { - std::string token; - std::stringstream rangeStream(rangeInfo); - std::stringstream pqmodeStream(pqmodeInfo); - std::stringstream formatStream(formatInfo); - std::stringstream sourceStream(sourceInfo); - std::stringstream indexStream(indexInfo); - - while( getline(rangeStream,token,',')) - { - range.push_back(token ); - token.clear(); - } - - while( getline(pqmodeStream,token,',') ) - { - pqmode.push_back(token ); - token.clear(); - } - - while( getline(formatStream,token,',')) - { - format.push_back( token ); - token.clear(); - } - - while( getline(sourceStream,token,',') ) - { - source.push_back( token ); - token.clear(); - } - - while( getline(indexStream,token,',') ) - { - index.push_back( token ); - token.clear(); - } - } - - bool AVOutputTV::isCapablityCheckPassed( std::string pqmodeInputInfo,std::string sourceInputInfo,std::string formatInputInfo,std::string param ) - { - - std::string rangeCapInfo; - std::string sourceCapInfo; - std::string formatCapInfo; - std::string pqmodeCapInfo; - std::string isPlatformSupport; - std::string indexInfo; - - std::set pqmodeCapSet; - std::set formatCapSet; - std::set sourceCapset; - std::set pqmodeInputSet; - std::set formatInputSet; - std::set sourceInputSet; - - if( ReadCapablitiesFromConfODM( rangeCapInfo, pqmodeCapInfo, formatCapInfo, sourceCapInfo,param, isPlatformSupport, indexInfo) ) - { - LOGINFO( "%s: readCapablitiesFromConf Failed !!!\n",__FUNCTION__); - return false; - } - - //Compare capablityInfo with Input params - - //1.convertCapablity Info to set for comparison - spliltStringsAndConvertToSet( pqmodeCapInfo, formatCapInfo, sourceCapInfo, pqmodeCapSet, formatCapSet, sourceCapset); - - //2.convert Application Input Info to set for comparison - spliltStringsAndConvertToSet( pqmodeInputInfo, formatInputInfo, sourceInputInfo, pqmodeInputSet, formatInputSet, sourceInputSet ); - - //3.Compare Each pqmode/format/source InputInfo against CapablityInfo - if ( isIncluded(pqmodeCapSet,pqmodeInputSet) && isIncluded(formatCapSet,formatInputSet) && isIncluded(sourceCapset,sourceInputSet) ) - { - LOGINFO("%s : Capablity Chesk passed \n", __FUNCTION__); - return true; - } - else - { - LOGERR("%s : Capablity Check Failed \n", __FUNCTION__); - return false; - } - } - - int AVOutputTV::UpdateAVoutputTVParam( std::string action, std::string tr181ParamName, std::string pqmode, std::string source, std::string format, tvPQParameterIndex_t pqParamIndex, int params[] ) - { - LOGINFO("Entry : %s\n",__FUNCTION__); - std::vector sources; - std::vector pictureModes; - std::vector formats; - int ret = 0; - bool sync = !(action.compare("sync")); - bool reset = !(action.compare("reset")); - bool set = !(action.compare("set")); - - LOGINFO("%s: Entry param : %s Action : %s pqmode : %s source :%s format :%s\n",__FUNCTION__,tr181ParamName.c_str(),action.c_str(),pqmode.c_str(),source.c_str(),format.c_str() ); - ret = getSaveConfig(pqmode, source, format, sources, pictureModes, formats); - if( 0 == ret ) - { - for(int sourceType: sources) - { - tvVideoSrcType_t source = (tvVideoSrcType_t)sourceType; - for(int mode : pictureModes) - { - for(int formatType : formats) - { - tvVideoFormatType_t format = (tvVideoFormatType_t)formatType; - switch(pqParamIndex) - { - case PQ_PARAM_BRIGHTNESS: - case PQ_PARAM_CONTRAST: - case PQ_PARAM_BACKLIGHT: - case PQ_PARAM_SATURATION: - case PQ_PARAM_SHARPNESS: - case PQ_PARAM_HUE: - case PQ_PARAM_COLOR_TEMPERATURE: - case PQ_PARAM_DIMMINGMODE: - case PQ_PARAM_LOWLATENCY_STATE: - case PQ_PARAM_DOLBY_MODE: - if(reset) - ret |= UpdateAVoutputTVParamToHAL(tr181ParamName,source, mode, format,0,false); - if(sync || reset) - { - int value=0; - if(getLocalparam(tr181ParamName,format,mode,source,value,pqParamIndex,sync)) continue; - params[0]=value; - } - if(set) - { - ret |= UpdateAVoutputTVParamToHAL(tr181ParamName,source, mode, format, params[0],true); - } - break; - default: - break; - } - - switch(pqParamIndex) - { - case PQ_PARAM_BRIGHTNESS: - ret |= SaveBrightness(source, mode,format,params[0]); - break; - case PQ_PARAM_CONTRAST: - ret |= SaveContrast(source, mode,format,params[0]); - break; - case PQ_PARAM_SHARPNESS: - ret |= SaveSharpness(source, mode,format,params[0]); - break; - case PQ_PARAM_HUE: - ret |= SaveHue(source, mode,format,params[0]); - break; - case PQ_PARAM_SATURATION: - ret |= SaveSaturation(source, mode,format,params[0]); - break; - case PQ_PARAM_COLOR_TEMPERATURE: - ret |= SaveColorTemperature(source, mode,format,(tvColorTemp_t)params[0]); - break; - case PQ_PARAM_BACKLIGHT: - ret |= SaveBacklight(source, mode,format,params[0]); - break; - case PQ_PARAM_DIMMINGMODE: - ret |= SaveTVDimmingMode(source,mode,format,(tvDimmingMode_t)params[0]); - break; - case PQ_PARAM_LOWLATENCY_STATE: - ret |= SaveLowLatencyState(source, mode,format,params[0]); - break; - case PQ_PARAM_DOLBY_MODE: - ret |= SaveTVDolbyVisionMode(source, mode,format,(tvDolbyMode_t)params[0]); - break; - - case PQ_PARAM_ASPECT_RATIO: - ret |= SaveAspectRatio(source,mode,format,(tvDisplayMode_t)params[0]); - break; - case PQ_PARAM_LOCALDIMMING_LEVEL: - { - if(sync) - { - int value=0; - getLocalparam(tr181ParamName,format,mode,source,value,pqParamIndex,sync); - params[0]=value; - } - ret |= SaveTVDimmingMode(source, mode,format,(tvDimmingMode_t)params[0]); - break; - } - case PQ_PARAM_CMS: - case PQ_PARAM_LDIM: - default: - break; - } - } - } - } - - } - return ret; - } - - tvError_t AVOutputTV::UpdateAVoutputTVParamToHAL(std::string forParam, int source, int pqmode, int format, int value,bool setNotDelete) - { - tvError_t ret = tvERROR_NONE; - std::string key; - - generateStorageIdentifier(key,forParam,format,pqmode,source); - if(key.empty()) - { - LOGERR("generateStorageIdentifierDirty failed\n"); - ret = tvERROR_GENERAL; - } - else - { - tr181ErrorCode_t err = tr181Success; - if(setNotDelete) - { - std::string toStore = std::to_string(value); - if (forParam.compare("ColorTemp") == 0) - { - getColorTempStringFromEnum(value, toStore); - } - else if(forParam.compare("DimmingMode") == 0 ) - { - getDimmingModeStringFromEnum(value, toStore); - } - else if (forParam.compare("DolbyVisionMode") == 0 ) - { - toStore = getDolbyModeStringFromEnum((tvDolbyMode_t)value); - } - err = setLocalParam(rfc_caller_id, key.c_str(),toStore.c_str()); - - } - else - { - err = clearLocalParam(rfc_caller_id, key.c_str()); - } - - if ( err != tr181Success ) - { - LOGERR("%s for %s Failed : %s\n", setNotDelete?"Set":"Delete", key.c_str(), getTR181ErrorString(err)); - ret = tvERROR_GENERAL; - } - } - return ret; - } - - int AVOutputTV::getSaveConfig(std::string pqmode, std::string source, std::string format,std::vector &sources,std::vector &picturemodes, std::vector &formats) - { - LOGINFO("Entry : %s pqmode : %s source :%s format :%s\n",__FUNCTION__,pqmode.c_str(),source.c_str(),format.c_str()); - - int ret = 0; - - if (getAvailableCapabilityModes(source, pqmode, format) != 0) - { - LOGERR("%s: failed to get picture/source/format mode capability \n", __FUNCTION__); - return -1; - } - //pqmode - char *modeString = strdup(pqmode.c_str()); - char *token = NULL; - while ((token = strtok_r(modeString,",",&modeString))) - { - std::string local = token; - picturemodes.push_back(getPictureModeIndex(local)); - } - //source - char *sourceString = strdup(source.c_str()); - char *sourceToken = NULL; - while ((sourceToken = strtok_r(sourceString,",",&sourceString))) - { - std::string local = sourceToken; - sources.push_back(getSourceIndex(local)); - } - //3)check format - char *formatString = strdup(format.c_str()); - char *formatToken = NULL; - while ((formatToken = strtok_r(formatString,",",&formatString))) - { - std::string local = formatToken; - formats.push_back(getFormatIndex(local)); - } - - LOGINFO("Exit : %s pqmode : %s source :%s format :%s ret:%d\n",__FUNCTION__,pqmode.c_str(),source.c_str(),format.c_str(), ret); - return ret; - } - - string AVOutputTV::convertSourceIndexToString(int source) - { - std::string ret; - std::map :: iterator it; - for (it = supportedSourcemap.begin(); it != supportedSourcemap.end(); it++) - { - if (it->second == source) - { - ret = it->first; - break; - } - } - return ret; - } - - string AVOutputTV::convertVideoFormatToString(int format) - { - std::string ret; - std::map :: iterator it; - for (it = supportedFormatmap.begin(); it != supportedFormatmap.end(); it++) - { - if (it->second == format) - { - ret = it->first; - break; - } - } - return ret; + returnResponse(true); } - string AVOutputTV::convertPictureIndexToString(int pqmode) + void AVOutputTV::InitializeIARM() { - std::string ret; - std::map :: iterator it; - for(it = supportedPictureModemap.begin(); it != supportedPictureModemap.end(); it++) - { - if (it->second == pqmode) - { - ret = it->first; - break; - } + AVOutputBase::InitializeIARM(); +#if !defined (HDMIIN_4K_ZOOM) + if (Utils::IARM::init()) { + IARM_Result_t res; + IARM_CHECK( IARM_Bus_RegisterEventHandler(IARM_BUS_DSMGR_NAME,IARM_BUS_DSMGR_EVENT_HDMI_IN_STATUS, dsHdmiStatusEventHandler) ); + IARM_CHECK( IARM_Bus_RegisterEventHandler(IARM_BUS_DSMGR_NAME,IARM_BUS_DSMGR_EVENT_HDMI_IN_VIDEO_MODE_UPDATE, dsHdmiVideoModeEventHandler) ); } - return ret; - } - - uint32_t AVOutputTV::generateStorageIdentifier(std::string &key, std::string forParam,int contentFormat, int pqmode, int source) - { - key+=std::string(AVOUTPUT_GENERIC_STRING_RFC_PARAM); - key+=STRING_SOURCE+convertSourceIndexToString(source)+std::string(".")+STRING_PICMODE+convertPictureIndexToString(pqmode)+std::string(".")+std::string(STRING_FORMAT)+convertVideoFormatToString(contentFormat)+std::string(".")+forParam; - return tvERROR_NONE; - } - - uint32_t AVOutputTV::generateStorageIdentifierDirty(std::string &key, std::string forParam,uint32_t contentFormat, int pqmode) - { - key+=std::string(AVOUTPUT_GENERIC_STRING_RFC_PARAM); - key+=STRING_PICMODE+std::to_string(pqmode)+std::string(".")+std::string(STRING_FORMAT)+std::to_string(contentFormat); - CREATE_DIRTY(key)+=forParam; - - return tvERROR_NONE; +#endif } - int AVOutputTV::getLocalparam( std::string forParam,int formatIndex,int pqIndex,int sourceIndex,int & value, - tvPQParameterIndex_t pqParamIndex,bool sync,int color ) + void AVOutputTV::DeinitializeIARM() { - string key; - TR181_ParamData_t param={0}; - generateStorageIdentifier(key,forParam,formatIndex,pqIndex,sourceIndex); - if(key.empty()) - { - LOGERR("generateStorageIdentifier failed\n"); - return -1; - } - - tr181ErrorCode_t err=getLocalParam(rfc_caller_id, key.c_str(), ¶m); - - if ( tr181Success == err )//Fetch new tr181format values - { - if( forParam.compare("ColorTemp") == 0 ) - { - if (strncmp(param.value, "Standard", strlen(param.value))==0) - value=tvColorTemp_STANDARD; - else if (strncmp(param.value, "Warm", strlen(param.value))==0) - value=tvColorTemp_WARM; - else if (strncmp(param.value, "Cold", strlen(param.value))==0) - value=tvColorTemp_COLD; - else if (strncmp(param.value, "User Defined", strlen(param.value))==0) - value=tvColorTemp_USER; - else - value=tvColorTemp_STANDARD; - return 0; - } - else if( forParam.compare("DimmingMode") == 0 ) - { - if (strncmp(param.value, "fixed", strlen(param.value))==0) - value=tvDimmingMode_Fixed; - else if (strncmp(param.value, "local", strlen(param.value))==0) - value=tvDimmingMode_Local; - else if (strncmp(param.value, "global", strlen(param.value))==0) - value=tvDimmingMode_Global; - return 0; - } - else if ( forParam.compare("DolbyVisionMode") == 0) - { - if (strncmp(param.value, "Dark", strlen(param.value)) == 0) { - value = tvDolbyMode_Dark; - } - else - { - value = tvDolbyMode_Bright; - } - return 0; - } - else - { - value=std::stoi(param.value); - return 0; - } - } - else // default value from DB + AVOutputBase::DeinitializeIARM(); +#if !defined (HDMIIN_4K_ZOOM) + if (Utils::IARM::isConnected()) { - if( sync ) - { - return 1; - } - GetDefaultPQParams(pqIndex,(tvVideoSrcType_t)sourceIndex,(tvVideoFormatType_t)formatIndex,pqParamIndex,&value); - LOGINFO("Default value from DB : %s : %d \n",key.c_str(),value); - return 0; - } - } - - bool AVOutputTV::isSetRequired(std::string pqmode,std::string source,std::string format) - { - bool ret=false; - char picMode[PIC_MODE_NAME_MAX]={0}; - tvError_t retVal = tvERROR_NONE; - tvVideoSrcType_t sourceIndex = VIDEO_SOURCE_IP; - std::string currentPicMode; - std::string currentSource; - std::string currentFormat; - - //GetCurrent pqmode - if(!getCurrentPictureMode(picMode)) - LOGERR("Failed to get the current picture mode\n"); - - currentPicMode = picMode; //Convert to string - - //GetCurrentSource - retVal = GetCurrentSource(&sourceIndex); - if(retVal != tvERROR_NONE) - { - LOGERR("%s : GetCurrentSource( ) Failed\n",__FUNCTION__); - return false; - } - currentSource = convertSourceIndexToString(sourceIndex); - - //GetCurrentFormat - tvVideoFormatType_t formatIndex = VIDEO_FORMAT_NONE; - GetCurrentVideoFormat(&formatIndex); - if ( formatIndex == VIDEO_FORMAT_NONE) formatIndex = VIDEO_FORMAT_SDR; - currentFormat = convertVideoFormatToString(formatIndex); - - - if( ( (pqmode.find(currentPicMode) != std::string::npos) || (pqmode.compare("Global") == 0) || (pqmode.compare("Current") == 0) || - (pqmode.compare("none") == 0) ) && - ((source.find(currentSource) != std::string::npos) || (source.compare("Global") == 0) || (source.compare("Current") == 0) || - (source.compare("none") == 0) ) && - ( (format.find(currentFormat) != std::string::npos) || (format.compare("Global") == 0) || (format.compare("Current") == 0) || - (format.compare("none") == 0) ) ) - ret=true; - - return ret; - } - - int AVOutputTV::getParamIndex(string source,string pqmode,string format,int& sourceIndex,int& pqmodeIndex,int& formatIndex) - { - LOGINFO("Entry : %s pqmode : %s source :%s format :%s\n",__FUNCTION__,pqmode.c_str(),source.c_str(),format.c_str()); - - if( source.compare("none") == 0 || source.compare("Current") == 0 ) - { - tvVideoSrcType_t currentSource = VIDEO_SOURCE_IP; - GetCurrentSource(¤tSource); - sourceIndex = (int)currentSource; - } - else - { - sourceIndex = getSourceIndex(source); - } - if( pqmode.compare("none") == 0 || pqmode.compare("Current") == 0) - { - char picMode[PIC_MODE_NAME_MAX]={0}; - if(!getCurrentPictureMode(picMode)) - { - LOGERR("Failed to get the Current picture mode\n"); - } - else - { - std::string local = picMode; - pqmodeIndex = getPictureModeIndex(local); - } - } - else - { - pqmodeIndex = getPictureModeIndex(pqmode); - } - - if( format.compare("none") == 0 || format.compare("Current") == 0) - { - tvVideoFormatType_t currentFormat = VIDEO_FORMAT_NONE; - GetCurrentVideoFormat(¤tFormat); - if( VIDEO_FORMAT_NONE == currentFormat ) - formatIndex = VIDEO_FORMAT_SDR; - else - formatIndex = (int)currentFormat; - } - else - { - formatIndex = getFormatIndex(format); - } - - if (sourceIndex == -1 || pqmodeIndex == -1 || formatIndex == -1) return -1; - LOGINFO("%s: Exit sourceIndex = %d pqmodeIndex = %d formatIndex = %d\n",__FUNCTION__,sourceIndex,pqmodeIndex,formatIndex); - - return 0; - } - - tvDataComponentColor_t AVOutputTV::getComponentColorEnum(std::string colorName) - { - tvDataComponentColor_t CompColorEnum = tvDataColor_MAX; - - if(!colorName.compare("none")) - { - CompColorEnum = tvDataColor_NONE; - } - else if (!colorName.compare("red")) - { - CompColorEnum = tvDataColor_RED; - } - else if (!colorName.compare("green")) - { - CompColorEnum = tvDataColor_GREEN; - } - else if (!colorName.compare("blue")) - { - CompColorEnum = tvDataColor_BLUE; - } - else if (!colorName.compare("yellow")) - { - CompColorEnum = tvDataColor_YELLOW; - } - else if (!colorName.compare("cyan")) - { - CompColorEnum = tvDataColor_CYAN; - } - else if (!colorName.compare("magenta")) - { - CompColorEnum = tvDataColor_MAGENTA; - } - return CompColorEnum; - } - - int AVOutputTV::getDolbyParams(tvContentFormatType_t format, std::string &s, std::string source) - { - int ret = -1; - TR181_ParamData_t param; - std::string rfc_param = AVOUTPUT_HDR10MODE_RFC_PARAM; - int dolby_mode_value = 0; - tvVideoSrcType_t sourceIndex = VIDEO_SOURCE_IP; - /*Since dolby vision is source specific, we should for check for specific source*/ - if (!source.empty()) - { - sourceIndex = (tvVideoSrcType_t)getSourceIndex(source); - } - else - { - GetCurrentSource(&sourceIndex); - } - - char picMode[PIC_MODE_NAME_MAX]={0}; - int pqmodeIndex = 0; - if(!getCurrentPictureMode(picMode)) - { - LOGERR("Failed to get the Current picture mode\n"); - } - else - { - std::string local = picMode; - pqmodeIndex = getPictureModeIndex(local); - } - memset(¶m, 0, sizeof(param)); - if (format == tvContentFormatType_HLG ) - { - rfc_param = AVOUTPUT_HLGMODE_RFC_PARAM; - } - else if (format == tvContentFormatType_DOVI) - { - rfc_param = AVOUTPUT_SOURCE_PICTUREMODE_STRING_RFC_PARAM + std::to_string(sourceIndex) + "."+"DolbyVisionMode"; - } - - tr181ErrorCode_t err = getLocalParam(rfc_caller_id, rfc_param.c_str(), ¶m); - if ( tr181Success != err) - { - tvError_t retVal = GetDefaultPQParams(pqmodeIndex,(tvVideoSrcType_t)sourceIndex, - (tvVideoFormatType_t)ConvertHDRFormatToContentFormatODM((tvhdr_type_t)format), - PQ_PARAM_DOLBY_MODE,&dolby_mode_value); - if( retVal != tvERROR_NONE ) - { - LOGERR("%s : failed\n",__FUNCTION__); - return ret; - } - s = getDolbyModeStringFromEnum((tvDolbyMode_t)dolby_mode_value); - ret = 0; - } - else - { - s += param.value; - ret = 0; - } - return ret; - } - - tvDimmingMode_t AVOutputTV::getDimmingModeIndex(std::string mode) - { - tvDimmingMode_t index = tvDimmingMode_MAX; - - if(mode.compare("local") == 0 ) - index=tvDimmingMode_Local; - else if(mode.compare("fixed") == 0 ) - index=tvDimmingMode_Fixed; - else if(mode.compare("global") == 0 ) - index=tvDimmingMode_Global; - else - LOGINFO("Return Default Dimmingmode:%d!!!\n",index); - - return index; - } - - void AVOutputTV::getDimmingModeStringFromEnum(int value, std::string &toStore) - { - const char *color_temp_string[] = { - [tvDimmingMode_Fixed] = "fixed", - [tvDimmingMode_Local] = "local", - [tvDimmingMode_Global] = "global", - }; - toStore.clear(); - toStore+=color_temp_string[value]; - } - - void AVOutputTV::getColorTempStringFromEnum(int value, std::string &toStore) - { - const char *color_temp_string[] = { - [tvColorTemp_STANDARD] = "Standard", - [tvColorTemp_WARM] = "Warm", - [tvColorTemp_COLD] = "Cold", - [tvColorTemp_USER] = "User Defined" - }; - toStore.clear(); - toStore+=color_temp_string[value]; - } - - int AVOutputTV::getCurrentPictureMode(char *picMode) - { - tvError_t ret = tvERROR_NONE; - TR181_ParamData_t param; - std::string tr181_param_name; - tvVideoSrcType_t currentSource = VIDEO_SOURCE_IP; - - ret = GetCurrentSource(¤tSource); - if(ret != tvERROR_NONE) - { - LOGERR("GetCurrentSource() Failed set source to default\n"); - return 0; - } - - tvVideoFormatType_t current_format = VIDEO_FORMAT_NONE; - GetCurrentVideoFormat(¤t_format); - if ( current_format == VIDEO_FORMAT_NONE) current_format = VIDEO_FORMAT_SDR; - - tr181_param_name += std::string(AVOUTPUT_SOURCE_PICTUREMODE_STRING_RFC_PARAM); - tr181_param_name += "." + convertSourceIndexToString(currentSource) + "." + "Format."+convertVideoFormatToString(current_format)+"."+"PictureModeString"; - - memset(¶m, 0, sizeof(param)); - - tr181ErrorCode_t err = getLocalParam(rfc_caller_id, tr181_param_name.c_str(), ¶m); - if ( err == tr181Success ) - { - strncpy(picMode, param.value, strlen(param.value)+1); - LOGINFO("getLocalParam success, mode = %s\n", picMode); - return 1; - } - else - { - LOGERR("getLocalParam failed"); - return 0; - } - } - - bool AVOutputTV::isIncluded(const std::set set1,const std::set set2) - { - for( const auto& element : set2){ - if(set1.find(element) == set1.end()) - return false; - } - return true; - } - - int AVOutputTV::getDolbyParamToSync(int sourceIndex, int formatIndex, int& value) - { - int ret=0; - TR181_ParamData_t param; - int pqmodeIndex = 0; - char picMode[PIC_MODE_NAME_MAX]={0}; - if(!getCurrentPictureMode(picMode)) - { - LOGERR("Failed to get the Current picture mode\n"); - } - else - { - std::string local = picMode; - pqmodeIndex = getPictureModeIndex(local); - } - std ::string rfc_param = AVOUTPUT_SOURCE_PICTUREMODE_STRING_RFC_PARAM + std::to_string(sourceIndex) + "."+"DolbyVisionMode"; - memset(¶m, 0, sizeof(param)); - tr181ErrorCode_t err = getLocalParam(rfc_caller_id, rfc_param.c_str(), ¶m); - - if ( tr181Success != err) - { - tvError_t retVal = GetDefaultPQParams(pqmodeIndex,(tvVideoSrcType_t)sourceIndex, (tvVideoFormatType_t)formatIndex, - PQ_PARAM_DOLBY_MODE, &value); - if( retVal != tvERROR_NONE ) - { - LOGERR("%s : failed\n",__FUNCTION__); - return -1; - } - ret = 0; - } - else - { - value=GetDolbyModeIndex(param.value); - ret = 0; - } - - return ret; - } - - void AVOutputTV::spliltStringsAndConvertToSet( std::string pqmodeInfo,std::string formatInfo,std::string sourceInfo,std::set &pqmode, std::set &format, std::set &source) - { - std::string token; - std::stringstream pqmodeStream(pqmodeInfo); - std::stringstream formatStream(formatInfo); - std::stringstream sourceStream(sourceInfo); - - while( getline(pqmodeStream,token,',') ) - { - pqmode.insert( token ); - token.clear(); - } - - while( getline(formatStream,token,',') ) - { - format.insert( token ); - token.clear(); - } - - while( getline(sourceStream,token,',')) - { - source.insert( token ); - token.clear(); - } - } - - std::string AVOutputTV::getDolbyModeStringFromEnum( tvDolbyMode_t mode) - - { - std::string value; - switch(mode) - { - case tvDolbyMode_Dark: - case tvHDR10Mode_Dark: - case tvHLGMode_Dark: - value = "Dark"; - break; - case tvDolbyMode_Bright: - case tvHDR10Mode_Bright: - case tvHLGMode_Bright: - value = "Bright"; - break; - default: - break; - } - - return value; - } - - int AVOutputTV::parsingSetInputArgument(const JsonObject& parameters, std::string pqparam, std::string & source, - std::string & pqmode, std::string & format) { - - JsonArray sourceArray; - JsonArray pqmodeArray; - JsonArray formatArray; - - - pqmodeArray = parameters.HasLabel("pictureMode") ? parameters["pictureMode"].Array() : JsonArray(); - for (int i = 0; i < pqmodeArray.Length(); ++i) - { - pqmode += pqmodeArray[i].String(); - if (i != (pqmodeArray.Length() - 1) ) pqmode += ","; - } - - sourceArray = parameters.HasLabel("videoSource") ? parameters["videoSource"].Array() : JsonArray(); - for (int i = 0; i < sourceArray.Length(); ++i) - { - source += sourceArray[i].String(); - if (i != (sourceArray.Length() - 1) ) source += ","; - } - - formatArray = parameters.HasLabel("videoFormat") ? parameters["videoFormat"].Array() : JsonArray(); - for (int i = 0; i < formatArray.Length(); ++i) - { - format += formatArray[i].String(); - if (i != (formatArray.Length() - 1) ) format += ","; - } - - if (source.empty()) source = "Global"; - if (pqmode.empty()) pqmode = "Global"; - if (format.empty()) format = "Global"; - - if (convertToValidInputParameter(pqparam, source, pqmode, format) != 0) - { - LOGERR("%s: Failed to convert the input paramters. \n", __FUNCTION__); - return -1; - } - - return 0; - } - - int AVOutputTV::parsingGetInputArgument(const JsonObject& parameters, std::string pqparam, - std::string & source, std::string & pqmode, std::string & format) { - pqmode = parameters.HasLabel("pictureMode") ? parameters["pictureMode"].String() : ""; - - source = parameters.HasLabel("videoSource") ? parameters["videoSource"].String() : ""; - - format = parameters.HasLabel("videoFormat") ? parameters["videoFormat"].String() : ""; - - if ( (source.compare("Global") == 0) || (pqmode.compare("Global") == 0) || (format.compare("Global") == 0) ) - { - LOGERR("%s: get cannot fetch the Global inputs \n", __FUNCTION__); - return -1; - } - - if (source.empty()) source = "Current"; - if (pqmode.empty()) pqmode = "Current"; - if (format.empty()) format = "Current"; - - if (convertToValidInputParameter(pqparam,source, pqmode, format) != 0) - { - LOGERR("%s: Failed to convert the input paramters. \n", __FUNCTION__); - return -1; - } - - return 0; - } - - int AVOutputTV::isPlatformSupport(std::string pqparam) - { - std::vector range; - std::vector sourceVec; - std::vector pqmodeVec; - std::vector formatVec; - std::string isPlatformSupport; - std::vector index; - - tvError_t ret = getParamsCaps(range, pqmodeVec, sourceVec, formatVec, pqparam, isPlatformSupport, index); - - if (ret != tvERROR_NONE) - { - LOGINFO("%s: failed to get the capability \n", __FUNCTION__); - return -1; - } - else - { - if(isPlatformSupport.compare("true") != 0) - { - LOGERR("%s: platform support not available\n", __FUNCTION__); - return -1; - } - } - return 0; - } - - int AVOutputTV::FetchCapablities(string pqparam, string & source, string & pqmode, string & format) { - - std::vector range; - std::vector sourceVec; - std::vector pqmodeVec; - std::vector formatVec; - - tvError_t ret = tvERROR_NONE; - - ret = getParamsCaps(range, pqmodeVec, sourceVec, formatVec, pqparam); - - if (ret != tvERROR_NONE) - { - LOGINFO("%s: failed to get the capability \n", __FUNCTION__); - return -1; - } - - if (sourceVec.size() != 0) - { - source = convertToString(sourceVec); - } - - if (pqmodeVec.size() != 0) - { - pqmode = convertToString(pqmodeVec); - } - - if (formatVec.size() != 0) - { - format = convertToString(formatVec); - } - - return 0; - } - - int AVOutputTV::getAvailableCapabilityModesWrapper(std::string param, std::string & outparam) - { - tvError_t err = tvERROR_NONE; - std::vector range; - std::vector picmodeVec; - std::vector sourceVec; - std::vector formatVec; - - err = getParamsCaps(range,picmodeVec,sourceVec,formatVec, param); - if (err != tvERROR_NONE) - { - LOGERR("%s: failed to get [%s] capability \n", __FUNCTION__, param.c_str()); - return -1; - } - outparam = convertToString(range); - - return 0; - } - - int AVOutputTV::getAvailableCapabilityModes(std::string & source, std::string & pqmode, std::string & format) - { - if ((pqmode.compare("none") == 0 )) - { - if (getAvailableCapabilityModesWrapper("PictureMode", pqmode) != 0) - { - LOGERR("%s: failed to get picture mode capability \n", __FUNCTION__); - return -1; - } - } - - if( (source.compare("none") == 0)) - { - if (getAvailableCapabilityModesWrapper("VideoSource",source) != 0) - { - LOGERR("%s: failed to get source capability \n", __FUNCTION__); - return -1; - } - } - - if( (format.compare("none") == 0) ) - { - if (getAvailableCapabilityModesWrapper("VideoFormat",format) != 0) - { - LOGERR("%s: failed to get format capability \n", __FUNCTION__); - return -1; - } - } - return 0; - } - - tvContentFormatType_t AVOutputTV::ConvertFormatStringToTVContentFormat(const char *format) - { - tvContentFormatType_t ret = tvContentFormatType_SDR; - - if( strncmp(format,"sdr",strlen(format)) == 0 || strncmp(format,"SDR",strlen(format)) == 0 ) - ret = tvContentFormatType_SDR; - else if( strncmp(format,"hdr10",strlen(format)) == 0 || strncmp(format,"HDR10",strlen(format))==0 ) - ret = tvContentFormatType_HDR10; - else if( strncmp(format,"hlg",strlen(format)) == 0 || strncmp(format,"HLG",strlen(format)) == 0 ) - ret = tvContentFormatType_HLG; - else if( strncmp(format,"dolby",strlen(format)) == 0 || strncmp(format,"DOLBY",strlen(format)) == 0 ) - ret=tvContentFormatType_DOVI; - - return ret; - } - - int AVOutputTV::validateInputParameter(std::string param, std::string inputValue) - { - - std::vector range; - std::vector pqmode; - std::vector source; - std::vector format; - - tvError_t ret = getParamsCaps(range, pqmode, source, format, param); - - if (ret != tvERROR_NONE) - { - LOGERR("Failed to fetch the range capability[%s] \n", param.c_str()); - return -1; - } - - if ( (param == "ColorTemperature") || - (param == "DimmingMode") || (param == "AutoBacklightControl") || - (param == "DolbyVisionMode") || (param == "HDR10Mode") || - (param == "HLGMode") || (param == "AspectRatio") || (param == "PictureMode") ) - { - auto iter = find(range.begin(), range.end(), inputValue); - - if (iter == range.end()) - { - LOGERR("Not a valid input value[%s].\n", inputValue.c_str()); - return -1; - } - } - return 0; - } - - int AVOutputTV::validateIntegerInputParameter(std::string param, int inputValue) - { - - std::vector range; - std::vector pqmode; - std::vector source; - std::vector format; - - tvError_t ret = getParamsCaps(range, pqmode, source, format, param); - - if (ret != tvERROR_NONE) - { - LOGERR("Failed to fetch the range capability[%s] \n", param.c_str()); - return -1; - } - - if ( (param == "Brightness") || (param == "Contrast") || - (param == "Sharpness") || (param == "Saturation") || - (param == "Hue") || (param == "WhiteBalance") || - (param == "ComponentSaturation") || (param == "Backlight") || - (param == "ComponentHue") || (param == "ComponentLuma") || (param == "LowLatencyState") ) - { - if (inputValue < stoi(range[0]) || inputValue > stoi(range[1])) - { - LOGERR("wrong Input value[%d]", inputValue); - return -1; - } - } - return 0; - } - - void AVOutputTV::BroadcastLowLatencyModeChangeEvent(bool lowLatencyMode) - { - LOGINFO("Entry:%d\n",lowLatencyMode); - JsonObject response; - response["lowLatencyMode"] = lowLatencyMode; - sendNotify("gameModeEvent", response); - } - - int AVOutputTV::getPqParamIndex() - { - std::vector localpq; - std::vector localformat; - std::vector localsource; - std::vector localrange; - std::string platformsupport; - std::vector index; - - tvError_t ret = getParamsCaps(localrange, localpq, localformat, localsource, - "VideoSource", platformsupport, index); - if (ret == tvERROR_NONE) - { - if (localrange.size() == index.size()) - { - for (unsigned int i = 0; i< localrange.size(); i++) - { - supportedSourcemap[localrange[i]] = stoi(index[i]); - } - } - } - else - { - LOGERR("%s: Failed to fetch the source index \n", __FUNCTION__); - return -1; - } - - if (!localpq.empty()) localpq.clear(); - if (!localformat.empty()) localformat.clear(); - if (!localsource.empty()) localsource.clear(); - if (!localrange.empty()) localrange.clear(); - if(!index.empty()) index.clear(); - - ret = getParamsCaps(localrange, localpq, localformat, localsource, - "PictureMode", platformsupport, index); - if (ret == tvERROR_NONE) - { - if (localrange.size() == index.size()) - { - for (unsigned int i = 0; i< localrange.size(); i++) - { - supportedPictureModemap[localrange[i]] = stoi(index[i]); - } - } - } - else - { - LOGERR("%s: Failed to fetch the picture index \n", __FUNCTION__); - return -1; - } - - if (!localpq.empty()) localpq.clear(); - if (!localformat.empty()) localformat.clear(); - if (!localsource.empty()) localsource.clear(); - if (!localrange.empty()) localrange.clear(); - if(!index.empty()) index.clear(); - - ret = getParamsCaps(localrange, localpq, localformat, localsource, - "VideoFormat", platformsupport, index); - if (ret == tvERROR_NONE) - { - if (localrange.size() == index.size()) - { - for (unsigned int i = 0; i< localrange.size(); i++) - { - supportedFormatmap[localrange[i]] = stoi(index[i]); - } - } - } - else - { - LOGERR("%s: Failed to fetch the format index \n", __FUNCTION__); - return -1; - } - - return 0; - } - - int AVOutputTV::getPictureModeIndex(std::string pqparam) - { - int index = -1; - std::map :: iterator it; - - for(it = supportedPictureModemap.begin(); it != supportedPictureModemap.end(); it++) - { - if (it->first == pqparam) - { - index = it->second; - break; - } - } - return index; - } - - int AVOutputTV::getSourceIndex(std::string pqparam) - { - int index = -1; - std::map :: iterator it; - - for(it = supportedSourcemap.begin(); it != supportedSourcemap.end(); it++) - { - if (it->first == pqparam) - { - index = it->second; - break; - } - } - return index; - } - - int AVOutputTV::getFormatIndex(std::string pqparam) - { - int index = -1; - std::map :: iterator it; - - for(it = supportedFormatmap.begin(); it != supportedFormatmap.end(); it++) - { - if (it->first == pqparam) - { - index = it->second; - break; - } - } - return index; - } - - std::string AVOutputTV::getErrorString (tvError_t eReturn) - { - switch (eReturn) - { - case tvERROR_NONE: - return "API SUCCESS"; - case tvERROR_GENERAL: - return "API FAILED"; - case tvERROR_OPERATION_NOT_SUPPORTED: - return "OPERATION NOT SUPPORTED ERROR"; - case tvERROR_INVALID_PARAM: - return "INVALID PARAM ERROR"; - case tvERROR_INVALID_STATE: - return "INVALID STATE ERROR"; - } - return "UNKNOWN ERROR"; - } - - void AVOutputTV::getDynamicAutoLatencyConfig() - { - RFC_ParamData_t param = {0}; - WDMP_STATUS status = getRFCParameter(AVOUTPUT_RFC_CALLERID, AVOUTPUT_DALS_RFC_PARAM, ¶m); - LOGINFO("RFC value for DALS - %s", param.value); - if(WDMP_SUCCESS == status && param.type == WDMP_BOOLEAN && (strncasecmp(param.value,"true",4) == 0)) { - m_isDalsEnabled = true; - LOGINFO("Value of m_isDalsEnabled is %d", m_isDalsEnabled); - } - else { - LOGINFO("Failed to fetch RFC or DALS is disabled"); - } - } - - - void AVOutputTV::InitializeIARM() - { - AVOutputBase::InitializeIARM(); -#if !defined (HDMIIN_4K_ZOOM) - if (Utils::IARM::init()) - { - IARM_Result_t res; - IARM_CHECK( IARM_Bus_RegisterEventHandler(IARM_BUS_DSMGR_NAME,IARM_BUS_DSMGR_EVENT_HDMI_IN_STATUS, dsHdmiStatusEventHandler) ); - IARM_CHECK( IARM_Bus_RegisterEventHandler(IARM_BUS_DSMGR_NAME,IARM_BUS_DSMGR_EVENT_HDMI_IN_VIDEO_MODE_UPDATE, dsHdmiVideoModeEventHandler) ); - } -#endif - } - - void AVOutputTV::DeinitializeIARM() - { - AVOutputBase::DeinitializeIARM(); -#if !defined (HDMIIN_4K_ZOOM) - if (Utils::IARM::isConnected()) - { - IARM_Result_t res; - IARM_CHECK( IARM_Bus_RemoveEventHandler(IARM_BUS_DSMGR_NAME,IARM_BUS_DSMGR_EVENT_HDMI_IN_STATUS, dsHdmiStatusEventHandler) ); - IARM_CHECK( IARM_Bus_RemoveEventHandler(IARM_BUS_DSMGR_NAME,IARM_BUS_DSMGR_EVENT_HDMI_IN_VIDEO_MODE_UPDATE, dsHdmiVideoModeEventHandler) ); - } -#endif - } - - tvError_t AVOutputTV::InitializePictureMode() - { - tvError_t ret = tvERROR_NONE; - TR181_ParamData_t param; - tvVideoSrcType_t current_source = VIDEO_SOURCE_IP; - std::string tr181_param_name = ""; - tvVideoFormatType_t current_format = VIDEO_FORMAT_NONE; - - GetCurrentVideoFormat(¤t_format); - if ( current_format == VIDEO_FORMAT_NONE) current_format = VIDEO_FORMAT_SDR; - // get current source - GetCurrentSource(¤t_source); - - tr181_param_name += std::string(AVOUTPUT_SOURCE_PICTUREMODE_STRING_RFC_PARAM); - tr181_param_name += "."+convertSourceIndexToString(current_source)+"."+"Format."+convertVideoFormatToString(current_format)+"."+"PictureModeString"; - - tr181ErrorCode_t err = getLocalParam(rfc_caller_id, tr181_param_name.c_str(), ¶m); - if ( tr181Success == err ) - { - std::string local = param.value; - transform(local.begin(), local.end(), local.begin(), ::tolower); - ret = SetTVPictureMode(local.c_str()); - - if(ret != tvERROR_NONE) - { - LOGWARN("Picture Mode set failed: %s\n",getErrorString(ret).c_str()); - } - else - { - LOGINFO("Picture Mode initialized successfully, tr181 value [%s] value: %s\n", tr181_param_name.c_str(), - param.value); - } - } - else - { - ret = tvERROR_GENERAL; - LOGWARN("getLocalParam for %s Failed : %s\n", tr181_param_name.c_str(), getTR181ErrorString(err)); - } - - return ret; - } - - tvError_t AVOutputTV::setAspectRatioZoomSettings(tvDisplayMode_t mode) - { - tvError_t ret = tvERROR_GENERAL; - LOGERR("%s: mode selected is: %d", __FUNCTION__, m_videoZoomMode); -#if !defined (HDMIIN_4K_ZOOM) - if (AVOutputTV::instance->m_isDisabledHdmiIn4KZoom) - { - if (AVOutputTV::instance->m_currentHdmiInResolutonm_isDisabledHdmiIn4KZoom); - ret = SetAspectRatio((tvDisplayMode_t)m_videoZoomMode); - } -#endif - return ret; - } - - tvError_t AVOutputTV::getUserSelectedAspectRatio (tvDisplayMode_t* mode) - { - tvError_t ret = tvERROR_GENERAL; -#if !defined (HDMIIN_4K_ZOOM) - LOGERR("%s:mode selected is: %d", __FUNCTION__, m_videoZoomMode); - if (AVOutputTV::instance->m_isDisabledHdmiIn4KZoom) - { - if (!(AVOutputTV::instance->m_currentHdmiInResolutonm_currentHdmiInResoluton))) - { - *mode = (tvDisplayMode_t)AVOutputTV::instance->m_videoZoomMode; - LOGWARN("%s: Getting zoom mode %d for display, for 4K and above", __FUNCTION__, *mode); - return tvERROR_NONE; - } + IARM_Result_t res; + IARM_CHECK( IARM_Bus_RemoveEventHandler(IARM_BUS_DSMGR_NAME,IARM_BUS_DSMGR_EVENT_HDMI_IN_STATUS, dsHdmiStatusEventHandler) ); + IARM_CHECK( IARM_Bus_RemoveEventHandler(IARM_BUS_DSMGR_NAME,IARM_BUS_DSMGR_EVENT_HDMI_IN_VIDEO_MODE_UPDATE, dsHdmiVideoModeEventHandler) ); } #endif - ret = GetAspectRatio(mode); - return ret; } }//namespace Plugin diff --git a/AVOutput/AVOutputTV.h b/AVOutput/AVOutputTV.h index d2e452809e..95eae073cd 100644 --- a/AVOutput/AVOutputTV.h +++ b/AVOutput/AVOutputTV.h @@ -87,35 +87,35 @@ class AVOutputTV : public AVOutputBase { DECLARE_JSON_RPC_METHOD(getColorTemperature ) DECLARE_JSON_RPC_METHOD(getBacklightDimmingMode ) DECLARE_JSON_RPC_METHOD(getSupportedDolbyVisionModes ) + DECLARE_JSON_RPC_METHOD(getDolbyVisionMode) DECLARE_JSON_RPC_METHOD(getSupportedPictureModes ) - DECLARE_JSON_RPC_METHOD(getVideoSourceCaps) - DECLARE_JSON_RPC_METHOD(getVideoFormatCaps) - DECLARE_JSON_RPC_METHOD(getVideoFrameRateCaps) - DECLARE_JSON_RPC_METHOD(getVideoResolutionCaps) DECLARE_JSON_RPC_METHOD(getPictureMode ) DECLARE_JSON_RPC_METHOD(getVideoFormat) DECLARE_JSON_RPC_METHOD(getVideoSource) DECLARE_JSON_RPC_METHOD(getVideoFrameRate) DECLARE_JSON_RPC_METHOD(getVideoResolution) DECLARE_JSON_RPC_METHOD(getLowLatencyState) - DECLARE_JSON_RPC_METHOD(getDolbyVisionMode) DECLARE_JSON_RPC_METHOD(getZoomMode) DECLARE_JSON_RPC_METHOD(getVideoContentType) /*Get Capability API's*/ DECLARE_JSON_RPC_METHOD(getBacklightCaps) - DECLARE_JSON_RPC_METHOD(getContrastCaps) DECLARE_JSON_RPC_METHOD(getBrightnessCaps) + DECLARE_JSON_RPC_METHOD(getContrastCaps) DECLARE_JSON_RPC_METHOD(getSharpnessCaps) DECLARE_JSON_RPC_METHOD(getSaturationCaps) DECLARE_JSON_RPC_METHOD(getHueCaps) DECLARE_JSON_RPC_METHOD(getColorTemperatureCaps) DECLARE_JSON_RPC_METHOD(getBacklightDimmingModeCaps ) DECLARE_JSON_RPC_METHOD(getDolbyVisionModeCaps ) - DECLARE_JSON_RPC_METHOD(getZoomModeCaps) - DECLARE_JSON_RPC_METHOD(getLowLatencyStateCaps) DECLARE_JSON_RPC_METHOD(getPictureModeCaps) + DECLARE_JSON_RPC_METHOD(getVideoFormatCaps) + DECLARE_JSON_RPC_METHOD(getVideoSourceCaps) + DECLARE_JSON_RPC_METHOD(getVideoFrameRateCaps) + DECLARE_JSON_RPC_METHOD(getVideoResolutionCaps) + DECLARE_JSON_RPC_METHOD(getLowLatencyStateCaps) + DECLARE_JSON_RPC_METHOD(getZoomModeCaps) /*Set API's*/ DECLARE_JSON_RPC_METHOD(setBacklight) @@ -127,11 +127,12 @@ class AVOutputTV : public AVOutputBase { DECLARE_JSON_RPC_METHOD(setColorTemperature ) DECLARE_JSON_RPC_METHOD(setBacklightDimmingMode ) DECLARE_JSON_RPC_METHOD(setDolbyVisionMode ) - DECLARE_JSON_RPC_METHOD(setWBCtrl ) DECLARE_JSON_RPC_METHOD(setPictureMode ) - DECLARE_JSON_RPC_METHOD(signalFilmMakerMode) - DECLARE_JSON_RPC_METHOD(setZoomMode) DECLARE_JSON_RPC_METHOD(setLowLatencyState) + DECLARE_JSON_RPC_METHOD(setZoomMode) + DECLARE_JSON_RPC_METHOD(setWBCtrl ) + DECLARE_JSON_RPC_METHOD(signalFilmMakerMode) + /*Reset API's*/ DECLARE_JSON_RPC_METHOD(resetBacklight) DECLARE_JSON_RPC_METHOD(resetBrightness ) @@ -143,8 +144,8 @@ class AVOutputTV : public AVOutputBase { DECLARE_JSON_RPC_METHOD(resetBacklightDimmingMode ) DECLARE_JSON_RPC_METHOD(resetDolbyVisionMode ) DECLARE_JSON_RPC_METHOD(resetPictureMode ) - DECLARE_JSON_RPC_METHOD(resetZoomMode) DECLARE_JSON_RPC_METHOD(resetLowLatencyState) + DECLARE_JSON_RPC_METHOD(resetZoomMode) private: @@ -155,7 +156,7 @@ class AVOutputTV : public AVOutputBase { int getFormatIndex(std::string format); int getPqParamIndex(); int getParamIndex(string source,string pqmode,string format,int& sourceIndex,int& pqmodeIndex,int& formatIndex); - int GetDolbyModeIndex(const char * dolbyMode); + int getDolbyModeIndex(const char * dolbyMode); tvDimmingMode_t getDimmingModeIndex(string mode); bool isIncluded(const std::set set1,const std::set set2); @@ -168,13 +169,13 @@ class AVOutputTV : public AVOutputBase { int parsingGetInputArgument(const JsonObject& parameters, std::string pqparam,std::string & source, std::string & pqmode, std::string & format); void spliltStringsAndConvertToSet( std::string pqmodeInfo,std::string formatInfo,std::string sourceInfo,std::set &pqmode, std::set &format, std::set &source); int validateIntegerInputParameter(std::string param, int inputValue); - int FetchCapablities(string pqparam, string & source, string & pqmode, string & format); + int fetchCapablities(string pqparam, string & source, string & pqmode, string & format); int validateInputParameter(std::string param, std::string inputValue); /* AVoutput ini file default entries */ - void LocatePQSettingsFile(void); + void locatePQSettingsFile(void); /* Intialise the last set picture mode at bootup */ - tvError_t InitializePictureMode(); + tvError_t initializePictureMode(); std::string convertToString(std::vector vec_strings); @@ -183,23 +184,23 @@ class AVOutputTV : public AVOutputBase { string convertSourceIndexToString(int source); string convertVideoFormatToString(int format); string convertPictureIndexToString(int pqmode); - tvContentFormatType_t ConvertFormatStringToTVContentFormat(const char *format); + tvContentFormatType_t convertFormatStringToTVContentFormat(const char *format); //std::string convertSourceIndexToString(int sourceIndex); //std::string convertVideoFormatToString( int formatIndex ); void convertUserScaleBacklightToDriverScale(int format,int * params); /* Update TR181 with new values when app calls set/reset calls */ - tvError_t UpdateAVoutputTVParamToHAL(std::string forParam, int source, int pqmode, int format, int value,bool setNotDelete); + tvError_t updateAVoutputTVParamToHAL(std::string forParam, int source, int pqmode, int format, int value,bool setNotDelete); /* updatePQParamsToCache will call updatePQParamToLocalCache for writing to TR181. * it will call TVSettings HAL for setting/saving the value * Will be called whenever the application invokes set/reset call */ - int UpdateAVoutputTVParam( std::string action, std::string tr181ParamName, std::string pqmode, std::string source, std::string format, tvPQParameterIndex_t pqParamIndex, int params[] ); + int updateAVoutputTVParam( std::string action, std::string tr181ParamName, std::string pqmode, std::string source, std::string format, tvPQParameterIndex_t pqParamIndex, int params[] ); /* Every bootup this function is called to sync TR181 to TVSettings HAL for saving the value */ - tvError_t SyncAvoutputTVParamsToHAL(std::string pqmode, std::string source, std::string format); + tvError_t syncAvoutputTVParamsToHAL(std::string pqmode, std::string source, std::string format); /* Every Bootup this function is called to sync TR181 to TVSettings HAL for saving the picture mode assiocation to source */ - int SyncAvoutputTVPQModeParamsToHAL(std::string pqmode, std::string source, std::string format); + int syncAvoutputTVPQModeParamsToHAL(std::string pqmode, std::string source, std::string format); uint32_t generateStorageIdentifier(std::string &key, std::string forParam,int contentFormat, int pqmode, int source); uint32_t generateStorageIdentifierDirty(std::string &key, std::string forParam,uint32_t contentFormat, int pqmode); @@ -229,7 +230,7 @@ class AVOutputTV : public AVOutputBase { void getDynamicAutoLatencyConfig(); tvError_t getUserSelectedAspectRatio (tvDisplayMode_t* mode); - void BroadcastLowLatencyModeChangeEvent(bool lowLatencyMode); + void broadcastLowLatencyModeChangeEvent(bool lowLatencyMode); tvError_t setAspectRatioZoomSettings(tvDisplayMode_t mode); tvError_t setDefaultAspectRatio(std::string pqmode="all",std::string format="all",std::string source="all"); diff --git a/AVOutput/AVOutputTVHelper.cpp b/AVOutput/AVOutputTVHelper.cpp new file mode 100644 index 0000000000..caac24409f --- /dev/null +++ b/AVOutput/AVOutputTVHelper.cpp @@ -0,0 +1,1701 @@ +/* +* If not stated otherwise in this file or this component's LICENSE file the +* following copyright and licenses apply: +* +* Copyright 2024 Sky UK +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#include +#include "AVOutputTV.h" +#include "UtilsIarm.h" +#include "rfcapi.h" + +static std::map supportedSourcemap; +static std::map supportedPictureModemap; +static std::map supportedFormatmap; +static bool m_isDalsEnabled = false; + +namespace WPEFramework { +namespace Plugin { + + tvContentFormatType_t AVOutputTV::getContentFormatIndex(tvVideoHDRFormat_t formatToConvert) + { + /* default to SDR always*/ + tvContentFormatType_t ret = tvContentFormatType_NONE; + switch(formatToConvert) { + case tvVideoHDRFormat_HLG: + ret = tvContentFormatType_HLG; + break; + + case tvVideoHDRFormat_HDR10: + ret = tvContentFormatType_HDR10; + break; + + case tvVideoHDRFormat_HDR10PLUS: + ret = tvContentFormatType_HDR10PLUS; + break; + + case tvVideoHDRFormat_DV: + ret = tvContentFormatType_DOVI; + break; + + case tvVideoHDRFormat_SDR: + case tvVideoHDRFormat_NONE: + default: + ret = tvContentFormatType_SDR; + break; + } + return ret; + } + + int AVOutputTV::getPictureModeIndex(std::string pqparam) + { + int index = -1; + std::map :: iterator it; + + for(it = supportedPictureModemap.begin(); it != supportedPictureModemap.end(); it++) { + if (it->first == pqparam) { + index = it->second; + break; + } + } + return index; + } + + int AVOutputTV::getSourceIndex(std::string pqparam) + { + int index = -1; + std::map :: iterator it; + + for(it = supportedSourcemap.begin(); it != supportedSourcemap.end(); it++) { + if (it->first == pqparam) { + index = it->second; + break; + } + } + return index; + } + + int AVOutputTV::getFormatIndex(std::string pqparam) + { + int index = -1; + std::map :: iterator it; + + for(it = supportedFormatmap.begin(); it != supportedFormatmap.end(); it++) { + if (it->first == pqparam) { + index = it->second; + break; + } + } + return index; + } + + int AVOutputTV::getPqParamIndex() + { + std::vector localpq; + std::vector localformat; + std::vector localsource; + std::vector localrange; + std::string platformsupport; + std::vector index; + + tvError_t ret = getParamsCaps(localrange, localpq, localformat, localsource, + "VideoSource", platformsupport, index); + if (ret == tvERROR_NONE) { + if (localrange.size() == index.size()) { + for (unsigned int i = 0; i< localrange.size(); i++) { + supportedSourcemap[localrange[i]] = stoi(index[i]); + } + } + } + else { + LOGERR("%s: Failed to fetch the source index \n", __FUNCTION__); + return -1; + } + if (!localpq.empty()) { + localpq.clear(); + } + if (!localformat.empty()) { + localformat.clear(); + } + if (!localsource.empty()) { + localsource.clear(); + } + if (!localrange.empty()) { + localrange.clear(); + } + if(!index.empty()) { + index.clear(); + } + + ret = getParamsCaps(localrange, localpq, localformat, localsource, + "PictureMode", platformsupport, index); + if (ret == tvERROR_NONE) { + if (localrange.size() == index.size()) { + for (unsigned int i = 0; i< localrange.size(); i++) { + supportedPictureModemap[localrange[i]] = stoi(index[i]); + } + } + } + else { + LOGERR("%s: Failed to fetch the picture index \n", __FUNCTION__); + return -1; + } + if (!localpq.empty()) { + localpq.clear(); + } + if (!localformat.empty()) { + localformat.clear(); + } + if (!localsource.empty()) { + localsource.clear(); + } + if (!localrange.empty()) { + localrange.clear(); + } + if(!index.empty()) { + index.clear(); + } + + ret = getParamsCaps(localrange, localpq, localformat, localsource, + "VideoFormat", platformsupport, index); + if (ret == tvERROR_NONE) { + if (localrange.size() == index.size()) { + for (unsigned int i = 0; i< localrange.size(); i++) { + supportedFormatmap[localrange[i]] = stoi(index[i]); + } + } + } + else { + LOGERR("%s: Failed to fetch the format index \n", __FUNCTION__); + return -1; + } + + return 0; + } + + int AVOutputTV::getParamIndex(string source,string pqmode,string format,int& sourceIndex,int& pqmodeIndex,int& formatIndex) + { + LOGINFO("Entry : %s pqmode : %s source :%s format :%s\n",__FUNCTION__,pqmode.c_str(),source.c_str(),format.c_str()); + + if( source.compare("none") == 0 || source.compare("Current") == 0 ) { + tvVideoSrcType_t currentSource = VIDEO_SOURCE_IP; + GetCurrentSource(¤tSource); + sourceIndex = (int)currentSource; + } + else { + sourceIndex = getSourceIndex(source); + } + if( pqmode.compare("none") == 0 || pqmode.compare("Current") == 0) { + char picMode[PIC_MODE_NAME_MAX]={0}; + if(!getCurrentPictureMode(picMode)) { + LOGERR("Failed to get the Current picture mode\n"); + } + else { + std::string local = picMode; + pqmodeIndex = getPictureModeIndex(local); + } + } + else { + pqmodeIndex = getPictureModeIndex(pqmode); + } + + if( format.compare("none") == 0 || format.compare("Current") == 0) { + tvVideoFormatType_t currentFormat = VIDEO_FORMAT_NONE; + GetCurrentVideoFormat(¤tFormat); + if( VIDEO_FORMAT_NONE == currentFormat ) { + formatIndex = VIDEO_FORMAT_SDR; + } + else { + formatIndex = (int)currentFormat; + } + } + else { + formatIndex = getFormatIndex(format); + } + + if (sourceIndex == -1 || pqmodeIndex == -1 || formatIndex == -1) { + return -1; + } + LOGINFO("%s: Exit sourceIndex = %d pqmodeIndex = %d formatIndex = %d\n",__FUNCTION__,sourceIndex,pqmodeIndex,formatIndex); + + return 0; + } + + int AVOutputTV::getDolbyModeIndex(const char * dolbyMode) + { + int mode = 0; + pic_modes_t *dolbyModes ; + unsigned short totalAvailable = 0; + + tvError_t ret = GetTVSupportedDolbyVisionModesODM(&dolbyModes,&totalAvailable); + if(ret == tvERROR_NONE) { + for(int count = 0;count set1,const std::set set2) + { + for( const auto& element : set2) { + if(set1.find(element) == set1.end()) { + return false; + } + } + return true; + } + + bool AVOutputTV::isSetRequired(std::string pqmode,std::string source,std::string format) + { + bool ret=false; + char picMode[PIC_MODE_NAME_MAX]={0}; + tvError_t retVal = tvERROR_NONE; + tvVideoSrcType_t sourceIndex = VIDEO_SOURCE_IP; + std::string currentPicMode; + std::string currentSource; + std::string currentFormat; + + //GetCurrent pqmode + if(!getCurrentPictureMode(picMode)) { + LOGERR("Failed to get the current picture mode\n"); + } + + currentPicMode = picMode; //Convert to string + + //GetCurrentSource + retVal = GetCurrentSource(&sourceIndex); + if(retVal != tvERROR_NONE) { + LOGERR("%s : GetCurrentSource( ) Failed\n",__FUNCTION__); + return false; + } + currentSource = convertSourceIndexToString(sourceIndex); + //GetCurrentFormat + tvVideoFormatType_t formatIndex = VIDEO_FORMAT_NONE; + GetCurrentVideoFormat(&formatIndex); + if ( formatIndex == VIDEO_FORMAT_NONE) { + formatIndex = VIDEO_FORMAT_SDR; + } + currentFormat = convertVideoFormatToString(formatIndex); + + if( ( (pqmode.find(currentPicMode) != std::string::npos) || (pqmode.compare("Global") == 0) || (pqmode.compare("Current") == 0) || + (pqmode.compare("none") == 0) ) && + ((source.find(currentSource) != std::string::npos) || (source.compare("Global") == 0) || (source.compare("Current") == 0) || + (source.compare("none") == 0) ) && + ( (format.find(currentFormat) != std::string::npos) || (format.compare("Global") == 0) || (format.compare("Current") == 0) || + (format.compare("none") == 0) ) ) { + ret=true; + } + + return ret; + } + + int AVOutputTV::isPlatformSupport(std::string pqparam) + { + std::vector range; + std::vector sourceVec; + std::vector pqmodeVec; + std::vector formatVec; + std::string isPlatformSupport; + std::vector index; + + tvError_t ret = getParamsCaps(range, pqmodeVec, sourceVec, formatVec, pqparam, isPlatformSupport, index); + + if (ret != tvERROR_NONE) { + LOGINFO("%s: failed to get the capability \n", __FUNCTION__); + return -1; + } + else { + if(isPlatformSupport.compare("true") != 0) { + LOGERR("%s: platform support not available\n", __FUNCTION__); + return -1; + } + } + return 0; + } + + void AVOutputTV::spliltCapablities( std::vector &range,std::vector &pqmode,std::vector &format, + std::vector &source, std::vector &index, std::string rangeInfo, + std::string pqmodeInfo, std::string formatInfo, std::string sourceInfo, std::string indexInfo) + { + std::string token; + std::stringstream rangeStream(rangeInfo); + std::stringstream pqmodeStream(pqmodeInfo); + std::stringstream formatStream(formatInfo); + std::stringstream sourceStream(sourceInfo); + std::stringstream indexStream(indexInfo); + + while( getline(rangeStream,token,',')) { + range.push_back(token ); + token.clear(); + } + + while( getline(pqmodeStream,token,',') ) { + pqmode.push_back(token ); + token.clear(); + } + + while( getline(formatStream,token,',')) { + format.push_back( token ); + token.clear(); + } + while( getline(sourceStream,token,',') ) { + source.push_back( token ); + token.clear(); + } + + while( getline(indexStream,token,',') ) { + index.push_back( token ); + token.clear(); + } + } + + bool AVOutputTV::isCapablityCheckPassed( std::string pqmodeInputInfo,std::string sourceInputInfo,std::string formatInputInfo,std::string param ) + { + + std::string rangeCapInfo; + std::string sourceCapInfo; + std::string formatCapInfo; + std::string pqmodeCapInfo; + std::string isPlatformSupport; + std::string indexInfo; + + std::set pqmodeCapSet; + std::set formatCapSet; + std::set sourceCapset; + std::set pqmodeInputSet; + std::set formatInputSet; + std::set sourceInputSet; + + if( ReadCapablitiesFromConfODM( rangeCapInfo, pqmodeCapInfo, formatCapInfo, sourceCapInfo,param, isPlatformSupport, indexInfo) ) { + LOGINFO( "%s: readCapablitiesFromConf Failed !!!\n",__FUNCTION__); + return false; + } + //Compare capablityInfo with Input params + + //1.convertCapablity Info to set for comparison + spliltStringsAndConvertToSet( pqmodeCapInfo, formatCapInfo, sourceCapInfo, pqmodeCapSet, formatCapSet, sourceCapset); + + //2.convert Application Input Info to set for comparison + spliltStringsAndConvertToSet( pqmodeInputInfo, formatInputInfo, sourceInputInfo, pqmodeInputSet, formatInputSet, sourceInputSet ); + + //3.Compare Each pqmode/format/source InputInfo against CapablityInfo + if ( isIncluded(pqmodeCapSet,pqmodeInputSet) && isIncluded(formatCapSet,formatInputSet) && isIncluded(sourceCapset,sourceInputSet) ) { + LOGINFO("%s : Capablity Chesk passed \n", __FUNCTION__); + return true; + } + else { + LOGERR("%s : Capablity Check Failed \n", __FUNCTION__); + return false; + } + } + + int AVOutputTV::parsingSetInputArgument(const JsonObject& parameters, std::string pqparam, std::string & source, + std::string & pqmode, std::string & format) { + + JsonArray sourceArray; + JsonArray pqmodeArray; + JsonArray formatArray; + + + pqmodeArray = parameters.HasLabel("pictureMode") ? parameters["pictureMode"].Array() : JsonArray(); + for (int i = 0; i < pqmodeArray.Length(); ++i) { + pqmode += pqmodeArray[i].String(); + if (i != (pqmodeArray.Length() - 1) ) { + pqmode += ","; + } + } + + sourceArray = parameters.HasLabel("videoSource") ? parameters["videoSource"].Array() : JsonArray(); + for (int i = 0; i < sourceArray.Length(); ++i) { + source += sourceArray[i].String(); + if (i != (sourceArray.Length() - 1) ) { + source += ","; + } + } + + formatArray = parameters.HasLabel("videoFormat") ? parameters["videoFormat"].Array() : JsonArray(); + for (int i = 0; i < formatArray.Length(); ++i) { + format += formatArray[i].String(); + if (i != (formatArray.Length() - 1) ) { + format += ","; + } + } + + if (source.empty()) { + source = "Global"; + } + if (pqmode.empty()) { + pqmode = "Global"; + } + if (format.empty()) { + format = "Global"; + } + + if (convertToValidInputParameter(pqparam, source, pqmode, format) != 0) { + LOGERR("%s: Failed to convert the input paramters. \n", __FUNCTION__); + return -1; + } + + return 0; + } + + int AVOutputTV::parsingGetInputArgument(const JsonObject& parameters, std::string pqparam, + std::string & source, std::string & pqmode, std::string & format) { + pqmode = parameters.HasLabel("pictureMode") ? parameters["pictureMode"].String() : ""; + + source = parameters.HasLabel("videoSource") ? parameters["videoSource"].String() : ""; + + format = parameters.HasLabel("videoFormat") ? parameters["videoFormat"].String() : ""; + + if ( (source.compare("Global") == 0) || (pqmode.compare("Global") == 0) || (format.compare("Global") == 0) ) { + LOGERR("%s: get cannot fetch the Global inputs \n", __FUNCTION__); + return -1; + } + + if (source.empty()) { + source = "Current"; + } + if (pqmode.empty()) { + pqmode = "Current"; + } + if (format.empty()) { + format = "Current"; + } + + if (convertToValidInputParameter(pqparam,source, pqmode, format) != 0) { + LOGERR("%s: Failed to convert the input paramters. \n", __FUNCTION__); + return -1; + } + + return 0; + } + + void AVOutputTV::spliltStringsAndConvertToSet( std::string pqmodeInfo,std::string formatInfo,std::string sourceInfo,std::set &pqmode, std::set &format, std::set &source) + { + std::string token; + std::stringstream pqmodeStream(pqmodeInfo); + std::stringstream formatStream(formatInfo); + std::stringstream sourceStream(sourceInfo); + + while( getline(pqmodeStream,token,',') ) { + pqmode.insert( token ); + token.clear(); + } + + while( getline(formatStream,token,',') ) { + format.insert( token ); + token.clear(); + } + + while( getline(sourceStream,token,',')) { + source.insert( token ); + token.clear(); + } + } + + int AVOutputTV::validateIntegerInputParameter(std::string param, int inputValue) + { + + std::vector range; + std::vector pqmode; + std::vector source; + std::vector format; + + tvError_t ret = getParamsCaps(range, pqmode, source, format, param); + + if (ret != tvERROR_NONE) { + LOGERR("Failed to fetch the range capability[%s] \n", param.c_str()); + return -1; + } + + if ( (param == "Brightness") || (param == "Contrast") || + (param == "Sharpness") || (param == "Saturation") || + (param == "Hue") || (param == "WhiteBalance") || + (param == "ComponentSaturation") || (param == "Backlight") || + (param == "ComponentHue") || (param == "ComponentLuma") || (param == "LowLatencyState") ) { + if (inputValue < stoi(range[0]) || inputValue > stoi(range[1])) { + LOGERR("wrong Input value[%d]", inputValue); + return -1; + } + } + return 0; + } + + int AVOutputTV::fetchCapablities(string pqparam, string & source, string & pqmode, string & format) { + + std::vector range; + std::vector sourceVec; + std::vector pqmodeVec; + std::vector formatVec; + + tvError_t ret = tvERROR_NONE; + + ret = getParamsCaps(range, pqmodeVec, sourceVec, formatVec, pqparam); + + if (ret != tvERROR_NONE) { + LOGINFO("%s: failed to get the capability \n", __FUNCTION__); + return -1; + } + + if (sourceVec.size() != 0) { + source = convertToString(sourceVec); + } + + if (pqmodeVec.size() != 0) { + pqmode = convertToString(pqmodeVec); + } + + if (formatVec.size() != 0) { + format = convertToString(formatVec); + } + + return 0; + } + + int AVOutputTV::validateInputParameter(std::string param, std::string inputValue) + { + + std::vector range; + std::vector pqmode; + std::vector source; + std::vector format; + + tvError_t ret = getParamsCaps(range, pqmode, source, format, param); + + if (ret != tvERROR_NONE) { + LOGERR("Failed to fetch the range capability[%s] \n", param.c_str()); + return -1; + } + + if ( (param == "ColorTemperature") || + (param == "DimmingMode") || (param == "AutoBacklightControl") || + (param == "DolbyVisionMode") || (param == "HDR10Mode") || + (param == "HLGMode") || (param == "AspectRatio") || (param == "PictureMode") ) { + auto iter = find(range.begin(), range.end(), inputValue); + + if (iter == range.end()) { + LOGERR("Not a valid input value[%s].\n", inputValue.c_str()); + return -1; + } + } + return 0; + } + + void AVOutputTV::locatePQSettingsFile() + { + LOGINFO("Entry\n"); + char panelId[20] = {0}; + std::string PQFileName = AVOUTPUT_RFC_CALLERID; + std::string FilePath = "/etc/rfcdefaults/"; + + /* The if condition is to override the tvsettings ini file so it helps the PQ tuning process for new panels */ + if(access(AVOUTPUT_OVERRIDE_PATH, F_OK) == 0) { + PQFileName = std::string(AVOUTPUT_RFC_CALLERID_OVERRIDE); + } + else { + int val=GetPanelIDODM(panelId); + if(val==0) { + LOGINFO("%s : panel id read is : %s\n",__FUNCTION__,panelId); + if(strncmp(panelId,AVOUTPUT_CONVERTERBOARD_PANELID,strlen(AVOUTPUT_CONVERTERBOARD_PANELID))!=0) { + PQFileName+=std::string("_")+panelId; + struct stat tmp_st; + + LOGINFO("%s: Looking for %s.ini \n",__FUNCTION__,PQFileName.c_str()); + if(stat((FilePath+PQFileName+std::string(".ini")).c_str(), &tmp_st)!=0) { + //fall back + LOGINFO("%s not available in %s Fall back to default\n",PQFileName.c_str(),FilePath.c_str()); + PQFileName =std::string(AVOUTPUT_RFC_CALLERID); + } + } + } + else { + LOGINFO("%s : GetPanelID failed : %d\n",__FUNCTION__,val); + } + } + strncpy(rfc_caller_id,PQFileName.c_str(),PQFileName.size()); + LOGINFO("%s : Default tvsettings file : %s\n",__FUNCTION__,rfc_caller_id); + } + + tvError_t AVOutputTV::initializePictureMode() + { + tvError_t ret = tvERROR_NONE; + TR181_ParamData_t param; + tvVideoSrcType_t current_source = VIDEO_SOURCE_IP; + std::string tr181_param_name = ""; + tvVideoFormatType_t current_format = VIDEO_FORMAT_NONE; + + GetCurrentVideoFormat(¤t_format); + if ( current_format == VIDEO_FORMAT_NONE) { + current_format = VIDEO_FORMAT_SDR; + } + // get current source + GetCurrentSource(¤t_source); + + tr181_param_name += std::string(AVOUTPUT_SOURCE_PICTUREMODE_STRING_RFC_PARAM); + tr181_param_name += "."+convertSourceIndexToString(current_source)+"."+"Format."+convertVideoFormatToString(current_format)+"."+"PictureModeString"; + tr181ErrorCode_t err = getLocalParam(rfc_caller_id, tr181_param_name.c_str(), ¶m); + if ( tr181Success == err ) { + std::string local = param.value; + transform(local.begin(), local.end(), local.begin(), ::tolower); + ret = SetTVPictureMode(local.c_str()); + + if(ret != tvERROR_NONE) { + LOGWARN("Picture Mode set failed: %s\n",getErrorString(ret).c_str()); + } + else { + LOGINFO("Picture Mode initialized successfully, tr181 value [%s] value: %s\n", tr181_param_name.c_str(), + param.value); + } + } + else { + ret = tvERROR_GENERAL; + LOGWARN("getLocalParam for %s Failed : %s\n", tr181_param_name.c_str(), getTR181ErrorString(err)); + } + + return ret; + } + + std::string AVOutputTV::convertToString(std::vector vec_strings) + { + std::string result = std::accumulate(vec_strings.begin(), vec_strings.end(), std::string(), + [](const std::string& a, const std::string& b) -> std::string { + return a.empty() ? b : a + "," + b; + }); + return result; + } + + int AVOutputTV::convertToValidInputParameter(std::string pqparam, std::string & source, std::string & pqmode, std::string & format) + { + + LOGINFO("Entry %s source %s pqmode %s format %s \n", __FUNCTION__, source.c_str(), pqmode.c_str(), format.c_str()); + + // converting pq to valid paramter format + if (pqmode == "Global") { + std::string localSource; + std::string localPqmode; + std::string localFormat; + if (fetchCapablities(pqparam, localSource, localPqmode, localFormat) == 0) { + pqmode = localPqmode; + //if pqmode none from capabilty then lets keep pqmode as global to fail the capabilty + } + else { + LOGINFO("%s, Failed to get picturemode capability\n", __FUNCTION__); + return -1; + } + } + else if (pqmode == "Current") { + char picMode[PIC_MODE_NAME_MAX]={0}; + if(!getCurrentPictureMode(picMode)) { + LOGINFO("Failed to get the Current picture mode\n"); + return -1; + } + else { + pqmode = picMode; + } + } + + if (source == "Global") { + std::string localSource; + std::string localPqmode; + std::string localFormat; + if (fetchCapablities(pqparam, localSource, localPqmode, localFormat) == 0) { + source = localSource; + } + else { + LOGINFO("%s, Failed to get source capability\n", __FUNCTION__); + return -1; + } + } + else if (source == "Current") { + tvVideoSrcType_t currentSource = VIDEO_SOURCE_IP; + tvError_t ret = GetCurrentSource(¤tSource); + + if(ret != tvERROR_NONE) { + LOGWARN("%s: GetCurrentSource( ) Failed \n",__FUNCTION__); + return -1; + } + source = convertSourceIndexToString(currentSource); + } + + //convert format into valid parameter + if (format == "Global") { + std::string localSource; + std::string localPqmode; + std::string localFormat; + if (fetchCapablities(pqparam, localSource, localPqmode, localFormat) == 0) { + format = localFormat; + } + else { + LOGINFO("%s, Failed to get format capability\n", __FUNCTION__); + return -1; + } + } + else if (format == "Current") { + tvVideoFormatType_t formatIndex = VIDEO_FORMAT_NONE; + GetCurrentVideoFormat(&formatIndex); + if ( formatIndex == VIDEO_FORMAT_NONE) { + formatIndex = VIDEO_FORMAT_SDR; + } + format = convertVideoFormatToString(formatIndex); + } + + LOGINFO("Exit %s source %s pqmode %s format %s \n", __FUNCTION__, source.c_str(), pqmode.c_str(), format.c_str()); + return 0; + } + + string AVOutputTV::convertSourceIndexToString(int source) + { + std::string ret; + std::map :: iterator it; + for (it = supportedSourcemap.begin(); it != supportedSourcemap.end(); it++) { + if (it->second == source) { + ret = it->first; + break; + } + } + return ret; + } + + string AVOutputTV::convertVideoFormatToString(int format) + { + std::string ret; + std::map :: iterator it; + for (it = supportedFormatmap.begin(); it != supportedFormatmap.end(); it++) { + if (it->second == format) { + ret = it->first; + break; + } + } + return ret; + } + + string AVOutputTV::convertPictureIndexToString(int pqmode) + { + std::string ret; + std::map :: iterator it; + for(it = supportedPictureModemap.begin(); it != supportedPictureModemap.end(); it++) { + if (it->second == pqmode) { + ret = it->first; + break; + } + } + return ret; + } + + tvContentFormatType_t AVOutputTV::convertFormatStringToTVContentFormat(const char *format) + { + tvContentFormatType_t ret = tvContentFormatType_SDR; + + if( strncmp(format,"sdr",strlen(format)) == 0 || strncmp(format,"SDR",strlen(format)) == 0 ) { + ret = tvContentFormatType_SDR; + } + else if( strncmp(format,"hdr10",strlen(format)) == 0 || strncmp(format,"HDR10",strlen(format))==0 ) { + ret = tvContentFormatType_HDR10; + } + else if( strncmp(format,"hlg",strlen(format)) == 0 || strncmp(format,"HLG",strlen(format)) == 0 ) { + ret = tvContentFormatType_HLG; + } + else if( strncmp(format,"dolby",strlen(format)) == 0 || strncmp(format,"DOLBY",strlen(format)) == 0 ) { + ret=tvContentFormatType_DOVI; + } + + return ret; + } + + tvError_t AVOutputTV::updateAVoutputTVParamToHAL(std::string forParam, int source, int pqmode, int format, int value,bool setNotDelete) + { + tvError_t ret = tvERROR_NONE; + std::string key; + + generateStorageIdentifier(key,forParam,format,pqmode,source); + if(key.empty()) { + LOGERR("generateStorageIdentifierDirty failed\n"); + ret = tvERROR_GENERAL; + } + else { + tr181ErrorCode_t err = tr181Success; + if(setNotDelete) { + std::string toStore = std::to_string(value); + if (forParam.compare("ColorTemp") == 0) { + getColorTempStringFromEnum(value, toStore); + } + else if(forParam.compare("DimmingMode") == 0 ) { + getDimmingModeStringFromEnum(value, toStore); + } + else if (forParam.compare("DolbyVisionMode") == 0 ) { + toStore = getDolbyModeStringFromEnum((tvDolbyMode_t)value); + } + err = setLocalParam(rfc_caller_id, key.c_str(),toStore.c_str()); + + } + else { + err = clearLocalParam(rfc_caller_id, key.c_str()); + } + + if ( err != tr181Success ) { + LOGERR("%s for %s Failed : %s\n", setNotDelete?"Set":"Delete", key.c_str(), getTR181ErrorString(err)); + ret = tvERROR_GENERAL; + } + } + return ret; + } + + int AVOutputTV::updateAVoutputTVParam( std::string action, std::string tr181ParamName, std::string pqmode, std::string source, std::string format, tvPQParameterIndex_t pqParamIndex, int params[] ) + { + LOGINFO("Entry : %s\n",__FUNCTION__); + std::vector sources; + std::vector pictureModes; + std::vector formats; + int ret = 0; + bool sync = !(action.compare("sync")); + bool reset = !(action.compare("reset")); + bool set = !(action.compare("set")); + + LOGINFO("%s: Entry param : %s Action : %s pqmode : %s source :%s format :%s\n",__FUNCTION__,tr181ParamName.c_str(),action.c_str(),pqmode.c_str(),source.c_str(),format.c_str() ); + ret = getSaveConfig(pqmode, source, format, sources, pictureModes, formats); + if( 0 == ret ) { + for(int sourceType: sources) { + tvVideoSrcType_t source = (tvVideoSrcType_t)sourceType; + for(int mode : pictureModes) { + for(int formatType : formats) { + tvVideoFormatType_t format = (tvVideoFormatType_t)formatType; + switch(pqParamIndex) { + case PQ_PARAM_BRIGHTNESS: + case PQ_PARAM_CONTRAST: + case PQ_PARAM_BACKLIGHT: + case PQ_PARAM_SATURATION: + case PQ_PARAM_SHARPNESS: + case PQ_PARAM_HUE: + case PQ_PARAM_COLOR_TEMPERATURE: + case PQ_PARAM_DIMMINGMODE: + case PQ_PARAM_LOWLATENCY_STATE: + case PQ_PARAM_DOLBY_MODE: + if(reset) { + ret |= updateAVoutputTVParamToHAL(tr181ParamName,source, mode, format,0,false); + } + if(sync || reset) { + int value=0; + if(getLocalparam(tr181ParamName,format,mode,source,value,pqParamIndex,sync)) { + continue; + } + params[0]=value; + } + if(set) { + ret |= updateAVoutputTVParamToHAL(tr181ParamName,source, mode, format, params[0],true); + } + break; + default: + break; + } + switch(pqParamIndex) { + case PQ_PARAM_BRIGHTNESS: + ret |= SaveBrightness(source, mode,format,params[0]); + break; + case PQ_PARAM_CONTRAST: + ret |= SaveContrast(source, mode,format,params[0]); + break; + case PQ_PARAM_SHARPNESS: + ret |= SaveSharpness(source, mode,format,params[0]); + break; + case PQ_PARAM_HUE: + ret |= SaveHue(source, mode,format,params[0]); + break; + case PQ_PARAM_SATURATION: + ret |= SaveSaturation(source, mode,format,params[0]); + break; + case PQ_PARAM_COLOR_TEMPERATURE: + ret |= SaveColorTemperature(source, mode,format,(tvColorTemp_t)params[0]); + break; + case PQ_PARAM_BACKLIGHT: + ret |= SaveBacklight(source, mode,format,params[0]); + break; + case PQ_PARAM_DIMMINGMODE: + ret |= SaveTVDimmingMode(source,mode,format,(tvDimmingMode_t)params[0]); + break; + case PQ_PARAM_LOWLATENCY_STATE: + ret |= SaveLowLatencyState(source, mode,format,params[0]); + break; + case PQ_PARAM_DOLBY_MODE: + ret |= SaveTVDolbyVisionMode(source, mode,format,(tvDolbyMode_t)params[0]); + break; + + case PQ_PARAM_ASPECT_RATIO: + ret |= SaveAspectRatio(source,mode,format,(tvDisplayMode_t)params[0]); + break; + case PQ_PARAM_LOCALDIMMING_LEVEL: + { + if(sync) { + int value=0; + getLocalparam(tr181ParamName,format,mode,source,value,pqParamIndex,sync); + params[0]=value; + } + ret |= SaveTVDimmingMode(source, mode,format,(tvDimmingMode_t)params[0]); + break; + } + case PQ_PARAM_CMS: + case PQ_PARAM_LDIM: + default: + break; + } + } + } + } + + } + return ret; + } + + tvError_t AVOutputTV::syncAvoutputTVParamsToHAL(std::string pqmode,std::string source,std::string format) + { + int params[3]={0}; + + LOGINFO("Entry %s : pqmode : %s source : %s format : %s\n",__FUNCTION__,pqmode.c_str(),source.c_str(),format.c_str()); + + if( !updateAVoutputTVParam("sync","Brightness",pqmode,source,format,PQ_PARAM_BRIGHTNESS,params)) { + LOGINFO("Brightness Successfully sync to Drive Cache\n"); + } + else { + LOGERR("Brightness Sync to cache Failed !!!\n"); + } + + if( !updateAVoutputTVParam("sync","Contrast",pqmode,source,format,PQ_PARAM_CONTRAST,params)) { + LOGINFO("Contrast Successfully Synced to Drive Cache\n"); + } + else { + LOGERR("Contrast Sync to cache Failed !!!\n"); + } + + if( !updateAVoutputTVParam("sync","Sharpness",pqmode,source,format,PQ_PARAM_SHARPNESS,params)) { + LOGINFO("Sharpness Successfully Synced to Drive Cache\n"); + } + else { + LOGERR("Sharpness Sync to cache Failed !!!\n"); + } + + if( !updateAVoutputTVParam("sync","Saturation",pqmode,source,format,PQ_PARAM_SATURATION,params)) { + LOGINFO("Saturation Successfully Synced to Drive Cache\n"); + } + else { + LOGERR("Saturation Sync to cache Failed !!!\n"); + } + + if( !updateAVoutputTVParam("sync","Hue",pqmode,source,format,PQ_PARAM_HUE,params)) { + LOGINFO("Hue Successfully Synced to Drive Cache\n"); + } + else { + LOGERR("Hue Sync to cache Failed !!!\n"); + } + + if( !updateAVoutputTVParam("sync","ColorTemp",pqmode,source,format,PQ_PARAM_COLOR_TEMPERATURE,params)) { + LOGINFO("ColorTemp Successfully Synced to Drive Cache\n"); + } + else { + LOGERR("ColorTemp Sync to cache Failed !!!\n"); + } + + if( !updateAVoutputTVParam("sync","DolbyVisionMode",pqmode,source,"DV",PQ_PARAM_DOLBY_MODE,params)) { + LOGINFO("dvmode Successfully Synced to Drive Cache\n"); + } + else { + LOGERR("dvmode Sync to cache Failed !!!\n"); + } + + if( !updateAVoutputTVParam("sync","DimmingMode",pqmode,source,format,PQ_PARAM_DIMMINGMODE,params)) { + LOGINFO("dimmingmode Successfully Synced to Drive Cache\n"); + } + else { + LOGERR("dimmingmode Sync to cache Failed !!!\n"); + } + + if( !updateAVoutputTVParam("sync","Backlight",pqmode,source,format,PQ_PARAM_BACKLIGHT,params) ) { + LOGINFO("Backlight Successfully Synced to Drive Cache\n"); + } + else { + LOGERR("Backlight Sync to cache Failed !!!\n"); + } + + LOGINFO("Exit %s : pqmode : %s source : %s format : %s\n",__FUNCTION__,pqmode.c_str(),source.c_str(),format.c_str()); + return tvERROR_NONE; + } + + int AVOutputTV::syncAvoutputTVPQModeParamsToHAL(std::string pqmode, std::string source, std::string format) + { + std::vector sources; + std::vector pictureModes; + std::vector formats; + tr181ErrorCode_t err = tr181Success; + TR181_ParamData_t param = {0}; + int ret = 0; + + ret = getSaveConfig(pqmode, source, format, sources, pictureModes, formats); + + if (ret == 0 ) { + for (int source : sources) { + tvVideoSrcType_t sourceType = (tvVideoSrcType_t)source; + for (int format : formats) { + tvVideoFormatType_t formatType = (tvVideoFormatType_t)format; + std::string tr181_param_name = ""; + tr181_param_name += std::string(AVOUTPUT_SOURCE_PICTUREMODE_STRING_RFC_PARAM); + tr181_param_name += "."+convertSourceIndexToString(sourceType)+"."+"Format."+ + convertVideoFormatToString(formatType)+"."+"PictureModeString"; + + err = getLocalParam(rfc_caller_id, tr181_param_name.c_str(), ¶m); + if ( tr181Success == err ) { + std::string local = param.value; + int pqmodeindex = (int)getPictureModeIndex(local); + + tvError_t tv_err = SaveSourcePictureMode(sourceType, formatType, pqmodeindex); + if (tv_err != tvERROR_NONE) { + LOGWARN("failed to SaveSourcePictureMode \n"); + return -1; + } + } + else { + LOGWARN("Failed to get the getLocalParam \n"); + return -1; + } + } + } + } + return ret; + } + + uint32_t AVOutputTV::generateStorageIdentifier(std::string &key, std::string forParam,int contentFormat, int pqmode, int source) + { + key+=std::string(AVOUTPUT_GENERIC_STRING_RFC_PARAM); + key+=STRING_SOURCE+convertSourceIndexToString(source)+std::string(".")+STRING_PICMODE+convertPictureIndexToString(pqmode)+std::string(".")+std::string(STRING_FORMAT)+convertVideoFormatToString(contentFormat)+std::string(".")+forParam; + return tvERROR_NONE; + } + + uint32_t AVOutputTV::generateStorageIdentifierDirty(std::string &key, std::string forParam,uint32_t contentFormat, int pqmode) + { + key+=std::string(AVOUTPUT_GENERIC_STRING_RFC_PARAM); + key+=STRING_PICMODE+std::to_string(pqmode)+std::string(".")+std::string(STRING_FORMAT)+std::to_string(contentFormat); + CREATE_DIRTY(key)+=forParam; + + return tvERROR_NONE; + } + + std::string AVOutputTV::getErrorString (tvError_t eReturn) + { + switch (eReturn) { + case tvERROR_NONE: + return "API SUCCESS"; + case tvERROR_GENERAL: + return "API FAILED"; + case tvERROR_OPERATION_NOT_SUPPORTED: + return "OPERATION NOT SUPPORTED ERROR"; + case tvERROR_INVALID_PARAM: + return "INVALID PARAM ERROR"; + case tvERROR_INVALID_STATE: + return "INVALID STATE ERROR"; + } + return "UNKNOWN ERROR"; + } + + int AVOutputTV::getSaveConfig(std::string pqmode, std::string source, std::string format,std::vector &sources,std::vector &picturemodes, std::vector &formats) + { + LOGINFO("Entry : %s pqmode : %s source :%s format :%s\n",__FUNCTION__,pqmode.c_str(),source.c_str(),format.c_str()); + + int ret = 0; + + if (getAvailableCapabilityModes(source, pqmode, format) != 0) { + LOGERR("%s: failed to get picture/source/format mode capability \n", __FUNCTION__); + return -1; + } + //pqmode + char *modeString = strdup(pqmode.c_str()); + char *token = NULL; + while ((token = strtok_r(modeString,",",&modeString))) { + std::string local = token; + picturemodes.push_back(getPictureModeIndex(local)); + } + //source + char *sourceString = strdup(source.c_str()); + char *sourceToken = NULL; + while ((sourceToken = strtok_r(sourceString,",",&sourceString))) { + std::string local = sourceToken; + sources.push_back(getSourceIndex(local)); + } + //3)check format + char *formatString = strdup(format.c_str()); + char *formatToken = NULL; + while ((formatToken = strtok_r(formatString,",",&formatString))) { + std::string local = formatToken; + formats.push_back(getFormatIndex(local)); + } + + LOGINFO("Exit : %s pqmode : %s source :%s format :%s ret:%d\n",__FUNCTION__,pqmode.c_str(),source.c_str(),format.c_str(), ret); + return ret; + } + + int AVOutputTV::getLocalparam( std::string forParam,int formatIndex,int pqIndex,int sourceIndex,int & value, + tvPQParameterIndex_t pqParamIndex,bool sync,int color ) + { + string key; + TR181_ParamData_t param={0}; + generateStorageIdentifier(key,forParam,formatIndex,pqIndex,sourceIndex); + if(key.empty()) { + LOGERR("generateStorageIdentifier failed\n"); + return -1; + } + + tr181ErrorCode_t err=getLocalParam(rfc_caller_id, key.c_str(), ¶m); + + if ( tr181Success == err ) {//Fetch new tr181format values + if( forParam.compare("ColorTemp") == 0 ) { + if (strncmp(param.value, "Standard", strlen(param.value))==0) { + value=tvColorTemp_STANDARD; + } + else if (strncmp(param.value, "Warm", strlen(param.value))==0) { + value=tvColorTemp_WARM; + } + else if (strncmp(param.value, "Cold", strlen(param.value))==0) { + value=tvColorTemp_COLD; + } + else if (strncmp(param.value, "User Defined", strlen(param.value))==0) { + value=tvColorTemp_USER; + } + else { + value=tvColorTemp_STANDARD; + } + return 0; + } + else if( forParam.compare("DimmingMode") == 0 ) { + if (strncmp(param.value, "fixed", strlen(param.value))==0) { + value=tvDimmingMode_Fixed; + } + else if (strncmp(param.value, "local", strlen(param.value))==0) { + value=tvDimmingMode_Local; + } + else if (strncmp(param.value, "global", strlen(param.value))==0) { + value=tvDimmingMode_Global; + } + return 0; + } + else if ( forParam.compare("DolbyVisionMode") == 0) { + if (strncmp(param.value, "Dark", strlen(param.value)) == 0) { + value = tvDolbyMode_Dark; + } + else { + value = tvDolbyMode_Bright; + } + return 0; + } + else { + value=std::stoi(param.value); + return 0; + } + } + else {// default value from DB + if( sync ) { + return 1; + } + GetDefaultPQParams(pqIndex,(tvVideoSrcType_t)sourceIndex,(tvVideoFormatType_t)formatIndex,pqParamIndex,&value); + LOGINFO("Default value from DB : %s : %d \n",key.c_str(),value); + return 0; + } + } + + tvDataComponentColor_t AVOutputTV::getComponentColorEnum(std::string colorName) + { + tvDataComponentColor_t CompColorEnum = tvDataColor_MAX; + + if(!colorName.compare("none")) { + CompColorEnum = tvDataColor_NONE; + } + else if (!colorName.compare("red")) { + CompColorEnum = tvDataColor_RED; + } + else if (!colorName.compare("green")) { + CompColorEnum = tvDataColor_GREEN; + } + else if (!colorName.compare("blue")) { + CompColorEnum = tvDataColor_BLUE; + } + else if (!colorName.compare("yellow")) { + CompColorEnum = tvDataColor_YELLOW; + } + else if (!colorName.compare("cyan")) { + CompColorEnum = tvDataColor_CYAN; + } + else if (!colorName.compare("magenta")) { + CompColorEnum = tvDataColor_MAGENTA; + } + return CompColorEnum; + } + + int AVOutputTV::getDolbyParams(tvContentFormatType_t format, std::string &s, std::string source) + { + int ret = -1; + TR181_ParamData_t param; + std::string rfc_param = AVOUTPUT_HDR10MODE_RFC_PARAM; + int dolby_mode_value = 0; + tvVideoSrcType_t sourceIndex = VIDEO_SOURCE_IP; + /*Since dolby vision is source specific, we should for check for specific source*/ + if (!source.empty()) { + sourceIndex = (tvVideoSrcType_t)getSourceIndex(source); + } + else { + GetCurrentSource(&sourceIndex); + } + + char picMode[PIC_MODE_NAME_MAX]={0}; + int pqmodeIndex = 0; + if(!getCurrentPictureMode(picMode)) { + LOGERR("Failed to get the Current picture mode\n"); + } + else { + std::string local = picMode; + pqmodeIndex = getPictureModeIndex(local); + } + memset(¶m, 0, sizeof(param)); + if (format == tvContentFormatType_HLG ) { + rfc_param = AVOUTPUT_HLGMODE_RFC_PARAM; + } + else if (format == tvContentFormatType_DOVI) { + rfc_param = AVOUTPUT_SOURCE_PICTUREMODE_STRING_RFC_PARAM + std::to_string(sourceIndex) + "."+"DolbyVisionMode"; + } + + tr181ErrorCode_t err = getLocalParam(rfc_caller_id, rfc_param.c_str(), ¶m); + if ( tr181Success != err) { + tvError_t retVal = GetDefaultPQParams(pqmodeIndex,(tvVideoSrcType_t)sourceIndex, + (tvVideoFormatType_t)ConvertHDRFormatToContentFormatODM((tvhdr_type_t)format), + PQ_PARAM_DOLBY_MODE,&dolby_mode_value); + if( retVal != tvERROR_NONE ) { + LOGERR("%s : failed\n",__FUNCTION__); + return ret; + } + s = getDolbyModeStringFromEnum((tvDolbyMode_t)dolby_mode_value); + ret = 0; + } + else { + s += param.value; + ret = 0; + } + return ret; + } + + tvError_t AVOutputTV::getParamsCaps(std::vector &range + , std::vector &pqmode, std::vector &source, std::vector &format,std::string param ) + { + tvError_t ret = tvERROR_NONE; + + std::string rangeInfo; + std::string sourceInfo; + std::string formatInfo; + std::string pqmodeInfo; + + std::string platformsupport; + std::string indexInfo; + std::vector localIndex; + + if( ReadCapablitiesFromConfODM( rangeInfo, pqmodeInfo, formatInfo ,sourceInfo,param, platformsupport, indexInfo)) { + LOGERR( "%s: ReadCapablitiesFromConf Failed !!!\n",__FUNCTION__); + return tvERROR_GENERAL; + } + else { + spliltCapablities( range, pqmode, format, source, localIndex,rangeInfo, pqmodeInfo, formatInfo, sourceInfo , indexInfo); + } + + return ret; + } + + tvError_t AVOutputTV::getParamsCaps(std::vector &range + , std::vector &pqmode, std::vector &source, std::vector &format,std::string param, + std::string & isPlatformSupport, std::vector & index) + { + tvError_t ret = tvERROR_NONE; + + std::string rangeInfo; + std::string sourceInfo; + std::string formatInfo; + std::string pqmodeInfo; + std::string indexInfo; + + if( ReadCapablitiesFromConfODM( rangeInfo, pqmodeInfo, formatInfo ,sourceInfo,param, isPlatformSupport, indexInfo)) { + LOGERR( "%s: ReadCapablitiesFromConf Failed !!!\n",__FUNCTION__); + return tvERROR_GENERAL; + } + else { + spliltCapablities( range, pqmode, format, source, index,rangeInfo, pqmodeInfo, formatInfo, sourceInfo, indexInfo); + } + + return ret; + } + + void AVOutputTV::getDimmingModeStringFromEnum(int value, std::string &toStore) + { + const char *color_temp_string[] = { + [tvDimmingMode_Fixed] = "fixed", + [tvDimmingMode_Local] = "local", + [tvDimmingMode_Global] = "global", + }; + toStore.clear(); + toStore+=color_temp_string[value]; + } + + void AVOutputTV::getColorTempStringFromEnum(int value, std::string &toStore) + { + const char *color_temp_string[] = { + [tvColorTemp_STANDARD] = "Standard", + [tvColorTemp_WARM] = "Warm", + [tvColorTemp_COLD] = "Cold", + [tvColorTemp_USER] = "User Defined" + }; + toStore.clear(); + toStore+=color_temp_string[value]; + } + + int AVOutputTV::getCurrentPictureMode(char *picMode) + { + tvError_t ret = tvERROR_NONE; + TR181_ParamData_t param; + std::string tr181_param_name; + tvVideoSrcType_t currentSource = VIDEO_SOURCE_IP; + + ret = GetCurrentSource(¤tSource); + if(ret != tvERROR_NONE) { + LOGERR("GetCurrentSource() Failed set source to default\n"); + return 0; + } + + tvVideoFormatType_t current_format = VIDEO_FORMAT_NONE; + GetCurrentVideoFormat(¤t_format); + if ( current_format == VIDEO_FORMAT_NONE) { + current_format = VIDEO_FORMAT_SDR; + } + + tr181_param_name += std::string(AVOUTPUT_SOURCE_PICTUREMODE_STRING_RFC_PARAM); + tr181_param_name += "." + convertSourceIndexToString(currentSource) + "." + "Format."+convertVideoFormatToString(current_format)+"."+"PictureModeString"; + + memset(¶m, 0, sizeof(param)); + + tr181ErrorCode_t err = getLocalParam(rfc_caller_id, tr181_param_name.c_str(), ¶m); + if ( err == tr181Success ) { + strncpy(picMode, param.value, strlen(param.value)+1); + LOGINFO("getLocalParam success, mode = %s\n", picMode); + return 1; + } + else { + LOGERR("getLocalParam failed"); + return 0; + } + } + + int AVOutputTV::getDolbyParamToSync(int sourceIndex, int formatIndex, int& value) + { + int ret=0; + TR181_ParamData_t param; + int pqmodeIndex = 0; + char picMode[PIC_MODE_NAME_MAX]={0}; + if(!getCurrentPictureMode(picMode)) { + LOGERR("Failed to get the Current picture mode\n"); + } + else { + std::string local = picMode; + pqmodeIndex = getPictureModeIndex(local); + } + std ::string rfc_param = AVOUTPUT_SOURCE_PICTUREMODE_STRING_RFC_PARAM + std::to_string(sourceIndex) + "."+"DolbyVisionMode"; + memset(¶m, 0, sizeof(param)); + tr181ErrorCode_t err = getLocalParam(rfc_caller_id, rfc_param.c_str(), ¶m); + + if ( tr181Success != err) { + tvError_t retVal = GetDefaultPQParams(pqmodeIndex,(tvVideoSrcType_t)sourceIndex, (tvVideoFormatType_t)formatIndex, + PQ_PARAM_DOLBY_MODE, &value); + if( retVal != tvERROR_NONE ) { + LOGERR("%s : failed\n",__FUNCTION__); + return -1; + } + ret = 0; + } + else { + value=getDolbyModeIndex(param.value); + ret = 0; + } + + return ret; + } + + std::string AVOutputTV::getDolbyModeStringFromEnum( tvDolbyMode_t mode) + + { + std::string value; + switch(mode) { + case tvDolbyMode_Dark: + case tvHDR10Mode_Dark: + case tvHLGMode_Dark: + value = "Dark"; + break; + case tvDolbyMode_Bright: + case tvHDR10Mode_Bright: + case tvHLGMode_Bright: + value = "Bright"; + break; + default: + break; + } + + return value; + } + + int AVOutputTV::getAvailableCapabilityModesWrapper(std::string param, std::string & outparam) + { + tvError_t err = tvERROR_NONE; + std::vector range; + std::vector picmodeVec; + std::vector sourceVec; + std::vector formatVec; + + err = getParamsCaps(range,picmodeVec,sourceVec,formatVec, param); + if (err != tvERROR_NONE) { + LOGERR("%s: failed to get [%s] capability \n", __FUNCTION__, param.c_str()); + return -1; + } + outparam = convertToString(range); + + return 0; + } + + int AVOutputTV::getAvailableCapabilityModes(std::string & source, std::string & pqmode, std::string & format) + { + if ((pqmode.compare("none") == 0 )) { + if (getAvailableCapabilityModesWrapper("PictureMode", pqmode) != 0) { + LOGERR("%s: failed to get picture mode capability \n", __FUNCTION__); + return -1; + } + } + + if( (source.compare("none") == 0)) { + if (getAvailableCapabilityModesWrapper("VideoSource",source) != 0) { + LOGERR("%s: failed to get source capability \n", __FUNCTION__); + return -1; + } + } + + if( (format.compare("none") == 0) ) { + if (getAvailableCapabilityModesWrapper("VideoFormat",format) != 0) { + LOGERR("%s: failed to get format capability \n", __FUNCTION__); + return -1; + } + } + return 0; + } + + int AVOutputTV::getCapabilitySource(JsonArray & rangeArray) + { + std::vector range,pqmode,source,format; + + tvError_t ret = getParamsCaps(range,pqmode,source,format,"VideoSource"); + + if(ret != tvERROR_NONE) { + return -1; + } + else { + if ((range.front()).compare("none") != 0) { + for (unsigned int index = 0; index < range.size(); index++) { + rangeArray.Add(range[index]); + } + } + } + return 0; + } + + int AVOutputTV::getRangeCapability(std::string param, std::vector & rangeInfo) + { + std::vector range,pqmode,source,format; + + tvError_t ret = getParamsCaps(range,pqmode,source,format, param); + + if(ret != tvERROR_NONE) { + return -1; + } + else { + if ((range.front()).compare("none") != 0) { + rangeInfo = range; + } + } + return 0; + } + + void AVOutputTV::getDynamicAutoLatencyConfig() + { + RFC_ParamData_t param = {0}; + WDMP_STATUS status = getRFCParameter(AVOUTPUT_RFC_CALLERID, AVOUTPUT_DALS_RFC_PARAM, ¶m); + LOGINFO("RFC value for DALS - %s", param.value); + if(WDMP_SUCCESS == status && param.type == WDMP_BOOLEAN && (strncasecmp(param.value,"true",4) == 0)) { + m_isDalsEnabled = true; + LOGINFO("Value of m_isDalsEnabled is %d", m_isDalsEnabled); + } + else { + LOGINFO("Failed to fetch RFC or DALS is disabled"); + } + } + + + tvError_t AVOutputTV::getUserSelectedAspectRatio (tvDisplayMode_t* mode) + { + tvError_t ret = tvERROR_GENERAL; +#if !defined (HDMIIN_4K_ZOOM) + LOGERR("%s:mode selected is: %d", __FUNCTION__, m_videoZoomMode); + if (AVOutputTV::instance->m_isDisabledHdmiIn4KZoom) { + if (!(AVOutputTV::instance->m_currentHdmiInResolutonm_currentHdmiInResoluton))) { + *mode = (tvDisplayMode_t)AVOutputTV::instance->m_videoZoomMode; + LOGWARN("%s: Getting zoom mode %d for display, for 4K and above", __FUNCTION__, *mode); + return tvERROR_NONE; + } + } +#endif + ret = GetAspectRatio(mode); + return ret; + } + + void AVOutputTV::broadcastLowLatencyModeChangeEvent(bool lowLatencyMode) + { + LOGINFO("Entry:%d\n",lowLatencyMode); + JsonObject response; + response["lowLatencyMode"] = lowLatencyMode; + sendNotify("gameModeEvent", response); + } + + tvError_t AVOutputTV::setAspectRatioZoomSettings(tvDisplayMode_t mode) + { + tvError_t ret = tvERROR_GENERAL; + LOGERR("%s: mode selected is: %d", __FUNCTION__, m_videoZoomMode); +#if !defined (HDMIIN_4K_ZOOM) + if (AVOutputTV::instance->m_isDisabledHdmiIn4KZoom) { + if (AVOutputTV::instance->m_currentHdmiInResolutonm_isDisabledHdmiIn4KZoom); + ret = SetAspectRatio((tvDisplayMode_t)m_videoZoomMode); + } +#endif + return ret; + } + + tvError_t AVOutputTV::setDefaultAspectRatio(std::string pqmode,std::string format,std::string source) + { + tvDisplayMode_t mode = tvDisplayMode_MAX; + TR181_ParamData_t param; + tvError_t ret = tvERROR_NONE; + + memset(¶m, 0, sizeof(param)); + tr181ErrorCode_t err = getLocalParam(rfc_caller_id, AVOUTPUT_ASPECTRATIO_RFC_PARAM, ¶m); + if ( tr181Success == err ) { + if(!std::string(param.value).compare("16:9")) { + mode = tvDisplayMode_16x9; + } + else if (!std::string(param.value).compare("4:3")) { + mode = tvDisplayMode_4x3; + } + else if (!std::string(param.value).compare("Full")) { + mode = tvDisplayMode_FULL; + } + else if (!std::string(param.value).compare("Normal")) { + mode = tvDisplayMode_NORMAL; + } + else if (!std::string(param.value).compare("TV AUTO")) { + mode = tvDisplayMode_AUTO; + } + else if (!std::string(param.value).compare("TV DIRECT")) { + mode = tvDisplayMode_DIRECT; + } + else if (!std::string(param.value).compare("TV NORMAL")) { + mode = tvDisplayMode_NORMAL; + } + else if (!std::string(param.value).compare("TV ZOOM")) { + mode = tvDisplayMode_ZOOM; + } + else if (!std::string(param.value).compare("TV 16X9 STRETCH")) { + mode = tvDisplayMode_16x9; + } + else if (!std::string(param.value).compare("TV 4X3 PILLARBOX")) { + mode = tvDisplayMode_4x3; + } + else { + mode = tvDisplayMode_AUTO; + } + + m_videoZoomMode = mode; + tvError_t ret = setAspectRatioZoomSettings (mode); + + if(ret != tvERROR_NONE) { + LOGERR("AspectRatio set failed: %s\n",getErrorString(ret).c_str()); + } + else { + //Save DisplayMode to ssm_data + int params[3]={0}; + params[0]=mode; + int retval=updateAVoutputTVParam("set","AspectRatio",pqmode,source,format,PQ_PARAM_ASPECT_RATIO,params); + + if(retval != 0) { + LOGERR("Failed to Save DisplayMode to ssm_data\n"); + ret = tvERROR_GENERAL; + } + LOGINFO("Aspect Ratio initialized successfully, value: %s\n", param.value); + } + + } + else { + LOGERR("getLocalParam for %s Failed : %s\n", AVOUTPUT_ASPECTRATIO_RFC_PARAM, getTR181ErrorString(err)); + ret = tvERROR_GENERAL; + } + return ret; + } + +} //namespace Plugin +} //namespace WPEFramework diff --git a/AVOutput/CMakeLists.txt b/AVOutput/CMakeLists.txt index 72a0c99207..b612af2597 100644 --- a/AVOutput/CMakeLists.txt +++ b/AVOutput/CMakeLists.txt @@ -46,7 +46,8 @@ include_directories(${STAGING_INCDIR}/rdk/ds) if (AVOUTPUT_TV) add_library(${MODULE_NAME} SHARED AVOutputBase.cpp - AVOutputTV.cpp + AVOutputTV.cpp + AVOutputTVHelper.cpp AVOutput.cpp Module.cpp) target_link_libraries(${MODULE_NAME} "-lglib-2.0 -lpthread -lIARMBus -ltvsettings-hal -ltr181api -lds") From 00a6207857901d35e6cf6dfba0f38f8574004a13 Mon Sep 17 00:00:00 2001 From: RAFI <103924677+cmuhammedrafi@users.noreply.github.com> Date: Thu, 13 Jun 2024 21:24:18 +0530 Subject: [PATCH 19/21] RDKTV-31166 posting internet event when interface connection changes (#5407) * RDKTV-31166 internetStatus Event posting updated * modefiy the same change in network manager --- Network/Network.cpp | 13 +++---------- Network/NetworkConnectivity.cpp | 1 + NetworkManager/NetworkManagerConnectivity.cpp | 1 + NetworkManager/NetworkManagerRDKProxy.cpp | 16 +++++++++++++--- 4 files changed, 18 insertions(+), 13 deletions(-) diff --git a/Network/Network.cpp b/Network/Network.cpp index a2a863f2e4..27a28c3300 100644 --- a/Network/Network.cpp +++ b/Network/Network.cpp @@ -1461,17 +1461,10 @@ typedef struct _IARM_BUS_NetSrvMgr_Iface_EventData_t { m_defInterfaceCache = ""; sendNotify("onConnectionStatusChanged", params); - if(connected) + connectivityMonitor.doInitialConnectivityMonitoring(30); + if(!connected) { - connectivityMonitor.doInitialConnectivityMonitoring(30); - } - else - { - if (!connectivityMonitor.isMonitorThreadRunning()) - { - /*run the thread again to notify no_internet state*/ - connectivityMonitor.doInitialConnectivityMonitoring(30); - } + /* if disconnectd need to stop the thread after one event */ connectivityMonitor.stopInitialConnectivityMonitoring(); } } diff --git a/Network/NetworkConnectivity.cpp b/Network/NetworkConnectivity.cpp index 58effcb677..9cff1a0aef 100644 --- a/Network/NetworkConnectivity.cpp +++ b/Network/NetworkConnectivity.cpp @@ -492,6 +492,7 @@ namespace WPEFramework { if (isMonitorThreadRunning() && stopFlag == false) { LOGINFO("Connectivity Monitor Thread is active so notify"); + g_internetState = nsm_internetState::UNKNOWN; cv_.notify_all(); } else diff --git a/NetworkManager/NetworkManagerConnectivity.cpp b/NetworkManager/NetworkManagerConnectivity.cpp index 12713f47cd..e7dc7a608d 100644 --- a/NetworkManager/NetworkManagerConnectivity.cpp +++ b/NetworkManager/NetworkManagerConnectivity.cpp @@ -425,6 +425,7 @@ namespace WPEFramework { if (isMonitorThreadRunning() && stopFlag == false) { NMLOG_INFO("Connectivity Monitor Thread is active so notify"); + g_internetState = nsm_internetState::UNKNOWN; cv_.notify_all(); } else diff --git a/NetworkManager/NetworkManagerRDKProxy.cpp b/NetworkManager/NetworkManagerRDKProxy.cpp index b98d99cc1e..861afcb4ec 100644 --- a/NetworkManager/NetworkManagerRDKProxy.cpp +++ b/NetworkManager/NetworkManagerRDKProxy.cpp @@ -425,8 +425,12 @@ namespace WPEFramework { if (e->status) ::_instance->ReportInterfaceStateChangedEvent(Exchange::INetworkManager::INTERFACE_LINK_UP, interface); - else - ::_instance->ReportInterfaceStateChangedEvent(Exchange::INetworkManager::INTERFACE_LINK_DOWN, interface); + else { + ::_instance->ReportInterfaceStateChangedEvent(Exchange::INetworkManager::INTERFACE_LINK_DOWN, interface); + /* when ever interface down we start connectivity monitor to post noInternet event */ + ::_instance->connectivityMonitor.doInitialConnectivityMonitoring(5); + ::_instance->connectivityMonitor.stopInitialConnectivityMonitoring(); + } } break; } @@ -436,8 +440,14 @@ namespace WPEFramework interface = e->interface; NMLOG_INFO ("IARM_BUS_NETWORK_MANAGER_EVENT_INTERFACE_IPADDRESS :: %s -- %s", interface.c_str(), e->ip_address); - if(interface == "eth0" || interface == "wlan0") + if(interface == "eth0" || interface == "wlan0") { ::_instance->ReportIPAddressChangedEvent(interface, e->acquired, e->is_ipv6, string(e->ip_address)); + if(e->acquired) + { + /* if ip address acquired we start connectivity monitor */ + ::_instance->connectivityMonitor.doInitialConnectivityMonitoring(5); + } + } break; } case IARM_BUS_NETWORK_MANAGER_EVENT_DEFAULT_INTERFACE: From af758c31a02f60eccfc6bea60f250727997ba25a Mon Sep 17 00:00:00 2001 From: Karunakaran A <48997923+karuna2git@users.noreply.github.com> Date: Thu, 13 Jun 2024 16:58:47 -0400 Subject: [PATCH 20/21] DELIA-65343 : Updated the trace results (#5410) Updated the trace results Signed-off-by: kamirt573_comcast --- NetworkManager/CMakeLists.txt | 2 +- NetworkManager/LegacyPlugin_NetworkAPIs.cpp | 10 ++--- .../NetworkManagerImplementation.cpp | 10 ++++- NetworkManager/NetworkManagerJsonRpc.cpp | 6 +-- docs/api/NetworkManagerPlugin.md | 40 +++++-------------- 5 files changed, 28 insertions(+), 40 deletions(-) diff --git a/NetworkManager/CMakeLists.txt b/NetworkManager/CMakeLists.txt index f8016c2dd0..d4573b9e2d 100644 --- a/NetworkManager/CMakeLists.txt +++ b/NetworkManager/CMakeLists.txt @@ -6,7 +6,7 @@ find_package(WPEFramework) list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/cmake") set(VERSION_MAJOR 0) set(VERSION_MINOR 2) -set(VERSION_PATCH 0) +set(VERSION_PATCH 3) add_compile_definitions(NETWORKMANAGER_MAJOR_VERSION=${VERSION_MAJOR}) add_compile_definitions(NETWORKMANAGER_MINOR_VERSION=${VERSION_MINOR}) diff --git a/NetworkManager/LegacyPlugin_NetworkAPIs.cpp b/NetworkManager/LegacyPlugin_NetworkAPIs.cpp index 71dd8f33e6..1611d11c28 100644 --- a/NetworkManager/LegacyPlugin_NetworkAPIs.cpp +++ b/NetworkManager/LegacyPlugin_NetworkAPIs.cpp @@ -579,7 +579,7 @@ const string CIDR_PREFIXES[CIDR_NETMASK_IP_LEN] = { tmpParameters["guid"] = parameters["guid"]; if (m_networkmanager) - rc = m_networkmanager->Invoke(5000, _T("Ping"), tmpParameters, response); + rc = m_networkmanager->Invoke(15000, _T("Ping"), tmpParameters, response); else rc = Core::ERROR_UNAVAILABLE; @@ -597,12 +597,12 @@ const string CIDR_PREFIXES[CIDR_NETMASK_IP_LEN] = { LOGINFOMETHOD(); uint32_t rc = Core::ERROR_GENERAL; JsonObject tmpParameters; - tmpParameters["endpoint"] = parameters["endpoint"].String(); - tmpParameters["noOfRequest"] = parameters["packets"].Number(); - tmpParameters["guid"] = ""; + tmpParameters["endpoint"] = parameters["endpoint"].String(); + tmpParameters["packets"] = parameters["packets"].Number(); + tmpParameters["guid"] = ""; if(m_networkmanager) - rc = m_networkmanager->Invoke(5000, _T("Trace"), tmpParameters, response); + rc = m_networkmanager->Invoke(20000, _T("Trace"), tmpParameters, response); else rc = Core::ERROR_UNAVAILABLE; diff --git a/NetworkManager/NetworkManagerImplementation.cpp b/NetworkManager/NetworkManagerImplementation.cpp index 56a7ce1b0f..e11cde15ac 100644 --- a/NetworkManager/NetworkManagerImplementation.cpp +++ b/NetworkManager/NetworkManagerImplementation.cpp @@ -300,6 +300,7 @@ namespace WPEFramework uint32_t NetworkManagerImplementation::Trace (const string ipversion /* @in */, const string endpoint /* @in */, const uint32_t noOfRequest /* @in */, const string guid /* @in */, string& response /* @out */) { char cmd[256] = ""; + string tempResult = ""; if(0 == strcasecmp("IPv6", ipversion.c_str())) { snprintf(cmd, 256, "traceroute6 -w 3 -m 6 -q %d %s 64 2>&1", noOfRequest, endpoint.c_str()); @@ -311,7 +312,12 @@ namespace WPEFramework NMLOG_INFO ("The Command is %s", cmd); string commandToExecute(cmd); - executeExternally(NETMGR_TRACE, commandToExecute, response); + executeExternally(NETMGR_TRACE, commandToExecute, tempResult); + + JsonObject temp; + temp["target"] = endpoint; + temp["results"] = tempResult; + temp.ToString(response); return Core::ERROR_NONE; } @@ -427,7 +433,7 @@ namespace WPEFramework while (!feof(pipe) && fgets(buffer, 1024, pipe) != NULL) { // remove newline from buffer - buffer[strcspn(buffer, "\n")] = '\0'; + buffer[strcspn(buffer, "\n")] = ' '; string line(buffer); list.Add(line); } diff --git a/NetworkManager/NetworkManagerJsonRpc.cpp b/NetworkManager/NetworkManagerJsonRpc.cpp index 9b7ebad3b9..8c2ab1142d 100644 --- a/NetworkManager/NetworkManagerJsonRpc.cpp +++ b/NetworkManager/NetworkManagerJsonRpc.cpp @@ -576,9 +576,9 @@ namespace WPEFramework response["ipversion"] = ipversion; response["success"] = true; - /* TODO :: Cache this public IP Address */ m_publicIPAddress = ipAddress; m_publicIPAddressType = ipversion; + PublishToThunderAboutInternet(); } LOGTRACEMETHODFIN(); return rc; @@ -661,8 +661,8 @@ namespace WPEFramework string result{}; const string ipversion = parameters["ipversion"].String(); const string endpoint = parameters["endpoint"].String(); - const uint32_t noOfRequest = parameters["noOfRequest"].Number(); - const string guid = parameters["guid"].String(); + const uint32_t noOfRequest = parameters["packets"].Number(); + const string guid = parameters["guid"].String(); if (_NetworkManager) rc = _NetworkManager->Trace(ipversion, endpoint, noOfRequest, guid, result); diff --git a/docs/api/NetworkManagerPlugin.md b/docs/api/NetworkManagerPlugin.md index e924017e39..a69fb5c4da 100644 --- a/docs/api/NetworkManagerPlugin.md +++ b/docs/api/NetworkManagerPlugin.md @@ -2,7 +2,7 @@ # NetworkManager Plugin -**Version: [0.2.0]()** +**Version: [0.2.3]()** A NetworkManager plugin for Thunder framework. @@ -1037,13 +1037,13 @@ No Events ### Parameters -| Name | Type | Description | -| :-------- | :-------- | :-------- | +| Name | Type | Description | +| :-------- | :-------- | :-------- | | params | object | | -| params.endpoint | string | The host name or IP address | -| params.ipversion | string | either IPv4 or IPv6 | -| params.noOfRequest | integer | The number of packets to send. Default is 15 | -| params.guid | string | The globally unique identifier | +| params.ipversion| string | *(optional)* The host name or IP address | +| params.endpoint | string | The host name or IP address | +| params.packets | integer | *(optional)* The number of packets to send. Default is 10 | +| params.guid | string | *(optional)* The globally unique identifier | ### Result @@ -1051,15 +1051,7 @@ No Events | :-------- | :-------- | :-------- | | result | object | | | result.target | string | The target IP address | -| result.packetsTransmitted | integer | The number of packets sent | -| result.packetsReceived | integer | The number of packets received | -| result.packetLoss | string | The number of packets lost | -| result.tripMin | string | The minimum amount of time to receive the packets | -| result.tripAvg | string | The average time to receive the packets | -| result.tripMax | string | The maximum amount of time to receive the packets | -| result.tripStdDev | string | The standard deviation for the trip | -| result.error | string | An error message | -| result.guid | string | The globally unique identifier | +| result.results | string | The results from `traceroute` | | result.success | boolean | Whether the request succeeded | ### Example @@ -1073,9 +1065,7 @@ No Events "method": "org.rdk.NetworkManager.Trace", "params": { "endpoint": "45.57.221.20", - "ipversion": "IPv4", - "noOfRequest": 10, - "guid": "..." + "packets": 10 } } ``` @@ -1088,16 +1078,8 @@ No Events "id": 42, "result": { "target": "45.57.221.20", - "packetsTransmitted": 10, - "packetsReceived": 10, - "packetLoss": "0.0", - "tripMin": "61.264", - "tripAvg": "130.397", - "tripMax": "230.832", - "tripStdDev": "80.919", - "error": "...", - "guid": "...", - "success": true + "success": true, + "results": "<<>>" } } ``` From 1ac1189b9fae9b62ee43dd49df429534d23c4ca1 Mon Sep 17 00:00:00 2001 From: DineshkumarJP <99791803+DineshkumarJP@users.noreply.github.com> Date: Fri, 14 Jun 2024 15:52:54 +0530 Subject: [PATCH 21/21] RDKVREFPLT-1727 - [BCM][Memcr][RDKVREL-279] OCIContainer support (#5362) * Memcr support for OCIContainer * Memcr support for OCIContainer * Memcr support for OCIContainer * Memcr support for OCIContainer * Memcr support for OCIContainer * Memcr support for OCIContainer --- OCIContainer/CMakeLists.txt | 4 ++ OCIContainer/OCIContainer.cpp | 129 ++++++++++++++++++++++++++++++++++ OCIContainer/OCIContainer.h | 8 +++ 3 files changed, 141 insertions(+) diff --git a/OCIContainer/CMakeLists.txt b/OCIContainer/CMakeLists.txt index 2aff9fc947..80a5700e0a 100644 --- a/OCIContainer/CMakeLists.txt +++ b/OCIContainer/CMakeLists.txt @@ -2,6 +2,7 @@ set(PLUGIN_NAME OCIContainer) set(MODULE_NAME ${NAMESPACE}${PLUGIN_NAME}) set(PLUGIN_OCICONTAINER_STARTUPORDER "" CACHE STRING "To configure startup order of OCIContainer plugin") +option(PLUGIN_HIBERNATESUPPORT "Include hibernate support in the build." OFF) find_package(PkgConfig) find_package(${NAMESPACE}Plugins REQUIRED) @@ -45,6 +46,9 @@ find_package_handle_standard_args( SYSTEMD_LIBRARIES SYSTEMD_INCLUDE_DIRS ) +if(PLUGIN_HIBERNATESUPPORT) + target_compile_definitions(${MODULE_NAME} PRIVATE HIBERNATE_SUPPORT_ENABLED=1) +endif() target_include_directories(${MODULE_NAME} PRIVATE diff --git a/OCIContainer/OCIContainer.cpp b/OCIContainer/OCIContainer.cpp index 830ed328f1..87c7456561 100644 --- a/OCIContainer/OCIContainer.cpp +++ b/OCIContainer/OCIContainer.cpp @@ -49,6 +49,10 @@ OCIContainer::OCIContainer() Register("pauseContainer", &OCIContainer::pauseContainer, this); Register("resumeContainer", &OCIContainer::resumeContainer, this); Register("executeCommand", &OCIContainer::executeCommand, this); + #ifdef HIBERNATE_SUPPORT_ENABLED + Register("hibernateContainer", &OCIContainer::hibernateContainer, this); + Register("wakeupContainer", &OCIContainer::wakeupContainer, this); + #endif } OCIContainer::~OCIContainer() @@ -97,6 +101,10 @@ void OCIContainer::Deinitialize(PluginHost::IShell *service) Unregister("pauseContainer"); Unregister("resumeContainer"); Unregister("executeCommand"); + #ifdef HIBERNATE_SUPPORT_ENABLED + Unregister("hibernateContainer"); + Unregister("wakeupContainer"); + #endif } string OCIContainer::Information() const @@ -187,6 +195,17 @@ uint32_t OCIContainer::getContainerState(const JsonObject ¶meters, JsonObjec case IDobbyProxyEvents::ContainerState::Stopped: containerState = "Stopped"; break; + #ifdef HIBERNATE_SUPPORT_ENABLED + case IDobbyProxyEvents::ContainerState::Hibernating: + containerState = "Hibernating"; + break; + case IDobbyProxyEvents::ContainerState::Hibernated: + containerState = "Hibernated"; + break; + case IDobbyProxyEvents::ContainerState::Awakening: + containerState = "Awakening"; + break; + #endif default: containerState = "Unknown"; break; @@ -529,6 +548,76 @@ uint32_t OCIContainer::resumeContainer(const JsonObject ¶meters, JsonObject returnResponse(true); } +#ifdef HIBERNATE_SUPPORT_ENABLED +/** + * @brief Hibernate a container + * + * @param[in] parameters Must include 'containerId' of container to resume. + * @param[out] response Success. + * + * @return A code indicating success. + */ +uint32_t OCIContainer::hibernateContainer(const JsonObject ¶meters, JsonObject &response) +{ + LOGINFO("Hibernate container"); + + // Need to have an ID to hibernate + returnIfStringParamNotFound(parameters, "containerId"); + std::string id = parameters["containerId"].String(); + std::string options; + + int cd = GetContainerDescriptorFromId(id); + if (cd < 0) + { + returnResponse(false); + } + + bool offloadSuccessfully = mDobbyProxy->hibernateContainer(cd,options); + + if (!offloadSuccessfully) + { + LOGERR("Failed to Hibernate container - internal Dobby error."); + returnResponse(false); + } + + returnResponse(true); + +} +/** + * @brief Wakeup a container + * + * @param[in] parameters Must include 'containerId' of container to resume. + * @param[out] response Success. + * + * @return A code indicating success. + */ +uint32_t OCIContainer::wakeupContainer(const JsonObject ¶meters, JsonObject &response) +{ + LOGINFO("Wakeup Container"); + + // Need to have an ID to wakeup + returnIfStringParamNotFound(parameters, "containerId"); + std::string id = parameters["containerId"].String(); + + int cd = GetContainerDescriptorFromId(id); + if (cd < 0) + { + returnResponse(false); + } + + bool wokeSuccessfully = mDobbyProxy->wakeupContainer(cd); + + if (!wokeSuccessfully) + { + LOGERR("Failed to Wake up container - internal Dobby error."); + returnResponse(false); + } + + returnResponse(true); + +} +#endif + /** * @brief Execute a command in a container. * @@ -568,6 +657,36 @@ uint32_t OCIContainer::executeCommand(const JsonObject ¶meters, JsonObject & returnResponse(true); } +#ifdef HIBERNATE_SUPPORT_ENABLED +/** + * @brief Send an event notifying that a container has hibernated. + * + * @param descriptor Container descriptor. + * @param name Container name. + */ +void OCIContainer::onContainerHibernated(int32_t descriptor, const std::string& name) +{ + JsonObject params; + params["descriptor"] = std::to_string(descriptor); + params["name"] = name; + sendNotify("onContainerHibernated", params); +} + +/** + * @brief Send an event notifying that a container has Awoken. + * + * @param descriptor Container descriptor. + * @param name Container name. + */ +void OCIContainer::onContainerAwoken(int32_t descriptor, const std::string& name) +{ + JsonObject params; + params["descriptor"] = std::to_string(descriptor); + params["name"] = name; + sendNotify("onContainerAwoken", params); +} +#endif + /** * @brief Send an event notifying that a container has started. @@ -666,6 +785,16 @@ const void OCIContainer::stateListener(int32_t descriptor, const std::string& na { __this->onContainerStopped(descriptor, name); } + #ifdef HIBERNATE_SUPPORT_ENABLED + else if (state == IDobbyProxyEvents::ContainerState::Hibernated) + { + __this->onContainerHibernated(descriptor, name); + } + else if (state == IDobbyProxyEvents::ContainerState::Awakening) + { + __this->onContainerAwoken(descriptor, name); + } + #endif else { LOGINFO("Received an unknown state event for container '%s'.", name.c_str()); diff --git a/OCIContainer/OCIContainer.h b/OCIContainer/OCIContainer.h index f0291eea8f..2748207944 100644 --- a/OCIContainer/OCIContainer.h +++ b/OCIContainer/OCIContainer.h @@ -45,12 +45,20 @@ class OCIContainer : public PluginHost::IPlugin, public PluginHost::JSONRPC uint32_t pauseContainer(const JsonObject ¶meters, JsonObject &response); uint32_t resumeContainer(const JsonObject ¶meters, JsonObject &response); uint32_t executeCommand(const JsonObject ¶meters, JsonObject &response); + #ifdef HIBERNATE_SUPPORT_ENABLED + uint32_t hibernateContainer(const JsonObject ¶meters, JsonObject &response); + uint32_t wakeupContainer(const JsonObject ¶meters, JsonObject &response); + #endif //End methods //Begin events void onContainerStarted(int32_t descriptor, const std::string& name); void onContainerStopped(int32_t descriptor, const std::string& name); void onVerityFailed(const std::string& name); + #ifdef HIBERNATE_SUPPORT_ENABLED + void onContainerHibernated(int32_t descriptor, const std::string& name); + void onContainerAwoken(int32_t descriptor, const std::string& name); + #endif //End events //Build QueryInterface implementation, specifying all possible interfaces to be returned.