+++ /dev/null
-/**
- * \file appMain.cpp
- * \brief SmartDeviceLink main application sources
- * Copyright (c) 2013, 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 <sys/stat.h>
-#include <signal.h>
-#include <fcntl.h>
-#include <unistd.h>
-//#include <getopt.h>
-#include <cstdio>
-#include <cstdlib>
-#include <vector>
-#include <string>
-#include <iostream> // cpplint: Streams are highly discouraged.
-#include <fstream> // cpplint: Streams are highly discouraged.
-
-// ----------------------------------------------------------------------------
-
-#include "./appMain.h"
-
-#include "utils/macro.h"
-#include "utils/logger.h"
-#include "config_profile/profile.h"
-
-#include "mobile_message_handler/mobile_message_handler_impl.h"
-#include "hmi_message_handler/hmi_message_handler_impl.h"
-#include "hmi_message_handler/messagebroker_adapter.h"
-#include "application_manager/application_manager_impl.h"
-#include "connection_handler/connection_handler_impl.h"
-#include "protocol_handler/protocol_handler_impl.h"
-#include "transport_manager/transport_manager.h"
-#include "transport_manager/transport_manager_default.h"
-// ----------------------------------------------------------------------------
-// Third-Party includes
-
-#include "CMessageBroker.hpp"
-#include "mb_tcpserver.hpp"
-#include "networking.h" // cpplint: Include the directory when naming .h files
-#include "system.h" // cpplint: Include the directory when naming .h files
-
-// ----------------------------------------------------------------------------
-
-#ifdef __cplusplus
-extern "C" void __gcov_flush();
-#endif
-
-namespace {
-
-const char kBrowser[] = "/usr/bin/chromium-browser";
-const char kBrowserName[] = "chromium-browser";
-const char kBrowserParams[] = "--auth-schemes=basic,digest,ntlm";
-
-/**
- * Initialize MessageBroker component
- * @return true if success otherwise false.
- */
-bool InitMessageBroker() { // TODO(AK): check memory allocation here.
- log4cxx::LoggerPtr logger = log4cxx::LoggerPtr(
- log4cxx::Logger::getLogger("appMain"));
-
- NsMessageBroker::CMessageBroker* message_broker =
- NsMessageBroker::CMessageBroker::getInstance();
- if (!message_broker) {
- LOG4CXX_INFO(logger, " Wrong pMessageBroker pointer!");
- return false;
- }
-
- NsMessageBroker::TcpServer* message_broker_server =
- new NsMessageBroker::TcpServer(
- profile::Profile::instance()->server_address(),
- profile::Profile::instance()->server_port(),
- message_broker);
- if (!message_broker_server) {
- LOG4CXX_INFO(logger, " Wrong pJSONRPC20Server pointer!");
- return false;
- }
- message_broker->startMessageBroker(message_broker_server);
- if (!networking::init()) {
- LOG4CXX_INFO(logger, " Networking initialization failed!");
- return false;
- }
-
- if (!message_broker_server->Bind()) {
- LOG4CXX_FATAL(logger, "Bind failed!");
- return false;
- } else {
- LOG4CXX_INFO(logger, "Bind successful!");
- }
-
- if (!message_broker_server->Listen()) {
- LOG4CXX_FATAL(logger, "Listen failed!");
- return false;
- } else {
- LOG4CXX_INFO(logger, " Listen successful!");
- }
-
- hmi_message_handler::MessageBrokerAdapter* mb_adapter =
- new hmi_message_handler::MessageBrokerAdapter(
- hmi_message_handler::HMIMessageHandlerImpl::instance());
-
- hmi_message_handler::HMIMessageHandlerImpl::instance()->AddHMIMessageAdapter(
- mb_adapter);
- if (!mb_adapter->Connect()) {
- LOG4CXX_INFO(logger, "Cannot connect to remote peer!");
- return false;
- }
-
- LOG4CXX_INFO(logger, "Start CMessageBroker thread!");
- System::Thread* th1 = new System::Thread(
- new System::ThreadArgImpl<NsMessageBroker::CMessageBroker>(
- *message_broker, &NsMessageBroker::CMessageBroker::MethodForThread,
- NULL));
- th1->Start(false);
-
- LOG4CXX_INFO(logger, "Start MessageBroker TCP server thread!");
- System::Thread* th2 = new System::Thread(
- new System::ThreadArgImpl<NsMessageBroker::TcpServer>(
- *message_broker_server, &NsMessageBroker::TcpServer::MethodForThread,
- NULL));
- th2->Start(false);
-
- LOG4CXX_INFO(logger, "StartAppMgr JSONRPC 2.0 controller receiver thread!");
- System::Thread* th3 = new System::Thread(
- new System::ThreadArgImpl<hmi_message_handler::MessageBrokerAdapter>(
- *mb_adapter,
- &hmi_message_handler::MessageBrokerAdapter::MethodForReceiverThread,
- NULL));
- th3->Start(false);
-
- mb_adapter->registerController();
- mb_adapter->SubscribeTo();
-
- return true;
-}
-
-/**
- * Initialize HTML based HMI.
- * @return true if success otherwise false.
- */
-bool InitHmi() {
- log4cxx::LoggerPtr logger = log4cxx::LoggerPtr(
- log4cxx::Logger::getLogger("appMain"));
-
- pid_t pid_hmi = 0;
- struct stat sb;
- if (stat("hmi_link", &sb) == -1) {
- LOG4CXX_INFO(logger, "File with HMI link doesn't exist!");
- return false;
- }
-
- std::ifstream file_str;
- file_str.open("hmi_link");
-
- if (!file_str.is_open()) {
- LOG4CXX_INFO(logger, "File with HMI link was not opened!");
- return false;
- }
-
- file_str.seekg(0, std::ios::end);
- int length = file_str.tellg();
- file_str.seekg(0, std::ios::beg);
-
- char* raw_data = new char[length + 1];
- if (!raw_data) {
- LOG4CXX_INFO(logger, "Memory allocation failed.");
- return false;
- }
-
- memset(raw_data, 0, length + 1);
- file_str.getline(raw_data, length + 1);
- std::string hmi_link = std::string(raw_data, strlen(raw_data));
- delete[] raw_data;
-
- LOG4CXX_INFO(logger,
- "Input string:" << hmi_link << " length = " << hmi_link.size());
- file_str.close();
-
- if (stat(hmi_link.c_str(), &sb) == -1) {
- LOG4CXX_INFO(logger, "HMI index.html doesn't exist!");
- return false;
- }
- // Create a child process.
- pid_hmi = fork();
-
- switch (pid_hmi) {
- case -1: { // Error
- LOG4CXX_INFO(logger, "fork() failed!");
- return false;
- }
- case 0: { // Child process
- int fd_dev0 = open("/dev/null", O_RDWR, S_IWRITE);
- if (0 > fd_dev0) {
- LOG4CXX_WARN(logger, "Open dev0 failed!");
- return false;
- }
- // close input/output file descriptors.
- close(STDIN_FILENO);
- close(STDOUT_FILENO);
- close(STDERR_FILENO);
-
- // move input/output to /dev/null.
- dup2(fd_dev0, STDIN_FILENO);
- dup2(fd_dev0, STDOUT_FILENO);
- dup2(fd_dev0, STDERR_FILENO);
-
- // Execute the program.
- execlp(kBrowser, kBrowserName, kBrowserParams, hmi_link.c_str(),
- reinterpret_cast<char*>(0));
- LOG4CXX_WARN(logger, "execl() failed! Install chromium-browser!");
-
- return true;
- }
- default: { /* Parent process */
- LOG4CXX_INFO(logger, "Process created with pid " << pid_hmi);
- return true;
- }
- }
-}
-}
-
-void flushCoverageInfo() {
- log4cxx::LoggerPtr logger = log4cxx::LoggerPtr(
- log4cxx::Logger::getLogger("appMain"));
- LOG4CXX_INFO(logger, "Flush code coverage info");
-#ifdef __cplusplus
- __gcov_flush();
-#endif
-}
-
-/**
- * \brief Entry point of the program.
- * \param argc number of argument
- * \param argv array of arguments
- * \return EXIT_SUCCESS or EXIT_FAILURE
- */
-int main(int argc, char** argv) {
-
- // --------------------------------------------------------------------------
- // Logger initialization
-
- log4cxx::LoggerPtr logger = log4cxx::LoggerPtr(
- log4cxx::Logger::getLogger("appMain"));
- //log4cxx::PropertyConfigurator::configure("log4cxx.properties");
-
- /*bool shouldReturn = false;
- bool shouldFlush = false;
- int next_option;
-
- const char* const short_options = "hf";
- const struct option long_options[] = {
- { "help", 0, NULL, 'h' },
- { "flush", 0, NULL, 'f' },
- { NULL, 0, NULL, 0 }
- };
-
- do
- {
- next_option = getopt_long(argc, argv, short_options,
- long_options, NULL);
-
- switch(next_option) {
- case 'h':
- LOG4CXX_INFO(logger, "-h or --help");
- shouldReturn = true;
- break;
- case 'f':
- LOG4CXX_INFO(logger, "-f or --flush flag");
- // -f or --flush flag
- shouldFlush = true;
- break;
- case '?':
- LOG4CXX_INFO(logger, "Wrong input");
- shouldReturn = true;
- break;
- case -1:
- LOG4CXX_INFO(logger, "No more options");
- break;
- default:
- break;
- }
- }
- while (next_option != -1);
-
- // Check shouldReturn fist
- if(shouldReturn) {
- return 0;
- }
-
- if(shouldFlush) {
- flushCoverageInfo();
- return 0;
- }*/
-
- LOG4CXX_INFO(logger, " Application started!");
-
- // --------------------------------------------------------------------------
- // Components initialization
-
- profile::Profile::instance()->config_file_name("smartDeviceLink.ini");
-
- ::transport_manager::TransportManager* transport_manager =
- ::transport_manager::TransportManagerDefault::Instance();
- DCHECK(transport_manager);
-
- protocol_handler::ProtocolHandlerImpl* protocol_handler =
- new protocol_handler::ProtocolHandlerImpl(transport_manager);
- DCHECK(protocol_handler);
-
- mobile_message_handler::MobileMessageHandlerImpl* mmh =
- mobile_message_handler::MobileMessageHandlerImpl::instance();
- DCHECK(mmh);
-
- connection_handler::ConnectionHandlerImpl* connection_handler =
- connection_handler::ConnectionHandlerImpl::instance();
- DCHECK(connection_handler);
-
- application_manager::ApplicationManagerImpl* app_manager =
- application_manager::ApplicationManagerImpl::instance();
- DCHECK(app_manager);
-
- hmi_message_handler::HMIMessageHandlerImpl* hmi_handler =
- hmi_message_handler::HMIMessageHandlerImpl::instance();
- DCHECK(hmi_handler)
-
- transport_manager->SetProtocolHandler(protocol_handler);
- transport_manager->AddEventListener(protocol_handler);
- transport_manager->AddEventListener(connection_handler);
-
- mmh->set_protocol_handler(protocol_handler);
- hmi_handler->set_message_observer(app_manager);
-
- protocol_handler->set_session_observer(connection_handler);
- protocol_handler->set_protocol_observer(mmh);
-
- connection_handler->set_transport_manager(transport_manager);
- connection_handler->set_connection_handler_observer(app_manager);
-
- app_manager->set_mobile_message_handler(mmh);
- mmh->AddMobileMessageListener(app_manager);
- app_manager->set_connection_handler(connection_handler);
- app_manager->set_hmi_message_handler(hmi_handler);
-
- // --------------------------------------------------------------------------
- // Third-Party components initialization.
-
- if (!InitMessageBroker()) {
- exit(EXIT_FAILURE);
- }
- /*LOG4CXX_INFO(logger, "InitMessageBroker successful");*/
-
- /* if (!InitHmi()) {
- exit(EXIT_FAILURE);
- }*/
- /*LOG4CXX_INFO(logger, "InitHmi successful");*/
-
- // --------------------------------------------------------------------------
-
- while (true) {
- sleep(100500);
- }
-}
-
+++ /dev/null
-/*
- * Copyright (c) 2013, 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.
- */
-/**
- * @name SDL.MediaNavigationView
- * @desc Navigation component
- * @category View
- * @filesource app/view/mediaNavigationView.js
- * @version 1.0
- */
-SDL.MediaNavigationView = Em.ContainerView.create( {
- /** View Id */
- elementId: 'MediaNavigationView',
-
- classNameBindings: [
- 'SDL.States.media.mediaNavigation.active:active_state:inactive_state'
- ],
-
- childViews: [
- 'videoView',
- SDL.BaseNavigationView
- ],
-
- actionMove:function(event){
-
- if (event.originalEvent.type == 'touchmove') {
- SDL.SDLModel.onTouchEvent(event);
- }
- },
-
- actionUp:function(event){
-
-
- if (event.originalEvent.type == 'touchend') {
- SDL.SDLModel.onTouchEvent(event);
- }
- },
- actionDown:function(event){
- if (event.originalEvent.type == 'mousedown') {
- SDL.SDLModel.onTouchEvent(event);
- }
- },
-
- actionDown:function(event){
-
-
- if (event.originalEvent.type == 'touchstart') {
- SDL.SDLModel.onTouchEvent(event);
- }
- },
-
- videoView: Ember.View.extend({
- templateName: "video",
- template: Ember.Handlebars.compile('<video id="html5Player"></video>')
- })
-
-});
+++ /dev/null
-/**
- * Copyright (c) 2013, 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 <climits>
-#include "application_manager/application_manager_impl.h"
-#include "application_manager/application.h"
-#include "application_manager/mobile_command_factory.h"
-#include "application_manager/hmi_command_factory.h"
-#include "application_manager/commands/command_impl.h"
-#include "application_manager/commands/command_notification_impl.h"
-#include "application_manager/message_chaining.h"
-#include "media_manager/audio_stream_sender_thread.h"
-#include "application_manager/message_helper.h"
-#include "connection_handler/connection_handler_impl.h"
-#include "mobile_message_handler/mobile_message_handler_impl.h"
-#include "formatters/formatter_json_rpc.h"
-#include "formatters/CFormatterJsonSDLRPCv2.hpp"
-#include "config_profile/profile.h"
-#include "utils/threads/thread.h"
-#include "utils/file_system.h"
-#include "utils/logger.h"
-#include "./from_hmh_thread_impl.h"
-#include "./to_hmh_thread_impl.h"
-#include "./from_mobile_thread_impl.h"
-#include "./to_mobile_thread_impl.h"
-
-namespace application_manager {
-
-log4cxx::LoggerPtr ApplicationManagerImpl::logger_ = log4cxx::LoggerPtr(
- log4cxx::Logger::getLogger("ApplicationManager"));
-unsigned int ApplicationManagerImpl::message_chain_current_id_ = 0;
-const unsigned int ApplicationManagerImpl::message_chain_max_id_ = UINT_MAX;
-
-namespace formatters = NsSmartDeviceLink::NsJSONHandler::Formatters;
-namespace jhs = NsSmartDeviceLink::NsJSONHandler::strings;
-
-ApplicationManagerImpl::ApplicationManagerImpl()
- : audio_pass_thru_flag_(false),
- is_distracting_driver_(false),
- is_vr_session_strated_(false),
- hmi_cooperating_(false),
- is_all_apps_allowed_(true),
- ui_language_(hmi_apis::Common_Language::INVALID_ENUM),
- vr_language_(hmi_apis::Common_Language::INVALID_ENUM),
- tts_language_(hmi_apis::Common_Language::INVALID_ENUM),
- vehicle_type_(NULL),
- hmi_handler_(NULL),
- mobile_handler_(NULL),
- connection_handler_(NULL),
- from_mobile_thread_(NULL),
- to_mobile_thread_(NULL),
- from_hmh_thread_(NULL),
- to_hmh_thread_(NULL),
- hmi_so_factory_(NULL),
- request_ctrl(),
- media_manager_(NULL) {
- LOG4CXX_INFO(logger_, "Creating ApplicationManager");
- from_mobile_thread_ = new threads::Thread(
- "application_manager::FromMobileThreadImpl",
- new FromMobileThreadImpl(this));
- if (!InitThread(from_mobile_thread_)) {
- return;
- }
- to_mobile_thread_ = new threads::Thread(
- "application_manager::ToMobileThreadImpl", new ToMobileThreadImpl(this));
- if (!InitThread(to_mobile_thread_)) {
- return;
- }
-
- to_hmh_thread_ = new threads::Thread("application_manager::ToHMHThreadImpl",
- new ToHMHThreadImpl(this));
- if (!InitThread(to_hmh_thread_)) {
- return;
- }
-
- from_hmh_thread_ = new threads::Thread(
- "application_manager::FromHMHThreadImpl", new FromHMHThreadImpl(this));
- if (!InitThread(from_hmh_thread_)) {
- return;
- }
-
- if (!policies_manager_.Init()) {
- LOG4CXX_ERROR(logger_, "Policies manager initialization failed.");
- return;
- }
-
- media_manager_ = media_manager::MediaManagerImpl::getMediaManager();
-}
-
-bool ApplicationManagerImpl::InitThread(threads::Thread* thread) {
- if (!thread) {
- LOG4CXX_ERROR(logger_, "Failed to allocate memory for thread object");
- return false;
- }
- LOG4CXX_INFO(
- logger_,
- "Starting thread with stack size "
- << profile::Profile::instance()->thread_min_stach_size());
- if (!thread->start()) {
- /*startWithOptions(
- threads::ThreadOptions(
- profile::Profile::instance()->thread_min_stach_size()))*/
- LOG4CXX_ERROR(logger_, "Failed to start thread");
- return false;
- }
- return true;
-}
-
-ApplicationManagerImpl::~ApplicationManagerImpl() {
- LOG4CXX_INFO(logger_, "Desctructing ApplicationManager.");
- message_chaining_.clear();
-
- if (vehicle_type_) {
- delete vehicle_type_;
- }
-
- if (from_mobile_thread_) {
- from_mobile_thread_->stop();
- delete from_mobile_thread_;
- from_mobile_thread_ = NULL;
- }
-
- if (to_hmh_thread_) {
- to_hmh_thread_->stop();
- delete to_hmh_thread_;
- to_hmh_thread_ = NULL;
- }
-
- if (from_hmh_thread_) {
- from_hmh_thread_->stop();
- delete from_hmh_thread_;
- from_hmh_thread_ = NULL;
- }
-
- if (to_mobile_thread_) {
- to_mobile_thread_->stop();
- delete to_mobile_thread_;
- to_mobile_thread_ = NULL;
- }
-
- message_chaining_.clear();
-
- if (media_manager_) {
- delete media_manager_;
- }
-}
-
-ApplicationManagerImpl* ApplicationManagerImpl::instance() {
- static ApplicationManagerImpl instance;
- return &instance;
-}
-
-Application* ApplicationManagerImpl::application(int app_id) {
- std::map<int, Application*>::iterator it = applications_.find(app_id);
- if (applications_.end() != it) {
- return it->second;
- } else {
- return NULL;
- }
-}
-
-Application* ApplicationManagerImpl::active_application() const {
- // TODO(DK) : check driver distraction
- for (std::set<Application*>::iterator it = application_list_.begin();
- application_list_.end() != it;
- ++it) {
- if ((*it)->IsFullscreen()) {
- return *it;
- }
- }
- return NULL;
-}
-
-std::vector<Application*> ApplicationManagerImpl::applications_by_button(
- unsigned int button) {
- std::vector<Application*> result;
- for (std::set<Application*>::iterator it = application_list_.begin();
- application_list_.end() != it; ++it) {
- if ((*it)->IsSubscribedToButton(
- static_cast<mobile_apis::ButtonName::eType>(button))) {
- result.push_back(*it);
- }
- }
- return result;
-}
-
-std::vector<Application*> ApplicationManagerImpl::applications_by_ivi(
- unsigned int vehicle_info) {
- std::vector<Application*> result;
- for (std::set<Application*>::iterator it = application_list_.begin();
- application_list_.end() != it;
- ++it) {
- if ((*it)->IsSubscribedToIVI(vehicle_info)) {
- result.push_back(*it);
- }
- }
- return result;
-}
-
-std::vector<Application*> ApplicationManagerImpl::applications_with_navi() {
- std::vector<Application*> result;
- for (std::set<Application*>::iterator it = application_list_.begin();
- application_list_.end() != it;
- ++it) {
- if ((*it)->allowed_support_navigation()) {
- result.push_back(*it);
- }
- }
- return result;
-}
-
-const std::set<connection_handler::Device>&
-ApplicationManagerImpl::device_list() {
- // TODO(PV): add updating functionality - request to TM.
- std::set<connection_handler::Device> devices;
- return devices;
-}
-
-Application* ApplicationManagerImpl::RegisterApplication(
- const utils::SharedPtr<smart_objects::SmartObject>&
- request_for_registration) {
- DCHECK(request_for_registration);
- smart_objects::SmartObject& message = *request_for_registration;
- unsigned int connection_key =
- message[strings::params][strings::connection_key];
-
- if (false == is_all_apps_allowed_) {
- LOG4CXX_INFO(logger_,
- "RegisterApplication: access to app's disabled by user");
- utils::SharedPtr<smart_objects::SmartObject> response(
- MessageHelper::CreateNegativeResponse(
- connection_key, mobile_apis::FunctionID::RegisterAppInterfaceID,
- message[strings::params][strings::correlation_id],
- mobile_apis::Result::DISALLOWED));
- ManageMobileCommand(response);
- return NULL;
- }
-
- unsigned int app_id = 0;
- std::list<int> sessions_list;
- unsigned int device_id = 0;
-
- if (connection_handler_) {
- connection_handler::ConnectionHandlerImpl* con_handler_impl =
- static_cast<connection_handler::ConnectionHandlerImpl*>(connection_handler_);
- if (con_handler_impl->GetDataOnSessionKey(connection_key, &app_id,
- &sessions_list, &device_id)
- == -1) {
- LOG4CXX_ERROR(logger_,
- "Failed to create application: no connection info.");
- utils::SharedPtr<smart_objects::SmartObject> response(
- MessageHelper::CreateNegativeResponse(
- connection_key, mobile_apis::FunctionID::RegisterAppInterfaceID,
- message[strings::params][strings::correlation_id],
- mobile_apis::Result::GENERIC_ERROR));
- ManageMobileCommand(response);
- return NULL;
- }
- }
-
- if (!MessageHelper::VerifyApplicationName(message[strings::msg_params])) {
-
- utils::SharedPtr<smart_objects::SmartObject> response(
- MessageHelper::CreateNegativeResponse(
- connection_key, mobile_apis::FunctionID::RegisterAppInterfaceID,
- message[strings::params][strings::correlation_id],
- mobile_apis::Result::INVALID_DATA));
- ManageMobileCommand(response);
- return NULL;
- }
-
- const std::string& name =
- message[strings::msg_params][strings::app_name].asString();
-
- for (std::set<Application*>::iterator it = application_list_.begin();
- application_list_.end() != it;
- ++it) {
- if ((*it)->app_id() == app_id) {
- LOG4CXX_ERROR(logger_, "Application has been registered already.");
- utils::SharedPtr<smart_objects::SmartObject> response(
- MessageHelper::CreateNegativeResponse(
- connection_key, mobile_apis::FunctionID::RegisterAppInterfaceID,
- message[strings::params][strings::correlation_id],
- mobile_apis::Result::APPLICATION_REGISTERED_ALREADY));
- ManageMobileCommand(response);
- return NULL;
- }
-
- if ((*it)->name().compare(name) == 0) {
- LOG4CXX_ERROR(logger_, "Application with this name already registered.");
- utils::SharedPtr<smart_objects::SmartObject> response(
- MessageHelper::CreateNegativeResponse(
- connection_key, mobile_apis::FunctionID::RegisterAppInterfaceID,
- message[strings::params][strings::correlation_id],
- mobile_apis::Result::DUPLICATE_NAME));
- ManageMobileCommand(response);
- return NULL;
- }
- }
-
- Application* application = new ApplicationImpl(app_id);
- if (!application) {
- utils::SharedPtr<smart_objects::SmartObject> response(
- MessageHelper::CreateNegativeResponse(
- connection_key, mobile_apis::FunctionID::RegisterAppInterfaceID,
- message[strings::params][strings::correlation_id],
- mobile_apis::Result::OUT_OF_MEMORY));
- ManageMobileCommand(response);
- return NULL;
- }
-
- application->set_name(name);
- application->set_device(device_id);
-
- application->set_language(
- static_cast<mobile_api::Language::eType>(
- message[strings::msg_params][strings::language_desired].asInt()));
- application->set_ui_language(
- static_cast<mobile_api::Language::eType>(
- message[strings::msg_params][strings::hmi_display_language_desired]
- .asInt()));
-
- Version version;
- int min_version =
- message[strings::msg_params][strings::sync_msg_version]
- [strings::minor_version].asInt();
-
- if (min_version < APIVersion::kAPIV2) {
- LOG4CXX_ERROR(logger_, "UNSUPPORTED_VERSION");
- utils::SharedPtr<smart_objects::SmartObject> response(
- MessageHelper::CreateNegativeResponse(
- connection_key, mobile_apis::FunctionID::RegisterAppInterfaceID,
- message[strings::params][strings::correlation_id],
- mobile_apis::Result::UNSUPPORTED_VERSION));
- ManageMobileCommand(response);
- delete application;
- return NULL;
- }
- version.min_supported_api_version = static_cast<APIVersion>(min_version);
-
- int max_version =
- message[strings::msg_params][strings::sync_msg_version]
- [strings::major_version].asInt();
-
- if (max_version > APIVersion::kAPIV2) {
- LOG4CXX_ERROR(logger_, "UNSUPPORTED_VERSION");
- utils::SharedPtr<smart_objects::SmartObject> response(
- MessageHelper::CreateNegativeResponse(
- connection_key, mobile_apis::FunctionID::RegisterAppInterfaceID,
- message[strings::params][strings::correlation_id],
- mobile_apis::Result::UNSUPPORTED_VERSION));
- ManageMobileCommand(response);
- delete application;
- return NULL;
- }
- version.max_supported_api_version = static_cast<APIVersion>(max_version);
- application->set_version(version);
-
- applications_.insert(std::pair<int, Application*>(app_id, application));
- application_list_.insert(application);
-
- // TODO(PV): add asking user to allow application
- // BasicCommunication_AllowApp
- // application->set_app_allowed(result);
-
- return application;
-}
-
-bool ApplicationManagerImpl::UnregisterApplication(int app_id) {
- std::map<int, Application*>::iterator it = applications_.find(app_id);
- if (applications_.end() == it) {
- return false;
- }
- Application* app_to_remove = it->second;
- applications_.erase(it);
- application_list_.erase(app_to_remove);
- delete app_to_remove;
- return true;
-}
-
-void ApplicationManagerImpl::UnregisterAllApplications(bool hmi_off) {
- applications_.clear();
- for (std::set<Application*>::iterator it = application_list_.begin();
- application_list_.end() != it;
- ++it) {
- delete(*it);
- }
- application_list_.clear();
-
- if (hmi_off) {
- hmi_cooperating_ = false;
- }
-}
-
-bool ApplicationManagerImpl::RemoveAppDataFromHMI(Application* application) {
- return true;
-}
-
-bool ApplicationManagerImpl::LoadAppDataToHMI(Application* application) {
- return true;
-}
-
-bool ApplicationManagerImpl::ActivateApplication(Application* application) {
- DCHECK(application);
-
- if (!application) {
- LOG4CXX_ERROR(logger_, "Null-pointer application received.");
- return false;
- }
-
- bool is_new_app_media = application->is_media_application();
-
- for (std::set<Application*>::iterator it = application_list_.begin();
- application_list_.end() != it;
- ++it) {
- Application* app = *it;
- if (app->app_id() == application->app_id()) {
- if (app->IsFullscreen()) {
- LOG4CXX_WARN(logger_, "Application is already active.");
- return false;
- }
- if (mobile_api::HMILevel::eType::HMI_LIMITED !=
- application->hmi_level()) {
- if (application->has_been_activated()) {
- MessageHelper::SendAppDataToHMI(application);
- } else {
- MessageHelper::SendChangeRegistrationRequestToHMI(application);
- }
- }
- if (!application->MakeFullscreen()) {
- return false;
- }
- MessageHelper::SendHMIStatusNotification(*application);
- } else {
- if (is_new_app_media) {
- if (app->IsAudible()) {
- app->MakeNotAudible();
- MessageHelper::SendHMIStatusNotification(*app);
- }
- }
- if (app->IsFullscreen()) {
- MessageHelper::RemoveAppDataFromHMI(app);
- }
- }
- }
- return true;
-}
-
-
-void ApplicationManagerImpl::DeactivateApplication(Application* application) {
- MessageHelper::SendDeleteCommandRequestToHMI(application);
- MessageHelper::ResetGlobalproperties(application);
-}
-
-void ApplicationManagerImpl::ConnectToDevice(unsigned int id) {
- // TODO(VS): Call function from ConnectionHandler
- if (!connection_handler_) {
- LOG4CXX_WARN(logger_, "Connection handler is not set.");
- return;
- }
-
- connection_handler_->ConnectToDevice(id);
-}
-
-void ApplicationManagerImpl::OnHMIStartedCooperation() {
- hmi_cooperating_ = true;
- LOG4CXX_INFO(logger_, "ApplicationManagerImpl::OnHMIStartedCooperation()");
-
- utils::SharedPtr<smart_objects::SmartObject> is_vr_ready(
- MessageHelper::CreateModuleInfoSO(hmi_apis::FunctionID::VR_IsReady));
- ManageHMICommand(is_vr_ready);
-
- utils::SharedPtr<smart_objects::SmartObject> is_tts_ready(
- MessageHelper::CreateModuleInfoSO(hmi_apis::FunctionID::TTS_IsReady));
- ManageHMICommand(is_tts_ready);
-
- utils::SharedPtr<smart_objects::SmartObject> is_ui_ready(
- MessageHelper::CreateModuleInfoSO(hmi_apis::FunctionID::UI_IsReady));
- ManageHMICommand(is_ui_ready);
-
- utils::SharedPtr<smart_objects::SmartObject> is_navi_ready(
- MessageHelper::CreateModuleInfoSO(
- hmi_apis::FunctionID::Navigation_IsReady));
- ManageHMICommand(is_navi_ready);
-
- utils::SharedPtr<smart_objects::SmartObject> is_ivi_ready(
- MessageHelper::CreateModuleInfoSO(
- hmi_apis::FunctionID::VehicleInfo_IsReady));
- ManageHMICommand(is_ivi_ready);
-
- utils::SharedPtr<smart_objects::SmartObject> button_capabilities(
- MessageHelper::CreateModuleInfoSO(
- hmi_apis::FunctionID::Buttons_GetCapabilities));
- ManageHMICommand(button_capabilities);
-
- if (!connection_handler_) {
- LOG4CXX_WARN(logger_, "Connection handler is not set.");
- } else {
- connection_handler_->StartTransportManager();
- }
-}
-
-unsigned int ApplicationManagerImpl::GetNextHMICorrelationID() {
- if (message_chain_current_id_ < message_chain_max_id_) {
- message_chain_current_id_++;
- } else {
- message_chain_current_id_ = 0;
- }
-
- return message_chain_current_id_;
-}
-
-MessageChaining* ApplicationManagerImpl::AddMessageChain(
- const unsigned int& connection_key, const unsigned int& correlation_id,
- const unsigned int& hmi_correlation_id, MessageChaining* msg_chaining,
- const smart_objects::SmartObject* data) {
- LOG4CXX_INFO(
- logger_,
- "ApplicationManagerImpl::AddMessageChain id " << hmi_correlation_id);
-
- if (NULL == msg_chaining) {
- MessageChaining* chain = new MessageChaining(connection_key,
- correlation_id);
-
- if (chain) {
- if (data) {
- chain->set_data(*data);
- }
-
- MessageChain::iterator it = message_chaining_.find(connection_key);
- if (message_chaining_.end() == it) {
- // Create new HMI request
- HMIRequest hmi_request;
- hmi_request[hmi_correlation_id] = MessageChainPtr(chain);
-
- // create new Mobile request
- MobileRequest mob_request;
- mob_request[correlation_id] = hmi_request;
-
- // add new application
- message_chaining_[connection_key] = mob_request;
- } else {
- // check if mobile correlation ID exist
- MobileRequest::iterator mob_request = it->second.find(correlation_id);
- if (it->second.end() == mob_request) {
- // Create new HMI request
- HMIRequest hmi_request;
- hmi_request[hmi_correlation_id] = MessageChainPtr(chain);
-
- // create new Mobile request
- it->second[correlation_id] = hmi_request;
- } else {
- // Add new HMI request
- mob_request->second[hmi_correlation_id] = MessageChainPtr(chain);
- }
- }
-
- return chain;
- } else {
- LOG4CXX_ERROR(logger_, "Null pointer message received.");
- return NULL;
- }
- } else {
- MessageChain::iterator it = message_chaining_.find(connection_key);
- if (message_chaining_.end() != it) {
- MobileRequest::iterator i = it->second.find(correlation_id);
- if (it->second.end() != i) {
- HMIRequest::iterator j = i->second.begin();
- for (; i->second.end() != j; ++j) {
- if ((*j->second) == *msg_chaining) {
- // copy existing MessageChaining
- i->second[hmi_correlation_id] = j->second;
- return &(*j->second);
- }
- }
- }
- }
- return NULL;
- }
-}
-
-bool ApplicationManagerImpl::DecreaseMessageChain(
- const unsigned int& hmi_correlation_id,
- unsigned int& mobile_correlation_id) {
- LOG4CXX_INFO(
- logger_,
- "ApplicationManagerImpl::DecreaseMessageChain id " << hmi_correlation_id);
-
- bool result = false;
-
- MessageChain::iterator i = message_chaining_.begin();
- for (; message_chaining_.end() != i; ++i) {
- MobileRequest::iterator j = i->second.begin();
- for (; i->second.end() != j; ++j) {
- HMIRequest::iterator it = j->second.find(hmi_correlation_id);
-
- if (j->second.end() != it) {
- (*it->second).DecrementCounter();
- LOG4CXX_INFO(
- logger_,
- "ApplicationManagerImpl::DecreaseMessageChain "
- "mobile request id " << (*it->second).correlation_id()
- << " is waiting for " << (*it->second).counter()
- << " responses");
-
- if (0 == (*it->second).counter()) {
- mobile_correlation_id = (*it->second).correlation_id();
-
- LOG4CXX_INFO(
- logger_,
- "HMI response id " << hmi_correlation_id
- << " is the final for mobile request id "
- << mobile_correlation_id);
-
- j->second.clear();
- i->second.erase(j);
-
- result = true;
- }
- }
- }
- }
-
- return result;
-}
-
-bool ApplicationManagerImpl::RemoveMobileRequestFromMessageChain(
- unsigned int mobile_correlation_id, unsigned int connection_key) {
- LOG4CXX_INFO(
- logger_,
- "ApplicationManagerImpl::RemoveMobileRequestFromMessageChain id "
- << mobile_correlation_id);
-
- bool result = false;
-
- MessageChain::iterator connection_chain = message_chaining_.find(
- connection_key);
- if (connection_chain != message_chaining_.end()) {
- MobileRequest::iterator request = connection_chain->second.find(
- mobile_correlation_id);
- if (request != connection_chain->second.end()) {
- connection_chain->second.erase(request);
- result = true;
- }
- }
-
- return result;
-}
-
-MessageChaining* ApplicationManagerImpl::GetMessageChain(
- const unsigned int& hmi_correlation_id) const {
- LOG4CXX_INFO(
- logger_,
- "ApplicationManagerImpl::GetMessageChain id " << hmi_correlation_id);
-
- MessageChain::const_iterator i = message_chaining_.begin();
- for (; message_chaining_.end() != i; ++i) {
- MobileRequest::const_iterator j = i->second.begin();
- for (; i->second.end() != j; ++j) {
- HMIRequest::const_iterator it = j->second.find(hmi_correlation_id);
-
- if (j->second.end() != it) {
- return &(*it->second);
- }
- }
- }
- return NULL;
-}
-
-bool ApplicationManagerImpl::audio_pass_thru_flag() const {
- return audio_pass_thru_flag_;
-}
-
-void ApplicationManagerImpl::set_audio_pass_thru_flag(bool flag) {
- audio_pass_thru_flag_ = flag;
-}
-
-void ApplicationManagerImpl::set_driver_distraction(bool is_distracting) {
- is_distracting_driver_ = is_distracting;
-}
-
-void ApplicationManagerImpl::set_vr_session_started(const bool& state) {
- is_vr_session_strated_ = state;
-}
-
-void ApplicationManagerImpl::set_active_ui_language(
- const hmi_apis::Common_Language::eType& language) {
- ui_language_ = language;
-}
-
-void ApplicationManagerImpl::set_active_vr_language(
- const hmi_apis::Common_Language::eType& language) {
- vr_language_ = language;
-}
-
-void ApplicationManagerImpl::set_active_tts_language(
- const hmi_apis::Common_Language::eType& language) {
- tts_language_ = language;
-}
-
-void ApplicationManagerImpl::set_vehicle_type(
- const smart_objects::SmartObject& vehicle_type) {
- if (vehicle_type_) {
- delete vehicle_type_;
- }
- vehicle_type_ = new smart_objects::SmartObject(vehicle_type);
-}
-
-const smart_objects::SmartObject*
-ApplicationManagerImpl::vehicle_type() const {
- return vehicle_type_;
-}
-
-void ApplicationManagerImpl::set_all_apps_allowed(const bool& allowed) {
- is_all_apps_allowed_ = allowed;
-}
-
-void ApplicationManagerImpl::StartAudioPassThruThread(int session_key,
- int correlation_id,
- int max_duration,
- int sampling_rate,
- int bits_per_sample,
- int audio_type) {
- LOG4CXX_ERROR(logger_, "START MICROPHONE RECORDER");
- if (NULL != media_manager_) {
- media_manager_->startMicrophoneRecording(std::string("record.wav"),
- static_cast<mobile_apis::SamplingRate::eType>(sampling_rate),
- max_duration,
- static_cast<mobile_apis::BitsPerSample::eType>(bits_per_sample),
- static_cast<unsigned int>(session_key),
- static_cast<unsigned int>(correlation_id));
- }
-}
-
-void ApplicationManagerImpl::SendAudioPassThroughNotification(
- unsigned int session_key,
- unsigned int correlation_id,
- std::vector<unsigned char> binaryData) {
- LOG4CXX_TRACE_ENTER(logger_);
-
- smart_objects::SmartObject* on_audio_pass = NULL;
- on_audio_pass = new smart_objects::SmartObject();
-
- if (NULL == on_audio_pass) {
- LOG4CXX_ERROR_EXT(logger_, "OnAudioPassThru NULL pointer");
-
- return;
- }
-
- LOG4CXX_INFO_EXT(logger_, "Fill smart object");
-
- (*on_audio_pass)[application_manager::strings::params][application_manager::strings::message_type] =
- application_manager::MessageType::kNotification;
- (*on_audio_pass)[application_manager::strings::params][application_manager::strings::correlation_id] =
- static_cast<int>(correlation_id);
-
- (*on_audio_pass)[application_manager::strings::params][application_manager::strings::connection_key] =
- static_cast<int>(session_key);
- (*on_audio_pass)[application_manager::strings::params][application_manager::strings::function_id] =
- mobile_apis::FunctionID::OnAudioPassThruID;
-
- LOG4CXX_INFO_EXT(logger_, "Fill binary data");
- // binary data
- (*on_audio_pass)[application_manager::strings::params][application_manager::strings::binary_data] =
- smart_objects::SmartObject(binaryData);
-
- LOG4CXX_INFO_EXT(logger_, "After fill binary data");
-
- if (audio_pass_thru_flag()) {
-
- LOG4CXX_INFO_EXT(logger_, "Send data");
-
- CommandSharedPtr command = MobileCommandFactory::CreateCommand(&(*on_audio_pass));
- command->Init();
- command->Run();
- command->CleanUp();
- }
-
-}
-
-void ApplicationManagerImpl::StopAudioPassThru() {
- LOG4CXX_TRACE_ENTER(logger_);
-
- if (NULL != media_manager_) {
- media_manager_->stopMicrophoneRecording();
- }
-}
-
-std::string ApplicationManagerImpl::GetDeviceName(
- connection_handler::DeviceHandle handle) {
- DCHECK(connection_handler_);
-
- std::string device_name = "";
- std::list<unsigned int> applications_list;
- connection_handler::ConnectionHandlerImpl* con_handler_impl =
- static_cast<connection_handler::ConnectionHandlerImpl*>(connection_handler_);
- if (con_handler_impl->GetDataOnDeviceID(handle, &device_name,
- &applications_list) == -1) {
- LOG4CXX_ERROR(logger_, "Failed to extract device name for id " << handle);
- } else {
- LOG4CXX_INFO(logger_, "\t\t\t\t\tDevice name is " << device_name);
- }
-
- return device_name;
-}
-
-void ApplicationManagerImpl::set_is_vr_cooperating(bool value) {
- is_vr_ready_response_recieved_ = true;
- is_vr_cooperating_ = value;
- if (is_vr_cooperating_) {
- utils::SharedPtr<smart_objects::SmartObject> get_language(
- MessageHelper::CreateModuleInfoSO(
- hmi_apis::FunctionID::VR_GetLanguage));
- ManageHMICommand(get_language);
- utils::SharedPtr<smart_objects::SmartObject> get_all_languages(
- MessageHelper::CreateModuleInfoSO(
- hmi_apis::FunctionID::VR_GetSupportedLanguages));
- ManageHMICommand(get_all_languages);
- utils::SharedPtr<smart_objects::SmartObject> get_capabilities(
- MessageHelper::CreateModuleInfoSO(
- hmi_apis::FunctionID::VR_GetCapabilities));
- ManageHMICommand(get_capabilities);
-
- MessageHelper::SendHelpVrCommand();
- }
-}
-
-void ApplicationManagerImpl::set_is_tts_cooperating(bool value) {
- is_tts_ready_response_recieved_ = true;
- is_tts_cooperating_ = value;
- if (is_tts_cooperating_) {
- utils::SharedPtr<smart_objects::SmartObject> get_language(
- MessageHelper::CreateModuleInfoSO(
- hmi_apis::FunctionID::TTS_GetLanguage));
- ManageHMICommand(get_language);
- utils::SharedPtr<smart_objects::SmartObject> get_all_languages(
- MessageHelper::CreateModuleInfoSO(
- hmi_apis::FunctionID::TTS_GetSupportedLanguages));
- ManageHMICommand(get_all_languages);
- }
-}
-
-void ApplicationManagerImpl::set_is_ui_cooperating(bool value) {
- is_ui_ready_response_recieved_ = true;
- is_ui_cooperating_ = value;
- if (is_ui_cooperating_) {
- utils::SharedPtr<smart_objects::SmartObject> get_language(
- MessageHelper::CreateModuleInfoSO(
- hmi_apis::FunctionID::UI_GetLanguage));
- ManageHMICommand(get_language);
- utils::SharedPtr<smart_objects::SmartObject> get_all_languages(
- MessageHelper::CreateModuleInfoSO(
- hmi_apis::FunctionID::UI_GetSupportedLanguages));
- ManageHMICommand(get_all_languages);
- utils::SharedPtr<smart_objects::SmartObject> get_capabilities(
- MessageHelper::CreateModuleInfoSO(
- hmi_apis::FunctionID::UI_GetCapabilities));
- ManageHMICommand(get_capabilities);
- }
-}
-
-void ApplicationManagerImpl::set_is_navi_cooperating(bool value) {
- is_navi_ready_response_recieved_ = true;
- is_navi_cooperating_ = value;
-}
-
-void ApplicationManagerImpl::set_is_ivi_cooperating(bool value) {
- is_ivi_ready_response_recieved_ = true;
- is_ivi_cooperating_ = value;
- if (is_ivi_cooperating_) {
- utils::SharedPtr<smart_objects::SmartObject> get_type(
- MessageHelper::CreateModuleInfoSO(
- hmi_apis::FunctionID::VehicleInfo_GetVehicleType));
- ManageHMICommand(get_type);
- }
-}
-
-void ApplicationManagerImpl::OnMobileMessageReceived(
- const MobileMessage& message) {
- LOG4CXX_INFO(logger_, "ApplicationManagerImpl::OnMobileMessageReceived");
-
- DCHECK(message);
- if (!message) {
- LOG4CXX_ERROR(logger_, "Null-pointer message received.");
- return;
- }
-
- messages_from_mobile_.push(message);
-}
-
-void ApplicationManagerImpl::OnMessageReceived(
- utils::SharedPtr<application_manager::Message> message) {
- LOG4CXX_INFO(logger_, "ApplicationManagerImpl::OnMessageReceived");
-
- DCHECK(message);
- if (!message) {
- LOG4CXX_ERROR(logger_, "Null-pointer message received.");
- return;
- }
-
- messages_from_hmh_.push(message);
-}
-
-void ApplicationManagerImpl::OnErrorSending(
- utils::SharedPtr<application_manager::Message> message) {
- return;
-}
-
-void ApplicationManagerImpl::OnDeviceListUpdated(
- const connection_handler::DeviceList& device_list) {
- LOG4CXX_INFO(logger_, "ApplicationManagerImpl::OnDeviceListUpdated");
- smart_objects::SmartObject* update_list = new smart_objects::SmartObject;
- smart_objects::SmartObject& so_to_send = *update_list;
- so_to_send[jhs::S_PARAMS][jhs::S_FUNCTION_ID] =
- hmi_apis::FunctionID::BasicCommunication_UpdateDeviceList;
- so_to_send[jhs::S_PARAMS][jhs::S_MESSAGE_TYPE] =
- hmi_apis::messageType::request;
- so_to_send[jhs::S_PARAMS][jhs::S_PROTOCOL_VERSION] = 2;
- so_to_send[jhs::S_PARAMS][jhs::S_PROTOCOL_TYPE] = 1;
- so_to_send[jhs::S_PARAMS][jhs::S_CORRELATION_ID] = GetNextHMICorrelationID();
- smart_objects::SmartObject* msg_params = MessageHelper::CreateDeviceListSO(
- device_list);
- if (!msg_params) {
- LOG4CXX_WARN(logger_, "Failed to create sub-smart object.");
- delete update_list;
- return;
- }
- so_to_send[jhs::S_MSG_PARAMS] = *msg_params;
- ManageHMICommand(update_list);
-}
-
-void ApplicationManagerImpl::RemoveDevice(
- const connection_handler::DeviceHandle device_handle) {
-}
-
-bool ApplicationManagerImpl::OnSessionStartedCallback(
- connection_handler::DeviceHandle device_handle, int session_key,
- int first_session_key, connection_handler::ServiceType type) {
- LOG4CXX_INFO(logger_, "Started session with type " << type);
- if (connection_handler::ServiceType::kNaviSession == type) {
- LOG4CXX_INFO(logger_, "Mobile Navi session is about to be started.");
-
- // send to HMI startStream request
- char url[100] = {'\0'};
- snprintf(url, sizeof(url) / sizeof(url[0]), "http://%s:%d",
- profile::Profile::instance()->server_address().c_str(),
- profile::Profile::instance()->navi_server_port());
-
- application_manager::MessageHelper::SendNaviStartStream(
- url, session_key);
-
- // !!!!!!!!!!!!!!!!!!!!!!!
- // TODO(DK): add check if navi streaming allowed for this app.
- }
- return true;
-}
-
-void ApplicationManagerImpl::OnSessionEndedCallback(int session_key,
- int first_session_key,
- connection_handler::ServiceType type) {
- LOG4CXX_INFO_EXT(
- logger_,
- "\n\t\t\t\tRemoving session " << session_key << " with first session "
- << first_session_key << " type " << type);
- switch (type) {
- case connection_handler::ServiceType::kRPCSession: {
- LOG4CXX_INFO(logger_, "Remove application.");
- std::map<int, Application*>::iterator it = applications_.find(
- first_session_key);
- if (it == applications_.end()) {
- LOG4CXX_ERROR(logger_, "Trying to remove not existing session.");
- return;
- }
- MessageHelper::RemoveAppDataFromHMI(it->second);
- MessageHelper::SendOnAppUnregNotificationToHMI(it->second);
- UnregisterApplication(first_session_key);
- break;
- }
- case connection_handler::ServiceType::kNaviSession: {
- LOG4CXX_INFO(logger_, "Stop video streaming.");
- application_manager::MessageHelper::SendNaviStopStream(session_key);
- media_manager_->stopVideoStreaming();
- break;
- }
- default:
- LOG4CXX_WARN(logger_, "Unknown type of service to be ended.");
- break;
- }
-}
-
-void ApplicationManagerImpl::set_hmi_message_handler(
- hmi_message_handler::HMIMessageHandler* handler) {
- hmi_handler_ = handler;
-}
-
-void ApplicationManagerImpl::set_mobile_message_handler(
- mobile_message_handler::MobileMessageHandler* handler) {
- mobile_handler_ = handler;
-}
-
-void ApplicationManagerImpl::set_connection_handler(
- connection_handler::ConnectionHandler* handler) {
- connection_handler_ = handler;
-}
-
-void ApplicationManagerImpl::StartDevicesDiscovery() {
- connection_handler::ConnectionHandlerImpl::instance()->
- StartDevicesDiscovery();
-}
-
-void ApplicationManagerImpl::SendMessageToMobile(
- const utils::SharedPtr<smart_objects::SmartObject>& message) {
- LOG4CXX_INFO(logger_, "ApplicationManagerImpl::SendMessageToMobile");
-
- DCHECK(message);
- if (!message) {
- LOG4CXX_ERROR(logger_, "Null-pointer message received.");
- return;
- }
-
- if (!mobile_handler_) {
- LOG4CXX_WARN(logger_, "No Mobile Handler set");
- return;
- }
-
- mobile_so_factory().attachSchema(*message);
- LOG4CXX_INFO(
- logger_,
- "Attached schema to message, result if valid: " << message->isValid());
-
- utils::SharedPtr<Message> message_to_send(new Message);
- if (!ConvertSOtoMessage((*message), (*message_to_send))) {
- LOG4CXX_WARN(logger_,
- "Cannot send message to Mobile: failed to create string");
- return;
- }
-
- smart_objects::SmartObject& msg_to_mobile = *message;
- if (msg_to_mobile[strings::params].keyExists(strings::correlation_id)) {
- request_ctrl.terminateRequest(
- msg_to_mobile[strings::params][strings::correlation_id].asInt());
- }
-
- messages_to_mobile_.push(message_to_send);
-}
-
-bool ApplicationManagerImpl::ManageMobileCommand(
- const utils::SharedPtr<smart_objects::SmartObject>& message) {
- LOG4CXX_INFO(logger_, "ApplicationManagerImpl::ManageMobileCommand");
-
- DCHECK(message);
- if (!message) {
- LOG4CXX_WARN(logger_, "Null-pointer message received.");
- return false;
- }
-
-#ifdef DEBUG
- MessageHelper::PrintSmartObject(*message);
-#endif
-
- LOG4CXX_INFO(logger_, "Trying to create message in mobile factory.");
- CommandSharedPtr command = MobileCommandFactory::CreateCommand(message);
-
- if (!command) {
- LOG4CXX_WARN(logger_, "Failed to create mobile command from smart object");
- return false;
- }
-
- mobile_apis::FunctionID::eType function_id =
- static_cast<mobile_apis::FunctionID::eType>(
- (*message)[strings::params][strings::function_id].asInt());
-
- if (((mobile_apis::FunctionID::RegisterAppInterfaceID != function_id)
- && ((*message)[strings::params][strings::protocol_type]
- == commands::CommandImpl::mobile_protocol_type_))
- && (mobile_apis::FunctionID::UnregisterAppInterfaceID != function_id)) {
- unsigned int app_id = (*message)[strings::params][strings::connection_key]
- .asUInt();
-
- mobile_apis::FunctionID::eType function_id =
- static_cast<mobile_apis::FunctionID::eType>(
- (*message)[strings::params][strings::function_id].asInt());
-
- unsigned int correlation_id =
- (*message)[strings::params][strings::correlation_id].asUInt();
-
- unsigned int connection_key =
- (*message)[strings::params][strings::connection_key].asUInt();
-
- Application* app = ApplicationManagerImpl::instance()->application(app_id);
- if (NULL == app) {
- LOG4CXX_ERROR_EXT(logger_, "APPLICATION_NOT_REGISTERED");
- smart_objects::SmartObject* response =
- MessageHelper::CreateNegativeResponse(
- connection_key, function_id, correlation_id,
- mobile_apis::Result::APPLICATION_NOT_REGISTERED);
- ApplicationManagerImpl::instance()->SendMessageToMobile(response);
- return false;
- }
-
- if (!policies_manager_.IsValidHmiStatus(function_id, app->hmi_level())) {
- LOG4CXX_WARN(
- logger_,
- "Request blocked by policies. " << "FunctionID: "
- << static_cast<int>(function_id) << " Application HMI status: "
- << static_cast<int>(app->hmi_level()));
-
- smart_objects::SmartObject* response =
- MessageHelper::CreateBlockedByPoliciesResponse(
- function_id, mobile_apis::Result::REJECTED, correlation_id,
- connection_key);
-
- ApplicationManagerImpl::instance()->SendMessageToMobile(response);
- return true;
- }
- }
-
- if (command->Init()) {
-
- if ((*message)[strings::params][strings::message_type].asInt() ==
- mobile_apis::messageType::request) {
- request_ctrl.addRequest(command);
- }
-
- command->Run();
- if (command->CleanUp()) {
- return true;
- }
- }
- return false;
-}
-
-void ApplicationManagerImpl::SendMessageToHMI(
- const utils::SharedPtr<smart_objects::SmartObject>& message) {
- LOG4CXX_INFO(logger_, "ApplicationManagerImpl::SendMessageToHMI");
-
- DCHECK(message);
- if (!message) {
- LOG4CXX_WARN(logger_, "Null-pointer message received.");
- return;
- }
-
- if (!hmi_handler_) {
- LOG4CXX_WARN(logger_, "No HMI Handler set");
- return;
- }
-
- utils::SharedPtr<Message> message_to_send(new Message);
- if (!message_to_send) {
- LOG4CXX_ERROR(logger_, "Null pointer");
- return;
- }
-
- hmi_so_factory().attachSchema(*message);
- LOG4CXX_INFO(
- logger_,
- "Attached schema to message, result if valid: " << message->isValid());
-
- if (!ConvertSOtoMessage(*message, *message_to_send)) {
- LOG4CXX_WARN(logger_,
- "Cannot send message to HMI: failed to create string");
- return;
- }
- messages_to_hmh_.push(message_to_send);
-}
-
-bool ApplicationManagerImpl::ManageHMICommand(
- const utils::SharedPtr<smart_objects::SmartObject>& message) {
- LOG4CXX_INFO(logger_, "ApplicationManagerImpl::ManageHMICommand");
-
- DCHECK(message);
- if (!message) {
- LOG4CXX_WARN(logger_, "Null-pointer message received.");
- return false;
- }
-
-#ifdef DEBUG
- MessageHelper::PrintSmartObject(*message);
-#endif
-
- CommandSharedPtr command = HMICommandFactory::CreateCommand(message);
-
- if (!command) {
- LOG4CXX_WARN(logger_, "Failed to create command from smart object");
- return false;
- }
-
- if (command->Init()) {
- command->Run();
- if (command->CleanUp()) {
- return true;
- }
- }
- return false;
-}
-
-void ApplicationManagerImpl::CreateHMIMatrix(HMIMatrix* matrix) {
-}
-
-void ApplicationManagerImpl::CreatePoliciesManager(PoliciesManager* managaer) {
-}
-
-bool ApplicationManagerImpl::CheckPolicies(smart_objects::SmartObject* message,
- Application* application) {
- return true;
-}
-
-bool ApplicationManagerImpl::CheckHMIMatrix(
- smart_objects::SmartObject* message) {
- return true;
-}
-
-bool ApplicationManagerImpl::ConvertMessageToSO(
- const Message& message, smart_objects::SmartObject& output) {
- LOG4CXX_INFO(
- logger_,
- "\t\t\tMessage to convert: protocol " << message.protocol_version()
- << "; json " << message.json_message());
-
- switch (message.protocol_version()) {
- case ProtocolVersion::kV2: {
- if (!formatters::CFormatterJsonSDLRPCv2::fromString(
- message.json_message(), output, message.function_id(), message.type(),
- message.correlation_id()) || !mobile_so_factory().attachSchema(output)
- || ((output.validate() != smart_objects::Errors::OK)
- && (output.validate()
- != smart_objects::Errors::UNEXPECTED_PARAMETER))) {
- LOG4CXX_WARN(logger_, "Failed to parse string to smart object");
- utils::SharedPtr<smart_objects::SmartObject> response(
- MessageHelper::CreateNegativeResponse(
- message.connection_key(), message.function_id(),
- message.correlation_id(), mobile_apis::Result::INVALID_DATA));
- ManageMobileCommand(response);
- return false;
- }
- LOG4CXX_INFO(
- logger_,
- "Convertion result for sdl object is true" << " function_id "
- << output[jhs::S_PARAMS][jhs::S_FUNCTION_ID].asInt());
- output[strings::params][strings::connection_key] =
- message.connection_key();
- if (message.binary_data()) {
- output[strings::params][strings::binary_data] =
- *(message.binary_data());
- }
- break;
- }
- case ProtocolVersion::kHMI: {
- int result = formatters::FormatterJsonRpc::FromString <
- hmi_apis::FunctionID::eType, hmi_apis::messageType::eType > (
- message.json_message(), output);
- LOG4CXX_INFO(
- logger_,
- "Convertion result: " << result << " function id "
- << output[jhs::S_PARAMS][jhs::S_FUNCTION_ID].asInt());
- if (!hmi_so_factory().attachSchema(output)) {
- LOG4CXX_WARN(logger_, "Failed to attach schema to object.");
- return false;
- }
- break;
- }
- default:
- // TODO(PV):
- // removed NOTREACHED() because some app can still have vesion 1.
- LOG4CXX_WARN(
- logger_,
- "Application used unsupported protocol " << message.protocol_version()
- << ".");
- return false;
- }
-
- LOG4CXX_INFO(logger_, "Successfully parsed message into smart object");
- return true;
-}
-
-bool ApplicationManagerImpl::ConvertSOtoMessage(
- const smart_objects::SmartObject& message, Message& output) {
- LOG4CXX_INFO(logger_, "Message to convert");
-
- if (smart_objects::SmartType_Null == message.getType()
- || smart_objects::SmartType_Invalid == message.getType()) {
- LOG4CXX_WARN(logger_, "Invalid smart object received.");
- return false;
- }
-
- LOG4CXX_INFO(
- logger_,
- "Message with protocol: "
- << message.getElement(jhs::S_PARAMS).getElement(jhs::S_PROTOCOL_TYPE)
- .asInt());
-
- std::string output_string;
- switch (message.getElement(jhs::S_PARAMS).getElement(jhs::S_PROTOCOL_TYPE)
- .asInt()) {
- case 0: {
- if (!formatters::CFormatterJsonSDLRPCv2::toString(message,
- output_string)) {
- LOG4CXX_WARN(logger_, "Failed to serialize smart object");
- return false;
- }
- output.set_protocol_version(application_manager::kV2);
- break;
- }
- case 1: {
- if (!formatters::FormatterJsonRpc::ToString(message, output_string)) {
- LOG4CXX_WARN(logger_, "Failed to serialize smart object");
- return false;
- }
- output.set_protocol_version(application_manager::kHMI);
- break;
- }
- default:
- NOTREACHED();
- return false;
- }
-
- LOG4CXX_INFO(logger_, "Convertion result: " << output_string);
-
- output.set_connection_key(
- message.getElement(jhs::S_PARAMS).getElement(strings::connection_key)
- .asInt());
-
- output.set_function_id(
- message.getElement(jhs::S_PARAMS).getElement(jhs::S_FUNCTION_ID).asInt());
-
- output.set_correlation_id(
- message.getElement(jhs::S_PARAMS).getElement(jhs::S_CORRELATION_ID)
- .asInt());
- output.set_message_type(
- static_cast<MessageType>(message.getElement(jhs::S_PARAMS).getElement(
- jhs::S_MESSAGE_TYPE).asInt()));
-
- // Currently formatter creates JSON = 3 bytes for empty SmartObject.
- // workaround for notification. JSON must be empty
- if (mobile_apis::FunctionID::OnAudioPassThruID
- != message.getElement(jhs::S_PARAMS).getElement(strings::function_id)
- .asInt()) {
- output.set_json_message(output_string);
- }
-
- if (message.getElement(jhs::S_PARAMS).keyExists(strings::binary_data)) {
- application_manager::BinaryData* binaryData =
- new application_manager::BinaryData(
- message.getElement(jhs::S_PARAMS).getElement(strings::binary_data)
- .asBinary());
-
- if (NULL == binaryData) {
- LOG4CXX_ERROR(logger_, "Null pointer");
- return false;
- }
- output.set_binary_data(binaryData);
- }
-
- LOG4CXX_INFO(logger_, "Successfully parsed message into smart object");
- return true;
-}
-
-void ApplicationManagerImpl::ProcessMessageFromMobile(
- const utils::SharedPtr<Message>& message) {
- LOG4CXX_INFO(logger_, "ApplicationManagerImpl::ProcessMessageFromMobile()");
-
- utils::SharedPtr<smart_objects::SmartObject> so_from_mobile(
- new smart_objects::SmartObject);
-
- if (!so_from_mobile) {
- LOG4CXX_ERROR(logger_, "Null pointer");
- return;
- }
-
- if (!ConvertMessageToSO(*message, *so_from_mobile)) {
- LOG4CXX_ERROR(logger_, "Cannot create smart object from message");
- return;
- }
-
- if (!ManageMobileCommand(so_from_mobile)) {
- LOG4CXX_ERROR(logger_, "Received command didn't run successfully");
- }
-}
-
-void ApplicationManagerImpl::ProcessMessageFromHMI(
- const utils::SharedPtr<Message>& message) {
- LOG4CXX_INFO(logger_, "ApplicationManagerImpl::ProcessMessageFromHMI()");
- utils::SharedPtr<smart_objects::SmartObject> smart_object(
- new smart_objects::SmartObject);
-
- if (!smart_object) {
- LOG4CXX_ERROR(logger_, "Null pointer");
- return;
- }
-
- if (!ConvertMessageToSO(*message, *smart_object)) {
- LOG4CXX_ERROR(logger_, "Cannot create smart object from message");
- return;
- }
-
- LOG4CXX_INFO(logger_, "Converted message, trying to create hmi command");
- if (!ManageHMICommand(smart_object)) {
- LOG4CXX_ERROR(logger_, "Received command didn't run successfully");
- }
-}
-
-hmi_apis::HMI_API& ApplicationManagerImpl::hmi_so_factory() {
- if (!hmi_so_factory_) {
- hmi_so_factory_ = new hmi_apis::HMI_API;
- if (!hmi_so_factory_) {
- LOG4CXX_ERROR(logger_, "Out of memory");
- CHECK(hmi_so_factory_);
- }
- }
- return *hmi_so_factory_;
-}
-
-mobile_apis::MOBILE_API& ApplicationManagerImpl::mobile_so_factory() {
- if (!mobile_so_factory_) {
- mobile_so_factory_ = new mobile_apis::MOBILE_API;
- if (!mobile_so_factory_) {
- LOG4CXX_ERROR(logger_, "Out of memory.");
- CHECK(mobile_so_factory_);
- }
- }
- return *mobile_so_factory_;
-}
-
-bool ApplicationManagerImpl::IsHMICapabilitiesInitialized() {
- bool result = true;
- if (is_vr_ready_response_recieved_ && is_tts_ready_response_recieved_
- && is_ui_ready_response_recieved_ && is_navi_ready_response_recieved_
- && is_ivi_ready_response_recieved_) {
- if (is_vr_cooperating_) {
- if ((!vr_supported_languages_)
- || (hmi_apis::Common_Language::INVALID_ENUM == vr_language_)) {
- result = false;
- }
- }
-
- if (is_tts_cooperating_) {
- if ((!tts_supported_languages_)
- || (hmi_apis::Common_Language::INVALID_ENUM == tts_language_)) {
- result = false;
- }
- }
-
- if (is_ui_cooperating_) {
- if ((!ui_supported_languages_)
- || (hmi_apis::Common_Language::INVALID_ENUM == ui_language_)) {
- result = false;
- }
- }
-
- if (is_ivi_cooperating_) {
- if (!vehicle_type_) {
- result = false;
- }
- }
- } else {
- result = false;
- }
-
- LOG4CXX_INFO(logger_,
- "HMICapabilities::IsHMICapabilitiesInitialized() " << result);
-
- return result;
-}
-
-void ApplicationManagerImpl::addNotification(const CommandSharedPtr& ptr) {
- notification_list_.push_back(ptr);
-}
-
-void ApplicationManagerImpl::removeNotification(const CommandSharedPtr& ptr) {
- std::list<CommandSharedPtr>::iterator it = notification_list_.begin();
- for (; notification_list_.end() != it; ++it) {
- if (*it == ptr) {
- notification_list_.erase(it);
- break;
- }
- }
-}
-
-void ApplicationManagerImpl::updateRequestTimeout(unsigned int connection_key,
- unsigned int mobile_correlation_id,
- unsigned int new_timeout_value) {
- request_ctrl.updateRequestTimeout(connection_key, mobile_correlation_id,
- new_timeout_value);
-}
-
-} // namespace application_manager
+++ /dev/null
-/**
- * Copyright (c) 2013, 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/message.h"
-#include "utils/macro.h"
-
-namespace {
-bool BinaryDataPredicate(unsigned char i, unsigned char j) {
- return (i == j);
-}
-}
-
-namespace application_manager {
-
-Message::Message()
- : function_id_(0),
- type_(kUnknownType),
- correlation_id_(0),
- connection_key_(0),
- binary_data_(NULL),
- version_(kUnknownProtocol) {
-}
-
-Message::Message(const Message& message) {
- *this = message;
-}
-
-Message& Message::operator=(const Message& message) {
- set_function_id(message.function_id_);
- set_correlation_id(message.correlation_id_);
- set_connection_key(message.connection_key_);
- set_message_type(message.type_);
- if (message.binary_data_) {
- set_binary_data(message.binary_data_);
- }
- set_json_message(message.json_message_);
- set_protocol_version(message.protocol_version());
-
- return *this;
-}
-
-bool Message::operator==(const Message& message) {
- bool function_id = function_id_ == message.function_id_;
- bool correlation_id = correlation_id_ == message.correlation_id_;
- bool connection_key = connection_key_ == message.connection_key_;
- bool type = type_ == message.type_;
- bool json_message = json_message_ == message.json_message_;
- bool version = version_ == message.version_;
-
- bool binary_data = std::equal(binary_data_->begin(), binary_data_->end(),
- message.binary_data_->begin(),
- BinaryDataPredicate);
-
- return function_id && correlation_id && connection_key && type && binary_data
- && json_message && version;
-}
-
-Message::~Message() {
- if (binary_data_) {
- delete binary_data_;
- }
-}
-
-int Message::function_id() const {
- return function_id_;
-}
-
-int Message::correlation_id() const {
- return correlation_id_;
-}
-
-int Message::connection_key() const {
- return connection_key_;
-}
-
-MessageType Message::type() const {
- return type_;
-}
-
-ProtocolVersion Message::protocol_version() const {
- return version_;
-}
-
-const std::string& Message::json_message() const {
- return json_message_;
-}
-
-const BinaryData* Message::binary_data() const {
- return binary_data_;
-}
-
-bool Message::has_binary_data() const {
- return (binary_data_ != NULL);
-}
-
-void Message::set_function_id(int id) {
- function_id_ = id;
-}
-
-void Message::set_correlation_id(int id) {
- correlation_id_ = id;
-}
-
-void Message::set_connection_key(int key) {
- connection_key_ = key;
-}
-
-void Message::set_message_type(MessageType type) {
- type_ = type;
-}
-
-void Message::set_binary_data(BinaryData* data) {
- if (NULL == data) {
- NOTREACHED();
- return;
- }
-
- if (binary_data_) {
- delete binary_data_;
- }
-
- binary_data_ = data;
-}
-
-void Message::set_json_message(const std::string& json_message) {
- json_message_ = json_message;
-}
-
-void Message::set_protocol_version(ProtocolVersion version) {
- version_ = version;
-}
-
-} // namespace application_manager
+++ /dev/null
-/**
-* Copyright (c) 2013, 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 "protocol_handler/message_from_mobile_app_handler.h"
-
-namespace protocol_handler {
-log4cxx::LoggerPtr MessagesFromMobileAppHandler::logger_ =
- log4cxx::LoggerPtr(log4cxx::Logger::getLogger( "ProtocolHandler"));
-
-MessagesFromMobileAppHandler::MessagesFromMobileAppHandler(
- ProtocolHandlerImpl* handler)
- : handler_(handler) {
- CHECK(handler_);
-}
-
-MessagesFromMobileAppHandler::~MessagesFromMobileAppHandler() {
-}
-
-void MessagesFromMobileAppHandler::threadMain() {
- while (1) {
- while (!handler_->messages_from_mobile_app_.empty()) {
- const transport_manager::RawMessageSptr& message = handler_
- ->messages_from_mobile_app_.pop();
- LOG4CXX_INFO_EXT(
- logger_,
- "Message " << message->data() << " from mobile app received of size "
- << message->data_size());
-
- if ((0 != message->data()) && (0 != message->data_size())
- && (MAXIMUM_FRAME_DATA_SIZE + PROTOCOL_HEADER_V2_SIZE
- >= message->data_size())) {
- ProtocolPacket* packet = new ProtocolPacket;
- LOG4CXX_INFO_EXT(logger_, "message" << message->protocol_version() << "Data: " << packet->data());
- if (packet->deserializePacket(message->data(), message->data_size())
- == RESULT_FAIL) {
- LOG4CXX_ERROR(logger_, "Failed to parse received message.");
- delete packet;
- } else {
- LOG4CXX_INFO_EXT(logger_,
- "Packet: dataSize " << packet->data_size() << "TEST:" << packet->data());
- handler_->HandleMessage(message, packet);
- }
- } else {
- LOG4CXX_WARN(
- logger_, "handleMessagesFromMobileApp() - incorrect or NULL data");
- }
-
- }
- handler_->messages_from_mobile_app_.wait();
- }
-}
-} // namespace protocol_handler
+++ /dev/null
-/**
- * \file ProtocolHandler.cpp
- * \brief ProtocolHandler class source file.
- *
- * Copyright (c) 2013, 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 <memory.h>
-
-#include "protocol_handler/session_observer.h"
-#include "protocol_handler/protocol_handler_impl.h"
-#include "protocol_handler/message_from_mobile_app_handler.h"
-#include "protocol_handler/messages_to_mobile_app_handler.h"
-
-#include "utils/macro.h"
-
-namespace protocol_handler {
-
-log4cxx::LoggerPtr ProtocolHandlerImpl::logger_ =
- log4cxx::LoggerPtr(log4cxx::Logger::getLogger("ProtocolHandler"));
-
-ProtocolHandlerImpl::ProtocolHandlerImpl(
- transport_manager::TransportManager* transport_manager)
- : protocol_observer_(0),
- session_observer_(0),
- transport_manager_(transport_manager),
- handle_messages_from_mobile_app_(NULL),
- handle_messages_to_mobile_app_(NULL) {
- LOG4CXX_TRACE_ENTER(logger_);
-
- handle_messages_from_mobile_app_ = new threads::Thread(
- "MessagesFromMobileAppHandler", new MessagesFromMobileAppHandler(this));
- handle_messages_from_mobile_app_->startWithOptions(
- threads::ThreadOptions(threads::Thread::kMinStackSize));
-
- handle_messages_to_mobile_app_ = new threads::Thread(
- "MessagesToMobileAppHandler", new MessagesToMobileAppHandler(this));
- handle_messages_to_mobile_app_->startWithOptions(
- threads::ThreadOptions(threads::Thread::kMinStackSize));
-
- LOG4CXX_TRACE_EXIT(logger_);
-}
-
-ProtocolHandlerImpl::~ProtocolHandlerImpl() {
- handle_messages_from_mobile_app_->stop();
- delete handle_messages_from_mobile_app_;
- handle_messages_from_mobile_app_ = NULL;
-
- handle_messages_to_mobile_app_->stop();
- delete handle_messages_to_mobile_app_;
- handle_messages_to_mobile_app_ = NULL;
-
- protocol_observer_ = 0;
- session_observer_ = 0;
- transport_manager_ = 0;
-}
-
-void ProtocolHandlerImpl::set_protocol_observer(ProtocolObserver* observer) {
- //LOG4CXX_TRACE_METHOD(logger_, __PRETTY_FUNCTION__);
- if (!observer) {
- LOG4CXX_ERROR(logger_, "Invalid (NULL) pointer to IProtocolObserver.");
- return;
- }
-
- protocol_observer_ = observer;
-}
-
-void ProtocolHandlerImpl::set_session_observer(SessionObserver* observer) {
- if (!observer) {
- LOG4CXX_ERROR(logger_, "Invalid (NULL) pointer to ISessionObserver.");
- return;
- }
-
- session_observer_ = observer;
-}
-
-void ProtocolHandlerImpl::SendEndSessionNAck(
- const transport_manager::RawMessageSptr& original_message,
- unsigned int session_id,
- unsigned char service_type) {
- LOG4CXX_TRACE_ENTER(logger_);
-
- ProtocolPacket packet(PROTOCOL_VERSION_2, COMPRESS_OFF, FRAME_TYPE_CONTROL,
- 0x0, FRAME_DATA_END_SESSION_NACK, session_id, 0, 0);
-
- if (RESULT_OK == SendFrame(original_message, packet)) {
- LOG4CXX_INFO(logger_, "sendStartSessionAck() - BT write OK");
- } else {
- LOG4CXX_ERROR(logger_, "sendStartSessionAck() - BT write FAIL");
- }
-
- LOG4CXX_TRACE_EXIT(logger_);
-}
-
-void ProtocolHandlerImpl::SendStartSessionAck(
- const transport_manager::RawMessageSptr& original_message,
- unsigned char session_id,
- unsigned char protocol_version,
- unsigned int hash_code,
- unsigned char service_type) {
- LOG4CXX_TRACE_ENTER(logger_);
-
- ProtocolPacket packet(protocol_version, COMPRESS_OFF, FRAME_TYPE_CONTROL,
- service_type, FRAME_DATA_START_SESSION_ACK,
- session_id, 0, hash_code);
-
- if (RESULT_OK == SendFrame(original_message, packet)) {
- LOG4CXX_INFO(
- logger_,
- "sendStartSessionAck() for connection " <<
- original_message->connection_key()
- << " for service_type " << service_type <<
- " session_id " << session_id);
- } else {
- LOG4CXX_ERROR(logger_, "sendStartSessionAck() - BT write FAIL");
- }
-
- LOG4CXX_TRACE_EXIT(logger_);
-}
-
-void ProtocolHandlerImpl::SendStartSessionNAck(
- const transport_manager::RawMessageSptr& original_message,
- unsigned char service_type) {
- LOG4CXX_TRACE_ENTER(logger_);
-
- unsigned char versionFlag = PROTOCOL_VERSION_1;
-
- ProtocolPacket packet(versionFlag, COMPRESS_OFF, FRAME_TYPE_CONTROL,
- service_type, FRAME_DATA_START_SESSION_NACK, 0x0, 0, 0);
-
- if (RESULT_OK == SendFrame(original_message, packet)) {
- LOG4CXX_INFO(logger_, "sendStartSessionAck() - BT write OK");
- } else {
- LOG4CXX_ERROR(logger_, "sendStartSessionAck() - BT write FAIL");
- }
-
- LOG4CXX_TRACE_EXIT(logger_);
-}
-
-void ProtocolHandlerImpl::SendMessageToMobileApp(
- const transport_manager::RawMessageSptr& message) {
- LOG4CXX_TRACE_ENTER(logger_);
- if (!message) {
- LOG4CXX_ERROR(logger_,
- "Invalid message for sending to mobile app is received.");
- LOG4CXX_TRACE_EXIT(logger_);
- return;
- }
- messages_to_mobile_app_.push(message);
- LOG4CXX_TRACE_EXIT(logger_);
-}
-
-unsigned int ProtocolHandlerImpl::GetPacketSize(unsigned int data_size, unsigned char* first_bytes) {
- DCHECK(first_bytes);
- unsigned char offset = sizeof(uint32_t);
- if (data_size < 2 * offset) {
- LOG4CXX_ERROR(logger_, "Received bytes are not enough to parse fram size.");
- return 0;
- }
-
- unsigned char* received_bytes = first_bytes;
- DCHECK(received_bytes);
-
- unsigned char version = received_bytes[0] >> 4u;
- uint32_t frame_body_size = received_bytes[offset++] << 24u;
- frame_body_size |= received_bytes[offset++] << 16u;
- frame_body_size |= received_bytes[offset++] << 8u;
- frame_body_size |= received_bytes[offset++];
-
- unsigned int required_size = frame_body_size;
- switch (version) {
- case PROTOCOL_VERSION_1:
- required_size += PROTOCOL_HEADER_V1_SIZE;
- break;
- case PROTOCOL_VERSION_2:
- required_size += PROTOCOL_HEADER_V2_SIZE;
- break;
- default:
- LOG4CXX_ERROR(logger_, "Unknown protocol version.");
- return 0;
- }
-
- return required_size;
-}
-
-void ProtocolHandlerImpl::OnTMMessageReceived(
- const transport_manager::RawMessageSptr message) {
- LOG4CXX_TRACE_ENTER(logger_);
-
- if (message.valid()) {
- LOG4CXX_INFO_EXT(logger_,
- "Received from TM " << message->data()
- << " with connection id " << message->connection_key());
- messages_from_mobile_app_.push(message);
- } else {
- LOG4CXX_ERROR(
- logger_,
- "Invalid incoming message received in"
- << " ProtocolHandler from Transport Manager.");
- }
-
- LOG4CXX_TRACE_EXIT(logger_);
-}
-
-void ProtocolHandlerImpl::OnTMMessageReceiveFailed(
- const transport_manager::DataReceiveError& error) {
- // TODO(PV): implement
- LOG4CXX_ERROR(logger_, "Received error on attemping to recieve message.")
-}
-
-void ProtocolHandlerImpl::OnTMMessageSend() {
- // TODO(PV): implement if needed.
- LOG4CXX_INFO(logger_, "Sending message finished successfully.");
-}
-
-void ProtocolHandlerImpl::OnTMMessageSendFailed(
- const transport_manager::DataSendError& error,
- const transport_manager::RawMessageSptr& message) {
- // TODO(PV): implement
- LOG4CXX_ERROR(logger_, "Sending message " <<
- message-> data() << " failed.");
-}
-
-RESULT_CODE ProtocolHandlerImpl::SendFrame(
- const transport_manager::RawMessageSptr& original_message,
- const ProtocolPacket& packet) {
- LOG4CXX_TRACE_ENTER(logger_);
- if (!packet.packet()) {
- LOG4CXX_ERROR(logger_, "Failed to create packet.");
-
- LOG4CXX_TRACE_EXIT(logger_);
- return RESULT_FAIL;
- }
-
- LOG4CXX_INFO_EXT(
- logger_,
- "Packet to be sent: " << packet.packet()
- << " of size: " << packet.packet_size());
-
- if (!session_observer_) {
- LOG4CXX_WARN(logger_, "No session_observer_ set.");
- return RESULT_FAIL;
- }
-
- transport_manager::ConnectionUID connection_uid = 0;
- unsigned char session_id = 0;
- session_observer_->PairFromKey(original_message->connection_key(),
- &connection_uid,
- &session_id);
-
- transport_manager::RawMessageSptr message_to_send(new RawMessage(
- connection_uid,
- original_message->protocol_version(),
- packet.packet(),
- packet.packet_size()));
-
- LOG4CXX_INFO(logger_, "Message to send with connection id "
- << connection_uid);
-
- if (transport_manager_) {
- transport_manager_->SendMessageToDevice(message_to_send);
- } else {
- LOG4CXX_WARN(logger_, "No Transport Manager found.");
- LOG4CXX_TRACE_EXIT(logger_);
- return RESULT_FAIL;
- }
-
- LOG4CXX_TRACE_EXIT(logger_);
- return RESULT_OK;
-}
-
-RESULT_CODE ProtocolHandlerImpl::SendSingleFrameMessage(
- const transport_manager::RawMessageSptr& original_message,
- const unsigned char session_id, unsigned int protocol_version,
- const unsigned char service_type, const unsigned int data_size,
- const unsigned char* data, const bool compress) {
- LOG4CXX_TRACE_ENTER(logger_);
-
- unsigned char versionF = PROTOCOL_VERSION_1;
- if (2 == protocol_version) {
- versionF = PROTOCOL_VERSION_2;
- }
-
- ProtocolPacket packet(versionF, compress, FRAME_TYPE_SINGLE, service_type, 0,
- session_id, data_size, message_counters_[session_id]++,
- data);
-
- LOG4CXX_TRACE_EXIT(logger_);
- return SendFrame(original_message, packet);
-}
-
-RESULT_CODE ProtocolHandlerImpl::SendMultiFrameMessage(
- const transport_manager::RawMessageSptr& original_message,
- const unsigned char session_id, unsigned int protocol_version,
- const unsigned char service_type, const unsigned int data_size,
- const unsigned char* data, const bool compress,
- const unsigned int maxdata_size) {
- LOG4CXX_TRACE_ENTER(logger_);
- RESULT_CODE retVal = RESULT_OK;
-
- LOG4CXX_INFO_EXT(
- logger_, " data size " << data_size << " maxdata_size " << maxdata_size);
-
- unsigned char versionF = PROTOCOL_VERSION_1;
- if (2 == protocol_version) {
- versionF = PROTOCOL_VERSION_2;
- }
-
- int numOfFrames = 0;
- int lastdata_size = 0;
-
- if (data_size % maxdata_size) {
- numOfFrames = (data_size / maxdata_size) + 1;
- lastdata_size = data_size % maxdata_size;
- } else {
- numOfFrames = data_size / maxdata_size;
- lastdata_size = maxdata_size;
- }
-
- LOG4CXX_INFO_EXT(
- logger_,
- "Data size " << data_size << " of " << numOfFrames
- << " frames with last frame " << lastdata_size);
-
- unsigned char* outDataFirstFrame = new unsigned char[FIRST_FRAME_DATA_SIZE];
- outDataFirstFrame[0] = data_size >> 24;
- outDataFirstFrame[1] = data_size >> 16;
- outDataFirstFrame[2] = data_size >> 8;
- outDataFirstFrame[3] = data_size;
-
- outDataFirstFrame[4] = numOfFrames >> 24;
- outDataFirstFrame[5] = numOfFrames >> 16;
- outDataFirstFrame[6] = numOfFrames >> 8;
- outDataFirstFrame[7] = numOfFrames;
-
- ProtocolPacket firstPacket(versionF, compress, FRAME_TYPE_FIRST,
- service_type, 0,
- session_id, FIRST_FRAME_DATA_SIZE,
- ++message_counters_[session_id],
- outDataFirstFrame);
-
- retVal = SendFrame(original_message, firstPacket);
-
- LOG4CXX_INFO_EXT(logger_, "First frame is sent.");
-
- delete[] outDataFirstFrame;
-
- unsigned char* outDataFrame = new unsigned char[maxdata_size];
-
- for (unsigned int i = 0; i < numOfFrames; i++) {
- if (i != (numOfFrames - 1)) {
- memcpy(outDataFrame, data + (maxdata_size * i), maxdata_size);
-
- ProtocolPacket packet(versionF, compress, FRAME_TYPE_CONSECUTIVE,
- service_type, ((i % FRAME_DATA_MAX_VALUE) + 1),
- session_id, maxdata_size,
- message_counters_[session_id], outDataFrame);
-
- retVal = SendFrame(original_message, packet);
- if (RESULT_FAIL == retVal) {
- break;
- }
- } else {
- memcpy(outDataFrame, data + (maxdata_size * i), lastdata_size);
-
- ProtocolPacket packet(versionF, compress, FRAME_TYPE_CONSECUTIVE,
- service_type, 0x0, session_id, lastdata_size,
- message_counters_[session_id], outDataFrame);
-
- retVal = SendFrame(original_message, packet);
- }
- }
-
- delete[] outDataFrame;
-
- LOG4CXX_TRACE_EXIT(logger_);
- return retVal;
-}
-
-RESULT_CODE ProtocolHandlerImpl::HandleMessage(
- const transport_manager::RawMessageSptr& original_message,
- ProtocolPacket* packet) {
- LOG4CXX_TRACE_ENTER(logger_);
-
- switch (packet->frame_type()) {
- case FRAME_TYPE_CONTROL: {
- LOG4CXX_INFO(logger_, "handleMessage() - case FRAME_TYPE_CONTROL");
-
- LOG4CXX_TRACE_EXIT(logger_);
- return HandleControlMessage(original_message, packet);
- }
- case FRAME_TYPE_SINGLE: {
- LOG4CXX_INFO(
- logger_,
- "FRAME_TYPE_SINGLE: of size " << packet->data_size()
- << ";message " << packet -> data());
-
- if (!session_observer_) {
- LOG4CXX_ERROR(
- logger_,
- "Cannot handle message from Transport"
- << " Manager: ISessionObserver doesn't exist.");
-
- LOG4CXX_TRACE_EXIT(logger_);
- return RESULT_FAIL;
- }
-
- int connection_key = session_observer_->KeyFromPair(
- original_message->connection_key(),
- packet->session_id());
-
- RawMessage* raw_message = new RawMessage(
- connection_key,
- packet->version(),
- packet->data(),
- packet->data_size());
-
- if (protocol_observer_) {
- protocol_observer_->OnMessageReceived(raw_message);
- }
-
- break;
- }
- case FRAME_TYPE_FIRST:
- case FRAME_TYPE_CONSECUTIVE: {
- LOG4CXX_INFO(logger_, "handleMessage() - case FRAME_TYPE_CONSECUTIVE");
-
- LOG4CXX_TRACE_EXIT(logger_);
- return HandleMultiFrameMessage(original_message, packet);
- }
- default: {
- LOG4CXX_WARN(logger_, "handleMessage() - case default!!!");
- }
- }
-
- LOG4CXX_TRACE_EXIT(logger_);
- return RESULT_OK;
-}
-
-RESULT_CODE ProtocolHandlerImpl::HandleMultiFrameMessage(
- const transport_manager::RawMessageSptr& original_message,
- ProtocolPacket* packet) {
- LOG4CXX_TRACE_ENTER(logger_);
-
- if (!session_observer_) {
- LOG4CXX_ERROR(logger_, "No ISessionObserver set.");
-
- LOG4CXX_TRACE_EXIT(logger_);
- return RESULT_FAIL;
- }
-
- LOG4CXX_INFO_EXT(
- logger_, "Packet " << packet << "; session_id " << packet -> session_id());
-
- int key = session_observer_->KeyFromPair(original_message->connection_key(),
- packet->session_id());
-
- if (packet->frame_type() == FRAME_TYPE_FIRST) {
- LOG4CXX_INFO(logger_, "handleMultiFrameMessage() - FRAME_TYPE_FIRST");
-
- // const unsigned char* data = packet -> getData();
- unsigned int total_data_bytes = packet->data()[0] << 24;
- total_data_bytes |= packet->data()[1] << 16;
- total_data_bytes |= packet->data()[2] << 8;
- total_data_bytes |= packet->data()[3];
-
- packet->set_total_data_bytes(total_data_bytes);
-
- incomplete_multi_frame_messages_[key] = packet;
- } else {
- LOG4CXX_INFO(logger_, "handleMultiFrameMessage() - Consecutive frame");
-
- std::map<int, ProtocolPacket*>::iterator it =
- incomplete_multi_frame_messages_.find(key);
-
- if (it == incomplete_multi_frame_messages_.end()) {
- LOG4CXX_ERROR(
- logger_, "Frame of multiframe message for non-existing session id");
-
- LOG4CXX_TRACE_EXIT(logger_);
- return RESULT_FAIL;
- }
-
- // LOG4CXX_INFO(mLogger, "Found message " << it->second->)
-
- if (it->second->appendData(packet->data(), packet->data_size())
- != RESULT_OK) {
- LOG4CXX_ERROR(logger_,
- "Failed to append frame for multiframe message.");
-
- LOG4CXX_TRACE_EXIT(logger_);
- return RESULT_FAIL;
- }
-
- if (packet->frame_data() == FRAME_DATA_LAST_FRAME) {
- LOG4CXX_INFO(logger_, "Last frame of multiframe message size "
- << packet->data_size() << "; connection key " << key);
- if (!protocol_observer_) {
- LOG4CXX_ERROR(
- logger_,
- "Cannot handle multiframe message: no IProtocolObserver is set.");
-
- LOG4CXX_TRACE_EXIT(logger_);
- return RESULT_FAIL;
- }
-
- ProtocolPacket* completePacket = it->second;
- RawMessage* rawMessage = new RawMessage(
- key, completePacket->version(), completePacket->data(),
- completePacket->total_data_bytes());
-
- protocol_observer_->OnMessageReceived(rawMessage);
-
- incomplete_multi_frame_messages_.erase(it);
- }
- }
-
- LOG4CXX_TRACE_EXIT(logger_);
- return RESULT_OK;
-}
-
-RESULT_CODE ProtocolHandlerImpl::HandleControlMessage(
- const transport_manager::RawMessageSptr& original_message,
- const ProtocolPacket* packet) {
- LOG4CXX_TRACE_ENTER(logger_);
-
- if (!session_observer_) {
- LOG4CXX_ERROR(logger_, "ISessionObserver is not set.");
-
- LOG4CXX_TRACE_EXIT(logger_);
- return RESULT_FAIL;
- }
-
- if (packet->frame_data() == FRAME_DATA_END_SESSION) {
- LOG4CXX_INFO(logger_, "handleControlMessage() - FRAME_DATA_END_SESSION");
-
- unsigned char currentsession_id = packet->session_id();
-
- unsigned int hash_code = 0;
- if (packet->version() == 2) {
- hash_code = packet->message_id();
- }
-
- bool success = true;
- int sessionhash_code = session_observer_->OnSessionEndedCallback(
- original_message->connection_key(),
- currentsession_id,
- hash_code);
-
- if (-1 != sessionhash_code) {
- // TODO(PV): check hash code only for second version of protocol.
- if (2 == packet->version()) {
- if (packet->message_id() != sessionhash_code) {
- success = false;
- }
- }
- } else {
- success = false;
- }
-
- if (success) {
- message_counters_.erase(currentsession_id);
- } else {
- LOG4CXX_INFO_EXT(
- logger_,
- "Refused to end session " << packet -> service_type() << " type.");
- SendEndSessionNAck(original_message, currentsession_id,
- packet->service_type());
- }
- }
-
- if (packet->frame_data() == FRAME_DATA_START_SESSION) {
- LOG4CXX_INFO(logger_,
- "handleControlMessage() - FRAME_DATA_START_SESSION");
- LOG4CXX_INFO_EXT(
- logger_, "Version 2 " << (packet -> version() == PROTOCOL_VERSION_2));
-
- int session_id = session_observer_->OnSessionStartedCallback(
- original_message->connection_key());
- if (-1 != session_id) {
- SendStartSessionAck(
- original_message, session_id, packet->version(),
- session_observer_->KeyFromPair(
- original_message->connection_key(), session_id),
- packet->service_type());
- } else {
- LOG4CXX_INFO_EXT(
- logger_,
- "Refused to create session " << packet -> service_type() << " type.");
- SendStartSessionNAck(original_message,
- packet->service_type());
- }
- }
-
- LOG4CXX_TRACE_EXIT(logger_);
- return RESULT_OK;
-}
-
-} // namespace protocol_handler
+++ /dev/null
-/**
- * \file ProtocolPacket.cpp
- * \brief ProtocolPacket class source file.
- *
- * Copyright (c) 2013, 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 <memory.h>
-#include <iostream> // TODO(AK): cpplink error - Streams are highly discouraged.
-#include "protocol_handler/protocol_packet.h"
-
-namespace protocol_handler {
-
-ProtocolPacket::ProtocolPacket()
- : packet_(0),
- total_packet_size_(0),
- data_offset_(0),
- packet_id_(0) {
-}
-
-ProtocolPacket::ProtocolPacket(unsigned char version, bool compress,
- unsigned char frameType,
- unsigned char serviceType,
- unsigned char frameData, unsigned char sessionID,
- unsigned int dataSize, unsigned int messageID,
- const unsigned char* data,
- unsigned int packet_id)
- : packet_(0),
- total_packet_size_(0),
- data_offset_(0),
- packet_id_(packet_id) {
- serializePacket(version, compress, frameType, serviceType, frameData,
- sessionID, dataSize, messageID, data);
-}
-
-ProtocolPacket::~ProtocolPacket() {
- // TODO(PV): where to clean?
- packet_ = 0;
- total_packet_size_ = 0;
- packet_id_ = 0;
-}
-
-// Serialization
-RESULT_CODE ProtocolPacket::serializePacket(unsigned char version,
- bool compress,
- unsigned char frameType,
- unsigned char serviceType,
- unsigned char frameData,
- unsigned char sessionID,
- unsigned int dataSize,
- unsigned int messageID,
- const unsigned char* data) {
- if (packet_) {
- delete[] packet_;
- packet_ = 0;
- total_packet_size_ = 0;
- }
-
- unsigned char offset = 0;
- unsigned char compressF = 0x0;
- packet_ = new unsigned char[MAXIMUM_FRAME_DATA_SIZE];
- if (compress) {
- compressF = 0x1;
- }
- unsigned char firstByte = ((version << 4) & 0xF0) | ((compressF << 3) & 0x08)
- | (frameType & 0x07);
-
- packet_[offset++] = firstByte;
- packet_[offset++] = serviceType;
- packet_[offset++] = frameData;
- packet_[offset++] = sessionID;
-
- packet_[offset++] = dataSize >> 24;
- packet_[offset++] = dataSize >> 16;
- packet_[offset++] = dataSize >> 8;
- packet_[offset++] = dataSize;
-
- if (version == PROTOCOL_VERSION_2) {
- packet_[offset++] = messageID >> 24;
- packet_[offset++] = messageID >> 16;
- packet_[offset++] = messageID >> 8;
- packet_[offset++] = messageID;
- }
-
- total_packet_size_ = offset;
-
- if (data) {
- if ((offset + dataSize) <= MAXIMUM_FRAME_DATA_SIZE) {
- printf("offset:%d\n", offset);
- memcpy(packet_ + offset, data, dataSize);
- total_packet_size_ += dataSize;
- } else {
- delete[] packet_;
- packet_ = 0;
- total_packet_size_ = 0;
- return RESULT_FAIL;
- }
- }
-
- return RESULT_OK;
-}
-
-unsigned char * ProtocolPacket::packet() const {
- return packet_;
-}
-
-unsigned int ProtocolPacket::packet_size() const {
- return total_packet_size_;
-}
-
-unsigned int ProtocolPacket::packet_id() const {
- return packet_id_;
-}
-
-RESULT_CODE ProtocolPacket::appendData(unsigned char* chunkData,
- unsigned int chunkDataSize) {
- if (data_offset_ + chunkDataSize <= packet_data_.totalDataBytes) {
- memcpy(packet_data_.data + data_offset_, chunkData, chunkDataSize);
- data_offset_ += chunkDataSize;
- return RESULT_OK;
- }
- return RESULT_FAIL;
-}
-// End of Serialization
-
-// Deserialization
-RESULT_CODE ProtocolPacket::deserializePacket(const unsigned char* message,
- unsigned int messageSize) {
- unsigned char offset = 0;
- unsigned char firstByte = message[offset];
- offset++;
-
- packet_header_.version = firstByte >> 4u;
-
- if (firstByte & 0x08u) {
- packet_header_.compress = true;
- } else {
- packet_header_.compress = false;
- }
-
- packet_header_.frameType = firstByte & 0x07u;
-
- packet_header_.serviceType = message[offset++];
- packet_header_.frameData = message[offset++];
- packet_header_.sessionId = message[offset++];
-
- packet_header_.dataSize = message[offset++] << 24u;
- packet_header_.dataSize |= message[offset++] << 16u;
- packet_header_.dataSize |= message[offset++] << 8u;
- packet_header_.dataSize |= message[offset++];
-
- if (packet_header_.version == PROTOCOL_VERSION_2) {
- packet_header_.messageId = message[offset++] << 24u;
- packet_header_.messageId |= message[offset++] << 16u;
- packet_header_.messageId |= message[offset++] << 8u;
- packet_header_.messageId |= message[offset++];
- } else {
- packet_header_.messageId = 0u;
- }
-
- const unsigned int dataPayloadSize = messageSize - offset;
-
- if (dataPayloadSize != packet_header_.dataSize) {
- return RESULT_FAIL;
- }
-
- unsigned char * data = 0;
- if (dataPayloadSize != 0u) {
- data = new unsigned char[messageSize - offset];
- memcpy(data, message + offset, dataPayloadSize);
- }
-
- packet_data_.data = data;
- packet_data_.totalDataBytes = dataPayloadSize;
- return RESULT_OK;
-}
-
-unsigned char ProtocolPacket::version() const {
- return packet_header_.version;
-}
-
-bool ProtocolPacket::is_compress() const {
- return packet_header_.compress;
-}
-
-unsigned char ProtocolPacket::frame_type() const {
- return packet_header_.frameType;
-}
-
-unsigned char ProtocolPacket::service_type() const {
- return packet_header_.serviceType;
-}
-
-unsigned char ProtocolPacket::frame_data() const {
- return packet_header_.frameData;
-}
-
-unsigned char ProtocolPacket::session_id() const {
- return packet_header_.sessionId;
-}
-
-unsigned int ProtocolPacket::data_size() const {
- return packet_header_.dataSize;
-}
-
-unsigned int ProtocolPacket::message_id() const {
- return packet_header_.messageId;
-}
-
-unsigned char* ProtocolPacket::data() const {
- return packet_data_.data;
-}
-
-void ProtocolPacket::set_total_data_bytes(unsigned int dataBytes) {
- if (dataBytes) {
- if (packet_data_.data) {
- delete[] packet_data_.data;
- packet_data_.data = 0;
- }
- packet_data_.data = new unsigned char[dataBytes];
- packet_data_.totalDataBytes = dataBytes;
- }
-}
-
-unsigned int ProtocolPacket::total_data_bytes() const {
- return packet_data_.totalDataBytes;
-}
-// End of Deserialization
-} // namespace protocol_handler
+++ /dev/null
-/**
- * \file tcp_socket_connection.cc
- * \brief TcpSocketConnection class source file.
- *
- * Copyright (c) 2013, 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 "transport_manager/transport_adapter/transport_adapter_controller.h"
-#include "transport_manager/tcp/tcp_socket_connection.h"
-#include "transport_manager/tcp/tcp_device.h"
-
-#include <memory.h>
-#include <signal.h>
-#include <errno.h>
-
-namespace transport_manager {
-namespace transport_adapter {
-
-TcpSocketConnection::TcpSocketConnection(const DeviceUID& device_uid,
- const ApplicationHandle& app_handle,
- TransportAdapterController* controller)
- : ThreadedSocketConnection(device_uid, app_handle, controller) {
-}
-
-TcpSocketConnection::~TcpSocketConnection() {
-}
-
-bool TcpSocketConnection::Establish(ConnectError** error) {
- return true;
-}
-
-TcpServerOiginatedSocketConnection::TcpServerOiginatedSocketConnection(
- const DeviceUID& device_uid, const ApplicationHandle& app_handle,
- TransportAdapterController* controller)
- : ThreadedSocketConnection(device_uid, app_handle, controller) {
-}
-
-TcpServerOiginatedSocketConnection::~TcpServerOiginatedSocketConnection() {
-}
-
-bool TcpServerOiginatedSocketConnection::Establish(ConnectError** error) {
- DeviceSptr device = controller()->FindDevice(device_handle());
- if (!device.valid()) {
- LOG4CXX_ERROR(
- logger_,
- "Device " << device_handle() << " not found");
- *error = new ConnectError();
- return false;
- }
- TcpDevice* tcp_device = static_cast<TcpDevice*>(device.get());
-
- int port;
- if (-1 == (port = tcp_device->GetApplicationPort(application_handle()))) {
- LOG4CXX_ERROR(
- logger_,
- "Application port for " << application_handle() << " not found");
- *error = new ConnectError();
- return false;
- }
-
- const int socket = ::socket(AF_INET, SOCK_STREAM, 0);
- if (socket < 0) {
- LOG4CXX_ERROR(logger_, "Failed to create socket");
- *error = new ConnectError();
- return false;
- }
-
- struct sockaddr_in addr;
- memset((char*) &addr, 0, sizeof(addr));
- addr.sin_family = AF_INET;
- addr.sin_addr.s_addr = tcp_device->in_addr();
- addr.sin_port = port;
-
- if (::connect(socket, (struct sockaddr*) &addr, sizeof(addr)) < 0) {
- LOG4CXX_ERROR(logger_,
- "Failed to Connect for application" << application_handle());
- *error = new ConnectError();
- return false;
- }
-
- set_socket(socket);
- return true;
-}
-
-} // namespace transport_adapter
-} // namespace transport_manager
-
+++ /dev/null
-/**
- * \file threaded_socket_connection.cc
- * \brief ThreadedSocketConnection class source file.
- * Copyright (c) 2013, 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 <errno.h>
-#include <fcntl.h>
-#include <memory.h>
-#include <unistd.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-
-#include "transport_manager/transport_adapter/threaded_socket_connection.h"
-#include "transport_manager/transport_adapter/transport_adapter_controller.h"
-
-namespace transport_manager {
-namespace transport_adapter {
-
-ThreadedSocketConnection::ThreadedSocketConnection(
- const DeviceUID& device_id, const ApplicationHandle& app_handle,
- TransportAdapterController* controller)
- : read_fd_(-1), write_fd_(-1), controller_(controller),
- frames_to_send_(),
- frames_to_send_mutex_(),
- thread_(),
- socket_(-1),
- terminate_flag_(false),
- unexpected_disconnect_(false),
- device_uid_(device_id),
- app_handle_(app_handle) {
- pthread_mutex_init(&frames_to_send_mutex_, 0);
-}
-
-ThreadedSocketConnection::~ThreadedSocketConnection() {
- LOG4CXX_TRACE_ENTER(logger_);
- terminate_flag_ = true;
- Notify();
- pthread_join(thread_, 0);
- pthread_mutex_destroy(&frames_to_send_mutex_);
-
- if (-1 != read_fd_)
- close(read_fd_);
- if (-1 != write_fd_)
- close(write_fd_);
-
- LOG4CXX_TRACE_EXIT(logger_);
-}
-
-void ThreadedSocketConnection::Abort() {
- LOG4CXX_TRACE_ENTER(logger_);
- unexpected_disconnect_ = true;
- terminate_flag_ = true;
- LOG4CXX_TRACE_EXIT(logger_);
-}
-
-void* StartThreadedSocketConnection(void* v) {
- LOG4CXX_TRACE_ENTER(logger_);
- ThreadedSocketConnection* connection =
- static_cast<ThreadedSocketConnection*>(v);
- connection->Thread();
- LOG4CXX_TRACE_EXIT(logger_);
- return 0;
-}
-
-TransportAdapter::Error ThreadedSocketConnection::Start() {
- LOG4CXX_TRACE_ENTER(logger_);
- int fds[2];
- const int pipe_ret = pipe(fds);
- if (0 == pipe_ret) {
- LOG4CXX_INFO(logger_, "pipe created(#" << pthread_self() << ")");
- read_fd_ = fds[0];
- write_fd_ = fds[1];
- } else {
- LOG4CXX_INFO(logger_, "pipe creation failed (#" << pthread_self() << ")");
- LOG4CXX_TRACE_EXIT(logger_);
- return TransportAdapter::FAIL;
- }
- const int fcntl_ret = fcntl(read_fd_, F_SETFL,
- fcntl(read_fd_, F_GETFL) | O_NONBLOCK);
- if (0 != fcntl_ret) {
- LOG4CXX_INFO(logger_, "fcntl failed (#" << pthread_self() << ")");
- LOG4CXX_TRACE_EXIT(logger_);
- return TransportAdapter::FAIL;
- }
-
- if (0 == pthread_create(&thread_, 0, &StartThreadedSocketConnection, this)) {
- LOG4CXX_INFO(logger_, "thread created (#" << pthread_self() << ")");
- LOG4CXX_TRACE_EXIT(logger_);
- return TransportAdapter::OK;
- } else {
- LOG4CXX_INFO(logger_, "thread creation failed (#" << pthread_self() << ")");
- LOG4CXX_TRACE_EXIT(logger_);
- return TransportAdapter::FAIL;
- }
-}
-
-void ThreadedSocketConnection::Finalize() {
- LOG4CXX_TRACE_ENTER(logger_);
- if (unexpected_disconnect_) {
- LOG4CXX_INFO(logger_, "unexpected_disconnect (#" << pthread_self() << ")");
- controller_->ConnectionAborted(device_handle(), application_handle(),
- CommunicationError());
- } else {
- LOG4CXX_INFO(logger_, "not unexpected_disconnect (#" << pthread_self() << ")");
- controller_->ConnectionFinished(device_handle(), application_handle());
- }
- close(socket_);
- LOG4CXX_INFO(logger_, "Connection finalized");
- LOG4CXX_TRACE_EXIT(logger_);
-}
-
-TransportAdapter::Error ThreadedSocketConnection::Notify() const {
- LOG4CXX_TRACE_ENTER(logger_);
- if (-1 == write_fd_) {
- LOG4CXX_ERROR_WITH_ERRNO(
- logger_, "Failed to wake up connection thread for connection " << this);
- LOG4CXX_INFO(logger_, "exit");
- return TransportAdapter::BAD_STATE;
- }
- uint8_t c = 0;
- if (1 == write(write_fd_, &c, 1)) {
- LOG4CXX_INFO(logger_, "exit");
- return TransportAdapter::OK;
- } else {
- LOG4CXX_ERROR_WITH_ERRNO(
- logger_, "Failed to wake up connection thread for connection " << this);
- LOG4CXX_TRACE_EXIT(logger_);
- return TransportAdapter::FAIL;
- }
-}
-
-TransportAdapter::Error ThreadedSocketConnection::SendData(
- RawMessageSptr message) {
- LOG4CXX_TRACE_ENTER(logger_);
- pthread_mutex_lock(&frames_to_send_mutex_);
- frames_to_send_.push(message);
- pthread_mutex_unlock(&frames_to_send_mutex_);
- LOG4CXX_TRACE_EXIT(logger_);
- return Notify();
-}
-
-TransportAdapter::Error ThreadedSocketConnection::Disconnect() {
- LOG4CXX_TRACE_ENTER(logger_);
- terminate_flag_ = true;
- LOG4CXX_TRACE_EXIT(logger_);
- return Notify();
-}
-
-void ThreadedSocketConnection::Thread() {
- LOG4CXX_TRACE_ENTER(logger_);
- controller_->ConnectionCreated(this, device_uid_, app_handle_);
- ConnectError* connect_error = nullptr;
- if (Establish(&connect_error)) {
- LOG4CXX_INFO(logger_, "Connection established (#" << pthread_self() << ")");
- controller_->ConnectDone(device_handle(), application_handle());
- while (!terminate_flag_) {
- LOG4CXX_INFO(logger_, "Inside Thread() while!term loop");
- Transmit();
- }
- LOG4CXX_INFO(logger_, "Connection is to finalize (#" << pthread_self() << ")");
- Finalize();
- while (!frames_to_send_.empty()) {
- LOG4CXX_INFO(logger_, "removing message (#" << pthread_self() << ")");
- RawMessageSptr message = frames_to_send_.front();
- frames_to_send_.pop();
- controller_->DataSendFailed(device_handle(), application_handle(),
- message, DataSendError());
- }
- controller_->DisconnectDone(device_handle(), application_handle());
- } else {
- LOG4CXX_INFO(logger_, "Connection Establish failed (#" << pthread_self() << ")");
- controller_->ConnectFailed(device_handle(), application_handle(),
- *connect_error);
- delete connect_error;
- }
- LOG4CXX_TRACE_EXIT(logger_);
-}
-
-void ThreadedSocketConnection::Transmit() {
- LOG4CXX_TRACE_ENTER(logger_);
- bool pipe_notified = false;
- bool pipe_terminated = false;
-
- const nfds_t poll_fds_size = 2;
- pollfd poll_fds[poll_fds_size];
- poll_fds[0].fd = socket_;
- poll_fds[0].events = POLLIN | POLLPRI | (frames_to_send_.empty() ? 0 : POLLOUT);
- poll_fds[1].fd = read_fd_;
- poll_fds[1].events = POLLIN | POLLPRI;
-
- LOG4CXX_INFO(logger_, "poll (#" << pthread_self() << ") " << this);
- if (-1 == poll(poll_fds, poll_fds_size, -1)) {
- LOG4CXX_ERROR_WITH_ERRNO(logger_, "poll failed for connection " << this);
- Abort();
- LOG4CXX_INFO(logger_, "exit");
- return;
- }
- LOG4CXX_INFO(logger_, "poll is ok (#" << pthread_self() << ") " << this << " revents0:" << std::hex << poll_fds[0].revents << " revents1:" << std::hex << poll_fds[1].revents);
- // error check
- if (0 != (poll_fds[1].revents & (POLLERR | POLLHUP | POLLNVAL))) {
- LOG4CXX_ERROR(logger_,
- "Notification pipe for connection " << this << " terminated");
- Abort();
- LOG4CXX_INFO(logger_, "exit");
- return;
- }
-
- if (0 != (poll_fds[0].revents & (POLLERR | POLLHUP | POLLNVAL))) {
- LOG4CXX_INFO(logger_, "Connection " << this << " terminated");
- Abort();
- LOG4CXX_INFO(logger_, "exit");
- return;
- }
-
- // send data if possible
- if (!frames_to_send_.empty() && (poll_fds[0].revents | POLLOUT)) {
- LOG4CXX_INFO(logger_, "frames_to_send_ not empty() (#" << pthread_self() << ")");
- // clear notifications
- char buffer[256];
- ssize_t bytes_read = -1;
- do {
- bytes_read = read(read_fd_, buffer, sizeof(buffer));
- } while (bytes_read > 0);
-
- if ((bytes_read < 0) && (EAGAIN != errno)) {
- LOG4CXX_ERROR_WITH_ERRNO(logger_, "Failed to clear notification pipe");
- LOG4CXX_ERROR_WITH_ERRNO(logger_, "poll failed for connection " << this);
- Abort();
- LOG4CXX_INFO(logger_, "exit");
- return;
- }
-
- // send data
- const bool send_ok = Send();
- if (!send_ok) {
- LOG4CXX_INFO(logger_, "Send() failed (#" << pthread_self() << ")");
- Abort();
- LOG4CXX_INFO(logger_, "exit");
- return;
- }
- }
-
- // receive data
- if (0 != poll_fds[0].revents & (POLLIN | POLLPRI)) {
- const bool receive_ok = Receive();
- if (!receive_ok) {
- LOG4CXX_INFO(logger_, "Receive() failed (#" << pthread_self() << ")");
- Abort();
- LOG4CXX_INFO(logger_, "exit");
- return;
- }
- }
- LOG4CXX_TRACE_EXIT(logger_);
-}
-
-bool ThreadedSocketConnection::Receive() {
- LOG4CXX_TRACE_ENTER(logger_);
- uint8_t buffer[4096];
- ssize_t bytes_read = -1;
-
- do {
- bytes_read = recv(socket_, buffer, sizeof(buffer), MSG_DONTWAIT);
-
- if (bytes_read > 0) {
- LOG4CXX_INFO(
- logger_,
- "Received " << bytes_read << " bytes for connection " << this);
-
- RawMessageSptr frame(
- new protocol_handler::RawMessage(0, 0, buffer, bytes_read));
- controller_->DataReceiveDone(device_handle(), application_handle(),
- frame);
- } else if (bytes_read < 0) {
- if (EAGAIN != errno && EWOULDBLOCK != errno) {
- LOG4CXX_ERROR_WITH_ERRNO(logger_,
- "recv() failed for connection " << this);
- LOG4CXX_TRACE_EXIT(logger_);
- return false;
- }
- } else {
- LOG4CXX_INFO(logger_, "Connection " << this << " closed by remote peer");
- LOG4CXX_TRACE_EXIT(logger_);
- return false;
- }
- } while (bytes_read > 0);
- LOG4CXX_TRACE_EXIT(logger_);
- return true;
-}
-
-bool ThreadedSocketConnection::Send() {
- LOG4CXX_TRACE_ENTER(logger_);
- FrameQueue frames_to_send;
- pthread_mutex_lock(&frames_to_send_mutex_);
- std::swap(frames_to_send, frames_to_send_);
- pthread_mutex_unlock(&frames_to_send_mutex_);
-
- bool frame_sent = false;
- size_t offset = 0;
- while (!frames_to_send.empty()) {
- LOG4CXX_INFO(logger_, "frames_to_send is not empty" << pthread_self() << ")");
- RawMessageSptr frame = frames_to_send.front();
-
- const ssize_t bytes_sent = ::send(socket_, frame->data() + offset,
- frame->data_size() - offset, 0);
-
- if (bytes_sent >= 0) {
- LOG4CXX_INFO(logger_, "bytes_sent >= 0" << pthread_self() << ")");
- offset += bytes_sent;
- if (offset == frame->data_size()) {
- frames_to_send.pop();
- offset = 0;
- controller_->DataSendDone(device_handle(), application_handle(), frame);
- }
- } else {
- LOG4CXX_INFO(logger_, "bytes_sent < 0" << pthread_self() << ")");
- LOG4CXX_ERROR_WITH_ERRNO(logger_, "Send failed for connection " << this);
- frames_to_send.pop();
- offset = 0;
- controller_->DataSendFailed(device_handle(), application_handle(), frame,
- DataSendError());
- }
- }
- LOG4CXX_TRACE_EXIT(logger_);
- return true;
-}
-
-} // namespace
-} // namespace
-
+++ /dev/null
-/**
- * \file transport_adapter_impl.cc
- * \brief TransportAdapterImpl class source file.
- * Copyright (c) 2013, 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 "transport_manager/transport_adapter/transport_adapter_impl.h"
-#include "transport_manager/transport_adapter/transport_adapter_listener.h"
-#include "transport_manager/transport_adapter/device_scanner.h"
-#include "transport_manager/transport_adapter/server_connection_factory.h"
-#include "transport_manager/transport_adapter/client_connection_listener.h"
-
-namespace transport_manager {
-
-namespace transport_adapter {
-
-log4cxx::LoggerPtr logger_ = log4cxx::LoggerPtr(
- log4cxx::Logger::getLogger("TransportManager"));
-
-TransportAdapterImpl::TransportAdapterImpl(
- DeviceScanner* device_scanner,
- ServerConnectionFactory* server_connection_factory,
- ClientConnectionListener* client_connection_listener)
- : listeners_(),
- initialised_(0),
- devices_(),
- devices_mutex_(),
- connections_(),
- connections_mutex_(),
- device_scanner_(device_scanner),
- server_connection_factory_(server_connection_factory),
- client_connection_listener_(client_connection_listener) {
- pthread_mutex_init(&devices_mutex_, 0);
- pthread_mutex_init(&connections_mutex_, 0);
-}
-
-TransportAdapterImpl::~TransportAdapterImpl() {
- if (device_scanner_) {
- device_scanner_->Terminate();
- delete device_scanner_;
- }
- if (server_connection_factory_) {
- server_connection_factory_->Terminate();
- delete server_connection_factory_;
- }
- if (client_connection_listener_) {
- client_connection_listener_->Terminate();
- delete client_connection_listener_;
- }
-
- pthread_mutex_lock(&connections_mutex_);
- ConnectionMap connections;
- std::swap(connections, connections_);
- pthread_mutex_unlock(&connections_mutex_);
- connections.clear();
-
- pthread_mutex_lock(&devices_mutex_);
- DeviceMap devices;
- std::swap(devices, devices_);
- pthread_mutex_unlock(&devices_mutex_);
- devices.clear();
-
- pthread_mutex_destroy(&connections_mutex_);
- pthread_mutex_destroy(&devices_mutex_);
-}
-
-TransportAdapter::Error TransportAdapterImpl::Init() {
- LOG4CXX_INFO(logger_, "Initializing device adapter");
-
- Error error = OK;
-
- if ((error == OK) && device_scanner_)
- error = device_scanner_->Init();
- if ((error == OK) && server_connection_factory_)
- error = server_connection_factory_->Init();
- if ((error == OK) && client_connection_listener_)
- error = client_connection_listener_->Init();
-
- initialised_ = (error == OK);
- return error;
-}
-
-TransportAdapter::Error TransportAdapterImpl::SearchDevices() {
- LOG4CXX_INFO(logger_, "enter");
- if (device_scanner_ == nullptr) {
- LOG4CXX_INFO(logger_, "not supported");
- return NOT_SUPPORTED;
- } else if (!device_scanner_->IsInitialised()) {
- LOG4CXX_INFO(logger_, "bad state");
- return BAD_STATE;
- }
- LOG4CXX_INFO(logger_, "exit");
- return device_scanner_->Scan();
-}
-
-TransportAdapter::Error TransportAdapterImpl::Connect(
- const DeviceUID& device_id, const ApplicationHandle& app_handle) {
- LOG4CXX_INFO(logger_,
- "enter TransportAdapter::Error TransportAdapterImpl::Connect");
- if (server_connection_factory_ == 0) {
- LOG4CXX_ERROR(logger_, "feature is NOT_SUPPORTED");
- return NOT_SUPPORTED;
- }
- if (!server_connection_factory_->IsInitialised()) {
- LOG4CXX_ERROR(logger_, "BAD_STATE");
- return BAD_STATE;
- }
-
- return server_connection_factory_->CreateConnection(device_id, app_handle);
-}
-
-TransportAdapter::Error TransportAdapterImpl::Disconnect(
- const DeviceUID& device_id, const ApplicationHandle& app_handle) {
- if (!initialised_)
- return BAD_STATE;
- ConnectionSptr connection = FindEstablishedConnection(device_id, app_handle);
- if (connection.valid()) {
- return connection->Disconnect();
- } else {
- return BAD_PARAM;
- }
-}
-
-TransportAdapter::Error TransportAdapterImpl::DisconnectDevice(
- const DeviceUID& device_id) {
- if (!initialised_)
- return BAD_STATE;
-
- Error error = OK;
- pthread_mutex_lock(&connections_mutex_);
- for (ConnectionMap::iterator it = connections_.begin();
- it != connections_.end(); ++it) {
-
- ConnectionInfo& info = it->second;
- if (info.device_id == device_id
- && info.state != ConnectionInfo::FINALISING) {
- if (OK != info.connection->Disconnect()) {
- error = FAIL;
- }
- }
- }
- pthread_mutex_unlock(&connections_mutex_);
-
- return OK;
-}
-
-TransportAdapter::Error TransportAdapterImpl::SendData(
- const DeviceUID& device_id, const ApplicationHandle& app_handle,
- const RawMessageSptr data) {
- if (!initialised_)
- return BAD_STATE;
-
- ConnectionSptr connection = FindEstablishedConnection(device_id, app_handle);
- if (connection.get() != 0) {
- connection->SendData(data);
- return OK;
- } else {
- return BAD_PARAM;
- }
-}
-
-TransportAdapter::Error TransportAdapterImpl::StartClientListening() {
- if (client_connection_listener_ == 0)
- return NOT_SUPPORTED;
- if (!client_connection_listener_->IsInitialised())
- return BAD_STATE;
- return client_connection_listener_->StartListening();
-}
-
-TransportAdapter::Error TransportAdapterImpl::StopClientListening() {
- if (client_connection_listener_ == 0)
- return NOT_SUPPORTED;
- if (!client_connection_listener_->IsInitialised())
- return BAD_STATE;
- return client_connection_listener_->StopListening();
-}
-
-DeviceList TransportAdapterImpl::GetDeviceList() const {
- DeviceList devices;
- pthread_mutex_lock(&devices_mutex_);
- for (DeviceMap::const_iterator it = devices_.begin(); it != devices_.end();
- ++it) {
- devices.push_back(it->first);
- }
- pthread_mutex_unlock(&devices_mutex_);
- return devices;
-}
-
-DeviceSptr TransportAdapterImpl::AddDevice(DeviceSptr device) {
- DeviceSptr existing_device;
- bool same_device_found = false;
- pthread_mutex_lock(&devices_mutex_);
- for (DeviceMap::const_iterator i = devices_.begin(); i != devices_.end();
- ++i) {
- existing_device = i->second;
- if (device->IsSameAs(existing_device.get())) {
- same_device_found = true;
- break;
- }
- }
- if (!same_device_found) {
- devices_[device->unique_device_id()] = device;
- }
- pthread_mutex_unlock(&devices_mutex_);
- if (same_device_found) {
- return existing_device;
- } else {
- for (TransportAdapterListenerList::iterator it = listeners_.begin();
- it != listeners_.end(); ++it) {
- (*it)->OnDeviceListUpdated(this);
- }
- return device;
- }
-}
-
-void TransportAdapterImpl::SearchDeviceDone(const DeviceVector& devices) {
- DeviceMap new_devices;
- for (DeviceVector::const_iterator it = devices.begin(); it != devices.end();
- ++it) {
- DeviceSptr device = *it;
- bool device_found = false;
-
- pthread_mutex_lock(&devices_mutex_);
- for (DeviceMap::iterator it = devices_.begin(); it != devices_.end();
- ++it) {
- DeviceSptr existing_device = it->second;
- if (device->IsSameAs(existing_device.get())) {
- device_found = true;
- break;
- }
- }
- pthread_mutex_unlock(&devices_mutex_);
-
- if (!device_found) {
- LOG4CXX_INFO(
- logger_,
- "Adding new device " << device->unique_device_id() << " (\""
- << device->name() << "\")");
- }
-
- new_devices[device->unique_device_id()] = device;
- }
-
- pthread_mutex_lock(&connections_mutex_);
- std::set<DeviceUID> connected_devices;
- for (ConnectionMap::const_iterator it = connections_.begin();
- it != connections_.end(); ++it) {
- const ConnectionInfo& info = it->second;
- if (info.state != ConnectionInfo::FINALISING)
- connected_devices.insert(info.device_id);
- }
- pthread_mutex_unlock(&connections_mutex_);
-
- pthread_mutex_lock(&devices_mutex_);
- for (DeviceMap::iterator it = devices_.begin(); it != devices_.end(); ++it) {
- DeviceSptr existing_device = it->second;
-
- if (new_devices.end() == new_devices.find(it->first)) {
- if (connected_devices.end() != connected_devices.find(it->first)) {
- new_devices[it->first] = existing_device;
- }
- }
- }
- devices_ = new_devices;
- pthread_mutex_unlock(&devices_mutex_);
-
- for (TransportAdapterListenerList::iterator it = listeners_.begin();
- it != listeners_.end(); ++it) {
- (*it)->OnDeviceListUpdated(this);
- (*it)->OnSearchDeviceDone(this);
- }
-}
-
-void TransportAdapterImpl::SearchDeviceFailed(const SearchDeviceError& error) {
- for (TransportAdapterListenerList::iterator it = listeners_.begin();
- it != listeners_.end(); ++it)
- (*it)->OnSearchDeviceFailed(this, error);
-}
-
-bool TransportAdapterImpl::IsSearchDevicesSupported() const {
- return device_scanner_ != 0;
-}
-
-bool TransportAdapterImpl::IsServerOriginatedConnectSupported() const {
- return server_connection_factory_ != 0;
-}
-
-bool TransportAdapterImpl::IsClientOriginatedConnectSupported() const {
- return client_connection_listener_ != 0;
-}
-
-void TransportAdapterImpl::ConnectionCreated(
- ConnectionSptr connection, const DeviceUID& device_id,
- const ApplicationHandle& app_handle) {
- pthread_mutex_lock(&connections_mutex_);
- ConnectionInfo& info = connections_[std::make_pair(device_id, app_handle)];
- info.app_handle = app_handle;
- info.device_id = device_id;
- info.connection = connection;
- info.state = ConnectionInfo::NEW;
- pthread_mutex_unlock(&connections_mutex_);
-}
-
-void TransportAdapterImpl::DisconnectDone(const DeviceUID& device_id,
- const ApplicationHandle& app_handle) {
- bool device_disconnected = true;
- pthread_mutex_lock(&connections_mutex_);
- for (ConnectionMap::const_iterator it = connections_.begin();
- it != connections_.end(); ++it) {
- const DeviceUID& current_device_id = it->first.first;
- const ApplicationHandle& current_app_handle = it->first.second;
- if (current_device_id == device_id && current_app_handle != app_handle) {
- device_disconnected = false;
- break;
- }
- }
- pthread_mutex_unlock(&connections_mutex_);
- for (TransportAdapterListenerList::iterator it = listeners_.begin();
- it != listeners_.end(); ++it) {
- TransportAdapterListener* listener = *it;
- listener->OnDisconnectDone(this, device_id, app_handle);
- if (device_disconnected)
- listener->OnDisconnectDeviceDone(this, device_id);
- }
- pthread_mutex_lock(&connections_mutex_);
- connections_.erase(std::make_pair(device_id, app_handle));
- pthread_mutex_unlock(&connections_mutex_);
-}
-
-void TransportAdapterImpl::DataReceiveDone(const DeviceUID& device_id,
- const ApplicationHandle& app_handle,
- RawMessageSptr message) {
- for (TransportAdapterListenerList::iterator it = listeners_.begin();
- it != listeners_.end(); ++it)
- (*it)->OnDataReceiveDone(this, device_id, app_handle, message);
-}
-
-void TransportAdapterImpl::DataReceiveFailed(
- const DeviceUID& device_id, const ApplicationHandle& app_handle,
- const DataReceiveError& error) {
- for (TransportAdapterListenerList::iterator it = listeners_.begin();
- it != listeners_.end(); ++it)
- (*it)->OnDataReceiveFailed(this, device_id, app_handle, error);
-}
-
-void TransportAdapterImpl::DataSendDone(const DeviceUID& device_id,
- const ApplicationHandle& app_handle,
- RawMessageSptr message) {
- for (TransportAdapterListenerList::iterator it = listeners_.begin();
- it != listeners_.end(); ++it)
- (*it)->OnDataSendDone(this, device_id, app_handle, message);
-}
-
-void TransportAdapterImpl::DataSendFailed(const DeviceUID& device_id,
- const ApplicationHandle& app_handle,
- RawMessageSptr message,
- const DataSendError& error) {
- for (TransportAdapterListenerList::iterator it = listeners_.begin();
- it != listeners_.end(); ++it)
- (*it)->OnDataSendFailed(this, device_id, app_handle, message, error);
-}
-
-DeviceSptr TransportAdapterImpl::FindDevice(const DeviceUID& device_id) const {
- DeviceSptr ret;
- pthread_mutex_lock(&devices_mutex_);
- LOG4CXX_INFO(
- logger_,
- "DeviceSptr TransportAdapterImpl::FindDevice(const DeviceUID& device_id) enter");
- DeviceMap::const_iterator it = devices_.find(device_id);
- LOG4CXX_INFO(logger_, "devices_.size() = " << devices_.size());
- if (it != devices_.end())
- ret = it->second;
- pthread_mutex_unlock(&devices_mutex_);
- LOG4CXX_INFO(
- logger_,
- "DeviceSptr TransportAdapterImpl::FindDevice(const DeviceUID& device_id) exit");
- return ret;
-}
-
-void TransportAdapterImpl::ConnectDone(const DeviceUID& device_id,
- const ApplicationHandle& app_handle) {
- LOG4CXX_INFO(logger_, "Entered Connect Done and acquiring lock");
- pthread_mutex_lock(&connections_mutex_);
- LOG4CXX_INFO(logger_, "Lock acquired on connections_mutex");
- ConnectionMap::iterator it = connections_.find(
- std::make_pair(device_id, app_handle));
- if (it != connections_.end()) {
- ConnectionInfo& info = it->second;
- info.state = ConnectionInfo::ESTABLISHED;
- }
- pthread_mutex_unlock(&connections_mutex_);
-
- for (TransportAdapterListenerList::iterator it = listeners_.begin();
- it != listeners_.end(); ++it)
- (*it)->OnConnectDone(this, device_id, app_handle);
-
- LOG4CXX_INFO(logger_, "Leaving ConnectDone!");
-}
-
-void TransportAdapterImpl::ConnectFailed(const DeviceUID& device_id,
- const ApplicationHandle& app_handle,
- const ConnectError& error) {
- pthread_mutex_lock(&connections_mutex_);
- connections_.erase(std::make_pair(device_id, app_handle));
- pthread_mutex_unlock(&connections_mutex_);
- for (TransportAdapterListenerList::iterator it = listeners_.begin();
- it != listeners_.end(); ++it)
- (*it)->OnConnectFailed(this, device_id, app_handle, error);
-}
-
-void TransportAdapterImpl::AddListener(TransportAdapterListener* listener) {
- listeners_.push_back(listener);
-}
-
-ApplicationList TransportAdapterImpl::GetApplicationList(
- const DeviceUID& device_id) const {
- LOG4CXX_INFO(
- logger_,
- "ApplicationList TransportAdapterImpl::GetApplicationList enter");
- DeviceSptr device = FindDevice(device_id);
- if (device.valid()) {
- LOG4CXX_INFO(logger_, "device is valid");
- return device->GetApplicationList();
- }
-
- LOG4CXX_INFO(logger_, "device is NOT valid. Return empty list");
- return ApplicationList();
-}
-
-void TransportAdapterImpl::ConnectionFinished(
- const DeviceUID& device_id, const ApplicationHandle& app_handle) {
- pthread_mutex_lock(&connections_mutex_);
- ConnectionMap::iterator it = connections_.find(
- std::make_pair(device_id, app_handle));
- if (it != connections_.end()) {
- ConnectionInfo& info = it->second;
- info.state = ConnectionInfo::FINALISING;
- }
- pthread_mutex_unlock(&connections_mutex_);
-}
-
-void TransportAdapterImpl::ConnectionAborted(
- const DeviceUID& device_id, const ApplicationHandle& app_handle,
- const CommunicationError& error) {
- ConnectionFinished(device_id, app_handle);
- for (TransportAdapterListenerList::iterator it = listeners_.begin();
- it != listeners_.end(); ++it)
- (*it)->OnUnexpectedDisconnect(this, device_id, app_handle, error);
-}
-
-bool TransportAdapterImpl::IsInitialised() const {
- if (!initialised_)
- return false;
- if (device_scanner_ && !device_scanner_->IsInitialised())
- return false;
- if (server_connection_factory_
- && !server_connection_factory_->IsInitialised())
- return false;
- if (client_connection_listener_
- && !client_connection_listener_->IsInitialised())
- return false;
- return true;
-}
-
-std::string TransportAdapterImpl::DeviceName(const DeviceUID &device_id) const {
- DeviceSptr device = FindDevice(device_id);
- if (device.valid()) {
- return device->name();
- } else {
- return "";
- }
-}
-
-void TransportAdapterImpl::RemoveListener(TransportAdapterListener* listener) {
- listeners_.remove(listener);
-}
-
-ConnectionSptr TransportAdapterImpl::FindEstablishedConnection(
- const DeviceUID& device_id, const ApplicationHandle& app_handle) {
- ConnectionSptr connection;
- pthread_mutex_lock(&connections_mutex_);
- ConnectionMap::iterator it = connections_.find(
- std::make_pair(device_id, app_handle));
- if (it != connections_.end()) {
- ConnectionInfo& info = it->second;
- if (info.state == ConnectionInfo::ESTABLISHED)
- connection = info.connection;
- }
- pthread_mutex_unlock(&connections_mutex_);
- return connection;
-}
-
-} // namespace transport_adapter
-
-} // namespace transport_manager
+++ /dev/null
-/**
- * \file transport_adapter_listener_impl.cc
- * \brief TransportAdapterListenerImpl class source file.
- *
- * Copyright (c) 2013, 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 "transport_manager/transport_adapter/transport_adapter_listener_impl.h"
-
-#include <algorithm>
-
-#include "transport_manager/transport_manager_impl.h"
-#include "transport_manager/common.h"
-
-using transport_manager::transport_adapter::TransportAdapter;
-
-namespace transport_manager {
-
-log4cxx::LoggerPtr TransportAdapterListenerImpl::logger_ = log4cxx::LoggerPtr(
- log4cxx::Logger::getLogger("TransportAdapterListener"));
-
-TransportAdapterListenerImpl::~TransportAdapterListenerImpl() {
-}
-
-TransportAdapterListenerImpl::TransportAdapterListenerImpl(
- transport_manager::TransportManagerImpl *tm) {
- transport_manager_impl_ = tm;
-}
-
-void TransportAdapterListenerImpl::OnSearchDeviceDone(
- const transport_adapter::TransportAdapter *transport_adapter) {
- AdapterIterator it;
- if (!FindSharedPtr(transport_adapter, it)) {
- LOG4CXX_ERROR(logger_,
- "Can't find transport adapter " << transport_adapter);
- return;
- }
-
- TransportAdapterEvent event(
- TransportAdapterListenerImpl::EventTypeEnum::ON_SEARCH_DONE, *it, "", 0,
- RawMessageSptr(), new BaseError());
-
- transport_manager_impl_->ReceiveEventFromDevice(event);
-}
-
-void TransportAdapterListenerImpl::OnSearchDeviceFailed(
- const transport_adapter::TransportAdapter* transport_adapter,
- const SearchDeviceError& error) {
- AdapterIterator it;
- if (!FindSharedPtr(transport_adapter, it)) {
- LOG4CXX_ERROR(logger_,
- "Can't find transport adapter " << transport_adapter);
- return;
- }
-
- SearchDeviceError *err = new SearchDeviceError(error);
- TransportAdapterEvent event(
- TransportAdapterListenerImpl::EventTypeEnum::ON_SEARCH_FAIL, *it, "", 0,
- RawMessageSptr(), err);
-
- transport_manager_impl_->ReceiveEventFromDevice(event);
-}
-
-void TransportAdapterListenerImpl::OnDeviceListUpdated(
- const TransportAdapter *transport_adapter) {
- AdapterIterator it;
- if (!FindSharedPtr(transport_adapter, it)) {
- LOG4CXX_ERROR(logger_,
- "Can't find transport adapter " << transport_adapter);
- return;
- }
-
- TransportAdapterEvent event(
- TransportAdapterListenerImpl::EventTypeEnum::ON_DEVICE_LIST_UPDATED, *it,
- "", 0, RawMessageSptr(), NULL);
-
- transport_manager_impl_->ReceiveEventFromDevice(event);
-}
-
-void TransportAdapterListenerImpl::OnConnectDone(
- const TransportAdapter* transport_adapter, const DeviceUID& device,
- const ApplicationHandle& application_id) {
- AdapterIterator it;
- LOG4CXX_INFO(logger_, "OnConnectDone Entered");
- if (!FindSharedPtr(transport_adapter, it)) {
- LOG4CXX_ERROR(logger_,
- "Can't find transport adapter " << transport_adapter);
- return;
- }
-
- TransportAdapterEvent event(
- TransportAdapterListenerImpl::EventTypeEnum::ON_CONNECT_DONE, *it, device,
- application_id, RawMessageSptr(), new BaseError());
-
- transport_manager_impl_->ReceiveEventFromDevice(event);
-}
-
-void TransportAdapterListenerImpl::OnConnectFailed(
- const TransportAdapter* transport_adapter, const DeviceUID& device,
- const ApplicationHandle& app_id, const ConnectError& error) {
- AdapterIterator it;
- if (!FindSharedPtr(transport_adapter, it)) {
- LOG4CXX_ERROR(logger_,
- "Can't find transport adapter " << transport_adapter);
- return;
- }
-
- ConnectError *err = new ConnectError(error);
- TransportAdapterEvent event(
- TransportAdapterListenerImpl::EventTypeEnum::ON_CONNECT_FAIL, *it, device,
- app_id, RawMessageSptr(), err);
-
- transport_manager_impl_->ReceiveEventFromDevice(event);
-}
-
-void TransportAdapterListenerImpl::OnDisconnectDone(
- const TransportAdapter* transport_adapter, const DeviceUID& device,
- const ApplicationHandle& app_id) {
- AdapterIterator it;
- if (!FindSharedPtr(transport_adapter, it)) {
- LOG4CXX_ERROR(logger_,
- "Can't find transport adapter " << transport_adapter);
- return;
- }
-
- TransportAdapterEvent event(
- TransportAdapterListenerImpl::EventTypeEnum::ON_DISCONNECT_DONE, *it,
- device, app_id, RawMessageSptr(), new BaseError());
-
- transport_manager_impl_->ReceiveEventFromDevice(event);
-}
-
-void TransportAdapterListenerImpl::OnDisconnectFailed(
- const TransportAdapter* transport_adapter, const DeviceUID& device,
- const ApplicationHandle& app_id, const DisconnectError& error) {
- AdapterIterator it;
- if (!FindSharedPtr(transport_adapter, it)) {
- LOG4CXX_ERROR(logger_,
- "Can't find transport adapter " << transport_adapter);
- return;
- }
-
- DisconnectError *err = new DisconnectError(error);
- TransportAdapterEvent event(
- TransportAdapterListenerImpl::EventTypeEnum::ON_DISCONNECT_FAIL, *it,
- device, app_id, RawMessageSptr(), err);
-
- transport_manager_impl_->ReceiveEventFromDevice(event);
-}
-
-void TransportAdapterListenerImpl::OnDisconnectDeviceDone(
- const TransportAdapter* transport_adapter, const DeviceUID& device) {
-
-}
-
-void TransportAdapterListenerImpl::OnDisconnectDeviceFailed(
- const TransportAdapter* transport_adapter, const DeviceUID& device,
- const DisconnectDeviceError& error) {
-
-}
-
-void TransportAdapterListenerImpl::OnDataReceiveDone(
- const TransportAdapter* transport_adapter, const DeviceUID& device,
- const ApplicationHandle& app_id, const RawMessageSptr data_container) {
- AdapterIterator it;
- if (!FindSharedPtr(transport_adapter, it)) {
- LOG4CXX_ERROR(logger_,
- "Can't find transport adapter " << transport_adapter);
- return;
- }
-
- TransportAdapterEvent event(
- TransportAdapterListenerImpl::EventTypeEnum::ON_RECEIVED_DONE, *it,
- device, app_id, data_container, new BaseError());
-
- transport_manager_impl_->ReceiveEventFromDevice(event);
-}
-
-void TransportAdapterListenerImpl::OnDataReceiveFailed(
- const TransportAdapter* transport_adapter, const DeviceUID& device,
- const ApplicationHandle& app_id,
-
- const DataReceiveError& error) {
- AdapterIterator it;
- if (!FindSharedPtr(transport_adapter, it)) {
- LOG4CXX_ERROR(logger_,
- "Can't find transport adapter " << transport_adapter);
- return;
- }
-
- DataReceiveError *err = new DataReceiveError(error);
- TransportAdapterEvent event(
- TransportAdapterListenerImpl::EventTypeEnum::ON_RECEIVED_FAIL, *it,
- device, app_id, RawMessageSptr(), err);
-
- transport_manager_impl_->ReceiveEventFromDevice(event);
-}
-
-void TransportAdapterListenerImpl::OnDataSendDone(
- const TransportAdapter* transport_adapter, const DeviceUID& device,
- const ApplicationHandle& app_id, const RawMessageSptr data_container) {
- AdapterIterator it;
- if (!FindSharedPtr(transport_adapter, it)) {
- LOG4CXX_ERROR(logger_,
- "Can't find transport adapter " << transport_adapter);
- return;
- }
-
- TransportAdapterEvent event(
- TransportAdapterListenerImpl::EventTypeEnum::ON_SEND_DONE, *it, device,
- app_id, data_container, new BaseError());
- transport_manager_impl_->ReceiveEventFromDevice(event);
-}
-
-void TransportAdapterListenerImpl::OnDataSendFailed(
- const TransportAdapter* transport_adapter, const DeviceUID& device,
- const ApplicationHandle& app_id, const RawMessageSptr data_container,
- const DataSendError& error) {
- AdapterIterator it;
- if (!FindSharedPtr(transport_adapter, it)) {
- LOG4CXX_ERROR(logger_,
- "Can't find transport adapter " << transport_adapter);
- return;
- }
-
- DataSendError *err = new DataSendError(error);
- TransportAdapterEvent event(
- TransportAdapterListenerImpl::EventTypeEnum::ON_SEND_FAIL, *it, device,
- app_id, data_container, err);
-
- transport_manager_impl_->ReceiveEventFromDevice(event);
-}
-
-void TransportAdapterListenerImpl::OnConnectRequested(
- const TransportAdapter* transport_adapter, const DeviceUID& device_handle,
- const ApplicationHandle& app_handle) {
-}
-
-void TransportAdapterListenerImpl::OnUnexpectedDisconnect(
- const transport_adapter::TransportAdapter* transport_adapter,
- const DeviceUID& device, const ApplicationHandle& application,
- const CommunicationError& error) {
- AdapterIterator it;
- if (!FindSharedPtr(transport_adapter, it)) {
- LOG4CXX_ERROR(logger_,
- "Can't find transport adapter " << transport_adapter);
- return;
- }
-
- CommunicationError* err = new CommunicationError(error);
- TransportAdapterEvent event(
- TransportAdapterListenerImpl::EventTypeEnum::ON_UNEXPECTED_DISCONNECT,
- *it, device, application, RawMessageSptr(), err);
-
- transport_manager_impl_->ReceiveEventFromDevice(event);
-}
-
-void TransportAdapterListenerImpl::OnCommunicationError(
- const TransportAdapter* transport_adapter, const DeviceUID& device,
- const ApplicationHandle& app_id) {
- AdapterIterator it;
- if (!FindSharedPtr(transport_adapter, it)) {
- LOG4CXX_ERROR(logger_,
- "Can't find transport adapter " << transport_adapter);
- return;
- }
-
- TransportAdapterEvent event(
- TransportAdapterListenerImpl::EventTypeEnum::ON_COMMUNICATION_ERROR, *it,
- device, app_id, RawMessageSptr(), new BaseError());
-
- transport_manager_impl_->ReceiveEventFromDevice(event);
-}
-
-bool TransportAdapterListenerImpl::FindSharedPtr(
- const TransportAdapter* transport_adapter, AdapterIterator &it) {
- it = std::find(transport_manager_impl_->transport_adapters_.begin(),
- transport_manager_impl_->transport_adapters_.end(),
- transport_adapter);
-
- return it != transport_manager_impl_->transport_adapters_.end();
-}
-
-} // namespace transport_manager
-
+++ /dev/null
-/**
- * \file transport_manager_impl.cc
- * \brief TransportManagerImpl class source file.
- *
- * Copyright (c) 2013, 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 <pthread.h>
-#include <cstring>
-#include <queue>
-#include <algorithm>
-#include <limits>
-#include <functional>
-
-#include "utils/macro.h"
-#include "protocol_handler/raw_message.h"
-#include "transport_manager/transport_manager_impl.h"
-#include "transport_manager/transport_manager_listener.h"
-#include "transport_manager/transport_manager_listener_impl.h"
-#include "transport_manager/transport_adapter/transport_adapter_listener_impl.h"
-#include "transport_manager/timer.h"
-#include "transport_manager/bluetooth/bluetooth_transport_adapter.h"
-#include "transport_manager/tcp/tcp_transport_adapter.h"
-#include "transport_manager/transport_adapter/transport_adapter.h"
-
-using ::transport_manager::transport_adapter::TransportAdapter;
-using ::transport_manager::transport_adapter::TransportAdapterSptr;
-
-namespace transport_manager {
-
-log4cxx::LoggerPtr TransportManagerImpl::logger_ = log4cxx::LoggerPtr(
- log4cxx::Logger::getLogger("TransportManager"));
-
-TransportManagerImpl::TransportManagerImpl(const TransportManagerAttr& config)
- : message_queue_mutex_(),
- all_thread_active_(false),
- messsage_queue_thread_(),
- event_queue_thread_(),
- device_listener_thread_wakeup_(),
- is_initialized_(false),
- connection_id_counter_(0),
- config_(config),
- protocol_handler_(NULL) {
- LOG4CXX_INFO(logger_, "==============================================");
- pthread_mutex_init(&message_queue_mutex_, nullptr);
- pthread_cond_init(&message_queue_cond, nullptr);
- pthread_mutex_init(&event_queue_mutex_, 0);
- pthread_cond_init(&device_listener_thread_wakeup_, NULL);
- LOG4CXX_INFO(logger_, "TransportManager object created");
-}
-
-TransportManagerImpl::~TransportManagerImpl() {
- all_thread_active_ = false;
-
- pthread_mutex_lock(&event_queue_mutex_);
- pthread_cond_signal(&device_listener_thread_wakeup_);
- pthread_mutex_unlock(&event_queue_mutex_);
-
- pthread_mutex_lock(&message_queue_mutex_);
- pthread_cond_signal(&message_queue_cond);
- pthread_mutex_unlock(&message_queue_mutex_);
-
- pthread_join(messsage_queue_thread_, 0);
- pthread_join(event_queue_thread_, 0);
-
- pthread_mutex_destroy(&message_queue_mutex_);
- pthread_cond_destroy(&message_queue_cond);
- pthread_mutex_destroy(&event_queue_mutex_);
- pthread_cond_destroy(&device_listener_thread_wakeup_);
-
- for (std::map<TransportAdapterSptr, TransportAdapterListenerImpl*>::iterator it =
- transport_adapter_listeners_.begin();
- it != transport_adapter_listeners_.end(); ++it) {
- delete it->second;
- }
- LOG4CXX_INFO(logger_, "TransportManager object destroyed");
-}
-
-std::vector<TransportManagerImpl::Connection> TransportManagerImpl::GetConnectionList() {
- std::vector<TransportManagerImpl::Connection> rc(connections_.size());
- std::transform(connections_.begin(), connections_.end(), rc.begin(),
- [&](ConnectionInternal & p) {
- Connection c;
- c.application = p.application;
- c.device = p.device;
- c.id = p.id;
- return c;
- });
- return rc;
-}
-
-int TransportManagerImpl::ConnectDevice(const DeviceHandle& device_handle) {
- LOG4CXX_INFO(
- logger_,
- "Connect device called with arguments device_handle " << device_handle);
- if (!this->is_initialized_) {
- LOG4CXX_ERROR(logger_, "TransportManager is not initialized.");
- return E_TM_IS_NOT_INITIALIZED;
- }
-
- DeviceUID device_id = converter_.HandleToUid(device_handle);
- LOG4CXX_INFO(logger_, "Convert handle to id " << device_id);
-
- transport_adapter::TransportAdapterSptr da = device_to_adapter_map_[device_id];
- if (!da.valid()) {
- LOG4CXX_ERROR(logger_, "No device adapter found by id " << device_id);
- return E_INVALID_HANDLE;
- }
- transport_adapter::DeviceList dl = da->GetDeviceList();
- transport_adapter::DeviceList::iterator it = std::find(dl.begin(), dl.end(),
- device_id);
- if (it == dl.end()) {
- LOG4CXX_INFO(
- logger_,
- "Device with handle " << device_handle << " and id " << device_id << " is not found");
- return E_INVALID_HANDLE;
- }
-
- ApplicationList app_list = da->GetApplicationList(device_id);
- LOG4CXX_INFO(logger_, "app_list.size() = " << app_list.size());
- for (ApplicationList::iterator it = app_list.begin(); it != app_list.end();
- ++it) {
- if (NULL != GetConnection(device_id, *it)) {
- LOG4CXX_ERROR(logger_, "Connect application failed E_CONNECTION_EXISTS");
- return E_CONNECTION_EXISTS;
- } else {
- LOG4CXX_ERROR(logger_, "attempt to Connect device");
- if (transport_adapter::TransportAdapter::OK
- != da->Connect(device_id, *it)) {
- LOG4CXX_ERROR(logger_, "Connect application failed E_INTERNAL_ERROR");
- return E_INTERNAL_ERROR;
- }
- }
- }
- LOG4CXX_INFO(logger_, "Connect device exit");
- return E_SUCCESS;
-}
-
-int TransportManagerImpl::DisconnectDevice(const DeviceHandle& device_handle) {
- LOG4CXX_INFO(logger_, "Disconnect device called");
- if (!this->is_initialized_) {
- LOG4CXX_ERROR(logger_, "TransportManager is not initialized.");
- return E_TM_IS_NOT_INITIALIZED;
- }
- DeviceUID device_id = converter_.HandleToUid(device_handle);
- LOG4CXX_INFO(logger_, "Convert handle to id" << device_id);
-
- transport_adapter::TransportAdapterSptr da = device_to_adapter_map_[device_id];
- if (!da.valid()) {
- LOG4CXX_ERROR(logger_, "No device adapter found by id " << device_id);
- return E_INVALID_HANDLE;
- }
- da->DisconnectDevice(device_id);
- LOG4CXX_INFO(logger_, "Disconnected");
- return E_SUCCESS;
-}
-
-void TransportManagerImpl::DisconnectFailedRoutine(void* p) {
- void** param = static_cast<void**>(p);
- TransportManagerImpl* tm = static_cast<TransportManagerImpl*>(param[0]);
- ConnectionInternal* c = static_cast<ConnectionInternal*>(param[1]);
- LOG4CXX_INFO(logger_, "Disconnection failed");
- tm->RaiseEvent(&TransportManagerListener::OnDisconnectFailed,
- tm->converter_.UidToHandle(c->device),
- DisconnectDeviceError());
- c->shutDown = false;
- c->timer.Stop();
- delete[] param;
-}
-
-int TransportManagerImpl::Disconnect(const ConnectionUID& cid) {
- if (!this->is_initialized_) {
- LOG4CXX_ERROR(logger_, "TransportManager is not initialized.");
- return E_TM_IS_NOT_INITIALIZED;
- }
-
- ConnectionInternal* connection = GetConnection(cid);
- if (connection == NULL) {
- LOG4CXX_ERROR(
- logger_, "TransportManagerImpl::Disconnect: Connection does not exist.");
- return E_INVALID_HANDLE;
- }
-
- pthread_mutex_lock(&event_queue_mutex_);
- int messages_count = 0;
- for (auto e : event_queue_) {
- if (e.application_id() == cid) {
- ++messages_count;
- }
- }
- pthread_mutex_unlock(&event_queue_mutex_);
-
- if (messages_count > 0) {
- connection->messages_count = messages_count;
- connection->shutDown = true;
- void** param = new void*[2];
- param[0] = this;
- param[1] = &connection;
- Timer timer(config_.disconnectTimeout, &DisconnectFailedRoutine, ¶m,
- true);
- connection->timer = timer;
- timer.Start();
- } else {
- connection->transport_adapter->Disconnect(connection->device,
- connection->application);
- }
- return E_SUCCESS;
-}
-
-int TransportManagerImpl::DisconnectForce(const ConnectionUID& cid) {
- if (false == this->is_initialized_) {
- LOG4CXX_ERROR(logger_, "TransportManager is not initialized.");
- return E_TM_IS_NOT_INITIALIZED;
- }
- pthread_mutex_lock(&event_queue_mutex_);
- // Clear messages for this connection
- // Note that MessageQueue typedef is assumed to be std::list,
- // or there is a problem here. One more point versus typedefs-everywhere
- auto e = message_queue_.begin();
- while (e != message_queue_.end()) {
- if ((*e)->connection_key() == cid) {
- RaiseEvent(&TransportManagerListener::OnTMMessageSendFailed,
- DataSendTimeoutError(), *e);
- e = message_queue_.erase(e);
- } else {
- ++e;
- }
- }
- pthread_mutex_unlock(&event_queue_mutex_);
- const ConnectionInternal* connection = GetConnection(cid);
- if (connection == NULL) {
- LOG4CXX_ERROR(
- logger_,
- "TransportManagerImpl::DisconnectForce: Connection does not exist.");
- return E_INVALID_HANDLE;
- }
- connection->transport_adapter->Disconnect(connection->device,
- connection->application);
- return E_SUCCESS;
-}
-
-int TransportManagerImpl::AddEventListener(TransportManagerListener* listener) {
- transport_manager_listener_.push_back(listener);
- return E_SUCCESS;
-}
-
-int TransportManagerImpl::RemoveEventListener(
- TransportManagerListener* listener) {
- transport_manager_listener_.remove(listener);
- return E_SUCCESS;
-}
-
-int TransportManagerImpl::SendMessageToDevice(const RawMessageSptr message) {
- LOG4CXX_INFO(logger_,
- "Send message to device called with arguments " << message.get());
- if (false == this->is_initialized_) {
- LOG4CXX_ERROR(logger_, "TM is not initialized.");
- return E_TM_IS_NOT_INITIALIZED;
- }
-
- const ConnectionInternal* connection = GetConnection(
- message->connection_key());
- if (connection == NULL) {
- LOG4CXX_ERROR(
- logger_,
- "Connection with id " << message->connection_key()
- << " does not exist.");
- return E_INVALID_HANDLE;
- }
-
- if (connection->shutDown) {
- LOG4CXX_ERROR(
- logger_,
- "TransportManagerImpl::Disconnect: Connection is to shut down.");
- return E_CONNECTION_IS_TO_SHUTDOWN;
- }
-
- this->PostMessage(message);
- LOG4CXX_INFO(logger_, "Message posted");
- return E_SUCCESS;
-}
-
-int TransportManagerImpl::ReceiveEventFromDevice(
- const TransportAdapterEvent& event) {
- LOG4CXX_INFO(logger_, "THIS IS SUPPOSED TO BE CALLED");
- if (false == this->is_initialized_) {
- LOG4CXX_ERROR(logger_, "TM is not initialized.");
- return E_TM_IS_NOT_INITIALIZED;
- }
- this->PostEvent(event);
- return E_SUCCESS;
-}
-
-int TransportManagerImpl::RemoveDevice(const DeviceHandle& device_handle) {
- DeviceUID device_id = converter_.HandleToUid(device_handle);
- if (false == this->is_initialized_) {
- LOG4CXX_ERROR(logger_, "TM is not initialized.");
- return E_TM_IS_NOT_INITIALIZED;
- }
- device_to_adapter_map_.erase(device_id);
- return E_SUCCESS;
-}
-
-int TransportManagerImpl::AddTransportAdapter(
- transport_adapter::TransportAdapterSptr transport_adapter) {
- LOG4CXX_INFO(
- logger_,
- "Add device adapter " << transport_adapter.get() << "[" << transport_adapter->GetDeviceType() << "]");
-
- transport_adapter_listeners_[transport_adapter] =
- new TransportAdapterListenerImpl(this);
- transport_adapter->AddListener(
- transport_adapter_listeners_[transport_adapter]);
-
- if (transport_adapter->IsInitialised()
- || transport_adapter->Init() == TransportAdapter::OK) {
- transport_adapters_.push_back(transport_adapter);
- }
-
- return E_SUCCESS;
-}
-
-int TransportManagerImpl::RemoveTransportAdapter(
- transport_adapter::TransportAdapterSptr transport_adapter) {
-
- std::vector<transport_adapter::TransportAdapterSptr>::iterator it;
- it = std::find(transport_adapters_.begin(), transport_adapters_.end(),
- transport_adapter);
- if (it != transport_adapters_.end()) {
- std::map<TransportAdapterSptr, TransportAdapterListenerImpl*>::iterator it_listener;
- it_listener = transport_adapter_listeners_.find(*it);
- if (it_listener != transport_adapter_listeners_.end()) {
- (*it)->RemoveListener(it_listener->second);
- delete it_listener->second;
- transport_adapter_listeners_.erase(it_listener);
- }
- transport_adapters_.erase(it);
- }
- return E_SUCCESS;
-}
-
-int TransportManagerImpl::SearchDevices(void) {
- if (!this->is_initialized_) {
- LOG4CXX_ERROR(logger_, "TM is not initialized");
- return E_TM_IS_NOT_INITIALIZED;
- }
-
- LOG4CXX_INFO(logger_, "Search device called");
-
- for (std::vector<TransportAdapterSptr>::iterator it = transport_adapters_
- .begin(); it != transport_adapters_.end(); ++it) {
- LOG4CXX_INFO(logger_, "Iterating over transport adapters");
- int scanResult = (*it)->SearchDevices();
- if (scanResult != transport_adapter::TransportAdapter::OK) {
- LOG4CXX_ERROR(
- logger_,
- "Transport Adapter search failed " << (*it).get() << "["
- << (*it)->GetDeviceType() << "]");
- switch (scanResult) {
- case transport_adapter::TransportAdapter::NOT_SUPPORTED:
- LOG4CXX_ERROR(
- logger_,
- "Search feature is not supported " << it->get() << "["
- << (*it)->GetDeviceType() << "]");
- break;
- case transport_adapter::TransportAdapter::BAD_STATE:
- LOG4CXX_ERROR(
- logger_,
- "Transport Adapter has bad state " << it->get() << "["
- << (*it)->GetDeviceType() << "]");
- break;
- }
- return scanResult;
- }
- }
- LOG4CXX_INFO(logger_, "SearchDevices() function is complete");
- return E_SUCCESS;
-}
-
-int TransportManagerImpl::Init(void) {
- LOG4CXX_INFO(logger_, "Init is called");
- all_thread_active_ = true;
- //this is what causes the problem in QNX
- //pthread_mutex_lock(&message_queue_mutex_);
- int error_code = pthread_create(&messsage_queue_thread_, 0,
- &MessageQueueStartThread, this);
- // Wait while thread starts loop
- LOG4CXX_INFO(logger_, "INIT: Ask for message_queue lock (post message queue thread start");
- pthread_mutex_lock(&message_queue_mutex_);
- LOG4CXX_INFO(logger_, "INIT: Message Queue Locked");
- pthread_mutex_unlock(&message_queue_mutex_);
- LOG4CXX_INFO(logger_, "INIT: Message Queue Unlocked");
-
- if (0 != error_code) {
- LOG4CXX_ERROR(
- logger_,
- "Message queue thread is not created exit with error code "
- << error_code);
- return E_TM_IS_NOT_INITIALIZED;
- }
- //This is what causes the problem on QNX
- //pthread_mutex_lock(&event_queue_mutex_);
- error_code = pthread_create(&event_queue_thread_, 0,
- &EventListenerStartThread, this);
- // Wait while thread starts loop
- LOG4CXX_INFO(logger_, "INIT: Post Event Listener ask for event queue lock");
- pthread_mutex_lock(&event_queue_mutex_);
- LOG4CXX_INFO(logger_, "INIT: Event queue mutex is locked");
- pthread_mutex_unlock(&event_queue_mutex_);
- LOG4CXX_INFO(logger_, "INIT: Event queue mutex unlocked");
-
- if (0 != error_code) {
- LOG4CXX_ERROR(
- logger_,
- "Event queue thread is not created exit with error code " << error_code);
- return E_TM_IS_NOT_INITIALIZED;
- }
-
- is_initialized_ = true;
- LOG4CXX_INFO(logger_, "Init complete");
- return E_SUCCESS;
-}
-
-int TransportManagerImpl::Visibility(const bool& on_off) const {
- bool ret;
-
- LOG4CXX_INFO(logger_, "Visibility change requested to " << on_off);
- if (false == this->is_initialized_) {
- LOG4CXX_ERROR(logger_, "TM is not initialized");
- return E_TM_IS_NOT_INITIALIZED;
- }
-
- for (std::vector<TransportAdapterSptr>::const_iterator it =
- transport_adapters_.begin(); it != transport_adapters_.end(); ++it) {
- if (on_off) {
- ret = (*it)->StartClientListening();
- } else {
- ret = (*it)->StopClientListening();
- }
- if (TransportAdapter::Error::NOT_SUPPORTED == ret) {
- LOG4CXX_INFO(
- logger_,
- "Visibility change is not supported for adapter " << (*it).get() << "[" << (*it)->GetDeviceType() << "]");
- }
- }
-
- LOG4CXX_INFO(logger_, "Visibility change requested complete");
- return E_SUCCESS;
-}
-
-std::vector<DeviceInfo> TransportManagerImpl::GetDeviceList() {
- std::vector<DeviceInfo> full_device_list;
- for (std::vector<TransportAdapterSptr>::const_iterator it =
- transport_adapters_.begin(); it != transport_adapters_.end(); ++it) {
- const TransportAdapterSptr& ta = *it;
- const transport_adapter::DeviceList dev_list = ta->GetDeviceList();
- for (transport_adapter::DeviceList::const_iterator it = dev_list.begin();
- it != dev_list.end(); ++it) {
- DeviceHandle device_handle = converter_.UidToHandle(*it);
- DeviceInfo info(device_handle, *it, ta->DeviceName(*it));
- full_device_list.push_back(info);
- }
- }
- return full_device_list;
-}
-
-void TransportManagerImpl::PostMessage(const RawMessageSptr message) {
- LOG4CXX_INFO(logger_, "Post message called serial number " << message.get());
-
- pthread_mutex_lock(&message_queue_mutex_);
- message_queue_.push_back(message);
- pthread_cond_signal(&message_queue_cond);
- pthread_mutex_unlock(&message_queue_mutex_);
- LOG4CXX_INFO(logger_, "Post message complete");
-}
-
-void TransportManagerImpl::RemoveMessage(const RawMessageSptr message) {
- // TODO: Reconsider necessity of this method, remove if it's useless,
- // make to work otherwise.
- // 2013-08-21 dchmerev@luxoft.com
- LOG4CXX_INFO(logger_, "Remove message called " << message.get());
- pthread_mutex_lock(&message_queue_mutex_);
- std::remove(message_queue_.begin(), message_queue_.end(), message);
- pthread_mutex_unlock(&message_queue_mutex_);
- LOG4CXX_INFO(logger_, "Remove message from queue complete");
-}
-
-void TransportManagerImpl::RemoveEvent(const TransportAdapterEvent& event) {
- LOG4CXX_INFO(logger_, "Remove event from queue called");
- pthread_mutex_lock(&event_queue_mutex_);
- std::remove(event_queue_.begin(), event_queue_.end(), event);
- pthread_cond_signal(&device_listener_thread_wakeup_);
- pthread_mutex_unlock(&event_queue_mutex_);
- LOG4CXX_INFO(logger_, "Remove event from queue complete");
-}
-
-void TransportManagerImpl::PostEvent(const TransportAdapterEvent& event) {
- LOG4CXX_INFO(logger_, "Post event reached and event_mutex locked");
- pthread_mutex_lock(&event_queue_mutex_);
- event_queue_.push_back(event);
- LOG4CXX_INFO(logger_, "pushing on the event queue and signalling device listener");
- pthread_cond_signal(&device_listener_thread_wakeup_);
- LOG4CXX_INFO(logger_, "unlocking the event queue mutex");
- pthread_mutex_unlock(&event_queue_mutex_);
-}
-
-void* TransportManagerImpl::EventListenerStartThread(void* data) {
- if (NULL != data) {
- static_cast<TransportManagerImpl*>(data)->EventListenerThread();
- }
- return 0;
-}
-
-void TransportManagerImpl::AddConnection(const ConnectionInternal& c) {
- connections_.push_back(c);
-}
-
-void TransportManagerImpl::RemoveConnection(int id) {
- for (std::vector<ConnectionInternal>::iterator it = connections_.begin();
- it != connections_.end(); ++it) {
- if (it->id == id) {
- connections_.erase(it);
- break;
- }
- }
-}
-
-TransportManagerImpl::ConnectionInternal* TransportManagerImpl::GetConnection(
- const ConnectionUID& id) {
- for (auto it = connections_.begin(); it != connections_.end(); ++it) {
- if (it->id == id) {
- return &*it;
- }
- }
- return NULL;
-}
-
-TransportManagerImpl::ConnectionInternal* TransportManagerImpl::GetConnection(
- const DeviceUID& device, const ApplicationHandle& application) {
- for (auto it = connections_.begin(); it != connections_.end(); ++it) {
- if (it->device == device && it->application == application) {
- return &*it;
- }
- }
- return NULL;
-}
-
-//YK: temp solution until B1.0 release - begin
-void TransportManagerImpl::AddDataToContainer(
- ConnectionUID id,
- std::map<ConnectionUID, std::pair<unsigned int, unsigned char*>>& container,
- unsigned char* data, unsigned int data_size) {
- unsigned int buff_size = container[id].first;
- unsigned char* buff = container[id].second;
- unsigned char* new_buff = new unsigned char[buff_size + data_size];
- memcpy(new_buff, buff, buff_size);
- memcpy(new_buff + buff_size, data, data_size);
- delete[] buff;
- container[id] = std::make_pair(buff_size + data_size, new_buff);
-
-}
-
-bool TransportManagerImpl::GetFrameSize(unsigned char* data,
- unsigned int data_size,
- unsigned int& frame_size) {
- unsigned int magic_number = 2 * sizeof(uint32_t);
- if (data_size < magic_number) {
- return false;
- }
- frame_size = protocol_handler_->GetPacketSize(data_size, data);
- return true;
-}
-bool TransportManagerImpl::GetFrame(
- std::map<ConnectionUID, std::pair<unsigned int, unsigned char*>>& container,
- ConnectionUID id, unsigned int frame_size, unsigned char** frame) {
-
- unsigned int buff_size = container[id].first;
- if (frame_size <= buff_size) {
- unsigned char* buff = container[id].second;
- *frame = new unsigned char[frame_size];
- memcpy(*frame, buff, frame_size);
- unsigned int new_buff_size = buff_size - frame_size;
- if (0 != new_buff_size) {
- unsigned char* new_buff = new unsigned char[new_buff_size];
- memcpy(new_buff, buff + frame_size, new_buff_size);
- container[id] = std::make_pair(new_buff_size, new_buff);
- } else {
- container.erase(id);
- }
- delete[] buff;
- return true;
- }
- return false;
-}
-//YK: temp solution until B1.0 release - end
-
-void TransportManagerImpl::OnDeviceListUpdated(const TransportAdapterSptr& ta) {
- const transport_adapter::DeviceList device_list = ta->GetDeviceList();
- LOG4CXX_INFO(logger_, "DEVICE_LIST_UPDATED " << device_list.size());
- for (transport_adapter::DeviceList::const_iterator it = device_list.begin();
- it != device_list.end(); ++it) {
- device_to_adapter_map_.insert(std::make_pair(*it, ta));
- DeviceHandle device_handle = converter_.UidToHandle(*it);
- DeviceInfo info(device_handle, *it, ta->DeviceName(*it));
- RaiseEvent(&TransportManagerListener::OnDeviceFound, info);
- }
- RaiseEvent(&TransportManagerListener::OnDeviceListUpdated, GetDeviceList());
-}
-
-void TransportManagerImpl::EventListenerThread(void) {
- //YK: temp solution until B1.0 release - begin
- bool frame_ready = true;
- bool size_ready = false;
- unsigned int frame_size = 0;
- unsigned char* frame = nullptr;
- bool is_new;
- std::map<ConnectionUID, std::pair<unsigned int, unsigned char*>> data_container;
- //YK: temp solution until B1.0 release - end
-
- LOG4CXX_INFO(logger_, "Event listener thread started");
- while (all_thread_active_) {
- LOG4CXX_INFO(logger_, "event_queue size is:" << event_queue_.size());
- LOG4CXX_INFO(logger_, "event_queue_mutex lock acquired");
- //pthread_mutex_lock(&event_queue_mutex_);
- LOG4CXX_INFO(logger_, "calling cond_wait device thread/event queue");
- pthread_cond_wait(&device_listener_thread_wakeup_, &event_queue_mutex_);
- LOG4CXX_INFO(logger_, "returned cond_wait device thread");
- //pthread_mutex_unlock(&event_queue_mutex_);
- LOG4CXX_INFO(logger_, "event_queue_mutex unlock");
- while (event_queue_.size() > 0) {
- LOG4CXX_INFO(logger_, "Event listener queue pushed to process events");
- EventQueue::iterator current = event_queue_.begin();
- TransportAdapterSptr ta = current->transport_adapter();
- ApplicationHandle app_handle = current->application_id();
- DeviceUID device_id = current->device_uid();
- DeviceHandle device_handle;
- BaseError* error = current->event_error();
- RawMessageSptr data = current->data();
-
- int event_type = current->event_type();
- event_queue_.erase(current);
- pthread_mutex_unlock(&event_queue_mutex_);
-
- transport_adapter::DeviceList dev_list;
- ConnectionInternal* connection = GetConnection(device_id, app_handle);
- std::vector<DeviceInfo>::iterator device_info_iterator;
-
- switch (event_type) {
- case TransportAdapterListenerImpl::EventTypeEnum::ON_SEARCH_DONE:
- LOG4CXX_INFO(logger_, "Event ON_SEARCH_DONE");
- RaiseEvent(&TransportManagerListener::OnScanDevicesFinished);
- break;
- case TransportAdapterListenerImpl::EventTypeEnum::ON_SEARCH_FAIL:
- LOG4CXX_INFO(logger_, "Event ON_SEARCH_FAIL")
- ;
- // error happened in real search process (external error)
- RaiseEvent(&TransportManagerListener::OnScanDevicesFailed,
- *static_cast<SearchDeviceError*>(error));
- break;
- case TransportAdapterListenerImpl::EventTypeEnum::ON_DEVICE_LIST_UPDATED:
- OnDeviceListUpdated(ta);
- break;
-
- case TransportAdapterListenerImpl::EventTypeEnum::ON_CONNECT_DONE:
- LOG4CXX_INFO(logger_, "Event ON_CONNECT_DONE");
- connections_.push_back(
- ConnectionInternal(ta, ++connection_id_counter_, device_id,
- app_handle));
- device_handle = converter_.UidToHandle(device_id);
- RaiseEvent(
- &TransportManagerListener::OnConnectionEstablished,
- DeviceInfo(device_handle, device_id, ta->DeviceName(device_id)),
- connection_id_counter_);
- break;
- case TransportAdapterListenerImpl::EventTypeEnum::ON_CONNECT_FAIL:
- LOG4CXX_INFO(logger_, "Event ON_CONNECT_FAIL");
- RaiseEvent(
- &TransportManagerListener::OnConnectionFailed,
- DeviceInfo(converter_.UidToHandle(device_id), device_id,
- ta->DeviceName(device_id)),
- ConnectError());
- break;
- case TransportAdapterListenerImpl::EventTypeEnum::ON_DISCONNECT_DONE: {
- LOG4CXX_INFO(logger_, "Event ON_DISCONNECT_DONE");
- if (connection == NULL) {
- LOG4CXX_ERROR(
- logger_,
- "Connection ('" << device_id << ", " << app_handle
- << ") not found");
- break;
- }
- RaiseEvent(&TransportManagerListener::OnConnectionClosed,
- connection->id);
- RemoveConnection(connection->id);
- }
- break;
- case TransportAdapterListenerImpl::EventTypeEnum::ON_DISCONNECT_FAIL: {
- LOG4CXX_INFO(logger_, "Event ON_DISCONNECT_FAIL");
- DeviceHandle device_handle = converter_.UidToHandle(device_id);
- RaiseEvent(&TransportManagerListener::OnDisconnectFailed,
- device_handle, DisconnectDeviceError());
- }
- break;
- case TransportAdapterListenerImpl::EventTypeEnum::ON_SEND_DONE: {
- LOG4CXX_INFO(logger_, "Event ON_SEND_DONE");
- if (connection == NULL) {
- LOG4CXX_ERROR(
- logger_,
- "Connection ('" << device_id << ", " << app_handle
- << ") not found");
- break;
- }
- RaiseEvent(&TransportManagerListener::OnTMMessageSend);
- this->RemoveMessage(data);
- if (connection->shutDown && --connection->messages_count == 0) {
- connection->timer.Stop();
- connection->transport_adapter->Disconnect(connection->device,
- connection->application);
- }
- }
- break;
- case TransportAdapterListenerImpl::EventTypeEnum::ON_SEND_FAIL: {
- LOG4CXX_INFO(logger_, "Event ON_SEND_FAIL");
- if (connection == NULL) {
- LOG4CXX_ERROR(
- logger_,
- "Connection ('" << device_id << ", " << app_handle
- << ") not found");
- break;
- }
-
- // TODO(YK): start timer here to wait before notify caller
- // and remove unsent messages
- LOG4CXX_ERROR(logger_, "Transport adapter failed to send data");
- // TODO(YK): potential error case -> thread unsafe
- // update of message content
- data->set_waiting(true);
- if (data.valid()) {
- data->set_waiting(true);
- } else {
- LOG4CXX_ERROR(logger_, "Data is invalid");
- }
- }
- break;
- case TransportAdapterListenerImpl::EventTypeEnum::ON_RECEIVED_DONE:
- LOG4CXX_INFO(logger_, "Event ON_RECEIVED_DONE");
- if (connection == NULL) {
- LOG4CXX_ERROR(
- logger_,
- "Connection ('" << device_id << ", " << app_handle << ") not found");
- break;
- }
- data->set_connection_key(connection->id);
- //YK: temp solution until B1.0 release - begin
- if (!size_ready) {
- //get size only when last complete frame successfully sent to upper level
- LOG4CXX_TRACE(
- logger_,
- "not size ready, adding to container, data_size:"
- << data->data_size() << ", container size:"
- << data_container[connection->id].first);
- this->AddDataToContainer(connection->id, data_container,
- data->data(), data->data_size());
- /*if (!(size_ready = this->GetFrameSize(data->data(),
- data->data_size(), frame_size))) {
- LOG4CXX_TRACE(logger_, "cannot get frame size");
- //save data for future use because there is not enough data in current mesage to get frame size
- break;
- }*/
- if (!(size_ready = this->GetFrameSize(data_container[connection->id].second,
- data_container[connection->id].first,
- frame_size))) {
- //save data for future use because there is not enough data in current mesage to get frame size
- break;
- }
- } else {
- //if current frame is not complete - accumulate data from each new message
- LOG4CXX_TRACE(
- logger_,
- "size ready, adding to container, data size:"
- << data->data_size() << ", container size:"
- << data_container[connection->id].first);
- this->AddDataToContainer(connection->id, data_container,
- data->data(), data->data_size());
- }
- if (0 == frame_size) {
- LOG4CXX_ERROR(logger_,
- "Unexpected zero size frame. Terminating connection.");
- this->DisconnectForce(connection->id);
- size_ready = false;
- frame_ready = false;
- } else {
- //get all completed frames from buffer until incomplete frame reached
- LOG4CXX_TRACE(
- logger_,
- "getting frame from container of size:"
- << data_container[connection->id].first);
- frame_ready = this->GetFrame(data_container, connection->id,
- frame_size, &frame);
- if (frame_ready) {
- LOG4CXX_TRACE(
- logger_,
- "frame of size " << frame_size
- << " ready, new container size:"
- << data_container[connection->id].first);
- } else {
- LOG4CXX_TRACE(
- logger_,
- "frame not ready, new container size:"
- << data_container[connection->id].first);
- }
- }
- while (frame_ready) {
- RawMessageSptr tmp_msg(
- new protocol_handler::RawMessage(data->connection_key(),
- data->protocol_version(),
- frame, frame_size));
- RaiseEvent(&TransportManagerListener::OnTMMessageReceived, tmp_msg);
- delete[] frame;
- LOG4CXX_TRACE(
- logger_,
- "message of size " << frame_size << " created and passed");
- size_ready = this->GetFrameSize(
- data_container[connection->id].second,
- data_container[connection->id].first, frame_size);
- if (0 == frame_size) {
- LOG4CXX_ERROR(
- logger_,
- "Unexpected zero size frame. Terminating connection.");
- this->DisconnectForce(connection->id);
- size_ready = false;
- }
- if (size_ready) {
- LOG4CXX_TRACE(
- logger_,
- "(in loop) size ready, getting frame from container of size:"
- << data_container[connection->id].first);
- frame_ready = this->GetFrame(data_container, connection->id,
- frame_size, &frame);
- if (frame_ready) {
- LOG4CXX_TRACE(
- logger_,
- "(in loop) frame of size " << frame_size
- << " ready, new container size:"
- << data_container[connection->id].first);
- } else {
- LOG4CXX_TRACE(
- logger_,
- "(in loop) frame not ready, new container size:"
- << data_container[connection->id].first);
- }
- } else {
- LOG4CXX_TRACE(logger_, "(in loop) not size ready");
- frame_ready = false;
- }
- }
- //YK: temp solution until B1.0 release - end
- break;
- case TransportAdapterListenerImpl::EventTypeEnum::ON_RECEIVED_FAIL: {
- LOG4CXX_INFO(logger_, "Event ON_RECEIVED_FAIL");
- if (connection == NULL) {
- LOG4CXX_ERROR(
- logger_,
- "Connection ('" << device_id << ", " << app_handle
- << ") not found");
- break;
- }
-
- RaiseEvent(&TransportManagerListener::OnTMMessageReceiveFailed,
- connection->id, *static_cast<DataReceiveError*>(error));
- }
- break;
- case TransportAdapterListenerImpl::EventTypeEnum::ON_COMMUNICATION_ERROR:
- LOG4CXX_INFO(logger_, "Event ON_COMMUNICATION_ERROR");
- break;
- case TransportAdapterListenerImpl::EventTypeEnum::ON_UNEXPECTED_DISCONNECT:
- LOG4CXX_INFO(logger_, "Event ON_UNEXPECTED_DISCONNECT");
- if (connection) {
- RaiseEvent(&TransportManagerListener::OnUnexpectedDisconnect,
- connection->id, *static_cast<CommunicationError*>(error));
- } else {
- LOG4CXX_ERROR(
- logger_,
- "Connection ('" << device_id << ", " << app_handle << ") not found");
- }
- break;
- } // switch
- delete error;
- pthread_mutex_lock(&event_queue_mutex_);
- } // while (event_queue_.size() > 0)
- } // while (all_thread_active_)
-
- LOG4CXX_INFO(logger_, "Event listener thread finished");
-}
-void* TransportManagerImpl::MessageQueueStartThread(void* data) {
- if (NULL != data) {
- static_cast<TransportManagerImpl*>(data)->MessageQueueThread();
- }
- return 0;
-}
-
-void TransportManagerImpl::MessageQueueThread(void) {
- LOG4CXX_INFO(logger_, "Message queue thread started");
-
- while (all_thread_active_) {
- // TODO(YK): add priority processing
- LOG4CXX_INFO(logger_, "Message queue mutex lock acquired");
- //pthread_mutex_lock(&message_queue_mutex_);
- pthread_cond_wait(&message_queue_cond, &message_queue_mutex_);
- LOG4CXX_INFO(logger_, "message_queue_cond_wait returned");
- //pthread_mutex_unlock(&message_queue_mutex_);
- LOG4CXX_INFO(logger_, "message queue mutex unlocked");
- while (message_queue_.size() > 0) {
- MessageQueue::iterator it = message_queue_.begin();
- while (it != message_queue_.end() && it->valid() && (*it)->IsWaiting()) {
- ++it;
- }
- if (it == message_queue_.end()) {
- break;
- }
- RawMessageSptr active_msg = *it;
- LOG4CXX_INFO(logger_, "Message queue mutex lock released");
- pthread_mutex_unlock(&message_queue_mutex_);
-
- if (active_msg.valid() && !active_msg->IsWaiting()) {
- ConnectionInternal* connection = GetConnection(
- active_msg->connection_key());
- if (connection == NULL) {
- std::stringstream ss;
- ss << "Connection " << active_msg->connection_key() << " not found";
- LOG4CXX_ERROR(logger_, ss.str());
- RaiseEvent(&TransportManagerListener::OnTMMessageSendFailed,
- DataSendError(ss.str()), active_msg);
- message_queue_.remove(active_msg);
- continue;
- }
- TransportAdapterSptr transport_adapter = connection->transport_adapter;
- LOG4CXX_INFO(
- logger_,
- "Got adapter " << transport_adapter.get() << "["
- << transport_adapter->GetDeviceType() << "]"
- << " by session id " << active_msg->connection_key());
-
- if (!transport_adapter.valid()) {
- std::string error_text =
- "Transport adapter is not found - message removed";
- LOG4CXX_ERROR(logger_, error_text);
- RaiseEvent(&TransportManagerListener::OnTMMessageSendFailed,
- DataSendError(error_text), active_msg);
- message_queue_.remove(active_msg);
- } else {
- if (TransportAdapter::OK
- == transport_adapter->SendData(connection->device,
- connection->application,
- active_msg)) {
- LOG4CXX_INFO(logger_, "Data sent to adapter");
- active_msg->set_waiting(true);
- } else {
- LOG4CXX_ERROR(logger_, "Data sent error");
- }
- }
- }
- pthread_mutex_lock(&message_queue_mutex_);
- }
- } // while(true)
-
- message_queue_.clear();
- LOG4CXX_INFO(logger_, "Message queue thread finished");
-}
-
-void TransportManagerImpl::SetProtocolHandler(
- protocol_handler::ProtocolHandler* ph) {
- //YK: temp solution until B1.0 release
- protocol_handler_ = ph;
-}
-
-} // namespace transport_manager
-
+++ /dev/null
-/**
- * \file usb_device_scanner.cc
- * \brief UsbDeviceScanner class source file.
- *
- * Copyright (c) 2013, 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 "transport_manager/transport_adapter/transport_adapter_impl.h"
-#include "transport_manager/usb/usb_device_scanner.h"
-#include "transport_manager/usb/usb_device.h"
-#include "transport_manager/usb/libusb_handler.h"
-
-namespace transport_manager {
-namespace transport_adapter {
-
-class AoaInitSequence : public UsbControlTransferSequence {
- public:
- AoaInitSequence(libusb_device_handle* device_handle);
- private:
- class AoaGetProtocolRequest;
- class AoaSendIdString;
- class AoaTurnIntoAccessoryMode;
-};
-
-bool IsGoogleAccessory(const libusb_device_descriptor& descriptor) {
- static const uint16_t AOA_VID = 0x18d1;
- static const uint16_t AOA_PID1 = 0x2d00;
- static const uint16_t AOA_PID2 = 0x2d01;
- return descriptor.idVendor == AOA_VID
- && (descriptor.idProduct == AOA_PID1 || descriptor.idProduct == AOA_PID2);
-}
-
-void UsbDeviceScanner::OnDeviceArrived(libusb_device* device) {
- LOG4CXX_INFO(
- logger_,
- "libusb device arrived (bus number " << static_cast<int>(libusb_get_bus_number(device)) << ", address " << static_cast<int>(libusb_get_device_address(device)) << ")");
-
- libusb_device_descriptor descriptor;
- int libusb_ret = libusb_get_device_descriptor(device, &descriptor);
- if (LIBUSB_SUCCESS != libusb_ret) {
- LOG4CXX_ERROR(logger_,
- "libusb_get_device_descriptor failed: " << libusb_ret);
- return;
- }
-
- libusb_device_handle* device_handle;
- libusb_ret = libusb_open(device, &device_handle);
- if (libusb_ret != LIBUSB_SUCCESS) {
- LOG4CXX_ERROR(logger_,
- "libusb_open failed: " << libusb_error_name(libusb_ret));
- return;
- }
-
- if (IsGoogleAccessory(descriptor)) {
- GoogleAccessoryFound(device, descriptor, device_handle);
- } else {
- TurnIntoAccessoryMode(descriptor, device_handle);
- }
-}
-
-void UsbDeviceScanner::OnDeviceLeft(libusb_device* device) {
- LOG4CXX_INFO(
- logger_,
- "libusb device left (bus number " << static_cast<int>(libusb_get_bus_number(device)) << ", address " << static_cast<int>(libusb_get_device_address(device)) << ")");
-
- pthread_mutex_lock(&device_descriptions_mutex_);
- for (DeviceDescriptions::iterator it = device_descriptions_.begin();
- it != device_descriptions_.end();) {
- const UsbDeviceDescription& description = *it;
- if (libusb_get_bus_number(device) == description.bus_number
- && libusb_get_device_address(device) == description.address) {
- it = device_descriptions_.erase(it);
- } else {
- ++it;
- }
- }
- pthread_mutex_unlock(&device_descriptions_mutex_);
-}
-
-UsbDeviceScanner::UsbDeviceScanner(TransportAdapterController* controller)
- : controller_(controller) {
- pthread_mutex_init(&device_descriptions_mutex_, 0);
-}
-
-UsbDeviceScanner::~UsbDeviceScanner() {
- pthread_mutex_destroy(&device_descriptions_mutex_);
-}
-
-class AoaInitSequence::AoaGetProtocolRequest : public UsbControlInTransfer {
- virtual ~AoaGetProtocolRequest() {
- }
- virtual libusb_request_type RequestType() const {
- return LIBUSB_REQUEST_TYPE_VENDOR;
- }
- virtual uint8_t Request() const {
- return 51;
- }
- virtual uint16_t Value() const {
- return 0;
- }
- virtual uint16_t Index() const {
- return 0;
- }
- virtual uint16_t Length() const {
- return 2;
- }
- virtual bool OnCompleted(unsigned char* data) const {
- const int protocol_version = data[1] << 8 | data[0];
- LOG4CXX_INFO(logger_, "AOA protocol version " << protocol_version);
- if (protocol_version == 0) {
- // AOA protocol not supported
- return false;
- }
- return true;
- }
-};
-
-class AoaInitSequence::AoaSendIdString : public UsbControlOutTransfer {
- public:
- AoaSendIdString(uint16_t index, const char* string, uint16_t length)
- : index_(index),
- string_(string),
- length_(length) {
- }
- private:
- virtual ~AoaSendIdString() {
- }
- virtual libusb_request_type RequestType() const {
- return LIBUSB_REQUEST_TYPE_VENDOR;
- }
- virtual uint8_t Request() const {
- return 52;
- }
- virtual uint16_t Value() const {
- return 0;
- }
- virtual uint16_t Index() const {
- return index_;
- }
- virtual uint16_t Length() const {
- return length_;
- }
- virtual const char* Data() const {
- return string_;
- }
- uint16_t index_;
- const char* string_;
- uint16_t length_;
-};
-
-class AoaInitSequence::AoaTurnIntoAccessoryMode : public UsbControlOutTransfer {
- virtual ~AoaTurnIntoAccessoryMode() {
- }
- virtual libusb_request_type RequestType() const {
- return LIBUSB_REQUEST_TYPE_VENDOR;
- }
- virtual uint8_t Request() const {
- return 53;
- }
- virtual uint16_t Value() const {
- return 0;
- }
- virtual uint16_t Index() const {
- return 0;
- }
- virtual uint16_t Length() const {
- return 0;
- }
- virtual const char* Data() const {
- return 0;
- }
-};
-
-static char manufacturer[] = "Ford";
-static char model_name[] = "HMI";
-static char description[] = "Human machine interface";
-static char version[] = "1.0";
-static char uri[] = "http://www.ford.com";
-static char serial_num[] = "N000000";
-
-AoaInitSequence::AoaInitSequence(libusb_device_handle* device_handle)
- : UsbControlTransferSequence(device_handle) {
- AddTransfer(new AoaGetProtocolRequest);
- AddTransfer(new AoaSendIdString(0, manufacturer, sizeof(manufacturer)));
- AddTransfer(new AoaSendIdString(1, model_name, sizeof(model_name)));
- AddTransfer(new AoaSendIdString(2, description, sizeof(description)));
- AddTransfer(new AoaSendIdString(3, version, sizeof(version)));
- AddTransfer(new AoaSendIdString(4, uri, sizeof(uri)));
- AddTransfer(new AoaSendIdString(5, serial_num, sizeof(serial_num)));
- AddTransfer(new AoaTurnIntoAccessoryMode);
-}
-
-void UsbDeviceScanner::TurnIntoAccessoryMode(
- const libusb_device_descriptor& descriptor,
- libusb_device_handle* device_handle) {
- LOG4CXX_INFO(
- logger_,
- "USB device descriptor VID:" << descriptor.idVendor << " PID:" << descriptor.idProduct << " turning into accessory mode");
-
- int libusb_ret = 0;
-
- libusb_ret = libusb_claim_interface(device_handle, 0);
- if (LIBUSB_SUCCESS != libusb_ret) {
- LOG4CXX_INFO(
- logger_,
- "libusb_claim_interface failed: " << libusb_error_name(libusb_ret));
- return;
- }
-
- GetLibusbHandler()->StartControlTransferSequence(
- new AoaInitSequence(device_handle));
-}
-
-bool FillUsbDeviceDescription(libusb_device* device,
- const libusb_device_descriptor& descriptor,
- libusb_device_handle* device_handle,
- UsbDeviceDescription* description) {
- int libusb_ret = 0;
- unsigned char buf[128];
- libusb_ret = libusb_get_string_descriptor_ascii(device_handle,
- descriptor.iManufacturer, buf,
- sizeof(buf));
- if (libusb_ret < 0) {
- LOG4CXX_INFO(
- logger_,
- "Failed to get USB device manufacturer: " << libusb_error_name(libusb_ret));
- return false;
- }
- description->manufacturer = std::string(reinterpret_cast<char*>(buf));
-
- libusb_ret = libusb_get_string_descriptor_ascii(device_handle,
- descriptor.iProduct, buf,
- sizeof(buf));
- if (libusb_ret < 0) {
- LOG4CXX_INFO(
- logger_,
- "Failed to get USB device product name: " << libusb_error_name(libusb_ret));
- return false;
- }
- description->product = std::string(reinterpret_cast<char*>(buf));
-
- libusb_ret = libusb_get_string_descriptor_ascii(device_handle,
- descriptor.iSerialNumber, buf,
- sizeof(buf));
- if (libusb_ret < 0) {
- LOG4CXX_INFO(
- logger_,
- "Failed to get USB device serial number: " << libusb_error_name(libusb_ret));
- return false;
- }
-
- description->usb_device = device;
- description->serial_number = std::string(reinterpret_cast<char*>(buf));
- description->vid = descriptor.idVendor;
- description->pid = descriptor.idProduct;
- description->bus_number = libusb_get_bus_number(device);
- description->address = libusb_get_device_address(device);
-
- return true;
-}
-
-void UsbDeviceScanner::GoogleAccessoryFound(
- libusb_device* device, const libusb_device_descriptor& descriptor,
- libusb_device_handle* device_handle) {
- LOG4CXX_INFO(logger_, "Google accessory found");
-
- UsbDeviceDescription usb_device_description;
- if (FillUsbDeviceDescription(device, descriptor, device_handle,
- &usb_device_description)) {
- pthread_mutex_lock(&device_descriptions_mutex_);
- device_descriptions_.push_back(usb_device_description);
- pthread_mutex_unlock(&device_descriptions_mutex_);
- LOG4CXX_INFO(
- logger_,
- "Google accessory (bus number " << static_cast<int>(usb_device_description.bus_number) << ", address " << static_cast<int>(usb_device_description.address) << ") identified as: " << usb_device_description.manufacturer << ", " << usb_device_description.product);
- UpdateList();
- }
-
- libusb_close(device_handle);
-}
-
-TransportAdapter::Error UsbDeviceScanner::Init() {
- return TransportAdapter::OK;
-}
-
-TransportAdapter::Error UsbDeviceScanner::Scan() {
- return TransportAdapter::OK;
-}
-
-void UsbDeviceScanner::UpdateList() {
- DeviceVector device_vector;
- pthread_mutex_lock(&device_descriptions_mutex_);
- for (DeviceDescriptions::const_iterator it = device_descriptions_.begin();
- it != device_descriptions_.end(); ++it) {
- const std::string device_name = it->manufacturer + it->product;
- std::ostringstream oss;
- oss << it->manufacturer << ":" << it->product << ":" << it->serial_number
- << ":" << static_cast<int>(it->bus_number) << ":"
- << static_cast<int>(it->address);
- const DeviceUID device_uid = oss.str();
- DeviceSptr device(new UsbDevice(it->usb_device, device_name, device_uid));
- device_vector.push_back(device);
- }
- pthread_mutex_unlock(&device_descriptions_mutex_);
-
- LOG4CXX_INFO(logger_, "USB search done " << device_vector.size());
- controller_->SearchDeviceDone(device_vector);
-}
-
-void UsbDeviceScanner::Terminate() {
-}
-
-bool UsbDeviceScanner::IsInitialised() const {
- return true;
-}
-
-} // namespace
-} // namespace