APPLINK-6501: updated from policyImpl branch
authorPolina Vyshnevska <PVyshnevska@luxoft.com>
Tue, 1 Apr 2014 13:27:22 +0000 (16:27 +0300)
committerJustin Dickow <jjdickow@gmail.com>
Tue, 8 Jul 2014 22:35:26 +0000 (18:35 -0400)
Signed-off-by: Justin Dickow <jjdickow@gmail.com>
Conflicts:
src/components/application_manager/CMakeLists.txt
src/components/application_manager/include/application_manager/commands/mobile/register_app_interface_request.h
src/components/application_manager/include/application_manager/message_helper.h
src/components/application_manager/src/commands/mobile/register_app_interface_request.cc
src/components/application_manager/src/message_helper.cc
src/components/media_manager/CMakeLists.txt
src/components/policy

15 files changed:
src/components/application_manager/CMakeLists.txt
src/components/application_manager/include/application_manager/application_impl.h
src/components/application_manager/include/application_manager/commands/hmi/on_app_permission_consent_notification.h [new file with mode: 0644]
src/components/application_manager/include/application_manager/commands/mobile/register_app_interface_request.h
src/components/application_manager/include/application_manager/message_helper.h
src/components/application_manager/include/application_manager/policies/policy_handler.h
src/components/application_manager/include/application_manager/usage_statistics.h [new file with mode: 0644]
src/components/application_manager/src/application_impl.cc
src/components/application_manager/src/application_manager_impl.cc
src/components/application_manager/src/commands/hmi/on_app_permission_consent_notification.cc [new file with mode: 0644]
src/components/application_manager/src/commands/mobile/register_app_interface_request.cc
src/components/application_manager/src/message_helper.cc
src/components/application_manager/src/policies/policy_handler.cc
src/components/application_manager/src/usage_statistics.cc [new file with mode: 0644]
src/components/media_manager/CMakeLists.txt

