Merge pull request #10 from matt2005/csng-alpha55

Csng alpha55
This commit is contained in:
Matthew Hilton 2020-10-13 21:02:52 +01:00 committed by GitHub
commit bc04598aee
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
33 changed files with 687 additions and 117 deletions

View File

@ -35,6 +35,7 @@ find_package(OpenSSL REQUIRED)
find_package(rtaudio REQUIRED)
find_package(taglib REQUIRED)
find_package(blkid REQUIRED)
find_package(gps REQUIRED)
if(WIN32)
set(WINSOCK2_LIBRARIES "ws2_32")
@ -55,7 +56,6 @@ include_directories(${CMAKE_CURRENT_BINARY_DIR}
${Qt5Bluetooth_INCLUDE_DIRS}
${Qt5Network_INCLUDE_DIRS}
${Boost_INCLUDE_DIRS}
${LIBUSB_1_INCLUDE_DIRS}
${PROTOBUF_INCLUDE_DIR}
${OPENSSL_INCLUDE_DIR}
${RTAUDIO_INCLUDE_DIRS}
@ -77,13 +77,12 @@ file(GLOB_RECURSE autoapp_source_files ${autoapp_sources_directory}/*.ui ${autoa
add_executable(autoapp ${autoapp_source_files})
target_link_libraries(autoapp
target_link_libraries(autoapp libusb
${Boost_LIBRARIES}
${Qt5Multimedia_LIBRARIES}
${Qt5MultimediaWidgets_LIBRARIES}
${Qt5Bluetooth_LIBRARIES}
${Qt5Network_LIBRARIES}
${LIBUSB_1_LIBRARIES}
${PROTOBUF_LIBRARIES}
${BCM_HOST_LIBRARIES}
${ILCLIENT_LIBRARIES}
@ -91,12 +90,13 @@ target_link_libraries(autoapp
${RTAUDIO_LIBRARIES}
${TAGLIB_LIBRARIES}
${BLKID_LIBRARIES}
${GPS_LIBRARIES}
${AASDK_PROTO_LIBRARIES}
${AASDK_LIBRARIES})
set(btservice_sources_directory ${sources_directory}/btservice)
set(btservice_include_directory ${include_directory}/f1x/openauto/btservice)
file(GLOB_RECURSE btservice_source_files ${btservice_sources_directory}/*.cpp ${btservice_include_directory}/*.hpp ${common_include_directory}/*.hpp)
file(GLOB_RECURSE btservice_source_files ${btservice_sources_directory}/*.cpp ${btservice_include_directory}/*.hpp ${autoapp_sources_directory}/Configuration/*.cpp ${autoapp_includes_directory}/Configuration/*.hpp ${common_include_directory}/*.hpp)
add_executable(btservice ${btservice_source_files})

View File

@ -0,0 +1,70 @@
#
# This file is part of openauto project.
# Copyright (C) 2018 f1x.studio (Michal Szwaj)
#
# openauto is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
# openauto is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with openauto. If not, see <http://www.gnu.org/licenses/>.
#
if (GPS_LIBRARIES AND GPS_INCLUDE_DIRS)
# in cache already
set(GPS_FOUND TRUE)
else (GPS_LIBRARIES AND GPS_INCLUDE_DIRS)
find_path(GPS_INCLUDE_DIR
NAMES
gps.h
PATHS
/usr/include
/usr/local/include
/opt/local/include
/sw/include
PATH_SUFFIXES
gps
)
find_library(GPS_LIBRARY
NAMES
gps
PATHS
/usr/lib
/usr/local/lib
/opt/local/lib
/sw/lib
)
set(GPS_INCLUDE_DIRS
${GPS_INCLUDE_DIR}
)
set(GPS_LIBRARIES
${GPS_LIBRARY}
)
if (GPS_INCLUDE_DIRS AND GPS_LIBRARIES)
set(GPS_FOUND TRUE)
endif (GPS_INCLUDE_DIRS AND GPS_LIBRARIES)
if (GPS_FOUND)
if (NOT gps_FIND_QUIETLY)
message(STATUS "Found gps:")
message(STATUS " - Includes: ${GPS_INCLUDE_DIRS}")
message(STATUS " - Libraries: ${GPS_LIBRARIES}")
endif (NOT gps_FIND_QUIETLY)
else (GPS_FOUND)
if (gps_FIND_REQUIRED)
message(FATAL_ERROR "Could not find gps")
endif (gps_FIND_REQUIRED)
endif (GPS_FOUND)
mark_as_advanced(GPS_INCLUDE_DIRS GPS_LIBRARIES)
endif (GPS_LIBRARIES AND GPS_INCLUDE_DIRS)

View File

@ -49,14 +49,14 @@ if (LIBUSB_1_LIBRARIES AND LIBUSB_1_INCLUDE_DIRS)
else (LIBUSB_1_LIBRARIES AND LIBUSB_1_INCLUDE_DIRS)
find_path(LIBUSB_1_INCLUDE_DIR
NAMES
libusb.h
libusb.h
PATHS
/usr/include
/usr/local/include
/opt/local/include
/sw/include
PATH_SUFFIXES
libusb-1.0
PATH_SUFFIXES
libusb-1.0
)
find_library(LIBUSB_1_LIBRARY
@ -83,8 +83,11 @@ else (LIBUSB_1_LIBRARIES AND LIBUSB_1_INCLUDE_DIRS)
if (LIBUSB_1_FOUND)
if (NOT libusb_1_FIND_QUIETLY)
message(STATUS "Found libusb-1.0:")
message(STATUS " - Includes: ${LIBUSB_1_INCLUDE_DIRS}")
message(STATUS " - Libraries: ${LIBUSB_1_LIBRARIES}")
message(STATUS " - Includes: ${LIBUSB_1_INCLUDE_DIRS}")
message(STATUS " - Libraries: ${LIBUSB_1_LIBRARIES}")
add_library(libusb INTERFACE)
target_include_directories(libusb SYSTEM INTERFACE ${LIBUSB_1_INCLUDE_DIR})
target_link_libraries(libusb INTERFACE ${LIBUSB_1_LIBRARY})
endif (NOT libusb_1_FIND_QUIETLY)
else (LIBUSB_1_FOUND)
if (libusb_1_FIND_REQUIRED)
@ -95,4 +98,4 @@ else (LIBUSB_1_LIBRARIES AND LIBUSB_1_INCLUDE_DIRS)
# show the LIBUSB_1_INCLUDE_DIRS and LIBUSB_1_LIBRARIES variables only in the advanced view
mark_as_advanced(LIBUSB_1_INCLUDE_DIRS LIBUSB_1_LIBRARIES)
endif (LIBUSB_1_LIBRARIES AND LIBUSB_1_INCLUDE_DIRS)
endif (LIBUSB_1_LIBRARIES AND LIBUSB_1_INCLUDE_DIRS)

View File

@ -59,12 +59,17 @@ private:
boost::asio::io_service& ioService_;
aasdk::usb::USBWrapper& usbWrapper_;
aasdk::tcp::ITCPWrapper& tcpWrapper_;
boost::asio::ip::tcp::acceptor acceptor_;
boost::asio::io_service::strand strand_;
service::IAndroidAutoEntityFactory& androidAutoEntityFactory_;
aasdk::usb::IUSBHub::Pointer usbHub_;
aasdk::usb::IConnectedAccessoriesEnumerator::Pointer connectedAccessoriesEnumerator_;
service::IAndroidAutoEntity::Pointer androidAutoEntity_;
bool isStopped_;
void startServerSocket();
void handleNewClient(std::shared_ptr<boost::asio::ip::tcp::socket> socket, const boost::system::error_code &err);
};
}

View File

@ -213,6 +213,7 @@ private:
static const std::string cInputScrollWheelButtonKey;
static const std::string cInputBackButtonKey;
static const std::string cInputEnterButtonKey;
static const std::string cInputNavButtonKey;
};
}

View File

@ -18,6 +18,8 @@
#include <QBluetoothLocalDevice>
#include <f1x/openauto/autoapp/Projection/IBluetoothDevice.hpp>
#include <QBluetoothServiceInfo>
#include <QtBluetooth/QBluetoothServer>
#pragma once
@ -60,6 +62,10 @@ private:
std::unique_ptr<QBluetoothLocalDevice> localDevice_;
PairingPromise::Pointer pairingPromise_;
QBluetoothAddress pairingAddress_;
QBluetoothServiceInfo serviceInfo_;
std::unique_ptr<QBluetoothServer> rfcommServer_;
void onClientConnected();
};
}

View File

@ -60,7 +60,7 @@ protected slots:
private:
QAudioFormat audioFormat_;
SequentialBuffer audioBuffer_;
QIODevice * audioBuffer_;
std::unique_ptr<QAudioOutput> audioOutput_;
bool playbackStarted_;
};

View File

@ -18,6 +18,7 @@
#pragma once
#include <gps.h>
#include <f1x/aasdk/Channel/Sensor/SensorServiceChannel.hpp>
#include <f1x/openauto/autoapp/Service/IService.hpp>
@ -51,13 +52,16 @@ private:
using std::enable_shared_from_this<SensorService>::shared_from_this;
void sendDrivingStatusUnrestricted();
void sendNightData();
void sendGPSLocationData();
bool is_file_exist(const char *filename);
void nightSensorPolling();
void sensorPolling();
bool firstRun = true;
boost::asio::deadline_timer timer_;
boost::asio::io_service::strand strand_;
aasdk::channel::sensor::SensorServiceChannel::Pointer channel_;
struct gps_data_t gpsData_;
bool gpsEnabled_ = false;
};
}

View File

@ -48,6 +48,7 @@ public:
void onChannelOpenRequest(const aasdk::proto::messages::ChannelOpenRequest& request) override;
void onAVChannelSetupRequest(const aasdk::proto::messages::AVChannelSetupRequest& request) override;
void onAVChannelStartIndication(const aasdk::proto::messages::AVChannelStartIndication& indication) override;
void onAVChannelStopIndication(const aasdk::proto::messages::AVChannelStopIndication& indication) override;
void onAVMediaWithTimestampIndication(aasdk::messenger::Timestamp::ValueType timestamp, const aasdk::common::DataConstBuffer& buffer) override;
void onAVMediaIndication(const aasdk::common::DataConstBuffer& buffer) override;
void onVideoFocusRequest(const aasdk::proto::messages::VideoFocusRequest& request) override;

View File

@ -0,0 +1,56 @@
/*
* This file is part of openauto project.
* Copyright (C) 2018 f1x.studio (Michal Szwaj)
*
* openauto is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
* openauto is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with openauto. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <f1x/openauto/autoapp/Configuration/IConfiguration.hpp>
#include <f1x/openauto/autoapp/Service/IService.hpp>
#include <boost/asio/io_service.hpp>
#include <f1x/aasdk/Messenger/IMessenger.hpp>
namespace f1x
{
namespace openauto
{
namespace autoapp
{
namespace service
{
class WifiService: public IService, public std::enable_shared_from_this<WifiService>
{
public:
typedef std::shared_ptr<WifiService> Pointer;
WifiService(configuration::IConfiguration::Pointer configuration);
void start() override;
void stop() override;
void pause() override;
void resume() override;
void fillFeatures(aasdk::proto::messages::ServiceDiscoveryResponse& response) override;
private:
using std::enable_shared_from_this<WifiService>::shared_from_this;
configuration::IConfiguration::Pointer configuration_;
};
}
}
}
}

View File

@ -22,6 +22,8 @@
#include <memory>
#include <QBluetoothServer>
#include <f1x/openauto/btservice/IAndroidBluetoothServer.hpp>
#include <f1x/openauto/autoapp/Configuration/IConfiguration.hpp>
#include <f1x/aasdk/Messenger/Message.hpp>
namespace f1x
{
@ -35,15 +37,31 @@ class AndroidBluetoothServer: public QObject, public IAndroidBluetoothServer
Q_OBJECT
public:
AndroidBluetoothServer();
AndroidBluetoothServer(autoapp::configuration::IConfiguration::Pointer configuration);
bool start(const QBluetoothAddress& address, uint16_t portNumber) override;
uint16_t start(const QBluetoothAddress& address) override;
private slots:
void onClientConnected();
private:
std::unique_ptr<QBluetoothServer> rfcommServer_;
QBluetoothSocket* socket = nullptr;
autoapp::configuration::IConfiguration::Pointer configuration_;
void readSocket();
QByteArray buffer;
void handleWifiInfoRequest(QByteArray &buffer, uint16_t length);
void sendMessage(const google::protobuf::Message &message, uint16_t type);
void handleWifiSecurityRequest(QByteArray &buffer, uint16_t length);
void handleWifiInfoRequestResponse(QByteArray &buffer, uint16_t length);
const ::std::string getIP4_(const QString intf);
};
}

View File

@ -32,7 +32,7 @@ class IAndroidBluetoothServer
public:
virtual ~IAndroidBluetoothServer() = default;
virtual bool start(const QBluetoothAddress& address, uint16_t portNumber) = 0;
virtual uint16_t start(const QBluetoothAddress& address) = 0;
};
}

View File

@ -38,6 +38,7 @@ App::App(boost::asio::io_service& ioService, aasdk::usb::USBWrapper& usbWrapper,
, androidAutoEntityFactory_(androidAutoEntityFactory)
, usbHub_(std::move(usbHub))
, connectedAccessoriesEnumerator_(std::move(connectedAccessoriesEnumerator))
, acceptor_(ioService, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 5000 ))
, isStopped_(false)
{
@ -69,17 +70,28 @@ void App::waitForUSBDevice()
void App::start(aasdk::tcp::ITCPEndpoint::SocketPointer socket)
{
strand_.dispatch([this, self = this->shared_from_this(), socket = std::move(socket)]() mutable {
OPENAUTO_LOG(info) << "Start from socket";
if(androidAutoEntity_ != nullptr)
{
tcpWrapper_.close(*socket);
OPENAUTO_LOG(warning) << "[App] android auto entity is still running.";
return;
// tcpWrapper_.close(*socket);
// OPENAUTO_LOG(warning) << "[App] android auto entity is still running.";
// return;
try {
androidAutoEntity_->stop();
} catch (...) {
OPENAUTO_LOG(error) << "[App] onAndroidAutoQuit: exception caused by androidAutoEntity_->stop();";
}
try {
androidAutoEntity_.reset();
} catch (...) {
OPENAUTO_LOG(error) << "[App] onAndroidAutoQuit: exception caused by androidAutoEntity_.reset();";
}
}
try
{
usbHub_->cancel();
connectedAccessoriesEnumerator_->cancel();
// usbHub_->cancel();
// connectedAccessoriesEnumerator_->cancel();
auto tcpEndpoint(std::make_shared<aasdk::tcp::TCPEndpoint>(tcpWrapper_, std::move(socket)));
androidAutoEntity_ = androidAutoEntityFactory_.create(std::move(tcpEndpoint));
@ -89,7 +101,7 @@ void App::start(aasdk::tcp::ITCPEndpoint::SocketPointer socket)
{
OPENAUTO_LOG(error) << "[App] TCP AndroidAutoEntity create error: " << error.what();
androidAutoEntity_.reset();
//androidAutoEntity_.reset();
this->waitForDevice();
}
});
@ -181,6 +193,25 @@ void App::waitForDevice()
promise->then(std::bind(&App::aoapDeviceHandler, this->shared_from_this(), std::placeholders::_1),
std::bind(&App::onUSBHubError, this->shared_from_this(), std::placeholders::_1));
usbHub_->start(std::move(promise));
startServerSocket();
}
void App::startServerSocket() {
strand_.dispatch([this, self = this->shared_from_this()]() {
OPENAUTO_LOG(info) << "Listening for WIFI clients on port 5000";
auto socket = std::make_shared<boost::asio::ip::tcp::socket>(ioService_);
acceptor_.async_accept(
*socket,
std::bind(&App::handleNewClient, this, socket, std::placeholders::_1)
);
});
}
void App::handleNewClient(std::shared_ptr<boost::asio::ip::tcp::socket> socket, const boost::system::error_code &err) {
OPENAUTO_LOG(info) << "WIFI Client connected";
if (!err) {
start(std::move(socket));
}
}
void App::pause()
@ -209,15 +240,19 @@ void App::onAndroidAutoQuit()
strand_.dispatch([this, self = this->shared_from_this()]() {
OPENAUTO_LOG(info) << "[App] onAndroidAutoQuit.";
try {
androidAutoEntity_->stop();
} catch (...) {
OPENAUTO_LOG(error) << "[App] onAndroidAutoQuit: exception caused by androidAutoEntity_->stop();";
}
try {
androidAutoEntity_.reset();
} catch (...) {
OPENAUTO_LOG(error) << "[App] onAndroidAutoQuit: exception caused by androidAutoEntity_.reset();";
//acceptor_.close();
if (androidAutoEntity_ != nullptr) {
try {
androidAutoEntity_->stop();
} catch (...) {
OPENAUTO_LOG(error) << "[App] onAndroidAutoQuit: exception caused by androidAutoEntity_->stop();";
}
try {
androidAutoEntity_.reset();
} catch (...) {
OPENAUTO_LOG(error) << "[App] onAndroidAutoQuit: exception caused by androidAutoEntity_.reset();";
}
}
if(!isStopped_)
@ -227,7 +262,6 @@ void App::onAndroidAutoQuit()
} catch (...) {
OPENAUTO_LOG(error) << "[App] onAndroidAutoQuit: exception caused by this->waitForDevice();";
}
}
});
}
@ -236,15 +270,15 @@ void App::onUSBHubError(const aasdk::error::Error& error)
{
OPENAUTO_LOG(error) << "[App] usb hub error: " << error.what();
if(error != aasdk::error::ErrorCode::OPERATION_ABORTED &&
error != aasdk::error::ErrorCode::OPERATION_IN_PROGRESS)
{
try {
this->waitForDevice();
} catch (...) {
OPENAUTO_LOG(error) << "[App] onUSBHubError: exception caused by this->waitForDevice();";
}
}
// if(error != aasdk::error::ErrorCode::OPERATION_ABORTED &&
// error != aasdk::error::ErrorCode::OPERATION_IN_PROGRESS)
// {
// try {
// this->waitForDevice();
// } catch (...) {
// OPENAUTO_LOG(error) << "[App] onUSBHubError: exception caused by this->waitForDevice();";
// }
// }
}
}

View File

@ -85,6 +85,7 @@ const std::string Configuration::cInputDownButtonKey = "Input.DownButton";
const std::string Configuration::cInputScrollWheelButtonKey = "Input.ScrollWheelButton";
const std::string Configuration::cInputBackButtonKey = "Input.BackButton";
const std::string Configuration::cInputEnterButtonKey = "Input.EnterButton";
const std::string Configuration::cInputNavButtonKey = "Input.NavButton";
Configuration::Configuration()
{
@ -698,6 +699,7 @@ void Configuration::readButtonCodes(boost::property_tree::ptree& iniConfig)
this->insertButtonCode(iniConfig, cInputScrollWheelButtonKey, aasdk::proto::enums::ButtonCode::SCROLL_WHEEL);
this->insertButtonCode(iniConfig, cInputBackButtonKey, aasdk::proto::enums::ButtonCode::BACK);
this->insertButtonCode(iniConfig, cInputEnterButtonKey, aasdk::proto::enums::ButtonCode::ENTER);
this->insertButtonCode(iniConfig, cInputNavButtonKey, aasdk::proto::enums::ButtonCode::NAVIGATION);
}
void Configuration::insertButtonCode(boost::property_tree::ptree& iniConfig, const std::string& buttonCodeKey, aasdk::proto::enums::ButtonCode::Enum buttonCode)
@ -726,6 +728,7 @@ void Configuration::writeButtonCodes(boost::property_tree::ptree& iniConfig)
iniConfig.put<bool>(cInputScrollWheelButtonKey, std::find(buttonCodes_.begin(), buttonCodes_.end(), aasdk::proto::enums::ButtonCode::SCROLL_WHEEL) != buttonCodes_.end());
iniConfig.put<bool>(cInputBackButtonKey, std::find(buttonCodes_.begin(), buttonCodes_.end(), aasdk::proto::enums::ButtonCode::BACK) != buttonCodes_.end());
iniConfig.put<bool>(cInputEnterButtonKey, std::find(buttonCodes_.begin(), buttonCodes_.end(), aasdk::proto::enums::ButtonCode::ENTER) != buttonCodes_.end());
iniConfig.put<bool>(cInputNavButtonKey, std::find(buttonCodes_.begin(), buttonCodes_.end(), aasdk::proto::enums::ButtonCode::NAVIGATION) != buttonCodes_.end());
}
}

View File

@ -164,6 +164,10 @@ bool InputDevice::handleKeyEvent(QEvent* event, QKeyEvent* key)
buttonCode = aasdk::proto::enums::ButtonCode::SCROLL_WHEEL;
break;
case Qt::Key_F:
buttonCode = aasdk::proto::enums::ButtonCode::NAVIGATION;
break;
default:
return true;
}

View File

@ -19,6 +19,8 @@
#include <QApplication>
#include <f1x/openauto/Common/Log.hpp>
#include <f1x/openauto/autoapp/Projection/LocalBluetoothDevice.hpp>
#include <QBluetoothUuid>
#include <QtBluetooth>
namespace f1x
{
@ -49,7 +51,47 @@ void LocalBluetoothDevice::createBluetoothLocalDevice()
connect(localDevice_.get(), &QBluetoothLocalDevice::pairingFinished, this, &LocalBluetoothDevice::onPairingFinished);
connect(localDevice_.get(), &QBluetoothLocalDevice::error, this, &LocalBluetoothDevice::onError);
connect(localDevice_.get(), &QBluetoothLocalDevice::hostModeStateChanged, this, &LocalBluetoothDevice::onHostModeStateChanged);
localDevice_->powerOn();
localDevice_->setHostMode(QBluetoothLocalDevice::HostDiscoverable);
//
// rfcommServer_ = std::make_unique<QBluetoothServer>(QBluetoothServiceInfo::RfcommProtocol, this);
// connect(rfcommServer_.get(), &QBluetoothServer::newConnection, this, &LocalBluetoothDevice::onClientConnected, Qt::QueuedConnection);
// if (rfcommServer_->listen(localDevice_->address())) {
// OPENAUTO_LOG(debug) << "Listening for rfcomm connections on port " << rfcommServer_->serverPort();
// }
// else {
// OPENAUTO_LOG(debug) << "Could not start rfcomm";
// }
//
// //"4de17a00-52cb-11e6-bdf4-0800200c9a66";
// //"669a0c20-0008-f4bd-e611-cb52007ae14d";
// const QBluetoothUuid serviceUuid(QLatin1String("4de17a00-52cb-11e6-bdf4-0800200c9a66"));
//
// QBluetoothServiceInfo::Sequence classId;
// classId << QVariant::fromValue(QBluetoothUuid(QBluetoothUuid::SerialPort));
// serviceInfo_.setAttribute(QBluetoothServiceInfo::BluetoothProfileDescriptorList, classId);
// classId.prepend(QVariant::fromValue(serviceUuid));
// serviceInfo_.setAttribute(QBluetoothServiceInfo::ServiceClassIds, classId);
// serviceInfo_.setAttribute(QBluetoothServiceInfo::ServiceName, "OpenAuto Bluetooth Service");
// serviceInfo_.setAttribute(QBluetoothServiceInfo::ServiceDescription, "AndroidAuto WiFi projection automatic setup");
// serviceInfo_.setAttribute(QBluetoothServiceInfo::ServiceProvider, "f1xstudio.com");
// serviceInfo_.setServiceUuid(serviceUuid);
//
// QBluetoothServiceInfo::Sequence publicBrowse;
// publicBrowse << QVariant::fromValue(QBluetoothUuid(QBluetoothUuid::PublicBrowseGroup));
// serviceInfo_.setAttribute(QBluetoothServiceInfo::BrowseGroupList, publicBrowse);
//
// QBluetoothServiceInfo::Sequence protocolDescriptorList;
// QBluetoothServiceInfo::Sequence protocol;
// protocol << QVariant::fromValue(QBluetoothUuid(QBluetoothUuid::L2cap));
// protocolDescriptorList.append(QVariant::fromValue(protocol));
// protocol.clear();
// protocol << QVariant::fromValue(QBluetoothUuid(QBluetoothUuid::Rfcomm))
// << QVariant::fromValue(quint8(rfcommServer_->serverPort()));
// protocolDescriptorList.append(QVariant::fromValue(protocol));
// serviceInfo_.setAttribute(QBluetoothServiceInfo::ProtocolDescriptorList, protocolDescriptorList);
// serviceInfo_.registerService(localDevice_->address());
}
void LocalBluetoothDevice::stop()
@ -178,6 +220,19 @@ void LocalBluetoothDevice::onHostModeStateChanged(QBluetoothLocalDevice::HostMod
}
}
void LocalBluetoothDevice::onClientConnected() {
auto socket = rfcommServer_->nextPendingConnection();
if(socket != nullptr)
{
OPENAUTO_LOG(info) << "[BluetoothServer] rfcomm client connected, peer name: " << socket->peerName().toStdString();
}
else
{
OPENAUTO_LOG(error) << "[BluetoothServer] received null socket during client connection.";
}
}
}
}
}

View File

@ -204,19 +204,19 @@ void OMXVideoOutput::stop()
bool OMXVideoOutput::createComponents()
{
if(ilclient_create_component(client_, &components_[VideoComponent::DECODER], "video_decode", static_cast<ILCLIENT_CREATE_FLAGS_T>(ILCLIENT_DISABLE_ALL_PORTS | ILCLIENT_ENABLE_INPUT_BUFFERS)) != 0)
if(ilclient_create_component(client_, &components_[VideoComponent::DECODER], const_cast<char*>("video_decode"), static_cast<ILCLIENT_CREATE_FLAGS_T>(ILCLIENT_DISABLE_ALL_PORTS | ILCLIENT_ENABLE_INPUT_BUFFERS)) != 0)
{
OPENAUTO_LOG(error) << "[OMXVideoOutput] video decode component creation failed.";
return false;
}
if(ilclient_create_component(client_, &components_[VideoComponent::RENDERER], "video_render", ILCLIENT_DISABLE_ALL_PORTS) != 0)
if(ilclient_create_component(client_, &components_[VideoComponent::RENDERER], const_cast<char*>("video_render"), ILCLIENT_DISABLE_ALL_PORTS) != 0)
{
OPENAUTO_LOG(error) << "[OMXVideoOutput] video renderer component creation failed.";
return false;
}
if(ilclient_create_component(client_, &components_[VideoComponent::CLOCK], "clock", ILCLIENT_DISABLE_ALL_PORTS) != 0)
if(ilclient_create_component(client_, &components_[VideoComponent::CLOCK], const_cast<char*>("clock"), ILCLIENT_DISABLE_ALL_PORTS) != 0)
{
OPENAUTO_LOG(error) << "[OMXVideoOutput] clock component creation failed.";
return false;
@ -228,7 +228,7 @@ bool OMXVideoOutput::createComponents()
return false;
}
if(ilclient_create_component(client_, &components_[VideoComponent::SCHEDULER], "video_scheduler", ILCLIENT_DISABLE_ALL_PORTS) != 0)
if(ilclient_create_component(client_, &components_[VideoComponent::SCHEDULER], const_cast<char*>("video_scheduler"), ILCLIENT_DISABLE_ALL_PORTS) != 0)
{
OPENAUTO_LOG(error) << "[OMXVideoOutput] video scheduler component creation failed.";
return false;

View File

@ -17,6 +17,7 @@
*/
#include <QApplication>
#include <QThread>
#include <f1x/openauto/autoapp/Projection/QtAudioOutput.hpp>
#include <f1x/openauto/Common/Log.hpp>
@ -30,7 +31,8 @@ namespace projection
{
QtAudioOutput::QtAudioOutput(uint32_t channelCount, uint32_t sampleSize, uint32_t sampleRate)
: playbackStarted_(false)
: audioBuffer_(nullptr)
, playbackStarted_(false)
{
audioFormat_.setChannelCount(channelCount);
audioFormat_.setSampleRate(sampleRate);
@ -39,7 +41,10 @@ QtAudioOutput::QtAudioOutput(uint32_t channelCount, uint32_t sampleSize, uint32_
audioFormat_.setByteOrder(QAudioFormat::LittleEndian);
audioFormat_.setSampleType(QAudioFormat::SignedInt);
this->moveToThread(QApplication::instance()->thread());
QThread * th = QApplication::instance()->thread();
this->moveToThread(th);
th->setPriority(QThread::TimeCriticalPriority);
connect(this, &QtAudioOutput::startPlayback, this, &QtAudioOutput::onStartPlayback);
connect(this, &QtAudioOutput::suspendPlayback, this, &QtAudioOutput::onSuspendPlayback);
connect(this, &QtAudioOutput::stopPlayback, this, &QtAudioOutput::onStopPlayback);
@ -55,12 +60,15 @@ void QtAudioOutput::createAudioOutput()
bool QtAudioOutput::open()
{
return audioBuffer_.open(QIODevice::ReadWrite);
return true;
}
void QtAudioOutput::write(aasdk::messenger::Timestamp::ValueType, const aasdk::common::DataConstBuffer& buffer)
{
audioBuffer_.write(reinterpret_cast<const char*>(buffer.cdata), buffer.size);
if (audioBuffer_ != nullptr)
{
audioBuffer_->write(reinterpret_cast<const char*>(buffer.cdata), buffer.size);
}
}
void QtAudioOutput::start()
@ -97,7 +105,7 @@ void QtAudioOutput::onStartPlayback()
{
if(!playbackStarted_)
{
audioOutput_->start(&audioBuffer_);
audioBuffer_ = audioOutput_->start();
playbackStarted_ = true;
}
else

View File

@ -71,13 +71,14 @@ void QtVideoOutput::onStartPlayback()
{
videoWidget_->setAspectRatioMode(Qt::IgnoreAspectRatio);
videoWidget_->setFocus();
videoWidget_->setWindowFlags(Qt::WindowStaysOnTopHint);
//videoWidget_->setWindowFlags(Qt::WindowStaysOnTopHint);
videoWidget_->setFullScreen(true);
videoWidget_->show();
mediaPlayer_->setVideoOutput(videoWidget_.get());
mediaPlayer_->setMedia(QMediaContent(), &videoBuffer_);
mediaPlayer_->play();
OPENAUTO_LOG(debug) << "Player error state -> " << mediaPlayer_->errorString().toStdString();
}
void QtVideoOutput::onStopPlayback()

View File

@ -257,8 +257,9 @@ void AndroidAutoEntity::onNavigationFocusRequest(const aasdk::proto::messages::N
controlServiceChannel_->receive(this->shared_from_this());
}
void AndroidAutoEntity::onPingResponse(const aasdk::proto::messages::PingResponse&)
void AndroidAutoEntity::onPingResponse(const aasdk::proto::messages::PingResponse& response)
{
OPENAUTO_LOG(info) << "[AndroidAutoEntity] Ping response, timestamp: " << response.timestamp();
pinger_->pong();
controlServiceChannel_->receive(this->shared_from_this());
}
@ -302,6 +303,8 @@ void AndroidAutoEntity::sendPing()
promise->then([]() {}, std::bind(&AndroidAutoEntity::onChannelError, this->shared_from_this(), std::placeholders::_1));
aasdk::proto::messages::PingRequest request;
auto timestamp = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now().time_since_epoch());
request.set_timestamp(timestamp.count());
controlServiceChannel_->sendPingRequest(request, std::move(promise));
}

View File

@ -78,6 +78,8 @@ void BluetoothService::fillFeatures(aasdk::proto::messages::ServiceDiscoveryResp
channelDescriptor->set_channel_id(static_cast<uint32_t>(channel_->getId()));
auto bluetoothChannel = channelDescriptor->mutable_bluetooth_channel();
bluetoothChannel->set_adapter_address(bluetoothDevice_->getLocalAddress());
bluetoothChannel->add_supported_pairing_methods(aasdk::proto::enums::BluetoothPairingMethod_Enum_HFP);
bluetoothChannel->add_supported_pairing_methods(aasdk::proto::enums::BluetoothPairingMethod_Enum_A2DP);
}
}

View File

@ -20,6 +20,7 @@
#include <f1x/openauto/Common/Log.hpp>
#include <f1x/openauto/autoapp/Service/SensorService.hpp>
#include <fstream>
#include <cmath>
namespace f1x
{
@ -41,19 +42,40 @@ SensorService::SensorService(boost::asio::io_service& ioService, aasdk::messenge
void SensorService::start()
{
strand_.dispatch([this, self = this->shared_from_this()]() {
if (gps_open("127.0.0.1", "2947", &this->gpsData_))
{
OPENAUTO_LOG(warning) << "[SensorService] can't connect to GPSD.";
}
else
{
OPENAUTO_LOG(info) << "[SensorService] Connected to GPSD.";
gps_stream(&this->gpsData_, WATCH_ENABLE | WATCH_JSON, NULL);
this->gpsEnabled_ = true;
}
if (is_file_exist("/tmp/night_mode_enabled")) {
this->isNight = true;
}
this->nightSensorPolling();
this->sensorPolling();
OPENAUTO_LOG(info) << "[SensorService] start.";
channel_->receive(this->shared_from_this());
});
}
void SensorService::stop()
{
this->stopPolling = true;
strand_.dispatch([this, self = this->shared_from_this()]() {
if (this->gpsEnabled_)
{
gps_stream(&this->gpsData_, WATCH_DISABLE, NULL);
gps_close(&this->gpsData_);
this->gpsEnabled_ = false;
}
OPENAUTO_LOG(info) << "[SensorService] stop.";
});
}
@ -81,7 +103,7 @@ void SensorService::fillFeatures(aasdk::proto::messages::ServiceDiscoveryRespons
auto* sensorChannel = channelDescriptor->mutable_sensor_channel();
sensorChannel->add_sensors()->set_type(aasdk::proto::enums::SensorType::DRIVING_STATUS);
//sensorChannel->add_sensors()->set_type(aasdk::proto::enums::SensorType::LOCATION);
sensorChannel->add_sensors()->set_type(aasdk::proto::enums::SensorType::LOCATION);
sensorChannel->add_sensors()->set_type(aasdk::proto::enums::SensorType::NIGHT_DATA);
}
@ -160,7 +182,42 @@ void SensorService::sendNightData()
}
}
void SensorService::nightSensorPolling()
void SensorService::sendGPSLocationData()
{
aasdk::proto::messages::SensorEventIndication indication;
auto * locInd = indication.add_gps_location();
// epoch seconds
locInd->set_timestamp(this->gpsData_.fix.time * 1e3);
// degrees
locInd->set_latitude(this->gpsData_.fix.latitude * 1e7);
locInd->set_longitude(this->gpsData_.fix.longitude * 1e7);
// meters
auto accuracy = sqrt(pow(this->gpsData_.fix.epx, 2) + pow(this->gpsData_.fix.epy, 2));
locInd->set_accuracy(accuracy * 1e3);
if (this->gpsData_.set & ALTITUDE_SET)
{
// meters above ellipsoid
locInd->set_altitude(this->gpsData_.fix.altitude * 1e2);
}
if (this->gpsData_.set & SPEED_SET)
{
// meters per second to knots
locInd->set_speed(this->gpsData_.fix.speed * 1.94384 * 1e3);
}
if (this->gpsData_.set & TRACK_SET)
{
// degrees
locInd->set_bearing(this->gpsData_.fix.track * 1e6);
}
auto promise = aasdk::channel::SendPromise::defer(strand_);
promise->then([]() {}, std::bind(&SensorService::onChannelError, this->shared_from_this(), std::placeholders::_1));
channel_->sendSensorEventIndication(indication, std::move(promise));
}
void SensorService::sensorPolling()
{
if (!this->stopPolling) {
strand_.dispatch([this, self = this->shared_from_this()]() {
@ -169,8 +226,20 @@ void SensorService::nightSensorPolling()
this->previous = this->isNight;
this->sendNightData();
}
timer_.expires_from_now(boost::posix_time::seconds(5));
timer_.async_wait(strand_.wrap(std::bind(&SensorService::nightSensorPolling, this->shared_from_this())));
if ((this->gpsEnabled_) &&
(gps_waiting(&this->gpsData_, 0)) &&
(gps_read(&this->gpsData_) > 0) &&
(this->gpsData_.status != STATUS_NO_FIX) &&
(this->gpsData_.fix.mode == MODE_2D || this->gpsData_.fix.mode == MODE_3D) &&
(this->gpsData_.set & TIME_SET) &&
(this->gpsData_.set & LATLON_SET))
{
this->sendGPSLocationData();
}
timer_.expires_from_now(boost::posix_time::milliseconds(250));
timer_.async_wait(strand_.wrap(std::bind(&SensorService::sensorPolling, this->shared_from_this())));
});
}
}

View File

@ -39,6 +39,7 @@
#include <f1x/openauto/autoapp/Projection/LocalBluetoothDevice.hpp>
#include <f1x/openauto/autoapp/Projection/RemoteBluetoothDevice.hpp>
#include <f1x/openauto/autoapp/Projection/DummyBluetoothDevice.hpp>
#include <f1x/openauto/autoapp/Service/WifiService.hpp>
namespace f1x
{
@ -67,6 +68,7 @@ ServiceList ServiceFactory::create(aasdk::messenger::IMessenger::Pointer messeng
serviceList.emplace_back(this->createVideoService(messenger));
serviceList.emplace_back(this->createBluetoothService(messenger));
serviceList.emplace_back(this->createInputService(messenger));
serviceList.emplace_back(std::make_shared<WifiService>(configuration_));
return serviceList;
}

View File

@ -110,6 +110,13 @@ void VideoService::onAVChannelStartIndication(const aasdk::proto::messages::AVCh
channel_->receive(this->shared_from_this());
}
void VideoService::onAVChannelStopIndication(const aasdk::proto::messages::AVChannelStopIndication& indication)
{
OPENAUTO_LOG(info) << "[VideoService] stop indication, session: " << session_;
channel_->receive(this->shared_from_this());
}
void VideoService::onAVMediaWithTimestampIndication(aasdk::messenger::Timestamp::ValueType timestamp, const aasdk::common::DataConstBuffer& buffer)
{
videoOutput_->write(timestamp, buffer);

View File

@ -0,0 +1,69 @@
/*
* This file is part of openauto project.
* Copyright (C) 2018 f1x.studio (Michal Szwaj)
*
* openauto is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
* openauto is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with openauto. If not, see <http://www.gnu.org/licenses/>.
*/
#include <f1x/openauto/Common/Log.hpp>
#include <f1x/openauto/autoapp/Service/WifiService.hpp>
#include <fstream>
#include <QString>
namespace f1x
{
namespace openauto
{
namespace autoapp
{
namespace service
{
WifiService::WifiService(configuration::IConfiguration::Pointer configuration)
: configuration_(std::move(configuration))
{
}
void WifiService::start()
{
}
void WifiService::stop()
{
}
void WifiService::pause()
{
}
void WifiService::resume()
{
}
void WifiService::fillFeatures(aasdk::proto::messages::ServiceDiscoveryResponse& response)
{
OPENAUTO_LOG(info) << "[WifiService] fill features.";
auto* channelDescriptor = response.add_channels();
channelDescriptor->set_channel_id(14);
auto* channel = channelDescriptor->mutable_wifi_channel();
channel->set_ssid(configuration_->getParamFromFile("/etc/hostapd/hostapd.conf","ssid").toStdString());
}
}
}
}
}

View File

@ -92,7 +92,7 @@ void ConnectDialog::onConnectionFailed(const QString& message)
ui_->progressBarConnect->hide();
QMessageBox errorMessage(QMessageBox::Critical, "Connect error", message, QMessageBox::Ok);
errorMessage.setWindowFlags(Qt::WindowStaysOnTopHint);
//errorMessage.setWindowFlags(Qt::WindowStaysOnTopHint);
errorMessage.exec();
}

View File

@ -1805,7 +1805,12 @@ void f1x::openauto::autoapp::ui::MainWindow::tmpChanged()
QFile deviceData(QString("/tmp/android_device"));
deviceData.open(QIODevice::ReadOnly);
QTextStream data_date(&deviceData);
QString linedate = data_date.readAll().split("\n")[1];
data_date.readLine();
// wait for second line to be written
QString linedate;
while (linedate.isNull()) {
linedate = data_date.readLine();
}
deviceData.close();
ui_->labelAndroidAutoBottom->setText(linedate.simplified().replace("_"," "));
} catch (...) {

View File

@ -469,7 +469,7 @@ void SettingsWindow::onSave()
void SettingsWindow::onResetToDefaults()
{
QMessageBox confirmationMessage(QMessageBox::Question, "Confirmation", "Are you sure you want to reset settings?", QMessageBox::Yes | QMessageBox::Cancel);
confirmationMessage.setWindowFlags(Qt::WindowStaysOnTopHint);
//confirmationMessage.setWindowFlags(Qt::WindowStaysOnTopHint);
if(confirmationMessage.exec() == QMessageBox::Yes)
{
configuration_->reset();
@ -565,6 +565,7 @@ void SettingsWindow::loadButtonCheckBoxes()
ui_->checkBoxScrollWheelButton->setChecked(std::find(buttonCodes.begin(), buttonCodes.end(), aasdk::proto::enums::ButtonCode::SCROLL_WHEEL) != buttonCodes.end());
ui_->checkBoxBackButton->setChecked(std::find(buttonCodes.begin(), buttonCodes.end(), aasdk::proto::enums::ButtonCode::BACK) != buttonCodes.end());
ui_->checkBoxEnterButton->setChecked(std::find(buttonCodes.begin(), buttonCodes.end(), aasdk::proto::enums::ButtonCode::ENTER) != buttonCodes.end());
ui_->checkBoxNavButton->setChecked(std::find(buttonCodes.begin(), buttonCodes.end(), aasdk::proto::enums::ButtonCode::NAVIGATION) != buttonCodes.end());
}
void SettingsWindow::setButtonCheckBoxes(bool value)
@ -585,6 +586,7 @@ void SettingsWindow::setButtonCheckBoxes(bool value)
ui_->checkBoxScrollWheelButton->setChecked(value);
ui_->checkBoxBackButton->setChecked(value);
ui_->checkBoxEnterButton->setChecked(value);
ui_->checkBoxNavButton->setChecked(value);
}
void SettingsWindow::saveButtonCheckBoxes()
@ -606,6 +608,7 @@ void SettingsWindow::saveButtonCheckBoxes()
this->saveButtonCheckBox(ui_->checkBoxScrollWheelButton, buttonCodes, aasdk::proto::enums::ButtonCode::SCROLL_WHEEL);
this->saveButtonCheckBox(ui_->checkBoxBackButton, buttonCodes, aasdk::proto::enums::ButtonCode::BACK);
this->saveButtonCheckBox(ui_->checkBoxEnterButton, buttonCodes, aasdk::proto::enums::ButtonCode::ENTER);
this->saveButtonCheckBox(ui_->checkBoxNavButton, buttonCodes, aasdk::proto::enums::ButtonCode::NAVIGATION);
configuration_->setButtonCodes(buttonCodes);
}
@ -1359,7 +1362,7 @@ void f1x::openauto::autoapp::ui::SettingsWindow::updateNetworkInfo()
ui_->lineEditWifiSSID->setText(configuration_->getParamFromFile("/etc/hostapd/hostapd.conf","ssid"));
ui_->lineEditPassword->show();
ui_->label_password->show();
ui_->lineEditPassword->setText("1234567890");
ui_->lineEditPassword->setText(configuration_->getParamFromFile("/etc/hostapd/hostapd.conf","wpa_passphrase"));
ui_->clientNetworkSelect->hide();
ui_->pushButtonNetworkAuto->hide();
ui_->label_notavailable->show();

View File

@ -4171,9 +4171,6 @@ border: 2px solid rgba(255,255,255,0.5);</string>
<property name="wordWrap">
<bool>true</bool>
</property>
<property name="itemAlignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
@ -4261,7 +4258,7 @@ height: 50px;
<enum>QListView::Static</enum>
</property>
<property name="isWrapping" stdset="0">
<bool>false</bool>
<bool>true</bool>
</property>
<property name="resizeMode">
<enum>QListView::Fixed</enum>
@ -4281,9 +4278,6 @@ height: 50px;
<property name="viewMode">
<enum>QListView::ListMode</enum>
</property>
<property name="itemAlignment">
<set>Qt::AlignCenter</set>
</property>
<property name="currentRow">
<number>-1</number>
</property>

View File

@ -2464,6 +2464,13 @@ QSlider::groove:horizontal { background: #6d6d6d; height: 32px;}</string>
</property>
</widget>
</item>
<item row="1" column="4">
<widget class="QCheckBox" name="checkBoxNavButton">
<property name="text">
<string>Nav [F]</string>
</property>
</widget>
</item>
<item row="2" column="3">
<widget class="QCheckBox" name="checkBoxScrollWheelButton">
<property name="text">

View File

@ -95,10 +95,10 @@ int main(int argc, char* argv[])
auto configuration = std::make_shared<autoapp::configuration::Configuration>();
autoapp::ui::MainWindow mainWindow(configuration);
mainWindow.setWindowFlags(Qt::WindowStaysOnTopHint);
//mainWindow.setWindowFlags(Qt::WindowStaysOnTopHint);
autoapp::ui::SettingsWindow settingsWindow(configuration);
settingsWindow.setWindowFlags(Qt::WindowStaysOnTopHint);
//settingsWindow.setWindowFlags(Qt::WindowStaysOnTopHint);
settingsWindow.setFixedSize(width, height);
settingsWindow.adjustSize();
@ -108,15 +108,15 @@ int main(int argc, char* argv[])
aasdk::tcp::TCPWrapper tcpWrapper;
autoapp::ui::ConnectDialog connectdialog(ioService, tcpWrapper, recentAddressesList);
connectdialog.setWindowFlags(Qt::WindowStaysOnTopHint);
//connectdialog.setWindowFlags(Qt::WindowStaysOnTopHint);
connectdialog.move((width - 500)/2,(height-300)/2);
autoapp::ui::WarningDialog warningdialog;
warningdialog.setWindowFlags(Qt::WindowStaysOnTopHint);
//warningdialog.setWindowFlags(Qt::WindowStaysOnTopHint);
warningdialog.move((width - 500)/2,(height-300)/2);
autoapp::ui::UpdateDialog updatedialog;
updatedialog.setWindowFlags(Qt::WindowStaysOnTopHint);
//updatedialog.setWindowFlags(Qt::WindowStaysOnTopHint);
updatedialog.setFixedSize(500, 260);
updatedialog.move((width - 500)/2,(height-260)/2);

View File

@ -16,41 +16,172 @@
* along with openauto. If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/algorithm/hex.hpp>
#include <f1x/openauto/Common/Log.hpp>
#include <f1x/openauto/autoapp/Configuration/IConfiguration.hpp>
#include <f1x/openauto/btservice/AndroidBluetoothServer.hpp>
#include <QString>
#include <QtCore/QDataStream>
#include <QNetworkInterface>
#include <aasdk_proto/WifiInfoRequestMessage.pb.h>
#include <aasdk_proto/WifiInfoResponseMessage.pb.h>
#include <aasdk_proto/WifiSecurityResponseMessage.pb.h>
namespace f1x
{
namespace openauto
{
namespace btservice
{
namespace f1x {
namespace openauto {
namespace btservice {
AndroidBluetoothServer::AndroidBluetoothServer()
: rfcommServer_(std::make_unique<QBluetoothServer>(QBluetoothServiceInfo::RfcommProtocol, this))
{
connect(rfcommServer_.get(), &QBluetoothServer::newConnection, this, &AndroidBluetoothServer::onClientConnected);
}
AndroidBluetoothServer::AndroidBluetoothServer(autoapp::configuration::IConfiguration::Pointer configuration)
: rfcommServer_(std::make_unique<QBluetoothServer>(QBluetoothServiceInfo::RfcommProtocol, this))
, configuration_(std::move(configuration))
{
connect(rfcommServer_.get(), &QBluetoothServer::newConnection, this,
&AndroidBluetoothServer::onClientConnected);
}
bool AndroidBluetoothServer::start(const QBluetoothAddress& address, uint16_t portNumber)
{
return rfcommServer_->listen(address, portNumber);
}
uint16_t AndroidBluetoothServer::start(const QBluetoothAddress &address) {
if (rfcommServer_->listen(address)) {
return rfcommServer_->serverPort();
}
return 0;
}
void AndroidBluetoothServer::onClientConnected()
{
auto socket = rfcommServer_->nextPendingConnection();
void AndroidBluetoothServer::onClientConnected() {
if (socket != nullptr) {
socket->deleteLater();
}
if(socket != nullptr)
{
OPENAUTO_LOG(info) << "[AndroidBluetoothServer] rfcomm client connected, peer name: " << socket->peerName().toStdString();
socket = rfcommServer_->nextPendingConnection();
if (socket != nullptr) {
OPENAUTO_LOG(info) << "[AndroidBluetoothServer] rfcomm client connected, peer name: "
<< socket->peerName().toStdString();
connect(socket, &QBluetoothSocket::readyRead, this, &AndroidBluetoothServer::readSocket);
// connect(socket, &QBluetoothSocket::disconnected, this,
// QOverload<>::of(&ChatServer::clientDisconnected));
f1x::aasdk::proto::messages::WifiInfoRequest request;
request.set_ip_address(getIP4_("wlan0"));
request.set_port(5000);
sendMessage(request, 1);
} else {
OPENAUTO_LOG(error) << "[AndroidBluetoothServer] received null socket during client connection.";
}
}
void AndroidBluetoothServer::readSocket() {
buffer += socket->readAll();
OPENAUTO_LOG(info) << "Received message";
if (buffer.length() < 4) {
OPENAUTO_LOG(debug) << "Not enough data, waiting for more";
return;
}
QDataStream stream(buffer);
uint16_t length;
stream >> length;
if (buffer.length() < length + 4) {
OPENAUTO_LOG(info) << "Not enough data, waiting for more: " << buffer.length();
return;
}
uint16_t messageId;
stream >> messageId;
//OPENAUTO_LOG(info) << "[AndroidBluetoothServer] " << length << " " << messageId;
switch (messageId) {
case 1:
handleWifiInfoRequest(buffer, length);
break;
case 2:
handleWifiSecurityRequest(buffer, length);
break;
case 7:
handleWifiInfoRequestResponse(buffer, length);
break;
default: {
std::stringstream ss;
ss << std::hex << std::setfill('0');
for (auto &&val : buffer) {
ss << std::setw(2) << static_cast<unsigned>(val);
}
OPENAUTO_LOG(info) << "Unknown message: " << messageId;
OPENAUTO_LOG(info) << ss.str();
break;
}
}
buffer = buffer.mid(length + 4);
}
void AndroidBluetoothServer::handleWifiInfoRequest(QByteArray &buffer, uint16_t length) {
f1x::aasdk::proto::messages::WifiInfoRequest msg;
msg.ParseFromArray(buffer.data() + 4, length);
OPENAUTO_LOG(info) << "WifiInfoRequest: " << msg.DebugString();
f1x::aasdk::proto::messages::WifiInfoResponse response;
response.set_ip_address(getIP4_("wlan0"));
response.set_port(5000);
response.set_status(aasdk::proto::messages::WifiInfoResponse_Status_STATUS_SUCCESS);
sendMessage(response, 7);
}
void AndroidBluetoothServer::handleWifiSecurityRequest(QByteArray &buffer, uint16_t length) {
f1x::aasdk::proto::messages::WifiSecurityReponse response;
response.set_ssid(configuration_->getParamFromFile("/etc/hostapd/hostapd.conf","ssid").toStdString());
response.set_bssid(QNetworkInterface::interfaceFromName("wlan0").hardwareAddress().toStdString());
response.set_key(configuration_->getParamFromFile("/etc/hostapd/hostapd.conf","wpa_passphrase").toStdString());
response.set_security_mode(aasdk::proto::messages::WifiSecurityReponse_SecurityMode_WPA2_PERSONAL);
response.set_access_point_type(aasdk::proto::messages::WifiSecurityReponse_AccessPointType_STATIC);
sendMessage(response, 3);
}
void AndroidBluetoothServer::sendMessage(const google::protobuf::Message& message, uint16_t type) {
int byteSize = message.ByteSize();
QByteArray out(byteSize + 4, 0);
QDataStream ds(&out, QIODevice::ReadWrite);
ds << (uint16_t) byteSize;
ds << type;
message.SerializeToArray(out.data() + 4, byteSize);
std::stringstream ss;
ss << std::hex << std::setfill('0');
for (auto &&val : out) {
ss << std::setw(2) << static_cast<unsigned>(val);
}
//OPENAUTO_LOG(info) << "Writing message: " << ss.str();
OPENAUTO_LOG(debug) << message.GetTypeName() << " - " + message.DebugString();
auto written = socket->write(out);
if (written > -1) {
OPENAUTO_LOG(info) << "Bytes written: " << written;
} else {
OPENAUTO_LOG(info) << "Could not write data";
}
}
void AndroidBluetoothServer::handleWifiInfoRequestResponse(QByteArray &buffer, uint16_t length) {
f1x::aasdk::proto::messages::WifiInfoResponse msg;
msg.ParseFromArray(buffer.data() + 4, length);
OPENAUTO_LOG(info) << "WifiInfoResponse: " << msg.DebugString();
}
const ::std::string AndroidBluetoothServer::getIP4_(const QString intf) {
for (const QNetworkAddressEntry &address: QNetworkInterface::interfaceFromName(intf).addressEntries()) {
if (address.ip().protocol() == QAbstractSocket::IPv4Protocol)
return address.ip().toString().toStdString();
}
return "";
}
}
}
else
{
OPENAUTO_LOG(error) << "[AndroidBluetoothServer] received null socket during client connection.";
}
}
}
}
}
}

View File

@ -16,23 +16,33 @@
* along with openauto. If not, see <http://www.gnu.org/licenses/>.
*/
#include <QApplication>
#include <QCoreApplication>
#include <QtBluetooth>
#include <f1x/openauto/Common/Log.hpp>
#include <f1x/openauto/autoapp/Configuration/Configuration.hpp>
#include <f1x/openauto/btservice/AndroidBluetoothService.hpp>
#include <f1x/openauto/btservice/AndroidBluetoothServer.hpp>
namespace btservice = f1x::openauto::btservice;
int main(int argc, char* argv[])
{
QApplication qApplication(argc, argv);
int main(int argc, char *argv[]) {
QLoggingCategory::setFilterRules(QStringLiteral("qt.bluetooth*=true"));
QCoreApplication qApplication(argc, argv);
const QBluetoothAddress address;
const uint16_t portNumber = 5000;
QBluetoothLocalDevice localDevice;
const QBluetoothAddress address = localDevice.address();
btservice::AndroidBluetoothServer androidBluetoothServer;
if(!androidBluetoothServer.start(address, portNumber))
{
auto configuration = std::make_shared<f1x::openauto::autoapp::configuration::Configuration>();
// Turn Bluetooth on
localDevice.powerOn();
// Make it visible to others
localDevice.setHostMode(QBluetoothLocalDevice::HostDiscoverable);
btservice::AndroidBluetoothServer androidBluetoothServer(configuration);
uint16_t portNumber = androidBluetoothServer.start(address);
if (portNumber == 0) {
OPENAUTO_LOG(error) << "[btservice] Server start failed.";
return 2;
}
@ -41,17 +51,16 @@ int main(int argc, char* argv[])
<< ", port: " << portNumber;
btservice::AndroidBluetoothService androidBluetoothService(portNumber);
if(!androidBluetoothService.registerService(address))
{
if (!androidBluetoothService.registerService(address)) {
OPENAUTO_LOG(error) << "[btservice] Service registration failed.";
return 1;
}
else
{
} else {
OPENAUTO_LOG(info) << "[btservice] Service registered, port: " << portNumber;
}
qApplication.exec();
QCoreApplication::exec();
OPENAUTO_LOG(info) << "stop";
androidBluetoothService.unregisterService();
return 0;