Introduce Event Services (#1653)

* Allow to enable/disable suspend & lock event handling

* Fix Windows

* Refactor event handling incl.CEC

* Revert "Auxiliary commit to revert individual files from 0d9a8b8a3a4a09609a339f54c7d8a9384c561282"

This reverts commit 80737d926ad151a07b2493dd1685ed502975cb2e.

* Support Events for Grabbers generically

* Have CECEvent to actions configurable, further clean-ups

* Remove handleEvent from V4L2grabber, as grabber will be stopped on suspend

* Validate that one CEC Event can only trigger one action

* MacOS lock/unlock added

* fast windows fix

* Corrections

* Fix CodeQL findings

* add macos lock/unlock handler

* Migration of CEC-config and have default actions

* Correct target_link_libraries

* Include Foundation

* macOS include AppKit

* Support Scheduled Events, cleanups.

* Fix destructing

* Fix coredump during free

* Consider additional error sceanrio

* Fix missing code

* install desktop icons

* correct bash logic

---------

Co-authored-by: Paulchen-Panther <16664240+Paulchen-Panther@users.noreply.github.com>
This commit is contained in:
LordGrey
2023-11-27 09:06:43 +01:00
committed by GitHub
parent 2e0cc9cfa8
commit a1f0821f33
53 changed files with 2306 additions and 829 deletions

View File

@@ -4,6 +4,7 @@
#include <algorithm>
#include <libcec/cecloader.h>
#include <events/EventHandler.h>
#include <QJsonArray>
#include <QJsonDocument>
@@ -12,13 +13,21 @@
#include <QFile>
/* Enable to turn on detailed CEC logs */
#define NO_VERBOSE_CEC
#define NOVERBOSE_CEC
CECHandler::CECHandler()
CECHandler::CECHandler(const QJsonDocument& config, QObject * parent)
: QObject(parent)
, _config(config)
, _isInitialised(false)
, _isEnabled(false)
, _buttonReleaseDelayMs(CEC_BUTTON_TIMEOUT)
, _buttonRepeatRateMs(0)
, _doubleTapTimeoutMs(CEC_DOUBLE_TAP_TIMEOUT_MS)
, _cecEventActionMap()
{
qRegisterMetaType<CECEvent>("CECEvent");
qRegisterMetaType<Event>("Event");
_logger = Logger::getInstance("CEC");
_logger = Logger::getInstance("EVENTS-CEC");
_cecCallbacks = getCallbacks();
_cecConfig = getConfig();
@@ -28,66 +37,151 @@ CECHandler::CECHandler()
CECHandler::~CECHandler()
{
stop();
}
void CECHandler::handleSettingsUpdate(settings::type type, const QJsonDocument& config)
{
if(type == settings::CECEVENTS)
{
if (_isInitialised)
{
const QJsonObject& obj = config.object();
_isEnabled = obj["enable"].toBool(false);
Debug(_logger, "CEC Event handling is %s", _isEnabled? "enabled" : "disabled");
if (_isEnabled)
{
_buttonReleaseDelayMs = obj["buttonReleaseDelayMs"].toInt(CEC_BUTTON_TIMEOUT);
_buttonRepeatRateMs = obj["buttonRepeatRateMs"].toInt(0);
_doubleTapTimeoutMs = obj["doubleTapTimeoutMs"].toInt(CEC_DOUBLE_TAP_TIMEOUT_MS);
Debug(_logger, "Remote button press release time : %dms",_buttonReleaseDelayMs);
Debug(_logger, "Remote button press repeat rate : %dms",_buttonRepeatRateMs);
Debug(_logger, "Remote button press delay before repeating : %dms",_doubleTapTimeoutMs);
_cecConfig.iButtonReleaseDelayMs = static_cast<uint32_t>(_buttonReleaseDelayMs);
_cecConfig.iButtonRepeatRateMs = static_cast<uint32_t>(_buttonRepeatRateMs);
_cecConfig.iDoubleTapTimeoutMs = static_cast<uint32_t>(_doubleTapTimeoutMs);
_cecEventActionMap.clear();
const QJsonArray actionItems = obj["actions"].toArray();
if (!actionItems.isEmpty())
{
for (const QJsonValue &item : actionItems)
{
QString cecEvent = item.toObject().value("event").toString();
QString action = item.toObject().value("action").toString();
_cecEventActionMap.insert(cecEvent, stringToEvent(action));
Debug(_logger, "CEC-Event : \"%s\" linked to action \"%s\"", QSTRING_CSTR(cecEvent), QSTRING_CSTR(action));
}
}
if (!_cecEventActionMap.isEmpty())
{
enable();
}
else
{
Warning(_logger, "No CEC events to listen to are configured currently.");
}
}
else
{
disable();
}
}
}
}
bool CECHandler::start()
{
if (_cecAdapter)
return true;
std::string library = std::string("" CEC_LIBRARY);
_cecAdapter = LibCecInitialise(&_cecConfig, QFile::exists(QString::fromStdString(library)) ? library.c_str() : nullptr);
if(!_cecAdapter)
_isInitialised = false;
if (_cecAdapter == nullptr)
{
Error(_logger, "Failed to loading libcec.so");
return false;
}
Info(_logger, "CEC handler started");
auto adapters = getAdapters();
if (adapters.isEmpty())
{
Error(_logger, "Failed to find CEC adapter");
UnloadLibCec(_cecAdapter);
_cecAdapter = nullptr;
return false;
}
Info(_logger, "Auto detecting CEC adapter");
bool opened = false;
for (const auto & adapter : adapters)
{
printAdapter(adapter);
if (!opened && openAdapter(adapter))
_cecAdapter = LibCecInitialise(&_cecConfig);
if(_cecAdapter == nullptr)
{
Info(_logger, "CEC Handler initialized with adapter : %s", adapter.strComName);
opened = true;
Error(_logger, "Failed loading libCEC library. CEC is not supported.");
}
else
{
_isInitialised = true;
}
handleSettingsUpdate(settings::CECEVENTS,_config);
}
return _isInitialised;
}
void CECHandler::stop()
{
if (_cecAdapter != nullptr)
{
Info(_logger, "Stopping CEC handler");
_cecAdapter->Close();
UnloadLibCec(_cecAdapter);
}
}
bool CECHandler::enable()
{
bool opened {false};
if (_isInitialised)
{
const auto adapters = getAdapters();
if (adapters.isEmpty())
{
Error(_logger, "Failed to find any CEC adapter. CEC event handling will be disabled.");
_cecAdapter->Close();
return false;
}
Info(_logger, "Auto detecting CEC adapter");
for (const auto & adapter : adapters)
{
printAdapter(adapter);
if (!opened && openAdapter(adapter))
{
Info(_logger, "CEC adapter '%s', type: %s initialized." , adapter.strComName, _cecAdapter->ToString(adapter.adapterType));
opened = true;
break;
}
}
#ifdef VERBOSE_CEC
std::cout << "Found Devices: " << scan().toStdString() << std::endl;
#endif
}
if (!opened)
{
UnloadLibCec(_cecAdapter);
_cecAdapter = nullptr;
Error(_logger, "Could not initialize any CEC adapter.");
_cecAdapter->Close();
}
else
{
if (!_cecAdapter->SetConfiguration(&_cecConfig))
{
Error(_logger, "Failed setting remote button press timing parameters");
}
QObject::connect(this, &CECHandler::signalEvent, EventHandler::getInstance(), &EventHandler::handleEvent);
Info(_logger, "CEC handler started");
}
return opened;
}
void CECHandler::stop()
void CECHandler::disable()
{
if (_cecAdapter)
if (_isInitialised)
{
Info(_logger, "Stopping CEC handler");
QObject::disconnect(this, &CECHandler::signalEvent, EventHandler::getInstance(), &EventHandler::handleEvent);
_cecAdapter->Close();
UnloadLibCec(_cecAdapter);
_cecAdapter = nullptr;
}
}
@@ -97,7 +191,6 @@ CECConfig CECHandler::getConfig() const
const std::string name("HyperionCEC");
name.copy(configuration.strDeviceName, std::min(name.size(), sizeof(configuration.strDeviceName)));
configuration.deviceTypes.Add(CEC::CEC_DEVICE_TYPE_RECORDING_DEVICE);
configuration.clientVersion = CEC::LIBCEC_VERSION_CURRENT;
@@ -121,11 +214,11 @@ CECCallbacks CECHandler::getCallbacks() const
QVector<CECAdapterDescriptor> CECHandler::getAdapters() const
{
if (!_cecAdapter)
if (_cecAdapter == nullptr)
return {};
QVector<CECAdapterDescriptor> descriptors(16);
int8_t size = _cecAdapter->DetectAdapters(descriptors.data(), descriptors.size(), nullptr, true /*quickscan*/);
int8_t size = _cecAdapter->DetectAdapters(descriptors.data(), static_cast<uint8_t>(descriptors.size()), nullptr, true /*quickscan*/);
descriptors.resize(size);
return descriptors;
@@ -133,15 +226,12 @@ QVector<CECAdapterDescriptor> CECHandler::getAdapters() const
bool CECHandler::openAdapter(const CECAdapterDescriptor & descriptor)
{
if (!_cecAdapter)
if (_cecAdapter == nullptr)
return false;
if(!_cecAdapter->Open(descriptor.strComName))
{
Error(_logger, "%s", QSTRING_CSTR(QString("Failed to open the CEC adaper on port %1")
.arg(descriptor.strComName))
);
Error(_logger, "CEC adapter '%s', type: %s failed to open.", descriptor.strComName, _cecAdapter->ToString(descriptor.adapterType));
return false;
}
return true;
@@ -149,28 +239,44 @@ bool CECHandler::openAdapter(const CECAdapterDescriptor & descriptor)
void CECHandler::printAdapter(const CECAdapterDescriptor & descriptor) const
{
Info(_logger, "%s", QSTRING_CSTR(QString("CEC Adapter:")));
Info(_logger, "%s", QSTRING_CSTR(QString("\tName : %1").arg(descriptor.strComName)));
Info(_logger, "%s", QSTRING_CSTR(QString("\tPath : %1").arg(descriptor.strComPath)));
Debug(_logger, "CEC Adapter:");
Debug(_logger, "\tName : %s", descriptor.strComName);
Debug(_logger, "\tPath : %s", descriptor.strComPath);
if (descriptor.iVendorId != 0)
{
Debug(_logger, "\tVendor id: %04x", descriptor.iVendorId);
}
if (descriptor.iProductId != 0)
{
Debug(_logger, "\tProduct id: %04x", descriptor.iProductId);
}
if (descriptor.iFirmwareVersion != 0)
{
Debug(_logger, "\tFirmware id: %d", descriptor.iFirmwareVersion);
}
if (descriptor.adapterType != CEC::ADAPTERTYPE_UNKNOWN)
{
Debug(_logger, "\tType : %s", _cecAdapter->ToString(descriptor.adapterType));
}
}
QString CECHandler::scan() const
{
if (!_cecAdapter)
if (_cecAdapter == nullptr)
return {};
Info(_logger, "Starting CEC scan");
QJsonArray devices;
CECLogicalAddresses addresses = _cecAdapter->GetActiveDevices();
for (int address = CEC::CECDEVICE_TV; address <= CEC::CECDEVICE_BROADCAST; ++address)
for (uint8_t address = CEC::CECDEVICE_TV; address <= CEC::CECDEVICE_BROADCAST; ++address)
{
if (addresses[address])
if (addresses[address] != 0)
{
CECLogicalAddress logicalAddress = (CECLogicalAddress)address;
CECLogicalAddress logicalAddress = static_cast<CECLogicalAddress>(address);
QJsonObject device;
CECVendorId vendor = (CECVendorId)_cecAdapter->GetDeviceVendorId(logicalAddress);
CECVendorId vendor = static_cast<CECVendorId>(_cecAdapter->GetDeviceVendorId(logicalAddress));
CECPowerStatus power = _cecAdapter->GetDevicePowerStatus(logicalAddress);
device["name" ] = _cecAdapter->GetDeviceOSDName(logicalAddress).c_str();
@@ -181,46 +287,48 @@ QString CECHandler::scan() const
devices << device;
Info(_logger, "%s", QSTRING_CSTR(QString("\tCECDevice: %1 / %2 / %3 / %4")
.arg(device["name"].toString(),
device["vendor"].toString(),
device["address"].toString(),
device["power"].toString()))
);
.arg(device["name"].toString(),
device["vendor"].toString(),
device["address"].toString(),
device["power"].toString())
)
);
}
}
return QJsonDocument(devices).toJson(QJsonDocument::Compact);
}
void CECHandler::triggerAction(const QString& cecEvent)
{
Event action = _cecEventActionMap.value(cecEvent, Event::Unknown);
Debug(_logger, "CEC-Event : \"%s\" triggers action \"%s\"", QSTRING_CSTR(cecEvent), eventToString(action) );
if ( action != Event::Unknown )
{
emit signalEvent(action);
}
}
void CECHandler::onCecLogMessage(void * context, const CECLogMessage * message)
{
#ifdef VERBOSE_CEC
CECHandler * handler = qobject_cast<CECHandler*>(static_cast<QObject*>(context));
if (!handler)
if (handler == nullptr)
return;
switch (message->level)
{
case CEC::CEC_LOG_ERROR:
Error(handler->_logger, QString("%1")
.arg(message->message)
.toLocal8Bit());
Error(handler->_logger, "%s", message->message);
break;
case CEC::CEC_LOG_WARNING:
Warning(handler->_logger, QString("%1")
.arg(message->message)
.toLocal8Bit());
Warning(handler->_logger, "%s", message->message);
break;
case CEC::CEC_LOG_TRAFFIC:
case CEC::CEC_LOG_NOTICE:
Info(handler->_logger, QString("%1")
.arg(message->message)
.toLocal8Bit());
Info(handler->_logger, "%s", message->message);
break;
case CEC::CEC_LOG_DEBUG:
Debug(handler->_logger, QString("%1")
.arg(message->message)
.toLocal8Bit());
Debug(handler->_logger, "%s", message->message);
break;
default:
break;
@@ -230,29 +338,36 @@ void CECHandler::onCecLogMessage(void * context, const CECLogMessage * message)
void CECHandler::onCecKeyPress(void * context, const CECKeyPress * key)
{
#ifdef VERBOSE_CEC
CECHandler * handler = qobject_cast<CECHandler*>(static_cast<QObject*>(context));
if (!handler)
if (handler == nullptr)
return;
CECAdapter * adapter = handler->_cecAdapter;
Debug(handler->_logger, QString("CECHandler::onCecKeyPress: %1")
.arg(adapter->ToString(key->keycode))
.toLocal8Bit());
#ifdef VERBOSE_CEC
Debug(handler->_logger, "CECHandler::onCecKeyPress: %s", adapter->ToString(key->keycode));
#endif
switch (key->keycode) {
case CEC::CEC_USER_CONTROL_CODE_F1_BLUE:
case CEC::CEC_USER_CONTROL_CODE_F2_RED:
case CEC::CEC_USER_CONTROL_CODE_F3_GREEN:
case CEC::CEC_USER_CONTROL_CODE_F4_YELLOW:
handler->triggerAction(adapter->ToString(key->keycode));
break;
default:
break;
}
}
void CECHandler::onCecAlert(void * context, const CECAlert alert, const CECParameter data)
void CECHandler::onCecAlert(void * context, const CECAlert alert, const CECParameter /* data */)
{
#ifdef VERBOSE_CEC
CECHandler * handler = qobject_cast<CECHandler*>(static_cast<QObject*>(context));
if (!handler)
if (handler == nullptr)
return;
Error(handler->_logger, QString("CECHandler::onCecAlert: %1")
.arg(alert)
.toLocal8Bit());
Error(handler->_logger, QSTRING_CSTR(QString("CECHandler::onCecAlert: %1")
.arg(alert)));
#endif
}
@@ -260,12 +375,10 @@ void CECHandler::onCecConfigurationChanged(void * context, const CECConfig * con
{
#ifdef VERBOSE_CEC
CECHandler * handler = qobject_cast<CECHandler*>(static_cast<QObject*>(context));
if (!handler)
if (handler == nullptr)
return;
Debug(handler->_logger, QString("CECHandler::onCecConfigurationChanged: %1")
.arg(configuration->strDeviceName)
.toLocal8Bit());
Debug(handler->_logger, "CECHandler::onCecConfigurationChanged: %s", configuration->strDeviceName);
#endif
}
@@ -278,9 +391,7 @@ int CECHandler::onCecMenuStateChanged(void * context, const CECMenuState state)
CECAdapter * adapter = handler->_cecAdapter;
Debug(handler->_logger, QString("CECHandler::onCecMenuStateChanged: %1")
.arg(adapter->ToString(state))
.toLocal8Bit());
Debug(handler->_logger, "CECHandler::onCecMenuStateChanged: %s", adapter->ToString(state));
#endif
return 0;
}
@@ -294,28 +405,25 @@ void CECHandler::onCecCommandReceived(void * context, const CECCommand * command
CECAdapter * adapter = handler->_cecAdapter;
#ifdef VERBOSE_CEC
Debug(handler->_logger, QString("CECHandler::onCecCommandReceived: %1 (%2 > %3)")
.arg(adapter->ToString(command->opcode))
.arg(adapter->ToString(command->initiator))
.arg(adapter->ToString(command->destination))
.toLocal8Bit());
Debug(handler->_logger, "CECHandler::onCecCommandReceived: %s %s > %s)",
adapter->ToString(command->opcode),
adapter->ToString(command->initiator),
adapter->ToString(command->destination)
);
#endif
/* We do NOT check sender */
// if (address == CEC::CECDEVICE_TV)
//if (address == CEC::CECDEVICE_TV)
{
if (command->opcode == CEC::CEC_OPCODE_SET_STREAM_PATH)
switch (command->opcode) {
case CEC::CEC_OPCODE_STANDBY:
case CEC::CEC_OPCODE_SET_STREAM_PATH:
{
Info(handler->_logger, "%s", QSTRING_CSTR(QString("CEC source activated: %1")
.arg(adapter->ToString(command->initiator)))
);
emit handler->cecEvent(CECEvent::On);
handler->triggerAction(adapter->ToString(command->opcode));
}
if (command->opcode == CEC::CEC_OPCODE_STANDBY)
{
Info(handler->_logger, "%s", QSTRING_CSTR(QString("CEC source deactivated: %1")
.arg(adapter->ToString(command->initiator)))
);
emit handler->cecEvent(CECEvent::Off);
break;
default:
break;
}
}
}
@@ -327,15 +435,14 @@ void CECHandler::onCecSourceActivated(void * context, const CECLogicalAddress ad
#ifdef VERBOSE_CEC
CECHandler * handler = qobject_cast<CECHandler*>(static_cast<QObject*>(context));
if (!handler)
if (handler == nullptr)
return;
CECAdapter * adapter = handler->_cecAdapter;
Debug(handler->_logger, QString("CEC source %1 : %2")
.arg(activated ? "activated" : "deactivated")
.arg(adapter->ToString(address))
.toLocal8Bit());
Debug(handler->_logger, QSTRING_CSTR(QString("CEC source %1 : %2")
.arg(activated ? "activated" : "deactivated",
adapter->ToString(address))
));
#endif
}

View File

@@ -7,7 +7,6 @@ else()
endif()
add_library(cechandler
${CMAKE_SOURCE_DIR}/include/cec/CECEvent.h
${CMAKE_SOURCE_DIR}/include/cec/CECHandler.h
${CMAKE_SOURCE_DIR}/libsrc/cec/CECHandler.cpp
)