index cee0ec1..bc26942 100644 (file)
@@ -1,3 +1,8 @@
+if (EXTENDED_POLICY_FLAG)
+  add_definitions(-DEXTENDED_POLICY)
+endif()
+
+
 include_directories (
   ./include/
   ../utils/include/
@@ -10,16 +15,20 @@ include_directories (
   ../config_profile/include/
   ../request_watchdog/include/
   ../transport_manager/include/
-  ../policies/include/
   ../resumption/include/
+  ../rpc_base/include/
   ../../thirdPartyLibs/jsoncpp/include/
   ../../thirdPartyLibs/encryption/include/
   ../../thirdPartyLibs/MessageBroker/include
   ${CMAKE_BINARY_DIR}/src/components/
+  ${CMAKE_SOURCE_DIR}/src/components/policy/src/policy/include/
+  ${CMAKE_SOURCE_DIR}/src/components/policy/src/policy/usage_statistics/include/
+  ${CMAKE_BINARY_DIR}/src/components/policy/src/policy/
 )
 
 set (SOURCES
 ./src/application_manager_impl.cc
+./src/usage_statistics.cc
 ./src/message.cc
 ./src/application_impl.cc
 ./src/mobile_command_factory.cc
@@ -33,9 +42,22 @@ set (SOURCES
 )
 
 set (POLICIES_MANAGER
-./src/policies_manager/policies_manager.cc
+./src/policies/policy_handler.cc
+./src/policies/policy_event_observer.cc
+./src/policies/policy_retry_sequence.cc
+./src/policies/pt_exchange_handler.cc
 )
 
+if (EXTENDED_POLICY_FLAG)
+  list(APPEND POLICIES_MANAGER
+    ./src/policies/pt_exchange_handler_ext.cc
+  )
+else ()
+  list(APPEND POLICIES_MANAGER
+    ./src/policies/pt_exchange_handler_impl.cc
+  )
+endif ()
+
 set (EVENT_ENGINE
 ./src/event_engine/event.cc
 ./src/event_engine/event_dispatcher.cc
@@ -150,14 +172,20 @@ set (MOBILE_COMMANDS_SOURCES
 set (HMI_COMMANDS_SOURCES
 ./src/commands/hmi/request_to_hmi.cc
 ./src/commands/hmi/response_from_hmi.cc
+./src/commands/hmi/request_from_hmi.cc
+./src/commands/hmi/response_to_hmi.cc
 ./src/commands/hmi/notification_to_hmi.cc
 ./src/commands/hmi/notification_from_hmi.cc
 ./src/commands/hmi/allow_all_apps_request.cc
 ./src/commands/hmi/allow_all_apps_response.cc
 ./src/commands/hmi/allow_app_request.cc
 ./src/commands/hmi/allow_app_response.cc
+./src/commands/hmi/update_sdl_request.cc
+./src/commands/hmi/update_sdl_response.cc
 ./src/commands/hmi/activate_app_request.cc
 ./src/commands/hmi/activate_app_response.cc
+./src/commands/hmi/sdl_activate_app_response.cc
+./src/commands/hmi/sdl_activate_app_request.cc
 ./src/commands/hmi/mixing_audio_supported_request.cc
 ./src/commands/hmi/mixing_audio_supported_response.cc
 ./src/commands/hmi/update_app_list_request.cc
@@ -165,6 +193,7 @@ set (HMI_COMMANDS_SOURCES
 ./src/commands/hmi/on_update_device_list.cc
 ./src/commands/hmi/update_device_list_request.cc
 ./src/commands/hmi/update_device_list_response.cc
+./src/commands/hmi/on_sdl_consent_needed_notification.cc
 ./src/commands/hmi/on_exit_all_applications_notification.cc
 ./src/commands/hmi/on_exit_application_notification.cc
 ./src/commands/hmi/on_start_device_discovery.cc
@@ -267,9 +296,13 @@ set (HMI_COMMANDS_SOURCES
 ./src/commands/hmi/on_system_context_notification.cc
 ./src/commands/hmi/on_device_chosen_notification.cc
 ./src/commands/hmi/on_update_device_list.cc
+./src/commands/hmi/on_allow_sdl_functionality_notification.cc
+./src/commands/hmi/on_app_permission_consent_notification.cc
 ./src/commands/hmi/on_app_registered_notification.cc
+./src/commands/hmi/on_app_permission_changed_notification.cc
 ./src/commands/hmi/on_app_unregistered_notification.cc
 ./src/commands/hmi/on_driver_distraction_notification.cc
+./src/commands/hmi/on_ignition_cycle_over_notification.cc
 ./src/commands/hmi/on_file_removed_notification.cc
 ./src/commands/hmi/on_play_tone_notification.cc
 ./src/commands/hmi/on_tts_started_notification.cc
@@ -347,5 +380,15 @@ if (${HMI_DBUS_API})
     set (HMI_COMMANDS_SOURCES ${HMI_COMMANDS_SOURCES} ${HMI_COMMANDS_SOURCES_DBUS})
 endif (${HMI_DBUS_API})
 
+SET (LIBRARIES
+  UsageStatistics
+  log4cxx
+  dl
+)
+
+IF(${CMAKE_SYSTEM_NAME} MATCHES "QNX")
+  list(REMOVE_ITEM LIBRARIES dl)
+endif()
+
 add_library("ApplicationManager" ${SOURCES} ${MOBILE_COMMANDS_SOURCES} ${HMI_COMMANDS_SOURCES} ${POLICIES_MANAGER} ${EVENT_ENGINE})
-target_link_libraries ("ApplicationManager" log4cxx)
+target_link_libraries ("ApplicationManager" ${LIBRARIES})
index ae7d1be..4be0875 100644 (file)
 #include <set>
 #include <vector>
 #include "application_manager/application_data_impl.h"
+#include "application_manager/usage_statistics.h"
 #include "connection_handler/device.h"
 
+namespace usage_statistics {
+class StatisticsManager;
+}  // namespace usage_statistics
+
 namespace application_manager {
 
 namespace mobile_api = mobile_apis;
@@ -46,7 +51,9 @@ namespace mobile_api = mobile_apis;
 class ApplicationImpl : public virtual InitialApplicationDataImpl,
     public virtual DynamicApplicationDataImpl {
  public:
-  explicit ApplicationImpl(uint32_t application_id);
+  ApplicationImpl(uint32_t application_id,
+                  const std::string& global_app_id,
+                  usage_statistics::StatisticsManager* statistics_manager);
   ~ApplicationImpl();
 
   /**
@@ -126,7 +133,7 @@ class ApplicationImpl : public virtual InitialApplicationDataImpl,
    */
   virtual uint32_t UpdateHash();
 
-
+  ApplicationUsageReport& usage_report();
  protected:
   void CleanupFiles();
 
@@ -158,6 +165,7 @@ class ApplicationImpl : public virtual InitialApplicationDataImpl,
   AppFilesMap app_files_;
   std::set<mobile_apis::ButtonName::eType> subscribed_buttons_;
   std::set<uint32_t> subscribed_vehicle_info_;
+  ApplicationUsageReport usage_report_;
   DISALLOW_COPY_AND_ASSIGN(ApplicationImpl);
 };
 
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_app_permission_consent_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_app_permission_consent_notification.h
new file mode 100644 (file)
index 0000000..bd3d74e
--- /dev/null
@@ -0,0 +1,72 @@
+/**
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_APP_PERMISSION_CONSENT_NOTIFICATION_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_APP_PERMISSION_CONSENT_NOTIFICATION_H_
+
+#include "application_manager/commands/hmi/notification_from_hmi.h"
+
+namespace application_manager {
+
+namespace commands {
+
+/**
+ * @brief OnAppPermissionConsent command class
+ **/
+class OnAppPermissionConsent : public NotificationFromHMI {
+  public:
+    /**
+     * @brief OnAppPermissionConsent class constructor
+     *
+     * @param message Incoming SmartObject message
+     **/
+    explicit OnAppPermissionConsent(const MessageSharedPtr& message);
+
+    /**
+     * @brief OnAppPermissionConsent class destructor
+     **/
+    virtual ~OnAppPermissionConsent();
+
+    /**
+     * @brief Execute command
+     **/
+    virtual void Run();
+
+  private:
+    DISALLOW_COPY_AND_ASSIGN(OnAppPermissionConsent);
+};
+
+}  // namespace commands
+
+}  // namespace application_manager
+
+#endif  //  SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_APP_PERMISSION_CONSENT_NOTIFICATION_H_
index 384a437..3bd41c3 100644 (file)
 #include "application_manager/commands/command_request_impl.h"
 #include "utils/macro.h"
 
+namespace policy {
+struct DeviceInfo;
+}
+
 namespace application_manager {
 
 class Application;
@@ -156,6 +160,19 @@ class RegisterAppInterfaceRequest : public CommandRequestImpl {
       const std::string &newItem_;
     };
 
+  /**
+   * @brief Check request parameters against policy table data
+   * @return SUCCESS if check ok, otherwise return appropriate error code
+   */
+  mobile_apis::Result::eType CheckWithPolicyData();
+
+  /**
+   * @brief Fill DeviceInfo struct with data from request, if any
+   * @param device_info Struct for device params from request
+   */
+  void FillDeviceInfo(policy::DeviceInfo* device_info);
+
+  std::string response_info_;
 
   DISALLOW_COPY_AND_ASSIGN(RegisterAppInterfaceRequest);
 };
index 24a2121..da1f995 100644 (file)
@@ -39,6 +39,8 @@
 #include "utils/macro.h"
 #include "connection_handler/device.h"
 #include "application_manager/application.h"
+#include "application_manager/vehicle_info_data.h"
+#include "policy/policy_types.h"
 
 namespace NsSmartDeviceLink {
 namespace NsSmartObjects {
@@ -78,39 +80,6 @@ typedef enum {
 } TextFieldName;
 
 /*
- * @brief Typedef for the vehicle data types that can
- * be published and subscribed to
- */
-typedef enum {
-  GPS = 0,
-  SPEED,
-  RPM,
-  FUELLEVEL,
-  FUELLEVEL_STATE,
-  FUELCONSUMPTION,
-  EXTERNTEMP,
-  VIN,
-  PRNDL,
-  TIREPRESSURE,
-  ODOMETER,
-  BELTSTATUS,
-  BODYINFO,
-  DEVICESTATUS,
-  ECALLINFO,
-  AIRBAGSTATUS,
-  EMERGENCYEVENT,
-  CLUSTERMODESTATUS,
-  MYKEY,
-  BRAKING,
-  WIPERSTATUS,
-  HEADLAMPSTATUS,
-  BATTVOLTAGE,
-  ENGINETORQUE,
-  ACCPEDAL,
-  STEERINGWHEEL
-} VehicleDataType;
-
-/*
  * @brief Typedef for VehicleData
  *
  * @param const char* Name of the parameter in mobile request
@@ -178,6 +147,23 @@ class MessageHelper {
      */
     static const VehicleData& vehicle_data();
 
+    /*
+    * @brief Used to obtain string representation of app's
+    * HMI Level.
+    * @param hmi_level Desired HMI Level
+    */
+    static const char* StringifiedHMILevel(
+      mobile_apis::HMILevel::eType hmi_level);
+
+    /*
+    * @brief Used to obtain function name by its id
+    * @param function_id Function ID
+    */
+    static const char* StringifiedFunctionID(
+      mobile_apis::FunctionID::eType function_id);
+
+    static void CreateGetDeviceData(int32_t correlation_id);
+
     static smart_objects::SmartObject* CreateBlockedByPoliciesResponse(
       mobile_apis::FunctionID::eType function_id,
       mobile_apis::Result::eType result, uint32_t correlation_id,
@@ -241,7 +227,23 @@ class MessageHelper {
     static void ResetGlobalproperties(ApplicationSharedPtr app);
 
     static void SendActivateAppToHMI(uint32_t const app_id);
+    static void GetDeviceInfoForHandle(const uint32_t device_handle,
+                                       policy::DeviceParams* device_info);
+    static void GetDeviceInfoForApp(const std::string& connection_key,
+                                    policy::DeviceParams* device_info);
 
+    /**
+    * @brief Send SDL_ActivateApp response to HMI
+    * @param permissions response parameters
+    */
+    static void SendActivateAppResponse(policy::AppPermissions& permissions,
+                                        uint32_t correlation_id);
+
+    /**
+    * @brief Send OnSDLConsentNeeded to HMI for device data consent by user
+    * @param device_info Device info, e.g. mac, handle, name
+    */
+    static void SendOnSDLConsentNeeded(const policy::DeviceParams& device_info);
 
     /*
      * @brief Sends notification to HMI to start video streaming
@@ -261,6 +263,34 @@ class MessageHelper {
     static void SendNaviStopStream(int32_t connection_key);
 
     /*
+    * @brief Send notification for Update of Policy Table
+    * with PT Snapshot.
+    * @param connection_key Id of application to send message to
+    * @param policy_data PT Snapshot
+    * @param url If empty string, no URL is provided
+    * @param timeout If -1 no timeout is provdied
+    */
+    static void SendPolicySnapshotNotification(
+      unsigned int connection_key, const std::vector<uint8_t>& policy_data,
+      const std::string& url = "", int timeout = -1);
+
+    /*
+    * @brief Send notification to mobile on application permissions update
+    * @param connection_key Id of application to send message to
+    * @param permissions updated permissions for application
+    */
+    static void SendOnPermissionsChangeNotification(
+      uint32_t connection_key, const policy::Permissions& permissions);
+
+    /*
+    * @brief Send notification to HMI on application permissions update
+    * @param connection_key Id of application to send message to
+    * @param permissions updated permissions for application
+    */
+    static void SendOnAppPermissionsChangedNotification(
+      uint32_t connection_key, const policy::AppPermissions& permissions);
+
+    /*
      * @brief Sends notification to HMI to start audio streaming
      *
      * @param url             URL for video streamng
@@ -301,7 +331,7 @@ class MessageHelper {
      *
      */
     static mobile_apis::Result::eType VerifyImage(smart_objects::SmartObject& image,
-                            ApplicationConstSharedPtr app);
+        ApplicationConstSharedPtr app);
 
     /*
      * @brief Finds "Image" structure in request and verify image file presence
@@ -320,8 +350,8 @@ class MessageHelper {
     static bool VerifySoftButtonText(smart_objects::SmartObject& soft_button);
 
     static mobile_apis::Result::eType ProcessSoftButtons(
-                                  smart_objects::SmartObject& message_params,
-                                  ApplicationConstSharedPtr app);
+      smart_objects::SmartObject& message_params,
+      ApplicationConstSharedPtr app);
 
     static bool PrintSmartObject(const smart_objects::SmartObject& object);
 
index e80e811..000ffb1 100644 (file)
@@ -55,145 +55,152 @@ typedef std::vector<uint32_t> AppIds;
 typedef std::vector<uint32_t> DeviceHandles;
 
 class PolicyHandler : public utils::Singleton<PolicyHandler>,
-  public PolicyListener {
-  public:
-    virtual ~PolicyHandler();
-    PolicyManager* LoadPolicyLibrary();
-    PolicyManager* LoadPolicyLibrary(const std::string& path);
-    PolicyManager* policy_manager() const {
-      return policy_manager_;
-    }
-    bool InitPolicyTable();
-    bool RevertPolicyTable();
-    bool SendMessageToSDK(const BinaryMessage& pt_string);
-    bool ReceiveMessageFromSDK(const BinaryMessage& pt_string);
-    bool UnloadPolicyLibrary();
-    void OnPTExchangeNeeded();
-    void OnPermissionsUpdated(const std::string& policy_app_id,
-                              const Permissions& permissions);
-    /**
-     * @brief Checks, if policy update is necessary for application
-     */
-    void CheckAppPolicyState(const std::string& application_id);
-
-    /**
-     * Starts proccess updating policy table
-     */
-    void StartPTExchange(bool skip_device_selection = false);
-
-    /**
-     * Lets client to notify PolicyHandler that more kilometers expired
-     * @param kms New value of odometer
-     */
-    void KmsChanged(int kms);
-
-    /**
-     * @brief Gather information for application and sends it to HMI
-     * @param connection_key Connection key for application
-     */
-    void OnActivateApp(const std::string& connection_key,
-                       uint32_t correlation_id);
-
-    /**
-     * @brief Process user consent on mobile data connection access
-     * @param Device id or 0, if concern to all SDL functionality
-     * @param User consent from response
-     */
-    void OnAllowSDLFunctionalityNotification(bool is_allowed, uint32_t device_id =
-          0);
-    /**
-     * @brief Send request to HMI for requesting the allowance for some
-     * application functionality
-     * @param List of permissions required by application
-     * @param Unique appication id, if omitted - allow/disallow all applications
-     */
-    void SendAllowApp(const PermissionsList& list_of_permissions,
-                      uint32_t application_id = 0);
-
-    /**
-     * @brief Process application permission, which was set by user
-     * @param List of user-defined permissions for application
-     */
-    void OnAllowAppResponse(PermissionsList& list_of_permissions);
-
-    /**
-     * @brief Process application permission, which was set by user
-     * @param List of user-defined permissions for application
-     * @param Unique application id, if omitted - allow/disallow all
-     * applications
-     */
-    void OnAllowAppNotification(PermissionsList& list_of_permissions,
-                                uint32_t appication_id = 0);
-
-    /**
-     * @brief Increment counter for ignition cycles
-     */
-    void OnIgnitionCycleOver();
-
-    /**
-     * @brief Send notification to HMI concerning revocation of application
-     * @param policy_app_id Unique identifier of application
-     */
-    void OnAppRevoked(const std::string& policy_app_id);
-
-    /**
-     * Initializes PT exchange at ignition if need
-     */
-    void PTExchangeAtIgnition();
-
-  protected:
-    /**
-     * Starts next retry exchange policy table
-     */
-    void StartNextRetry();
-
-    /**
-     * Initializes PT exchange at odometer if need
-     * @param kilometers value from odometer in kilometers
-     */
-    void PTExchangeAtOdometer(int kilometers);
-
-  private:
-    /**
-     * @brief Choose application id to be used for snapshot sending
-     * @return Application id or 0, if there are no applications registered
-     */
-    uint32_t GetAppIdForSending();
-
-    /**
-     * @brief Choose device according to app HMI status and user consent for
-     * device
-     * @param device_info Struct with selected device parameters
-     * @return consent status for selected device
-     */
-    DeviceConsent GetDeviceForSending(DeviceInfo& device_info);
-
-  private:
-    PolicyHandler();
-    static PolicyHandler* instance_;
-    static const std::string kLibrary;
-    PolicyManager* policy_manager_;
-    void* dl_handle_;
-    AppIds last_used_app_ids_;
-    static log4cxx::LoggerPtr logger_;
-    threads::Thread retry_sequence_;
-    sync_primitives::Lock retry_sequence_lock_;
-    PTExchangeHandler* exchange_handler_;
-    utils::SharedPtr<PolicyEventObserver> event_observer_;
-
-    /**
-     * @brief Contains device handles, which were sent for user consent to HMI
-     */
-    DeviceHandles pending_device_handles_;
-
-    /**
-     * @brief True, if PTS was sent, but PTU was not reseived yet,
-     * otherwise - false
-     * Used for limiting device consent request per PTS/PTU session
-     */
-    bool is_exchange_in_progress_;
-
-    inline PolicyManager* CreateManager();
+    public PolicyListener {
+ public:
+  virtual ~PolicyHandler();
+  PolicyManager* LoadPolicyLibrary();
+  PolicyManager* LoadPolicyLibrary(const std::string& path);
+  PolicyManager* policy_manager() const {
+    return policy_manager_;
+  }
+  bool InitPolicyTable();
+  bool RevertPolicyTable();
+  bool SendMessageToSDK(const BinaryMessage& pt_string);
+  bool ReceiveMessageFromSDK(const BinaryMessage& pt_string);
+  bool UnloadPolicyLibrary();
+  void OnPTExchangeNeeded();
+  void OnPermissionsUpdated(const std::string& policy_app_id,
+                            const Permissions& permissions);
+  /**
+   * @brief Checks, if policy update is necessary for application
+   */
+  void CheckAppPolicyState(const std::string& application_id);
+
+  /**
+   * Starts proccess updating policy table
+   */
+  void StartPTExchange(bool skip_device_selection = false);
+
+  /**
+   * Lets client to notify PolicyHandler that more kilometers expired
+   * @param kms New value of odometer
+   */
+  void KmsChanged(int kms);
+
+  /**
+   * @brief Gather information for application and sends it to HMI
+   * @param connection_key Connection key for application
+   */
+  void OnActivateApp(const std::string& connection_key,
+                     uint32_t correlation_id);
+
+  /**
+   * @brief Process user consent on mobile data connection access
+   * @param Device id or 0, if concern to all SDL functionality
+   * @param User consent from response
+   */
+  void OnAllowSDLFunctionalityNotification(bool is_allowed, uint32_t device_id =
+                                               0);
+  /**
+   * @brief Send request to HMI for requesting the allowance for some
+   * application functionality
+   * @param List of permissions required by application
+   * @param Unique appication id, if omitted - allow/disallow all applications
+   */
+  void SendAllowApp(const PermissionsList& list_of_permissions,
+                    uint32_t application_id = 0);
+
+  /**
+   * @brief Process application permission, which was set by user
+   * @param List of user-defined permissions for application
+   */
+  void OnAllowAppResponse(PermissionsList& list_of_permissions);
+
+  /**
+   * @brief Process application permission, which was set by user
+   * @param List of user-defined permissions for application
+   * @param Unique application id, if omitted - allow/disallow all
+   * applications
+   */
+  void OnAllowAppNotification(PermissionsList& list_of_permissions,
+                              uint32_t appication_id = 0);
+
+  /**
+   * @brief Increment counter for ignition cycles
+   */
+  void OnIgnitionCycleOver();
+
+  /**
+   * @brief Send notification to HMI concerning revocation of application
+   * @param policy_app_id Unique identifier of application
+   */
+  void OnAppRevoked(const std::string& policy_app_id);
+
+  /**
+   * Initializes PT exchange at ignition if need
+   */
+  void PTExchangeAtIgnition();
+
+  /**
+   * @brief Save device info for specific device to policy table
+   * @param device_id Device mac address
+   * @param device_info Device params
+   */
+  void SetDeviceInfo(std::string& device_id, const DeviceInfo& device_info);
+
+ protected:
+  /**
+   * Starts next retry exchange policy table
+   */
+  void StartNextRetry();
+
+  /**
+   * Initializes PT exchange at odometer if need
+   * @param kilometers value from odometer in kilometers
+   */
+  void PTExchangeAtOdometer(int kilometers);  
+
+ private:
+  /**
+   * @brief Choose application id to be used for snapshot sending
+   * @return Application id or 0, if there are no applications registered
+   */
+  uint32_t GetAppIdForSending();
+
+  /**
+   * @brief Choose device according to app HMI status and user consent for
+   * device
+   * @param device_info Struct with selected device parameters
+   * @return consent status for selected device
+   */
+   DeviceConsent GetDeviceForSending(DeviceParams& device_params);
+
+ private:
+  PolicyHandler();
+  static PolicyHandler* instance_;
+  static const std::string kLibrary;
+  PolicyManager* policy_manager_;
+  void* dl_handle_;
+  AppIds last_used_app_ids_;
+  static log4cxx::LoggerPtr logger_;
+  threads::Thread retry_sequence_;
+  sync_primitives::Lock retry_sequence_lock_;
+  PTExchangeHandler* exchange_handler_;
+  utils::SharedPtr<PolicyEventObserver> event_observer_;
+
+  /**
+   * @brief Contains device handles, which were sent for user consent to HMI
+   */
+  DeviceHandles pending_device_handles_;
+
+  /**
+   * @brief True, if PTS was sent, but PTU was not reseived yet,
+   * otherwise - false
+   * Used for limiting device consent request per PTS/PTU session
+   */
+  bool is_exchange_in_progress_;
+
+  inline PolicyManager* CreateManager();
 
     DISALLOW_COPY_AND_ASSIGN(PolicyHandler); FRIEND_BASE_SINGLETON_CLASS(PolicyHandler);
     friend class RetrySequence;
diff --git a/src/components/application_manager/include/application_manager/usage_statistics.h b/src/components/application_manager/include/application_manager/usage_statistics.h
new file mode 100644 (file)
index 0000000..66cdb1a
--- /dev/null
@@ -0,0 +1,59 @@
+/**
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "usage_statistics/counter.h"
+#include "smart_objects/smart_object.h"
+
+#include "interfaces/MOBILE_API.h"
+
+namespace application_manager {
+
+class ApplicationUsageReport {
+ public:
+  ApplicationUsageReport(const std::string& app_id,
+                         usage_statistics::StatisticsManager* statistics_manager);
+  void RecordHmiStateChanged(mobile_apis::HMILevel::eType new_hmi_level);
+  void RecordAppRegistrationGuiLanguage(
+      mobile_apis::Language::eType gui_language);
+  void RecordAppRegistrationVuiLanguage(
+      mobile_apis::Language::eType vui_language);
+  void RecordRpcSentInHMINone();
+  void RecordPolicyRejectedRpcCall();
+ private:
+  usage_statistics::AppStopwatch time_in_hmi_state_;
+  usage_statistics::AppInfo      app_registration_language_gui_;
+  usage_statistics::AppInfo      app_registration_language_vui_;
+  usage_statistics::AppCounter   count_of_rejected_rpc_calls_;
+  usage_statistics::AppCounter   count_of_rpcs_sent_in_hmi_none_;
+};
+
+}  // namespace application_manager
index 57d3f35..ab487fb 100644 (file)
@@ -44,7 +44,10 @@ log4cxx::LoggerPtr g_logger = log4cxx::Logger::getLogger("ApplicationManager");
 
 namespace application_manager {
 
-ApplicationImpl::ApplicationImpl(uint32_t application_id)
+ApplicationImpl::ApplicationImpl(
+    uint32_t application_id,
+    const std::string& global_app_id,
+    usage_statistics::StatisticsManager* statistics_manager)
     : app_id_(application_id),
       active_message_(NULL),
       is_media_(false),
@@ -59,8 +62,8 @@ ApplicationImpl::ApplicationImpl(uint32_t application_id)
       is_app_allowed_(true),
       has_been_activated_(false),
       tts_speak_state_(false),
-      device_(0) {
-  srand(time(NULL));
+      device_(0),
+      usage_report_(global_app_id, statistics_manager) {
 }
 
 ApplicationImpl::~ApplicationImpl() {
@@ -194,6 +197,7 @@ void ApplicationImpl::set_hmi_level(
   }
 
   hmi_level_ = hmi_level;
+  usage_report_.RecordHmiStateChanged(hmi_level);
 }
 
 void ApplicationImpl::set_hmi_supports_navi_streaming(const bool& supports) {
@@ -323,6 +327,10 @@ bool ApplicationImpl::UnsubscribeFromIVI(uint32_t vehicle_info_type_) {
   return (subscribed_vehicle_info_.size() == old_size - 1);
 }
 
+ApplicationUsageReport& ApplicationImpl::usage_report() {
+  return usage_report_;
+}
+
 const std::set<mobile_apis::ButtonName::eType>& ApplicationImpl::SubscribedButtons() const {
   return subscribed_buttons_;
 }
index 279dbb4..85251ee 100644 (file)
@@ -247,7 +247,11 @@ ApplicationSharedPtr ApplicationManagerImpl::RegisterApplication(
     }
   }
 
-  ApplicationSharedPtr application(new ApplicationImpl(app_id));
+  smart_objects::SmartObject& params = message[strings::msg_params];
+
+  ApplicationSharedPtr application(new ApplicationImpl(app_id,
+                                                 params[strings::app_id].asString(),
+                                                 NULL));
   if (!application) {
     utils::SharedPtr<smart_objects::SmartObject> response(
       MessageHelper::CreateNegativeResponse(
diff --git a/src/components/application_manager/src/commands/hmi/on_app_permission_consent_notification.cc b/src/components/application_manager/src/commands/hmi/on_app_permission_consent_notification.cc
new file mode 100644 (file)
index 0000000..2cc09f4
--- /dev/null
@@ -0,0 +1,54 @@
+
+/**
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "application_manager/commands/hmi/on_app_permission_consent_notification.h"
+#include "application_manager/policies/policy_handler.h"
+
+namespace application_manager {
+
+namespace commands {
+
+OnAppPermissionConsent::OnAppPermissionConsent(const MessageSharedPtr& message)
+    : NotificationFromHMI(message) {
+}
+
+OnAppPermissionConsent::~OnAppPermissionConsent() {
+}
+
+void OnAppPermissionConsent::Run() {
+  LOG4CXX_INFO(logger_, "OnAppPermissionConsent::Run");
+}
+
+}  // namespace commands
+
+}  // namespace application_manager
index 1eff740..bc96780 100644 (file)
 #include "application_manager/application_manager_impl.h"
 #include "application_manager/application_impl.h"
 #include "application_manager/message_helper.h"
+#include "application_manager/policies/policy_handler.h"
 #include "config_profile/profile.h"
 #include "interfaces/MOBILE_API.h"
 
+namespace {
+
+mobile_apis::AppHMIType::eType StringToAppHMIType(const std::string& str) {
+  if ("DEFAULT" == str) {
+    return mobile_apis::AppHMIType::DEFAULT;
+  } else if ("COMMUNICATION" == str) {
+    return mobile_apis::AppHMIType::COMMUNICATION;
+  } else if ("MEDIA" == str) {
+    return mobile_apis::AppHMIType::MEDIA;
+  } else if ("MESSAGING" == str) {
+    return mobile_apis::AppHMIType::MESSAGING;
+  } else if ("NAVIGATION" == str) {
+    return mobile_apis::AppHMIType::NAVIGATION;
+  } else if ("INFORMATION" == str) {
+    return mobile_apis::AppHMIType::INFORMATION;
+  } else if ("SOCIAL" == str) {
+    return mobile_apis::AppHMIType::SOCIAL;
+  } else if ("BACKGROUND_PROCESS" == str) {
+    return mobile_apis::AppHMIType::BACKGROUND_PROCESS;
+  } else if ("TESTING" == str) {
+    return mobile_apis::AppHMIType::TESTING;
+  } else if ("SYSTEM" == str) {
+    return mobile_apis::AppHMIType::SYSTEM;
+  } else {
+    return mobile_apis::AppHMIType::INVALID_ENUM;
+  }
+}
+
+struct AppHMITypeInserter {
+  AppHMITypeInserter(smart_objects::SmartObject& so_array)
+      : so_array_(so_array),
+        index_(0) {
+  }
+
+  bool operator()(const std::string& app_hmi_type) {
+    so_array_[index_] = StringToAppHMIType(app_hmi_type);
+    ++index_;
+    return true;
+  }
+
+ private:
+  uint32_t index_;
+  smart_objects::SmartObject& so_array_;
+};
+
+struct CheckMissedTypes {
+  CheckMissedTypes(const policy::StringArray& policy_app_types,
+                   std::string& log)
+      : policy_app_types_(policy_app_types),
+        log_(log) {
+  }
+
+  bool operator()(const smart_objects::SmartArray::value_type& value) {
+    std::string app_type_str = value.asString();
+    policy::StringArray::const_iterator it = policy_app_types_.begin();
+    policy::StringArray::const_iterator it_end = policy_app_types_.end();
+    for (; it != it_end; ++it) {
+      if (app_type_str == *it) {
+        return true;
+      }
+    }
+
+    log_ += app_type_str;
+    log_ += ",";
+
+    return true;
+  }
+
+ private:
+  const policy::StringArray& policy_app_types_;
+  std::string& log_;
+};
+}
+
 namespace application_manager {
 
 namespace commands {
@@ -100,8 +175,15 @@ void RegisterAppInterfaceRequest::Run() {
     return;
   }
 
-  ApplicationSharedPtr app =
-      ApplicationManagerImpl::instance()->RegisterApplication(message_);
+  mobile_apis::Result::eType policy_result = CheckWithPolicyData();
+  if (mobile_apis::Result::SUCCESS != policy_result
+      && mobile_apis::Result::WARNINGS != policy_result) {
+    SendResponse(false, policy_result);
+    return;
+  }
+
+  ApplicationSharedPtr app = ApplicationManagerImpl::instance()->RegisterApplication(
+      message_);
 
   const smart_objects::SmartObject& msg_params =
       (*message_)[strings::msg_params];
@@ -481,8 +563,104 @@ RegisterAppInterfaceRequest::CheckCoincidence() {
   return mobile_apis::Result::SUCCESS;
 }  // method end
 
-mobile_apis::Result::eType
-RegisterAppInterfaceRequest::CheckRestrictions() const {
+mobile_apis::Result::eType RegisterAppInterfaceRequest::CheckWithPolicyData() {
+  LOG4CXX_INFO(logger_, "CheckWithPolicyData");
+  smart_objects::SmartObject& message = *message_;
+  policy::StringArray app_nicknames;
+  policy::StringArray app_hmi_types;
+
+  bool init_result = policy::PolicyHandler::instance()->policy_manager()
+      ->GetInitialAppData(
+      message[strings::msg_params][strings::app_id].asString(), &app_nicknames,
+      &app_hmi_types);
+
+  if (!init_result) {
+    LOG4CXX_INFO(logger_, "Error during initial application data check.");
+    return mobile_apis::Result::INVALID_DATA;
+  }
+
+  if (!app_nicknames.empty()) {
+    policy::StringArray::const_iterator it = std::find(
+        app_nicknames.begin(), app_nicknames.end(),
+        message[strings::msg_params][strings::app_name].asString());
+    if (app_nicknames.end() == it) {
+      LOG4CXX_INFO(logger_,
+                   "Application name was not found in nicknames list.");
+      //App should be unregistered, if its name is not present in nicknames list
+      return mobile_apis::Result::INVALID_DATA;
+    }
+  }
+
+  mobile_apis::Result::eType result = mobile_apis::Result::SUCCESS;
+
+  // If AppHMIType is not included in policy - allow any type
+  if (!app_hmi_types.empty()) {
+    if (message[strings::msg_params].keyExists(strings::app_hmi_type)) {
+      // If AppHMITypes are partially same, the system should allow those listed
+      // in the policy table and send warning info on missed values
+      smart_objects::SmartArray app_types =
+          *(message[strings::msg_params][strings::app_hmi_type].asArray());
+
+      std::string log;
+      CheckMissedTypes checker(app_hmi_types, log);
+      std::for_each(app_types.begin(), app_types.end(), checker);
+      if (!log.empty()) {
+        response_info_ = "Following AppHMITypes are not present in policy "
+            "table:" + log;
+        result = mobile_apis::Result::WARNINGS;
+      }
+    }
+    // Replace AppHMITypes in request with values allowed by policy table
+    message[strings::msg_params][strings::app_hmi_type] =
+        smart_objects::SmartObject(smart_objects::SmartType_Array);
+
+    smart_objects::SmartObject& app_hmi_type =
+        message[strings::msg_params][strings::app_hmi_type];
+
+    AppHMITypeInserter inserter(app_hmi_type);
+    std::for_each(app_hmi_types.begin(), app_hmi_types.end(), inserter);
+  }
+
+  return result;
+}
+
+void RegisterAppInterfaceRequest::FillDeviceInfo(
+    policy::DeviceInfo* device_info) {
+  const std::string hardware = "hardware";
+  const std::string firmware_rev = "firmwareRev";
+  const std::string os = "os";
+  const std::string os_ver = "osVersion";
+  const std::string carrier = "carrier";
+  const std::string max_number_rfcom_ports = "maxNumberRFCOMMPorts";
+
+  const smart_objects::SmartObject& msg_params =
+      (*message_)[strings::msg_params];
+
+  const smart_objects::SmartObject& device_info_so =
+      msg_params[strings::device_info];
+
+  if (device_info_so.keyExists(hardware)) {
+    device_info->hardware = msg_params[strings::device_info][hardware].asString();
+  }
+  if (device_info_so.keyExists(firmware_rev)) {
+    device_info->firmware_rev = msg_params[strings::device_info][firmware_rev].asString();
+  }
+  if (device_info_so.keyExists(os)) {
+    device_info->os = device_info_so[os].asString();
+  }
+  if (device_info_so.keyExists(os_ver)) {
+    device_info->os_ver = device_info_so[os_ver].asString();
+  }
+  if (device_info_so.keyExists(carrier)) {
+    device_info->carrier = device_info_so[carrier].asString();
+  }
+  if (device_info_so.keyExists(max_number_rfcom_ports)) {
+    device_info->max_number_rfcom_ports =
+        device_info_so[max_number_rfcom_ports].asInt();
+  }
+}
+
+mobile_apis::Result::eType RegisterAppInterfaceRequest::CheckRestrictions() const {
 
   LOG4CXX_INFO(logger_, "RegisterAppInterfaceRequest::CheckRestrictions");
 
index 6b76ac7..7fec88b 100644 (file)
@@ -37,6 +37,7 @@
 #include "utils/macro.h"
 #include "application_manager/application_manager_impl.h"
 #include "application_manager/message_helper.h"
+//#include "application_manager/policies/policy_handler.h"
 #include "application_manager/commands/command_impl.h"
 #include "connection_handler/connection_handler_impl.h"
 #include "application_manager/application.h"
 namespace {
 
 log4cxx::LoggerPtr g_logger =
-    log4cxx::LoggerPtr(log4cxx::Logger::getLogger("ApplicationManager"));
+  log4cxx::LoggerPtr(log4cxx::Logger::getLogger("ApplicationManager"));
 
 hmi_apis::Common_Language::eType ToCommonLanguage(
-    mobile_apis::Language::eType mobile_language) {
+  mobile_apis::Language::eType mobile_language) {
   // Update this check if mobile_api::Language
   // or hmi_apis::Common_Language changes.
   // Or, better, generate functions like this from XML
@@ -60,7 +61,7 @@ hmi_apis::Common_Language::eType ToCommonLanguage(
   long max_mobile_lang = long(mobile_apis::Language::NO_NO);
   if (max_common_lang_val != max_mobile_lang) {
     LOG4CXX_ERROR(g_logger, "Mapping between Common_Language and Language"
-                            " has changed! Please update converter function");
+                  " has changed! Please update converter function");
   }
   if (lang_val > max_common_lang_val) {
     LOG4CXX_ERROR(g_logger, "Non-convertable language ID");
@@ -96,75 +97,75 @@ bool ValidateSoftButtons(smart_objects::SmartObject& soft_buttons) {
 
 }
 std::pair<const char*, VehicleDataType> kVehicleDataInitializer[] = {
-std::make_pair(strings::gps,  VehicleDataType::GPS),
-std::make_pair(strings::speed, VehicleDataType::SPEED),
-std::make_pair(strings::rpm, VehicleDataType::RPM),
-std::make_pair(strings::fuel_level, VehicleDataType::FUELLEVEL),
-std::make_pair(strings::fuel_level_state, VehicleDataType::FUELLEVEL_STATE),
-std::make_pair(strings::instant_fuel_consumption, VehicleDataType::FUELCONSUMPTION),
-std::make_pair(strings::external_temp, VehicleDataType::EXTERNTEMP),
-std::make_pair(strings::vin, VehicleDataType::VIN ),
-std::make_pair(strings::prndl, VehicleDataType::PRNDL),
-std::make_pair(strings::tire_pressure, VehicleDataType::TIREPRESSURE),
-std::make_pair(strings::odometer, VehicleDataType::ODOMETER),
-std::make_pair(strings::belt_status, VehicleDataType::BELTSTATUS),
-std::make_pair(strings::body_information, VehicleDataType::BODYINFO),
-std::make_pair(strings::device_status, VehicleDataType::DEVICESTATUS),
-std::make_pair(strings::driver_braking, VehicleDataType::BRAKING),
-std::make_pair(strings::wiper_status, VehicleDataType::WIPERSTATUS),
-std::make_pair(strings::head_lamp_status, VehicleDataType::HEADLAMPSTATUS),
-std::make_pair(strings::e_call_info, VehicleDataType::ECALLINFO),
-std::make_pair(strings::airbag_status, VehicleDataType::AIRBAGSTATUS),
-std::make_pair(strings::emergency_event, VehicleDataType::EMERGENCYEVENT),
-std::make_pair(strings::cluster_mode_status, VehicleDataType::CLUSTERMODESTATUS),
-std::make_pair(strings::my_key, VehicleDataType::MYKEY),
-/*
- NOT DEFINED in mobile API
- std::make_pair(strings::gps,                      VehicleDataType::BATTVOLTAGE),
- */
-std::make_pair(strings::engine_torque, VehicleDataType::ENGINETORQUE ),
-std::make_pair(strings::acc_pedal_pos, VehicleDataType::ACCPEDAL),
-std::make_pair(strings::steering_wheel_angle, VehicleDataType::STEERINGWHEEL),
+  std::make_pair(strings::gps,  VehicleDataType::GPS),
+  std::make_pair(strings::speed, VehicleDataType::SPEED),
+  std::make_pair(strings::rpm, VehicleDataType::RPM),
+  std::make_pair(strings::fuel_level, VehicleDataType::FUELLEVEL),
+  std::make_pair(strings::fuel_level_state, VehicleDataType::FUELLEVEL_STATE),
+  std::make_pair(strings::instant_fuel_consumption, VehicleDataType::FUELCONSUMPTION),
+  std::make_pair(strings::external_temp, VehicleDataType::EXTERNTEMP),
+  std::make_pair(strings::vin, VehicleDataType::VIN),
+  std::make_pair(strings::prndl, VehicleDataType::PRNDL),
+  std::make_pair(strings::tire_pressure, VehicleDataType::TIREPRESSURE),
+  std::make_pair(strings::odometer, VehicleDataType::ODOMETER),
+  std::make_pair(strings::belt_status, VehicleDataType::BELTSTATUS),
+  std::make_pair(strings::body_information, VehicleDataType::BODYINFO),
+  std::make_pair(strings::device_status, VehicleDataType::DEVICESTATUS),
+  std::make_pair(strings::driver_braking, VehicleDataType::BRAKING),
+  std::make_pair(strings::wiper_status, VehicleDataType::WIPERSTATUS),
+  std::make_pair(strings::head_lamp_status, VehicleDataType::HEADLAMPSTATUS),
+  std::make_pair(strings::e_call_info, VehicleDataType::ECALLINFO),
+  std::make_pair(strings::airbag_status, VehicleDataType::AIRBAGSTATUS),
+  std::make_pair(strings::emergency_event, VehicleDataType::EMERGENCYEVENT),
+  std::make_pair(strings::cluster_mode_status, VehicleDataType::CLUSTERMODESTATUS),
+  std::make_pair(strings::my_key, VehicleDataType::MYKEY),
+  /*
  NOT DEFINED in mobile API
  std::make_pair(strings::gps,                      VehicleDataType::BATTVOLTAGE),
  */
+  std::make_pair(strings::engine_torque, VehicleDataType::ENGINETORQUE),
+  std::make_pair(strings::acc_pedal_pos, VehicleDataType::ACCPEDAL),
+  std::make_pair(strings::steering_wheel_angle, VehicleDataType::STEERINGWHEEL),
 };
 
 const VehicleData MessageHelper::vehicle_data_(kVehicleDataInitializer,
-                                               kVehicleDataInitializer +
-                                               ARRAYSIZE(kVehicleDataInitializer));
+    kVehicleDataInitializer +
+    ARRAYSIZE(kVehicleDataInitializer));
 
 
 #ifdef HMI_DBUS_API
 namespace {
-  struct VehicleInfo_Requests {
-    hmi_apis::FunctionID::eType func_id;
-    const char* str;
-  };
-  static VehicleInfo_Requests ivi_subrequests[] = {
-    { hmi_apis::FunctionID::VehicleInfo_SubscribeGps, strings::gps},
-    { hmi_apis::FunctionID::VehicleInfo_SubscribeSpeed, strings::speed},
-    { hmi_apis::FunctionID::VehicleInfo_SubscribeRpm, strings::rpm},
-    { hmi_apis::FunctionID::VehicleInfo_SubscribeFuelLevel, strings::fuel_level},
-    { hmi_apis::FunctionID::VehicleInfo_SubscribeFuelLevel_State, strings::fuel_level_state},
-    { hmi_apis::FunctionID::VehicleInfo_SubscribeInstantFuelConsumption, strings::instant_fuel_consumption},
-    { hmi_apis::FunctionID::VehicleInfo_SubscribeExternalTemperature, strings::external_temp},
-    { hmi_apis::FunctionID::VehicleInfo_SubscribeVin, strings::vin},
-    { hmi_apis::FunctionID::VehicleInfo_SubscribePrndl, strings::prndl},
-    { hmi_apis::FunctionID::VehicleInfo_SubscribeTirePressure, strings::tire_pressure},
-    { hmi_apis::FunctionID::VehicleInfo_SubscribeOdometer, strings::odometer},
-    { hmi_apis::FunctionID::VehicleInfo_SubscribeBeltStatus, strings::belt_status},
-    { hmi_apis::FunctionID::VehicleInfo_SubscribeBodyInformation, strings::body_information},
-    { hmi_apis::FunctionID::VehicleInfo_SubscribeDeviceStatus, strings::device_status},
-    { hmi_apis::FunctionID::VehicleInfo_SubscribeDriverBraking, strings::driver_braking},
-    { hmi_apis::FunctionID::VehicleInfo_SubscribeWiperStatus, strings::wiper_status},
-    { hmi_apis::FunctionID::VehicleInfo_SubscribeHeadLampStatus, strings::head_lamp_status},
-    { hmi_apis::FunctionID::VehicleInfo_SubscribeEngineTorque, strings::engine_torque},
-    { hmi_apis::FunctionID::VehicleInfo_SubscribeAccPedalPosition, strings::acc_pedal_pos},
-    { hmi_apis::FunctionID::VehicleInfo_SubscribeSteeringWheelAngle, strings::steering_wheel_angle},
-    { hmi_apis::FunctionID::VehicleInfo_SubscribeECallInfo, strings::e_call_info},
-    { hmi_apis::FunctionID::VehicleInfo_SubscribeAirbagStatus, strings::airbag_status},
-    { hmi_apis::FunctionID::VehicleInfo_SubscribeEmergencyEvent, strings::emergency_event},
-    { hmi_apis::FunctionID::VehicleInfo_SubscribeClusterModeStatus, strings::cluster_mode_status},
-    { hmi_apis::FunctionID::VehicleInfo_SubscribeMyKey, strings::my_key},
-  };
+struct VehicleInfo_Requests {
+  hmi_apis::FunctionID::eType func_id;
+  const char* str;
+};
+static VehicleInfo_Requests ivi_subrequests[] = {
+  { hmi_apis::FunctionID::VehicleInfo_SubscribeGps, strings::gps},
+  { hmi_apis::FunctionID::VehicleInfo_SubscribeSpeed, strings::speed},
+  { hmi_apis::FunctionID::VehicleInfo_SubscribeRpm, strings::rpm},
+  { hmi_apis::FunctionID::VehicleInfo_SubscribeFuelLevel, strings::fuel_level},
+  { hmi_apis::FunctionID::VehicleInfo_SubscribeFuelLevel_State, strings::fuel_level_state},
+  { hmi_apis::FunctionID::VehicleInfo_SubscribeInstantFuelConsumption, strings::instant_fuel_consumption},
+  { hmi_apis::FunctionID::VehicleInfo_SubscribeExternalTemperature, strings::external_temp},
+  { hmi_apis::FunctionID::VehicleInfo_SubscribeVin, strings::vin},
+  { hmi_apis::FunctionID::VehicleInfo_SubscribePrndl, strings::prndl},
+  { hmi_apis::FunctionID::VehicleInfo_SubscribeTirePressure, strings::tire_pressure},
+  { hmi_apis::FunctionID::VehicleInfo_SubscribeOdometer, strings::odometer},
+  { hmi_apis::FunctionID::VehicleInfo_SubscribeBeltStatus, strings::belt_status},
+  { hmi_apis::FunctionID::VehicleInfo_SubscribeBodyInformation, strings::body_information},
+  { hmi_apis::FunctionID::VehicleInfo_SubscribeDeviceStatus, strings::device_status},
+  { hmi_apis::FunctionID::VehicleInfo_SubscribeDriverBraking, strings::driver_braking},
+  { hmi_apis::FunctionID::VehicleInfo_SubscribeWiperStatus, strings::wiper_status},
+  { hmi_apis::FunctionID::VehicleInfo_SubscribeHeadLampStatus, strings::head_lamp_status},
+  { hmi_apis::FunctionID::VehicleInfo_SubscribeEngineTorque, strings::engine_torque},
+  { hmi_apis::FunctionID::VehicleInfo_SubscribeAccPedalPosition, strings::acc_pedal_pos},
+  { hmi_apis::FunctionID::VehicleInfo_SubscribeSteeringWheelAngle, strings::steering_wheel_angle},
+  { hmi_apis::FunctionID::VehicleInfo_SubscribeECallInfo, strings::e_call_info},
+  { hmi_apis::FunctionID::VehicleInfo_SubscribeAirbagStatus, strings::airbag_status},
+  { hmi_apis::FunctionID::VehicleInfo_SubscribeEmergencyEvent, strings::emergency_event},
+  { hmi_apis::FunctionID::VehicleInfo_SubscribeClusterModeStatus, strings::cluster_mode_status},
+  { hmi_apis::FunctionID::VehicleInfo_SubscribeMyKey, strings::my_key},
+};
 }
 #endif // #ifdef HMI_DBUS_API
 
@@ -182,7 +183,7 @@ void MessageHelper::SendHMIStatusNotification(
     static_cast<int32_t>(mobile_api::FunctionID::OnHMIStatusID);
 
   message[strings::params][strings::message_type] =
-      static_cast<int32_t>(application_manager::MessageType::kNotification);
+    static_cast<int32_t>(application_manager::MessageType::kNotification);
 
   message[strings::params][strings::connection_key] =
     static_cast<int32_t>(application_impl.app_id());
@@ -194,13 +195,13 @@ void MessageHelper::SendHMIStatusNotification(
     static_cast<int32_t>(application_impl.audio_streaming_state());
 
   message[strings::msg_params][strings::system_context] =
-      static_cast<int32_t>(application_impl.system_context());
+    static_cast<int32_t>(application_impl.system_context());
 
   DCHECK(ApplicationManagerImpl::instance()->ManageMobileCommand(notification));
 }
 
 void MessageHelper::SendOnAppRegisteredNotificationToHMI(
-  const Application& application_impl, bool resumption ) {
+  const Application& application_impl, bool resumption) {
   smart_objects::SmartObject* notification = new smart_objects::SmartObject;
   if (!notification) {
     // TODO(VS): please add logger.
@@ -267,9 +268,9 @@ smart_objects::SmartObject* MessageHelper::GetHashUpdateNotification(const uint3
   DCHECK(app.get());
 
   smart_objects::SmartObject* message = new smart_objects::SmartObject(
-                                          smart_objects::SmartType_Map);
+    smart_objects::SmartType_Map);
   (*message)[strings::params][strings::function_id] =
-      mobile_apis::FunctionID::OnHashChangeID;
+    mobile_apis::FunctionID::OnHashChangeID;
   (*message)[strings::params][strings::connection_key] = app_id;
 
   return message;
@@ -288,8 +289,8 @@ void MessageHelper::SendRemoveVrCommandsOnUnregisterApp(ApplicationConstSharedPt
 
   if (app->vr_synonyms()) {
     SendRemoveCommandToHMI(
-        static_cast<int32_t>(hmi_apis::FunctionID::VR_DeleteCommand),
-        max_cmd_id + app->app_id(), app->app_id());
+      static_cast<int32_t>(hmi_apis::FunctionID::VR_DeleteCommand),
+      max_cmd_id + app->app_id(), app->app_id());
   }
 }
 
@@ -321,6 +322,154 @@ const VehicleData& MessageHelper::vehicle_data() {
   return vehicle_data_;
 }
 
+const char* MessageHelper::StringifiedHMILevel(
+  mobile_apis::HMILevel::eType hmi_level) {
+  switch (hmi_level) {
+    case mobile_apis::HMILevel::HMI_FULL:
+      return hmi_levels::kFull;
+    case mobile_apis::HMILevel::HMI_LIMITED:
+      return hmi_levels::kLimited;
+    case mobile_apis::HMILevel::HMI_BACKGROUND:
+      return hmi_levels::kBackground;
+    case mobile_apis::HMILevel::HMI_NONE:
+      return hmi_levels::kNone;
+    default:
+      return "";
+  }
+}
+
+const char* MessageHelper::StringifiedFunctionID(
+  mobile_apis::FunctionID::eType function_id) {
+  switch (function_id) {
+    case mobile_apis::FunctionID::RegisterAppInterfaceID:
+      return "RegisterAppInterface";
+    case mobile_apis::FunctionID::UnregisterAppInterfaceID:
+      return "UnregisterAppInterface";
+    case mobile_apis::FunctionID::SetGlobalPropertiesID:
+      return "SetGlobalProperties";
+    case mobile_apis::FunctionID::ResetGlobalPropertiesID:
+      return "ResetGlobalProperties";
+    case mobile_apis::FunctionID::AddCommandID:
+      return "AddCommand";
+    case mobile_apis::FunctionID::DeleteCommandID:
+      return "DeleteCommand";
+    case mobile_apis::FunctionID::AddSubMenuID:
+      return "AddSubMenu";
+    case mobile_apis::FunctionID::DeleteSubMenuID:
+      return "DeleteSubMenu";
+    case mobile_apis::FunctionID::CreateInteractionChoiceSetID:
+      return "CreateInteractionChoiceSet";
+    case mobile_apis::FunctionID::PerformInteractionID:
+      return "PerformInteraction";
+    case mobile_apis::FunctionID::DeleteInteractionChoiceSetID:
+      return "DeleteInteractionChoiceSet";
+    case mobile_apis::FunctionID::AlertID:
+      return "Alert";
+    case mobile_apis::FunctionID::ShowID:
+      return "Show";
+    case mobile_apis::FunctionID::SpeakID:
+      return "Speak";
+    case mobile_apis::FunctionID::SetMediaClockTimerID:
+      return "SetMediaClockTimer";
+    case mobile_apis::FunctionID::EncodedSyncPDataID:
+      return "EncodedSyncPData";
+    case mobile_apis::FunctionID::SyncPDataID:
+      return "SyncPData";
+    case mobile_apis::FunctionID::PerformAudioPassThruID:
+      return "PerformAudioPassThru";
+    case mobile_apis::FunctionID::EndAudioPassThruID:
+      return "EndAudioPassThru";
+    case mobile_apis::FunctionID::SubscribeButtonID:
+      return "SubscribeButton";
+    case mobile_apis::FunctionID::UnsubscribeButtonID:
+      return "UnsubscribeButton";
+    case mobile_apis::FunctionID::SubscribeVehicleDataID:
+      return "SubscribeVehicleData";
+    case mobile_apis::FunctionID::UnsubscribeVehicleDataID:
+      return "UnsubscribeVehicleData";
+    case mobile_apis::FunctionID::GetVehicleDataID:
+      return "GetVehicleData";
+    case mobile_apis::FunctionID::ReadDIDID:
+      return "ReadDID";
+    case mobile_apis::FunctionID::GetDTCsID:
+      return "GetDTCs";
+    case mobile_apis::FunctionID::ScrollableMessageID:
+      return "ScrollableMessage";
+    case mobile_apis::FunctionID::SliderID:
+      return "Slider";
+    case mobile_apis::FunctionID::ShowConstantTBTID:
+      return "ShowConstantTBT";
+    case mobile_apis::FunctionID::AlertManeuverID:
+      return "AlertManeuver";
+    case mobile_apis::FunctionID::UpdateTurnListID:
+      return "UpdateTurnList";
+    case mobile_apis::FunctionID::ChangeRegistrationID:
+      return "ChangeRegistration";
+    case mobile_apis::FunctionID::GenericResponseID:
+      return "GenericResponse";
+    case mobile_apis::FunctionID::PutFileID:
+      return "PutFile";
+    case mobile_apis::FunctionID::DeleteFileID:
+      return "DeleteFile";
+    case mobile_apis::FunctionID::ListFilesID:
+      return "ListFiles";
+    case mobile_apis::FunctionID::SetAppIconID:
+      return "SetAppIcon";
+    case mobile_apis::FunctionID::SetDisplayLayoutID:
+      return "SetDisplayLayout";
+    case mobile_apis::FunctionID::OnHMIStatusID:
+      return "OnHMIStatus";
+    case mobile_apis::FunctionID::OnAppInterfaceUnregisteredID:
+      return "OnAppInterfaceUnregistered";
+    case mobile_apis::FunctionID::OnButtonEventID:
+      return "OnButtonEvent";
+    case mobile_apis::FunctionID::OnButtonPressID:
+      return "OnButtonPress";
+    case mobile_apis::FunctionID::OnVehicleDataID:
+      return "OnVehicleData";
+    case mobile_apis::FunctionID::OnCommandID:
+      return "OnCommand";
+    case mobile_apis::FunctionID::OnEncodedSyncPDataID:
+      return "OnEncodedSyncPData";
+    case mobile_apis::FunctionID::OnTBTClientStateID:
+      return "OnTBTClientState";
+    case mobile_apis::FunctionID::OnPermissionsChangeID:
+      return "OnPermissionsChange";
+    case mobile_apis::FunctionID::OnAudioPassThruID:
+      return "OnAudioPassThru";
+    case mobile_apis::FunctionID::OnLanguageChangeID:
+      return "OnLanguageChange";
+    case mobile_apis::FunctionID::OnDriverDistractionID:
+      return "OnDriverDistraction";
+    case mobile_apis::FunctionID::OnSyncPDataID:
+      return "OnSyncPData";
+    case mobile_apis::FunctionID::OnSystemRequestID:
+      return "OnSystemRequest";
+    default:
+      return "";
+  }
+}
+
+void MessageHelper::CreateGetDeviceData(int32_t correlation_id) {
+  smart_objects::SmartObject* request = new smart_objects::SmartObject;
+  if (!request) {
+    return;
+  }
+  smart_objects::SmartObject& object = *request;
+  object[strings::params][strings::message_type] = static_cast<int>(kRequest);
+  object[strings::params][strings::function_id] =
+    static_cast<int>(hmi_apis::FunctionID::VehicleInfo_GetVehicleData);
+  object[strings::params][strings::correlation_id] = correlation_id;
+  object[strings::params][strings::protocol_version] =
+    commands::CommandImpl::protocol_version_;
+  object[strings::params][strings::protocol_type] =
+    commands::CommandImpl::hmi_protocol_type_;
+  object[strings::msg_params] = smart_objects::SmartObject(
+                                  smart_objects::SmartType_Map);
+  object[strings::msg_params][strings::odometer] = true;
+  ApplicationManagerImpl::instance()->ManageHMICommand(request);
+}
+
 smart_objects::SmartObject* MessageHelper::CreateBlockedByPoliciesResponse(
   mobile_apis::FunctionID::eType function_id,
   mobile_apis::Result::eType result, uint32_t correlation_id,
@@ -339,7 +488,7 @@ smart_objects::SmartObject* MessageHelper::CreateBlockedByPoliciesResponse(
   (*response)[strings::params][strings::protocol_type] =
     commands::CommandImpl::mobile_protocol_type_;
   (*response)[strings::params][strings::protocol_version] =
-     static_cast<int>(kV2);
+    static_cast<int>(kV2);
   return response;
 }
 
@@ -360,7 +509,7 @@ smart_objects::SmartObject* MessageHelper::CreateDeviceListSO(
        devices.end() != it; ++it) {
     const connection_handler::Device& d = static_cast<connection_handler::Device>(it->second);
     list_so[index][strings::name] =
-        d.user_friendly_name();
+      d.user_friendly_name();
     list_so[index][strings::id] = it->second.device_handle();
     ++index;
   }
@@ -464,7 +613,7 @@ MessageHelper::SmartObjectList MessageHelper::GetIVISubscribtionRequests(const u
     }
   }
 #endif // #ifdef HMI_DBUS_API
- return hmi_requests;
 return hmi_requests;
 }
 
 void MessageHelper::SendAppDataToHMI(ApplicationConstSharedPtr app) {
@@ -616,7 +765,7 @@ smart_objects::SmartObject* MessageHelper::CreateAppVrHelp(ApplicationConstShare
     vr_help[strings::vr_help] = (*app->vr_help());
   } else {
     const std::set<ApplicationSharedPtr>& apps = ApplicationManagerImpl::instance()
-                                         ->applications();
+        ->applications();
 
     int32_t index = 0;
     std::set<ApplicationSharedPtr>::const_iterator it_app = apps.begin();
@@ -756,7 +905,7 @@ MessageHelper::SmartObjectList MessageHelper::CreateAddCommandRequestToHMI(Appli
           && (0 < (*i->second)[strings::cmd_icon][strings::value].length())) {
         msg_params[strings::cmd_icon] = (*i->second)[strings::cmd_icon];
         msg_params[strings::cmd_icon][strings::value] =
-            (*i->second)[strings::cmd_icon][strings::value].asString();
+          (*i->second)[strings::cmd_icon][strings::value].asString();
       }
       (*ui_command)[strings::msg_params] = msg_params;
       requests.push_back(ui_command);
@@ -803,9 +952,9 @@ smart_objects::SmartObject* MessageHelper::CreateChangeRegistration(
 
 void MessageHelper::SendChangeRegistrationRequestToHMI(ApplicationConstSharedPtr app) {
   hmi_apis::Common_Language::eType app_common_language =
-      ToCommonLanguage(app->language());
+    ToCommonLanguage(app->language());
   const HMICapabilities& hmi_capabilities =
-  ApplicationManagerImpl::instance()->hmi_capabilities();
+    ApplicationManagerImpl::instance()->hmi_capabilities();
   if (mobile_apis::Language::INVALID_ENUM != app->language()) {
     smart_objects::SmartObject* vr_command = CreateChangeRegistration(
           hmi_apis::FunctionID::VR_ChangeRegistration, app->language(),
@@ -845,7 +994,7 @@ void MessageHelper::SendAddVRCommandToHMI(
   DCHECK(ApplicationManagerImpl::instance()->ManageHMICommand(request));
 }
 
-smart_objects::SmartObject* MessageHelper::CreateAddVRCommandToHMI(uint32_t cmd_id, const NsSmartDeviceLink::NsSmartObjects::SmartObject &vr_commands, uint32_t app_id) {
+smart_objects::SmartObject* MessageHelper::CreateAddVRCommandToHMI(uint32_t cmd_id, const NsSmartDeviceLink::NsSmartObjects::SmartObjectvr_commands, uint32_t app_id) {
   smart_objects::SmartObject* vr_command = new smart_objects::SmartObject(
     smart_objects::SmartType_Map);
 
@@ -936,16 +1085,16 @@ void MessageHelper::RemoveAppDataFromHMI(ApplicationSharedPtr app) {
 
 void MessageHelper::SendOnSdlCloseNotificationToHMI() {
   smart_objects::SmartObject* notification = new smart_objects::SmartObject(
-      smart_objects::SmartType_Map);
-    if (!notification) {
-      return;
-    }
-    smart_objects::SmartObject& message = *notification;
-    message[strings::params][strings::function_id] =
-        hmi_apis::FunctionID::BasicCommunication_OnSDLClose;
-    message[strings::params][strings::message_type] = MessageType::kNotification;
+    smart_objects::SmartType_Map);
+  if (!notification) {
+    return;
+  }
+  smart_objects::SmartObject& message = *notification;
+  message[strings::params][strings::function_id] =
+    hmi_apis::FunctionID::BasicCommunication_OnSDLClose;
+  message[strings::params][strings::message_type] = MessageType::kNotification;
 
-    ApplicationManagerImpl::instance()->ManageHMICommand(&message);
+  ApplicationManagerImpl::instance()->ManageHMICommand(&message);
 }
 
 void MessageHelper::SendOnAppUnregNotificationToHMI(ApplicationConstSharedPtr app) {
@@ -976,14 +1125,14 @@ void MessageHelper::SendDeleteCommandRequestToHMI(ApplicationConstSharedPtr app)
   for (; commands.end() != i; ++i) {
     if ((*i->second).keyExists(strings::menu_params)) {
       SendRemoveCommandToHMI(
-          static_cast<int32_t>(hmi_apis::FunctionID::UI_DeleteCommand),
-          i->first, app->app_id());
+        static_cast<int32_t>(hmi_apis::FunctionID::UI_DeleteCommand),
+        i->first, app->app_id());
     }
 
     if ((*i->second).keyExists(strings::vr_commands)) {
       SendRemoveCommandToHMI(
-          static_cast<int32_t>(hmi_apis::FunctionID::VR_DeleteCommand),
-          i->first, app->app_id());
+        static_cast<int32_t>(hmi_apis::FunctionID::VR_DeleteCommand),
+        i->first, app->app_id());
     }
   }
 }
@@ -1073,6 +1222,110 @@ void MessageHelper::SendActivateAppToHMI(uint32_t const app_id) {
   ApplicationManagerImpl::instance()->ManageHMICommand(message);
 }
 
+void MessageHelper::GetDeviceInfoForHandle(const uint32_t device_handle,
+                                           policy::DeviceParams* device_info) {
+  if (!device_info) {
+    return;
+  }
+  connection_handler::ConnectionHandlerImpl::instance()->GetDataOnDeviceID(
+    device_handle, &device_info->device_name, NULL,
+    &device_info->device_mac_address);
+}
+
+void MessageHelper::GetDeviceInfoForApp(const std::string& connection_key,
+                                        policy::DeviceParams* device_info) {
+  if (!device_info) {
+    return;
+  }
+
+  const std::set<utils::SharedPtr<Application>> app_list =
+        application_manager::ApplicationManagerImpl::instance()->applications();
+  std::set<utils::SharedPtr<Application>>::const_iterator it = app_list.begin();
+  std::set<utils::SharedPtr<Application>>::const_iterator it_end = app_list.end();
+  for (; it != it_end; ++it) {
+    if ((*it)->app_id() == atoi(connection_key.c_str())) {
+      device_info->device_handle = (*it)->device();
+      break;
+    }
+  }
+
+  GetDeviceInfoForHandle(device_info->device_handle, device_info);
+}
+
+void MessageHelper::SendActivateAppResponse(policy::AppPermissions& permissions,
+    uint32_t correlation_id) {
+  smart_objects::SmartObject* message = new smart_objects::SmartObject(
+    smart_objects::SmartType_Map);
+  if (!message) {
+    return;
+  }
+
+  (*message)[strings::params][strings::function_id] =
+    hmi_apis::FunctionID::SDL_ActivateApp;
+  (*message)[strings::params][strings::message_type] = MessageType::kResponse;
+  (*message)[strings::params][strings::correlation_id] = correlation_id/*
+   ApplicationManagerImpl::instance()->GetNextHMICorrelationID()*/;
+  (*message)[strings::params][strings::protocol_type] =
+    commands::CommandImpl::hmi_protocol_type_;
+  (*message)[strings::params][strings::protocol_version] =
+    commands::CommandImpl::protocol_version_;
+  (*message)[strings::params]["code"] = 0;
+
+  bool isSDLAllowed = permissions.isSDLAllowed;
+  if (!isSDLAllowed) {
+    (*message)[strings::msg_params]["device"]["name"] = permissions.deviceInfo
+        .device_name;
+    // TODO(AOleynik): Change id assignment
+    (*message)[strings::msg_params]["device"]["id"] = permissions.deviceInfo
+        .device_handle;
+  }
+
+  (*message)[strings::msg_params]["isSDLAllowed"] = isSDLAllowed;
+
+  // TODO(AOleynik): Add processing of other parameters  
+  (*message)[strings::msg_params]["isPermissionsConsentNeeded"] = false;  
+  (*message)[strings::msg_params]["isAppRevoked"] = false;
+
+  ApplicationManagerImpl::instance()->ManageHMICommand(message);
+
+  // If application is revoked it should not be activated
+  if ((*message)[strings::msg_params]["isAppRevoked"].asBool()) {
+    return;
+  }
+
+  // Send HMI status notification to mobile
+  const std::set<ApplicationSharedPtr> app_list =
+        application_manager::ApplicationManagerImpl::instance()->applications();
+  std::set<ApplicationSharedPtr>::const_iterator it = app_list.begin();
+  std::set<ApplicationSharedPtr>::const_iterator it_end = app_list.end();
+  for (; it != it_end; ++it) {
+    if ((*it)->app_id() == permissions.application_id) {
+      ApplicationManagerImpl::instance()->ActivateApplication((*it));
+      break;
+    }
+  }
+}
+
+
+void MessageHelper::SendOnSDLConsentNeeded(
+    const policy::DeviceParams& device_info) {
+  smart_objects::SmartObject* message = new smart_objects::SmartObject(
+    smart_objects::SmartType_Map);
+  if (!message) {
+    return;
+  }
+
+  (*message)[strings::params][strings::function_id] =
+    hmi_apis::FunctionID::SDL_OnSDLConsentNeeded;
+  (*message)[strings::params][strings::message_type] =
+    MessageType::kNotification;
+
+  (*message)[strings::msg_params]["device"]["id"] = device_info.device_handle;
+  (*message)[strings::msg_params]["device"]["name"] = device_info.device_name;
+
+  ApplicationManagerImpl::instance()->ManageHMICommand(message);
+}
+
 smart_objects::SmartObject* MessageHelper::CreateNegativeResponse(
   uint32_t connection_key, int32_t function_id, uint32_t correlation_id,
   int32_t result_code) {
@@ -1143,7 +1396,7 @@ void MessageHelper::ResetGlobalproperties(ApplicationSharedPtr app) {
       // use only first
       vr_help_items[index][strings::position] = (index + 1);
       vr_help_items[index++][strings::text] =
-          (*command_it->second)[strings::vr_commands][0];
+        (*command_it->second)[strings::vr_commands][0];
     }
   }
 
@@ -1179,8 +1432,8 @@ void MessageHelper::SendNaviStartStream(
 
   uint32_t app_id = 0;
   connection_handler::ConnectionHandlerImpl::instance()->GetDataOnSessionKey(
-      connection_key,
-      &app_id);
+    connection_key,
+    &app_id);
 
   msg_params[strings::app_id] = app_id;
   msg_params[strings::url] = url;
@@ -1214,8 +1467,8 @@ void MessageHelper::SendNaviStopStream(int32_t connection_key) {
 
   uint32_t app_id = 0;
   connection_handler::ConnectionHandlerImpl::instance()->GetDataOnSessionKey(
-      connection_key,
-      &app_id);
+    connection_key,
+    &app_id);
 
   msg_params[strings::app_id] = app_id;
 
@@ -1250,8 +1503,8 @@ void MessageHelper::SendAudioStartStream(
 
   uint32_t app_id = 0;
   connection_handler::ConnectionHandlerImpl::instance()->GetDataOnSessionKey(
-      connection_key,
-      &app_id);
+    connection_key,
+    &app_id);
 
   msg_params[strings::app_id] = app_id;
   msg_params[strings::url] = url;
@@ -1285,8 +1538,8 @@ void MessageHelper::SendAudioStopStream(int32_t connection_key) {
 
   uint32_t app_id = 0;
   connection_handler::ConnectionHandlerImpl::instance()->GetDataOnSessionKey(
-      connection_key,
-      &app_id);
+    connection_key,
+    &app_id);
 
   msg_params[strings::app_id] = app_id;
 
@@ -1296,10 +1549,10 @@ void MessageHelper::SendAudioStopStream(int32_t connection_key) {
 }
 
 bool MessageHelper::SendStopAudioPathThru() {
-  LOG4CXX_INFO(g_logger,"MessageHelper::SendAudioStopAudioPathThru");
+  LOG4CXX_INFO(g_logger, "MessageHelper::SendAudioStopAudioPathThru");
 
   NsSmartDeviceLink::NsSmartObjects::SmartObject* result =
-      new NsSmartDeviceLink::NsSmartObjects::SmartObject;
+    new NsSmartDeviceLink::NsSmartObjects::SmartObject;
   const uint32_t hmi_correlation_id = ApplicationManagerImpl::instance()->
                                       GetNextHMICorrelationID();
   NsSmartDeviceLink::NsSmartObjects::SmartObject& request = *result;
@@ -1307,12 +1560,182 @@ bool MessageHelper::SendStopAudioPathThru() {
   request[strings::params][strings::function_id] = hmi_apis::FunctionID::UI_EndAudioPassThru;
   request[strings::params][strings::correlation_id] = hmi_correlation_id;
   request[strings::params][strings::protocol_version] =
-      commands::CommandImpl::protocol_version_;
+    commands::CommandImpl::protocol_version_;
   request[strings::params][strings::protocol_type] =
-      commands::CommandImpl::hmi_protocol_type_;
+    commands::CommandImpl::hmi_protocol_type_;
   return ApplicationManagerImpl::instance()->ManageHMICommand(result);
 }
 
+void MessageHelper::SendPolicySnapshotNotification(
+  unsigned int connection_key, const std::vector<uint8_t>& policy_data,
+  const std::string& url, int timeout) {
+  printf("\n\t\t\t\tSendPolicySnapshotNotification\n");
+  smart_objects::SmartObject* pt_notification = new smart_objects::SmartObject(
+    smart_objects::SmartType_Map);
+  smart_objects::SmartObject& content = *pt_notification;
+  ;
+  content[strings::params][strings::function_id] =
+    mobile_apis::FunctionID::OnSystemRequestID;
+  content[strings::params][strings::message_type] =
+    mobile_apis::messageType::notification;
+  content[strings::params][strings::protocol_type] =
+    commands::CommandImpl::mobile_protocol_type_;
+  content[strings::params][strings::protocol_version] =
+    commands::CommandImpl::protocol_version_;
+  content[strings::params][strings::connection_key] = connection_key;
+  if (!url.empty()) {
+    content[strings::msg_params][mobile_notification::syncp_url] = url;
+  }
+  content[strings::msg_params][strings::file_type] =
+    mobile_apis::FileType::JSON;
+  content[strings::msg_params][strings::request_type] =
+    mobile_apis::RequestType::HTTP;
+  /*if (-1 != timeout) {
+   content[strings::msg_params][mobile_notification::syncp_timeout] = timeout;
+   }*/
+  content[strings::params][strings::binary_data] = smart_objects::SmartObject(
+        policy_data);
+  ApplicationManagerImpl::instance()->ManageMobileCommand(pt_notification);
+}
+
+void MessageHelper::SendOnPermissionsChangeNotification(
+  uint32_t connection_key, const policy::Permissions& permissions) {
+  smart_objects::SmartObject* notification = new smart_objects::SmartObject(
+    smart_objects::SmartType_Map);
+  smart_objects::SmartObject& content = *notification;
+  ;
+  content[strings::params][strings::function_id] =
+    mobile_apis::FunctionID::OnPermissionsChangeID;
+  content[strings::params][strings::message_type] =
+    mobile_apis::messageType::notification;
+  content[strings::params][strings::protocol_type] =
+    commands::CommandImpl::mobile_protocol_type_;
+  content[strings::params][strings::protocol_version] =
+    commands::CommandImpl::protocol_version_;
+  content[strings::params][strings::connection_key] = connection_key;
+
+  smart_objects::SmartObject* p_msg_params = new smart_objects::SmartObject(
+    smart_objects::SmartType_Map);
+
+  smart_objects::SmartObject& msg_params = *p_msg_params;
+
+  content[strings::msg_params] = msg_params;
+
+  content[strings::msg_params][strings::app_id] = connection_key;
+
+  content[strings::msg_params]["permissionItem"] = smart_objects::SmartObject(
+        smart_objects::SmartType_Array);
+
+  smart_objects::SmartObject& permissions_item_array =
+    content[strings::msg_params]["permissionItem"];
+
+  policy::Permissions::const_iterator it_permissions = permissions.begin();
+  policy::Permissions::const_iterator it_permissions_end = permissions.end();
+
+  for (size_t index_pi = 0; it_permissions != it_permissions_end;
+       ++it_permissions, ++index_pi) {
+
+    permissions_item_array[index_pi] = smart_objects::SmartObject(
+                                         smart_objects::SmartType_Map);
+
+    smart_objects::SmartObject& permission_item =
+      permissions_item_array[index_pi];
+
+    // Filling the rpcName of PermissionItem
+    permission_item["rpcName"] = (*it_permissions).first;
+    const policy::RpcPermissions& rpc_permissions = (*it_permissions).second;
+
+    // Creating SO for hmiPermissions
+    permission_item["hmiPermissions"] = smart_objects::SmartObject(
+                                          smart_objects::SmartType_Map);
+
+    smart_objects::SmartObject& hmi_permissions =
+      permission_item["hmiPermissions"];
+
+    policy::HMIPermissions::const_iterator it_hmi_permissions = rpc_permissions
+        .hmi_permissions.begin();
+    policy::HMIPermissions::const_iterator it_hmi_permissions_end =
+      rpc_permissions.hmi_permissions.end();
+
+    // Filling the hmiPermissions of PermissionItem
+    for (; it_hmi_permissions != it_hmi_permissions_end; ++it_hmi_permissions) {
+      // Possible key names are "allowed", "userDisallowed"
+      hmi_permissions[(*it_hmi_permissions).first] = smart_objects::SmartObject(
+            smart_objects::SmartType_Array);
+
+      smart_objects::SmartObject& hmi_levels =
+        hmi_permissions[(*it_hmi_permissions).first];
+
+      std::set<policy::HMILevel>::const_iterator it_hmi_levels =
+        (*it_hmi_permissions).second.begin();
+      std::set<policy::HMILevel>::const_iterator it_hmi_levels_end =
+        (*it_hmi_permissions).second.end();
+
+      for (size_t index_hmi_levels = 0; it_hmi_levels != it_hmi_levels_end;
+           ++it_hmi_levels, ++index_hmi_levels) {
+        hmi_levels[index_hmi_levels] = *it_hmi_levels;
+      }
+    }
+
+    // Creating SO for parameterPermissions
+    permission_item["parameterPermissions"] = smart_objects::SmartObject(
+          smart_objects::SmartType_Map);
+
+    smart_objects::SmartObject& parameter_permissions =
+      permission_item["parameterPermissions"];
+
+    policy::ParameterPermissions::const_iterator it_parameter_permissions =
+      rpc_permissions.parameter_permissions.begin();
+    policy::ParameterPermissions::const_iterator it_parameter_permissions_end =
+      rpc_permissions.parameter_permissions.end();
+
+    // Filling the parameterPermissions of PermissionItem
+    for (; it_parameter_permissions != it_parameter_permissions_end;
+         ++it_parameter_permissions) {
+      // Possible key names are "allowed", "userDisallowed"
+      parameter_permissions[(*it_parameter_permissions).first] =
+        smart_objects::SmartObject(smart_objects::SmartType_Array);
+
+      smart_objects::SmartObject& parameters =
+        parameter_permissions[(*it_parameter_permissions).first];
+
+      std::set<policy::Parameter>::const_iterator it_parameters =
+        (*it_parameter_permissions).second.begin();
+      std::set<policy::Parameter>::const_iterator it_parameters_end =
+        (*it_parameter_permissions).second.end();
+
+      for (size_t index_parameters = 0; it_parameters != it_parameters_end;
+           ++it_parameters, ++index_parameters) {
+        parameters[index_parameters] = *it_parameters;
+      }
+    }
+  }
+
+  ApplicationManagerImpl::instance()->ManageMobileCommand(notification);
+}
+
+void MessageHelper::SendOnAppPermissionsChangedNotification(
+  uint32_t connection_key, const policy::AppPermissions& permissions) {
+  smart_objects::SmartObject* notification = new smart_objects::SmartObject(
+    smart_objects::SmartType_Map);
+  if (!notification) {
+    return;
+  }
+
+  smart_objects::SmartObject& message = *notification;
+
+  message[strings::params][strings::function_id] =
+    hmi_apis::FunctionID::SDL_OnAppPermissionChanged;
+
+  message[strings::params][strings::message_type] = MessageType::kNotification;
+  message[strings::msg_params][strings::app_id] = connection_key;
+
+  // TODO(AOleynik): Add other parameters processing from incoming struct
+  message[strings::msg_params]["appRevoked"] = permissions.appRevoked;
+
+  ApplicationManagerImpl::instance()->ManageHMICommand(&message);
+}
+
 mobile_apis::Result::eType MessageHelper::VerifyImageFiles(
   smart_objects::SmartObject& message, ApplicationConstSharedPtr app) {
   if (NsSmartDeviceLink::NsSmartObjects::SmartType_Array == message.getType()) {
@@ -1326,7 +1749,7 @@ mobile_apis::Result::eType MessageHelper::VerifyImageFiles(
              == message.getType()) {
     if (message.keyExists(strings::image_type)) {
       mobile_apis::Result::eType verification_result =
-                                                  VerifyImage(message, app);
+        VerifyImage(message, app);
 
       if (mobile_apis::Result::SUCCESS != verification_result) {
         return verification_result; // exit point
@@ -1350,7 +1773,7 @@ mobile_apis::Result::eType MessageHelper::VerifyImageFiles(
 }
 
 mobile_apis::Result::eType MessageHelper::VerifyImage(
-    smart_objects::SmartObject& image, ApplicationConstSharedPtr app) {
+  smart_objects::SmartObject& image, ApplicationConstSharedPtr app) {
   const std::string& file_name = image[strings::value].asString();
 
   std::string str = file_name;
@@ -1360,7 +1783,7 @@ mobile_apis::Result::eType MessageHelper::VerifyImage(
   }
 
   std::string relative_file_path;
-  if (file_name.size() > 0 && file_name[0] == '/' ) {
+  if (file_name.size() > 0 && file_name[0] == '/') {
     relative_file_path = file_name;
   } else {
     relative_file_path = app->name();
@@ -1375,10 +1798,10 @@ mobile_apis::Result::eType MessageHelper::VerifyImage(
   }
 
   const HMICapabilities& hmi_capabilities =
-      ApplicationManagerImpl::instance()->hmi_capabilities();
+    ApplicationManagerImpl::instance()->hmi_capabilities();
   mobile_apis::ImageType::eType image_type =
-      static_cast<mobile_apis::ImageType::eType>(image[strings::image_type]
-      .asInt());
+    static_cast<mobile_apis::ImageType::eType>(image[strings::image_type]
+        .asInt());
   if (!hmi_capabilities.VerifyImageType(image_type)) {
     return mobile_apis::Result::UNSUPPORTED_RESOURCE;
   }
@@ -1403,30 +1826,31 @@ bool MessageHelper::VerifySoftButtonText
 }
 
 mobile_apis::Result::eType MessageHelper::ProcessSoftButtons(
-    smart_objects::SmartObject& message_params, ApplicationConstSharedPtr app) {
+  smart_objects::SmartObject& message_params, ApplicationConstSharedPtr app) {
   if (!message_params.keyExists(strings::soft_buttons)) {
     return mobile_apis::Result::SUCCESS;
   }
 
   const HMICapabilities& hmi_capabilities =
-      ApplicationManagerImpl::instance()->hmi_capabilities();
+    ApplicationManagerImpl::instance()->hmi_capabilities();
   const smart_objects::SmartObject* soft_button_capabilities =
-      hmi_capabilities.soft_button_capabilities();
+    hmi_capabilities.soft_button_capabilities();
   bool image_supported = false;
   if (soft_button_capabilities) {
     image_supported =
-         (*soft_button_capabilities)[hmi_response::image_supported].asBool();
+      (*soft_button_capabilities)[hmi_response::image_supported].asBool();
   }
 
   smart_objects::SmartObject& request_soft_buttons =
-      message_params[strings::soft_buttons];
+    message_params[strings::soft_buttons];
 
   // Check whether soft buttons request is well-formed
-  if (!ValidateSoftButtons(request_soft_buttons))
+  if (!ValidateSoftButtons(request_soft_buttons)) {
     return mobile_apis::Result::INVALID_DATA;
+  }
 
   smart_objects::SmartObject soft_buttons = smart_objects::SmartObject(
-      smart_objects::SmartType_Array);
+        smart_objects::SmartType_Array);
   bool flag_unsuported_resource = false;
 
   int32_t j = 0;
@@ -1439,7 +1863,7 @@ mobile_apis::Result::eType MessageHelper::ProcessSoftButtons(
 
         if (request_soft_buttons[i].keyExists(strings::image)) {
           mobile_apis::Result::eType verification_result = VerifyImage(
-              request_soft_buttons[i][strings::image], app);
+                request_soft_buttons[i][strings::image], app);
 
           if (mobile_apis::Result::SUCCESS != verification_result) {
             if (mobile_apis::Result::UNSUPPORTED_RESOURCE ==
@@ -1482,7 +1906,7 @@ mobile_apis::Result::eType MessageHelper::ProcessSoftButtons(
         }
         if (image_exist) {
           mobile_apis::Result::eType verification_result = VerifyImage(
-              request_soft_buttons[i][strings::image], app);
+                request_soft_buttons[i][strings::image], app);
 
           if (mobile_apis::Result::SUCCESS != verification_result) {
             if (mobile_apis::Result::UNSUPPORTED_RESOURCE ==
@@ -1506,7 +1930,7 @@ mobile_apis::Result::eType MessageHelper::ProcessSoftButtons(
 
     if (!soft_buttons[j].keyExists(strings::system_action)) {
       soft_buttons[j][strings::system_action] =
-          mobile_apis::SystemAction::DEFAULT_ACTION;
+        mobile_apis::SystemAction::DEFAULT_ACTION;
     }
 
     ++j;
index acbdc7c..dc2ee03 100644 (file)
@@ -184,7 +184,7 @@ uint32_t PolicyHandler::GetAppIdForSending() {
   return selected_app_id;
 }
 
-DeviceConsent PolicyHandler::GetDeviceForSending(DeviceInfo& device_info) {
+DeviceConsent PolicyHandler::GetDeviceForSending(DeviceParams& device_params) {
   uint32_t app_id = 0;
   uint32_t app_id_previous = 0;
   while (true) {
@@ -205,25 +205,31 @@ DeviceConsent PolicyHandler::GetDeviceForSending(DeviceInfo& device_info) {
     char buffer[16];
     snprintf(buffer, 16, "%d", app_id);
     application_manager::MessageHelper::GetDeviceInfoForApp(std::string(buffer),
-        &device_info);
+                                                            &device_params);
 
     DeviceConsent consent =
-      policy_manager_->GetUserConsentForDevice(device_info.device_mac_address);
+        policy_manager_->GetUserConsentForDevice(device_params.device_mac_address);
     switch (consent) {
-      case kDeviceAllowed:
-        return consent;
-      case kDeviceDisallowed:
-        continue;
-      case kDeviceHasNoConsent:
-        return consent;
-      default:
-        LOG4CXX_WARN(logger_, "Consent result is not impelemented.");
-        return consent;
+    case kDeviceAllowed:
+      return consent;
+    case kDeviceDisallowed:
+      continue;
+    case kDeviceHasNoConsent:
+      return consent;
+    default:
+      LOG4CXX_WARN(logger_, "Consent result is not impelemented.");
+      return consent;
     }
   }
   return kDeviceDisallowed;
 }
 
+void PolicyHandler::SetDeviceInfo(std::string& device_id,
+                                  const DeviceInfo& device_info) {
+  LOG4CXX_INFO(logger_, "SetDeviceInfo");
+  policy_manager_->SetDeviceInfo(device_id, device_info);
+}
+
 void PolicyHandler::OnAppRevoked(const std::string& policy_app_id) {
   LOG4CXX_INFO(logger_, "OnAppRevoked");
   const ApplicationList app_list =
@@ -324,18 +330,18 @@ void PolicyHandler::StartPTExchange(bool skip_device_selection) {
   }
 
   if (!skip_device_selection) {
-    DeviceInfo device_info;
-    DeviceConsent consent = GetDeviceForSending(device_info);
+    DeviceParams device_params;
+    DeviceConsent consent = GetDeviceForSending(device_params);
     switch (consent) {
-      case kDeviceHasNoConsent:
-        // Send OnSDLConsentNeeded to HMI for user consent on device usage
-        pending_device_handles_.push_back(device_info.device_handle);
-        application_manager::MessageHelper::SendOnSDLConsentNeeded(device_info);
-        return;
-      case kDeviceDisallowed:
-        return;
-      default:
-        break;
+    case kDeviceHasNoConsent:
+      // Send OnSDLConsentNeeded to HMI for user consent on device usage
+      pending_device_handles_.push_back(device_params.device_handle);
+      application_manager::MessageHelper::SendOnSDLConsentNeeded(device_params);
+      return;
+    case kDeviceDisallowed:
+      return;
+    default:
+      break;
     }
   }
 
@@ -358,11 +364,11 @@ void PolicyHandler::OnAllowSDLFunctionalityNotification(bool is_allowed,
     uint32_t device_id) {
   LOG4CXX_INFO(logger_, "OnAllowSDLFunctionalityNotification");
   if (device_id) {
-    DeviceInfo device_info;
+    DeviceParams device_params;
     application_manager::MessageHelper::GetDeviceInfoForHandle(device_id,
-        &device_info);
-    policy_manager_->SetUserConsentForDevice(device_info.device_mac_address,
-        is_allowed);
+                                                               &device_params);
+    policy_manager_->SetUserConsentForDevice(device_params.device_mac_address,
+                                             is_allowed);
 
     DeviceHandles::iterator it = std::find(pending_device_handles_.begin(),
                                            pending_device_handles_.end(),
diff --git a/src/components/application_manager/src/usage_statistics.cc b/src/components/application_manager/src/usage_statistics.cc
new file mode 100644 (file)
index 0000000..18cd5c3
--- /dev/null
@@ -0,0 +1,117 @@
+/**
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "application_manager/usage_statistics.h"
+
+#include "smart_objects/enum_schema_item.h"
+#include "usage_statistics/statistics_manager.h"
+#include "utils/macro.h"
+
+using namespace mobile_apis;
+using namespace NsSmartDeviceLink::NsSmartObjects;
+using namespace usage_statistics;
+
+namespace application_manager {
+
+namespace {
+
+std::string LanguageIdToString(Language::eType lang_id) {
+  typedef std::map<Language::eType, std::string> EnumMap;
+  const EnumMap& enum_map =
+    TEnumSchemaItem<Language::eType>::getEnumElementsStringRepresentation();
+  EnumMap::const_iterator found = enum_map.find(lang_id);
+  if (found != enum_map.end()) {
+    return found->second;
+  } else {
+    return "unknown";
+  }
+}
+
+}  // namespace
+
+ApplicationUsageReport::ApplicationUsageReport(
+    const std::string& app_id,
+    usage_statistics::StatisticsManager* statistics_manager)
+  : time_in_hmi_state_(statistics_manager, app_id),
+    app_registration_language_gui_(statistics_manager, app_id,
+                                   LANGUAGE_GUI),
+    app_registration_language_vui_(statistics_manager, app_id,
+                                   LANGUAGE_VUI),
+    count_of_rejected_rpc_calls_(statistics_manager, app_id,
+                              REJECTED_RPC_CALLS),
+    count_of_rpcs_sent_in_hmi_none_(statistics_manager, app_id,
+                              RPCS_IN_HMI_NONE) {
+  time_in_hmi_state_.Start(SECONDS_HMI_NONE);
+}
+
+void ApplicationUsageReport::RecordHmiStateChanged(
+    mobile_apis::HMILevel::eType new_hmi_level) {
+  using namespace mobile_apis::HMILevel;
+  AppStopwatchId next_stopwatch = SECONDS_HMI_NONE;
+  switch(new_hmi_level) {
+    case HMI_FULL:
+      next_stopwatch = SECONDS_HMI_FULL;
+      break;
+    case HMI_LIMITED:
+      next_stopwatch = SECONDS_HMI_LIMITED;
+      break;
+    case HMI_BACKGROUND:
+      next_stopwatch = SECONDS_HMI_BACKGROUND;
+      break;
+    case HMI_NONE:
+      next_stopwatch = SECONDS_HMI_NONE;
+      break;
+    default:
+      NOTREACHED();
+  }
+  time_in_hmi_state_.Switch(next_stopwatch);
+}
+
+void ApplicationUsageReport::RecordAppRegistrationGuiLanguage(
+    Language::eType gui_language) {
+  app_registration_language_gui_.Update(LanguageIdToString(gui_language));
+}
+
+void ApplicationUsageReport::RecordAppRegistrationVuiLanguage(
+    mobile_apis::Language::eType vui_language) {
+  app_registration_language_gui_.Update(LanguageIdToString(vui_language));
+}
+
+void ApplicationUsageReport::RecordRpcSentInHMINone() {
+  ++count_of_rpcs_sent_in_hmi_none_;
+}
+
+void ApplicationUsageReport::RecordPolicyRejectedRpcCall() {
+  ++count_of_rejected_rpc_calls_;
+}
+
+}  // namespace application_manager
index 0349dc2..9365019 100644 (file)
@@ -60,6 +60,8 @@ include_directories (
   ../config_profile/include/
   ../../thirdPartyLibs/jsoncpp/include/
   ${CMAKE_BINARY_DIR}/src/components/
+  ${CMAKE_SOURCE_DIR}/src/components/policy/src/policy/include/
+  ${CMAKE_SOURCE_DIR}/src/components/policy/src/policy/usage_statistics/include/
   ${default_includes}
 )
 
@@ -73,7 +75,3 @@ set (SOURCES
 
 add_library("MediaManager" ${SOURCES} ${default_sources})
 target_link_libraries("MediaManager" ${LIBRARIES})
-
-if( BUILD_SHARED_LIBS )
-  install (FILES ${CMAKE_CURRENT_BINARY_DIR}/libMediaManager.so DESTINATION lib)
-endif()