X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Flib%2FCECProcessor.cpp;h=8fc71dc31a2502e88e457c576063fac780414abe;hb=42d28d15d07f893b491051970ade1bd56bb596eb;hp=19984f0312c3b33b68eb04a6fc6a79e092001afd;hpb=e41b06f9e1fc5c8af372eabf338dbb691ee7ac4c;p=deb_libcec.git diff --git a/src/lib/CECProcessor.cpp b/src/lib/CECProcessor.cpp index 19984f0..034c7e6 100644 --- a/src/lib/CECProcessor.cpp +++ b/src/lib/CECProcessor.cpp @@ -1,7 +1,7 @@ /* * This file is part of the libCEC(R) library. * - * libCEC(R) is Copyright (C) 2011 Pulse-Eight Limited. All rights reserved. + * libCEC(R) is Copyright (C) 2011-2012 Pulse-Eight Limited. All rights reserved. * libCEC(R) is an original work, containing original code. * * libCEC(R) is a trademark of Pulse-Eight Limited. @@ -32,380 +32,802 @@ #include "CECProcessor.h" -#include "AdapterCommunication.h" +#include "adapter/USBCECAdapterCommunication.h" #include "devices/CECBusDevice.h" +#include "devices/CECAudioSystem.h" +#include "devices/CECPlaybackDevice.h" +#include "devices/CECRecordingDevice.h" +#include "devices/CECTuner.h" +#include "devices/CECTV.h" +#include "implementations/CECCommandHandler.h" #include "LibCEC.h" -#include "util/StdString.h" -#include "platform/timeutils.h" +#include "CECClient.h" +#include "CECTypeUtils.h" +#include "platform/util/timeutils.h" +#include "platform/util/util.h" using namespace CEC; using namespace std; +using namespace PLATFORM; -CCECProcessor::CCECProcessor(CLibCEC *controller, CAdapterCommunication *serComm, const char *strDeviceName, cec_logical_address iLogicalAddress /* = CECDEVICE_PLAYBACKDEVICE1 */, uint16_t iPhysicalAddress /* = CEC_DEFAULT_PHYSICAL_ADDRESS*/) : - m_iLogicalAddress(iLogicalAddress), - m_strDeviceName(strDeviceName), - m_communication(serComm), - m_controller(controller), - m_bMonitor(false), - m_bLogicalAddressSet(false) +#define CEC_PROCESSOR_SIGNAL_WAIT_TIME 1000 +#define ACTIVE_SOURCE_CHECK_TIMEOUT 10000 + +#define ToString(x) CCECTypeUtils::ToString(x) + +CCECProcessor::CCECProcessor(CLibCEC *libcec) : + m_bInitialised(false), + m_communication(NULL), + m_libcec(libcec), + m_iStandardLineTimeout(3), + m_iRetryLineTimeout(3), + m_iLastTransmission(0) { - for (int iPtr = 0; iPtr < 16; iPtr++) - m_busDevices[iPtr] = new CCECBusDevice(this, (cec_logical_address) iPtr, iPtr == iLogicalAddress ? iPhysicalAddress : 0); + m_busDevices = new CCECDeviceMap(this); } CCECProcessor::~CCECProcessor(void) { - m_startCondition.Broadcast(); + Close(); + DELETE_AND_NULL(m_busDevices); +} + +bool CCECProcessor::Start(const char *strPort, uint16_t iBaudRate /* = CEC_SERIAL_DEFAULT_BAUDRATE */, uint32_t iTimeoutMs /* = CEC_DEFAULT_CONNECT_TIMEOUT */) +{ + CLockObject lock(m_mutex); + // open a connection + if (!OpenConnection(strPort, iBaudRate, iTimeoutMs)) + return false; + + // create the processor thread + if (!IsRunning()) + { + if (!CreateThread()) + { + m_libcec->AddLog(CEC_LOG_ERROR, "could not create a processor thread"); + return false; + } + } + + return true; +} + +void CCECProcessor::Close(void) +{ + // mark as uninitialised + SetCECInitialised(false); + + // stop the processor StopThread(); - m_communication = NULL; - m_controller = NULL; - for (unsigned int iPtr = 0; iPtr < 16; iPtr++) - delete m_busDevices[iPtr]; + + // close the connection + DELETE_AND_NULL(m_communication); +} + +void CCECProcessor::ResetMembers(void) +{ + // close the connection + DELETE_AND_NULL(m_communication); + + // reset the other members to the initial state + m_iStandardLineTimeout = 3; + m_iRetryLineTimeout = 3; + m_iLastTransmission = 0; + m_busDevices->ResetDeviceStatus(); } -bool CCECProcessor::Start(void) +bool CCECProcessor::OpenConnection(const char *strPort, uint16_t iBaudRate, uint32_t iTimeoutMs, bool bStartListening /* = true */) { - CLockObject lock(&m_mutex); - if (!m_communication || !m_communication->IsOpen()) + bool bReturn(false); + CTimeout timeout(iTimeoutMs > 0 ? iTimeoutMs : CEC_DEFAULT_TRANSMIT_WAIT); + + // ensure that a previous connection is closed + Close(); + + // reset all member to the initial state + ResetMembers(); + + // check whether the Close() method deleted any previous connection + if (m_communication) { - m_controller->AddLog(CEC_LOG_ERROR, "connection is closed"); - return false; + m_libcec->AddLog(CEC_LOG_ERROR, "previous connection could not be closed"); + return bReturn; } - if (!SetLogicalAddress(m_iLogicalAddress)) + // create a new connection + m_communication = new CUSBCECAdapterCommunication(this, strPort, iBaudRate); + + // open a new connection + unsigned iConnectTry(0); + while (timeout.TimeLeft() > 0 && (bReturn = m_communication->Open((timeout.TimeLeft() / CEC_CONNECT_TRIES), false, bStartListening)) == false) { - m_controller->AddLog(CEC_LOG_ERROR, "could not set the logical address"); - return false; + m_libcec->AddLog(CEC_LOG_ERROR, "could not open a connection (try %d)", ++iConnectTry); + m_communication->Close(); + CEvent::Sleep(CEC_DEFAULT_CONNECT_RETRY_WAIT); + } + + m_libcec->AddLog(CEC_LOG_NOTICE, "connection opened"); + + // mark as initialised + SetCECInitialised(true); + + return bReturn; +} + +bool CCECProcessor::CECInitialised(void) +{ + CLockObject lock(m_threadMutex); + return m_bInitialised; +} + +void CCECProcessor::SetCECInitialised(bool bSetTo /* = true */) +{ + { + CLockObject lock(m_mutex); + m_bInitialised = bSetTo; } + if (!bSetTo) + UnregisterClients(); +} - if (CreateThread()) +bool CCECProcessor::TryLogicalAddress(cec_logical_address address) +{ + // find the device + CCECBusDevice *device = m_busDevices->At(address); + if (device) { - if (!m_startCondition.Wait(&m_mutex)) - { - m_controller->AddLog(CEC_LOG_ERROR, "could not create a processor thread"); + // check if it's already marked as present or used + if (device->IsPresent() || device->IsHandledByLibCEC()) return false; - } - return true; + + // poll the LA if not + SetAckMask(0); + return device->TryLogicalAddress(); } - else - m_controller->AddLog(CEC_LOG_ERROR, "could not create a processor thread"); return false; } -void *CCECProcessor::Process(void) +void CCECProcessor::ReplaceHandlers(void) { + if (!CECInitialised()) + return; + + // check each device + for (CECDEVICEMAP::iterator it = m_busDevices->Begin(); it != m_busDevices->End(); it++) + it->second->ReplaceHandler(true); +} + +void CCECProcessor::CheckPendingActiveSource(void) +{ + if (!CECInitialised()) + return; + + // check each device + for (CECDEVICEMAP::iterator it = m_busDevices->Begin(); it != m_busDevices->End(); it++) { - CLockObject lock(&m_mutex); - m_controller->AddLog(CEC_LOG_DEBUG, "processor thread started"); - m_startCondition.Signal(); + if (it->second->GetHandler()->ActiveSourcePending()) + it->second->ActivateSource(); } +} + +bool CCECProcessor::OnCommandReceived(const cec_command &command) +{ + return m_inBuffer.Push(command); +} - cec_command command; - CCECAdapterMessage msg; +void *CCECProcessor::Process(void) +{ + m_libcec->AddLog(CEC_LOG_DEBUG, "processor thread started"); - m_communication->SetAckMask(0x1 << (uint8_t)m_iLogicalAddress); + cec_command command; + CTimeout activeSourceCheck(ACTIVE_SOURCE_CHECK_TIMEOUT); - while (!IsStopped()) + // as long as we're not being stopped and the connection is open + while (!IsStopped() && m_communication->IsOpen()) { - bool bParseFrame(false); - command.clear(); - msg.clear(); + // wait for a new incoming command, and process it + if (m_inBuffer.Pop(command, CEC_PROCESSOR_SIGNAL_WAIT_TIME)) + ProcessCommand(command); + if (CECInitialised()) { - CLockObject lock(&m_mutex); - if (m_communication->IsOpen() && m_communication->Read(msg, 50)) - bParseFrame = ParseMessage(msg) && !IsStopped(); + // check clients for keypress timeouts + m_libcec->CheckKeypressTimeout(); + + // check if we need to replace handlers + ReplaceHandlers(); - if (bParseFrame) - command = m_currentframe; + // check whether we need to activate a source, if it failed before + if (activeSourceCheck.TimeLeft() == 0) + { + CheckPendingActiveSource(); + activeSourceCheck.Init(ACTIVE_SOURCE_CHECK_TIMEOUT); + } } + } - if (bParseFrame) - ParseCommand(command); + return NULL; +} - m_controller->CheckKeypressTimeout(); +bool CCECProcessor::ActivateSource(uint16_t iStreamPath) +{ + bool bReturn(false); - for (unsigned int iDevicePtr = 0; iDevicePtr < 16; iDevicePtr++) - m_busDevices[iDevicePtr]->PollVendorId(); + // find the device with the given PA + CCECBusDevice *device = GetDeviceByPhysicalAddress(iStreamPath); + // and make it the active source when found + if (device) + bReturn = device->ActivateSource(); + else + m_libcec->AddLog(CEC_LOG_DEBUG, "device with PA '%04x' not found", iStreamPath); - if (!IsStopped()) - Sleep(5); - } + return bReturn; +} - return NULL; +void CCECProcessor::SetStandardLineTimeout(uint8_t iTimeout) +{ + CLockObject lock(m_mutex); + m_iStandardLineTimeout = iTimeout; } -bool CCECProcessor::SetActiveView(void) +uint8_t CCECProcessor::GetStandardLineTimeout(void) { - if (!IsRunning()) - return false; + CLockObject lock(m_mutex); + return m_iStandardLineTimeout; +} - if (m_iLogicalAddress != CECDEVICE_UNKNOWN && m_busDevices[m_iLogicalAddress]) - return m_busDevices[m_iLogicalAddress]->BroadcastActiveView(); - return false; +void CCECProcessor::SetRetryLineTimeout(uint8_t iTimeout) +{ + CLockObject lock(m_mutex); + m_iRetryLineTimeout = iTimeout; } -bool CCECProcessor::SetInactiveView(void) +uint8_t CCECProcessor::GetRetryLineTimeout(void) { - if (!IsRunning()) - return false; + CLockObject lock(m_mutex); + return m_iRetryLineTimeout; +} - if (m_iLogicalAddress != CECDEVICE_UNKNOWN && m_busDevices[m_iLogicalAddress]) - return m_busDevices[m_iLogicalAddress]->BroadcastInactiveView(); - return false; +bool CCECProcessor::PhysicalAddressInUse(uint16_t iPhysicalAddress) +{ + CCECBusDevice *device = GetDeviceByPhysicalAddress(iPhysicalAddress); + return device != NULL; } void CCECProcessor::LogOutput(const cec_command &data) { CStdString strTx; - strTx.Format("<< %02x:%02x", ((uint8_t)data.initiator << 4) + (uint8_t)data.destination, (uint8_t)data.opcode); + // initiator and destination + strTx.Format("<< %02x", ((uint8_t)data.initiator << 4) + (uint8_t)data.destination); + + // append the opcode + if (data.opcode_set) + strTx.AppendFormat(":%02x", (uint8_t)data.opcode); + + // append the parameters for (uint8_t iPtr = 0; iPtr < data.parameters.size; iPtr++) strTx.AppendFormat(":%02x", data.parameters[iPtr]); - m_controller->AddLog(CEC_LOG_TRAFFIC, strTx.c_str()); + + // and log it + m_libcec->AddLog(CEC_LOG_TRAFFIC, strTx.c_str()); +} + +bool CCECProcessor::PollDevice(cec_logical_address iAddress) +{ + // try to find the primary device + CCECBusDevice *primary = GetPrimaryDevice(); + // poll the destination, with the primary as source + if (primary) + return primary->TransmitPoll(iAddress); + + // try to find the destination + CCECBusDevice *device = m_busDevices->At(iAddress); + // and poll the destination, with the same LA as source + if (device) + return device->TransmitPoll(iAddress); + + return false; +} + +CCECBusDevice *CCECProcessor::GetDeviceByPhysicalAddress(uint16_t iPhysicalAddress, bool bSuppressUpdate /* = true */) +{ + return m_busDevices ? + m_busDevices->GetDeviceByPhysicalAddress(iPhysicalAddress, bSuppressUpdate) : + NULL; +} + +CCECBusDevice *CCECProcessor::GetDevice(cec_logical_address address) const +{ + return m_busDevices ? + m_busDevices->At(address) : + NULL; } -bool CCECProcessor::SetLogicalAddress(cec_logical_address iLogicalAddress /* = CECDEVICE_UNKNOWN */) +cec_logical_address CCECProcessor::GetActiveSource(bool bRequestActiveSource /* = true */) { - if (iLogicalAddress != CECDEVICE_UNKNOWN) + // get the device that is marked as active source from the device map + CCECBusDevice *activeSource = m_busDevices->GetActiveSource(); + if (activeSource) + return activeSource->GetLogicalAddress(); + + if (bRequestActiveSource) { - CStdString strLog; - strLog.Format("<< setting logical address to %1x", iLogicalAddress); - m_controller->AddLog(CEC_LOG_NOTICE, strLog.c_str()); - m_iLogicalAddress = iLogicalAddress; - m_bLogicalAddressSet = false; + // request the active source from the bus + CCECBusDevice *primary = GetPrimaryDevice(); + if (primary) + { + primary->RequestActiveSource(); + return GetActiveSource(false); + } } - if (!m_bLogicalAddressSet && m_iLogicalAddress != CECDEVICE_UNKNOWN) - m_bLogicalAddressSet = m_communication && m_communication->SetAckMask(0x1 << (uint8_t)m_iLogicalAddress); + // unknown or none + return CECDEVICE_UNKNOWN; +} - return m_bLogicalAddressSet; +bool CCECProcessor::IsActiveSource(cec_logical_address iAddress) +{ + CCECBusDevice *device = m_busDevices->At(iAddress); + return device && device->IsActiveSource(); } -bool CCECProcessor::SetPhysicalAddress(uint16_t iPhysicalAddress) +bool CCECProcessor::Transmit(const cec_command &data) { - if (m_iLogicalAddress != CECDEVICE_UNKNOWN && m_busDevices[m_iLogicalAddress]) + uint8_t iMaxTries(0); + bool bRetry(true); + uint8_t iTries(0); + + // get the current timeout setting + uint8_t iLineTimeout(GetStandardLineTimeout()); + + // reset the state of this message to 'unknown' + cec_adapter_message_state adapterState = ADAPTER_MESSAGE_STATE_UNKNOWN; + + LogOutput(data); + + // find the initiator device + CCECBusDevice *initiator = m_busDevices->At(data.initiator); + if (!initiator) { - m_busDevices[m_iLogicalAddress]->SetPhysicalAddress(iPhysicalAddress); - return m_busDevices[m_iLogicalAddress]->BroadcastActiveView(); + m_libcec->AddLog(CEC_LOG_WARNING, "invalid initiator"); + return false; } - return false; + + // find the destination device, if it's not the broadcast address + if (data.destination != CECDEVICE_BROADCAST) + { + // check if the device is marked as handled by libCEC + CCECBusDevice *destination = m_busDevices->At(data.destination); + if (destination && destination->IsHandledByLibCEC()) + { + // and reject the command if it's trying to send data to a device that is handled by libCEC + m_libcec->AddLog(CEC_LOG_WARNING, "not sending data to myself!"); + return false; + } + } + + { + CLockObject lock(m_mutex); + m_iLastTransmission = GetTimeMs(); + // set the number of tries + iMaxTries = initiator->GetHandler()->GetTransmitRetries() + 1; + } + + // and try to send the command + while (bRetry && ++iTries < iMaxTries) + { + if (initiator->IsUnsupportedFeature(data.opcode)) + return false; + + adapterState = !IsStopped() && m_communication && m_communication->IsOpen() ? + m_communication->Write(data, bRetry, iLineTimeout) : + ADAPTER_MESSAGE_STATE_ERROR; + iLineTimeout = m_iRetryLineTimeout; + } + + return adapterState == ADAPTER_MESSAGE_STATE_SENT_ACKED; } -bool CCECProcessor::SwitchMonitoring(bool bEnable) +void CCECProcessor::TransmitAbort(cec_logical_address source, cec_logical_address destination, cec_opcode opcode, cec_abort_reason reason /* = CEC_ABORT_REASON_UNRECOGNIZED_OPCODE */) { - CStdString strLog; - strLog.Format("== %s monitoring mode ==", bEnable ? "enabling" : "disabling"); - m_controller->AddLog(CEC_LOG_NOTICE, strLog.c_str()); + m_libcec->AddLog(CEC_LOG_DEBUG, "<< transmitting abort message"); - m_bMonitor = bEnable; - if (bEnable) - return m_communication && m_communication->SetAckMask(0); - else - return m_communication && m_communication->SetAckMask(0x1 << (uint8_t)m_iLogicalAddress); + cec_command command; + cec_command::Format(command, source, destination, CEC_OPCODE_FEATURE_ABORT); + command.parameters.PushBack((uint8_t)opcode); + command.parameters.PushBack((uint8_t)reason); + + Transmit(command); } -cec_version CCECProcessor::GetDeviceCecVersion(cec_logical_address iAddress) +void CCECProcessor::ProcessCommand(const cec_command &command) { - return m_busDevices[iAddress]->GetCecVersion(); + // log the command + CStdString dataStr; + dataStr.Format(">> %1x%1x", command.initiator, command.destination); + if (command.opcode_set == 1) + dataStr.AppendFormat(":%02x", command.opcode); + for (uint8_t iPtr = 0; iPtr < command.parameters.size; iPtr++) + dataStr.AppendFormat(":%02x", (unsigned int)command.parameters[iPtr]); + m_libcec->AddLog(CEC_LOG_TRAFFIC, dataStr.c_str()); + + // find the initiator + CCECBusDevice *device = m_busDevices->At(command.initiator); + + if (device) + device->HandleCommand(command); } -bool CCECProcessor::GetDeviceMenuLanguage(cec_logical_address iAddress, cec_menu_language *language) +bool CCECProcessor::IsPresentDevice(cec_logical_address address) { - if (m_busDevices[iAddress]) - { - *language = m_busDevices[iAddress]->GetMenuLanguage(); - return (strcmp(language->language, "???") == 0); - } - return false; + CCECBusDevice *device = m_busDevices->At(address); + return device && device->GetStatus() == CEC_DEVICE_STATUS_PRESENT; } -uint64_t CCECProcessor::GetDeviceVendorId(cec_logical_address iAddress) +bool CCECProcessor::IsPresentDeviceType(cec_device_type type) { - if (m_busDevices[iAddress]) - return m_busDevices[iAddress]->GetVendorId(); - return false; + CECDEVICEVEC devices; + m_busDevices->GetByType(type, devices); + CCECDeviceMap::FilterActive(devices); + return !devices.empty(); } -cec_power_status CCECProcessor::GetDevicePowerStatus(cec_logical_address iAddress) +uint16_t CCECProcessor::GetDetectedPhysicalAddress(void) const { - if (m_busDevices[iAddress]) - return m_busDevices[iAddress]->GetPowerStatus(); - return CEC_POWER_STATUS_UNKNOWN; + return m_communication ? m_communication->GetPhysicalAddress() : CEC_INVALID_PHYSICAL_ADDRESS; } -bool CCECProcessor::Transmit(const cec_command &data) +bool CCECProcessor::SetAckMask(uint16_t iMask) { - SetLogicalAddress(); + return m_communication ? m_communication->SetAckMask(iMask) : false; +} - bool bReturn(false); - LogOutput(data); +bool CCECProcessor::StandbyDevices(const cec_logical_address initiator, const CECDEVICEVEC &devices) +{ + bool bReturn(true); + for (CECDEVICEVEC::const_iterator it = devices.begin(); it != devices.end(); it++) + bReturn &= (*it)->Standby(initiator); + return bReturn; +} - CCECAdapterMessagePtr output(new CCECAdapterMessage(data)); +bool CCECProcessor::StandbyDevice(const cec_logical_address initiator, cec_logical_address address) +{ + CCECBusDevice *device = m_busDevices->At(address); + return device ? device->Standby(initiator) : false; +} - CLockObject lock(&m_mutex); - { - CLockObject msgLock(&output->mutex); - if (!m_communication || !m_communication->Write(output)) - return bReturn; - else - { - output->condition.Wait(&output->mutex, 1000); - if (output->state != ADAPTER_MESSAGE_STATE_SENT) - { - m_controller->AddLog(CEC_LOG_ERROR, "command was not sent"); - return bReturn; - } - } +bool CCECProcessor::PowerOnDevices(const cec_logical_address initiator, const CECDEVICEVEC &devices) +{ + bool bReturn(true); + for (CECDEVICEVEC::const_iterator it = devices.begin(); it != devices.end(); it++) + bReturn &= (*it)->PowerOn(initiator); + return bReturn; +} + +bool CCECProcessor::PowerOnDevice(const cec_logical_address initiator, cec_logical_address address) +{ + CCECBusDevice *device = m_busDevices->At(address); + return device ? device->PowerOn(initiator) : false; +} - if (data.ack_timeout > 0) +bool CCECProcessor::StartBootloader(const char *strPort /* = NULL */) +{ + bool bReturn(false); + // open a connection if no connection has been opened + if (!m_communication && strPort) + { + IAdapterCommunication *comm = new CUSBCECAdapterCommunication(this, strPort); + CTimeout timeout(CEC_DEFAULT_CONNECT_TIMEOUT); + int iConnectTry(0); + while (timeout.TimeLeft() > 0 && (bReturn = comm->Open(timeout.TimeLeft() / CEC_CONNECT_TRIES, true)) == false) { - bool bError(false); - if ((bReturn = WaitForAck(&bError, output->size(), data.ack_timeout)) == false) - m_controller->AddLog(CEC_LOG_ERROR, "did not receive ack"); + m_libcec->AddLog(CEC_LOG_ERROR, "could not open a connection (try %d)", ++iConnectTry); + comm->Close(); + Sleep(CEC_DEFAULT_TRANSMIT_RETRY_WAIT); } - else + if (comm->IsOpen()) { - bReturn = true; + bReturn = comm->StartBootloader(); + DELETE_AND_NULL(comm); } + return bReturn; + } + else + { + m_communication->StartBootloader(); + Close(); + bReturn = true; } return bReturn; } -void CCECProcessor::TransmitAbort(cec_logical_address address, cec_opcode opcode, ECecAbortReason reason /* = CEC_ABORT_REASON_UNRECOGNIZED_OPCODE */) +bool CCECProcessor::PingAdapter(void) { - m_controller->AddLog(CEC_LOG_DEBUG, "<< transmitting abort message"); + return m_communication->PingAdapter(); +} - cec_command command; - cec_command::format(command, m_iLogicalAddress, address, CEC_OPCODE_FEATURE_ABORT); - command.parameters.push_back((uint8_t)opcode); - command.parameters.push_back((uint8_t)reason); +void CCECProcessor::HandlePoll(cec_logical_address initiator, cec_logical_address destination) +{ + CCECBusDevice *device = m_busDevices->At(destination); + if (device) + device->HandlePollFrom(initiator); +} - Transmit(command); +bool CCECProcessor::HandleReceiveFailed(cec_logical_address initiator) +{ + CCECBusDevice *device = m_busDevices->At(initiator); + return !device || !device->HandleReceiveFailed(); } -bool CCECProcessor::WaitForAck(bool *bError, uint8_t iLength, uint32_t iTimeout /* = 1000 */) +bool CCECProcessor::SetStreamPath(uint16_t iPhysicalAddress) { - bool bTransmitSucceeded = false; - uint8_t iPacketsLeft(iLength / 4); - *bError = false; + // stream path changes are sent by the TV + return GetTV()->GetHandler()->TransmitSetStreamPath(iPhysicalAddress); +} + +bool CCECProcessor::CanPersistConfiguration(void) +{ + return m_communication ? m_communication->GetFirmwareVersion() >= 2 : false; +} - int64_t iNow = GetTimeMs(); - int64_t iTargetTime = iNow + (uint64_t) iTimeout; +bool CCECProcessor::PersistConfiguration(const libcec_configuration &configuration) +{ + return m_communication ? m_communication->PersistConfiguration(configuration) : false; +} - while (!bTransmitSucceeded && !*bError && (iTimeout == 0 || iNow < iTargetTime)) +void CCECProcessor::RescanActiveDevices(void) +{ + for (CECDEVICEMAP::iterator it = m_busDevices->Begin(); it != m_busDevices->End(); it++) + it->second->GetStatus(true); +} + +bool CCECProcessor::GetDeviceInformation(const char *strPort, libcec_configuration *config, uint32_t iTimeoutMs /* = CEC_DEFAULT_CONNECT_TIMEOUT */) +{ + if (!OpenConnection(strPort, CEC_SERIAL_DEFAULT_BAUDRATE, iTimeoutMs, false)) + return false; + + config->iFirmwareVersion = m_communication->GetFirmwareVersion(); + config->iPhysicalAddress = m_communication->GetPhysicalAddress(); + config->iFirmwareBuildDate = m_communication->GetFirmwareBuildDate(); + + return true; +} + +bool CCECProcessor::TransmitPendingActiveSourceCommands(void) +{ + bool bReturn(true); + for (CECDEVICEMAP::iterator it = m_busDevices->Begin(); it != m_busDevices->End(); it++) + bReturn &= it->second->TransmitPendingActiveSourceCommands(); + return bReturn; +} + +CCECTV *CCECProcessor::GetTV(void) const +{ + return CCECBusDevice::AsTV(m_busDevices->At(CECDEVICE_TV)); +} + +CCECAudioSystem *CCECProcessor::GetAudioSystem(void) const +{ + return CCECBusDevice::AsAudioSystem(m_busDevices->At(CECDEVICE_AUDIOSYSTEM)); +} + +CCECPlaybackDevice *CCECProcessor::GetPlaybackDevice(cec_logical_address address) const +{ + return CCECBusDevice::AsPlaybackDevice(m_busDevices->At(address)); +} + +CCECRecordingDevice *CCECProcessor::GetRecordingDevice(cec_logical_address address) const +{ + return CCECBusDevice::AsRecordingDevice(m_busDevices->At(address)); +} + +CCECTuner *CCECProcessor::GetTuner(cec_logical_address address) const +{ + return CCECBusDevice::AsTuner(m_busDevices->At(address)); +} + +bool CCECProcessor::RegisterClient(CCECClient *client) +{ + if (!client) + return false; + + libcec_configuration &configuration = *client->GetConfiguration(); + + if (configuration.clientVersion >= CEC_CLIENT_VERSION_1_6_3 && configuration.bMonitorOnly == 1) + return true; + + if (!CECInitialised()) { - CCECAdapterMessage msg; + m_libcec->AddLog(CEC_LOG_ERROR, "failed to register a new CEC client: CEC processor is not initialised"); + return false; + } - if (!m_communication->Read(msg, iTimeout > 0 ? (int32_t)(iTargetTime - iNow) : 1000)) - { - iNow = GetTimeMs(); - continue; - } + // ensure that we know the vendor id of the TV + GetTV()->GetVendorId(CECDEVICE_UNREGISTERED); - *bError = msg.is_error(); - m_controller->AddLog(msg.is_error() ? CEC_LOG_WARNING : CEC_LOG_DEBUG, msg.ToString()); + // unregister the client first if it's already been marked as registered + if (client->IsRegistered()) + UnregisterClient(client); - switch(msg.message()) - { - case MSGCODE_COMMAND_ACCEPTED: - iPacketsLeft--; - break; - case MSGCODE_TRANSMIT_SUCCEEDED: - bTransmitSucceeded = (iPacketsLeft == 0); - *bError = !bTransmitSucceeded; - break; - default: - CStdString strLog; - strLog.Format("received unexpected reply '%1x' instead of ack", msg.message()); - m_controller->AddLog(CEC_LOG_WARNING, strLog); - *bError = true; - break; - } + // get the configuration from the client + m_libcec->AddLog(CEC_LOG_NOTICE, "registering new CEC client - v%s", ToString((cec_client_version)configuration.clientVersion)); + + // mark as uninitialised and unregistered + client->SetRegistered(false); + client->SetInitialised(false); + + // get the current ackmask, so we can restore it if polling fails + uint16_t iPreviousMask(m_communication->GetAckMask()); + + // find logical addresses for this client + if (!client->AllocateLogicalAddresses()) + { + m_libcec->AddLog(CEC_LOG_ERROR, "failed to register the new CEC client - cannot allocate the requested device types"); + SetAckMask(iPreviousMask); + return false; + } + + // register this client on the new addresses + CECDEVICEVEC devices; + m_busDevices->GetByLogicalAddresses(devices, configuration.logicalAddresses); + for (CECDEVICEVEC::const_iterator it = devices.begin(); it != devices.end(); it++) + { + // replace a previous client + CLockObject lock(m_mutex); + m_clients.erase((*it)->GetLogicalAddress()); + m_clients.insert(make_pair((*it)->GetLogicalAddress(), client)); + } - iNow = GetTimeMs(); + // get the settings from the rom + if (configuration.bGetSettingsFromROM == 1) + { + libcec_configuration config; + m_communication->GetConfiguration(config); + + CLockObject lock(m_mutex); + if (!config.deviceTypes.IsEmpty()) + configuration.deviceTypes = config.deviceTypes; + if (CLibCEC::IsValidPhysicalAddress(config.iPhysicalAddress)) + configuration.iPhysicalAddress = config.iPhysicalAddress; + snprintf(configuration.strDeviceName, 13, "%s", config.strDeviceName); } - return bTransmitSucceeded && !*bError; + // set the firmware version and build date + configuration.serverVersion = LIBCEC_VERSION_CURRENT; + configuration.iFirmwareVersion = m_communication->GetFirmwareVersion(); + configuration.iFirmwareBuildDate = m_communication->GetFirmwareBuildDate(); + + // mark the client as registered + client->SetRegistered(true); + + // set the new ack mask + bool bReturn = SetAckMask(GetLogicalAddresses().AckMask()) && + // and initialise the client + client->OnRegister(); + + // log the new registration + CStdString strLog; + strLog.Format("%s: %s", bReturn ? "CEC client registered" : "failed to register the CEC client", client->GetConnectionInfo().c_str()); + m_libcec->AddLog(bReturn ? CEC_LOG_NOTICE : CEC_LOG_ERROR, strLog); + + // display a warning if the firmware can be upgraded + if (bReturn && !IsRunningLatestFirmware()) + { + const char *strUpgradeMessage = "The firmware of this adapter can be upgraded. Please visit http://blog.pulse-eight.com/ for more information."; + m_libcec->AddLog(CEC_LOG_WARNING, strUpgradeMessage); + libcec_parameter param; + param.paramData = (void*)strUpgradeMessage; param.paramType = CEC_PARAMETER_TYPE_STRING; + client->Alert(CEC_ALERT_SERVICE_DEVICE, param); + } + + // ensure that the command handler for the TV is initialised + if (bReturn) + { + CCECCommandHandler *handler = GetTV()->GetHandler(); + if (handler) + handler->InitHandler(); + } + + return bReturn; } -bool CCECProcessor::ParseMessage(const CCECAdapterMessage &msg) +bool CCECProcessor::UnregisterClient(CCECClient *client) { - bool bEom = false; + if (!client) + return false; - if (msg.empty()) - return bEom; + if (client->IsRegistered()) + m_libcec->AddLog(CEC_LOG_NOTICE, "unregistering client: %s", client->GetConnectionInfo().c_str()); - m_controller->AddLog(msg.is_error() ? CEC_LOG_WARNING : CEC_LOG_DEBUG, msg.ToString()); + // notify the client that it will be unregistered + client->OnUnregister(); - switch(msg.message()) { - case MSGCODE_FRAME_START: - { - m_currentframe.clear(); - if (msg.size() >= 2) - { - m_currentframe.initiator = msg.initiator(); - m_currentframe.destination = msg.destination(); - m_currentframe.ack = msg.ack(); - m_currentframe.eom = msg.eom(); - } - } - break; - case MSGCODE_FRAME_DATA: + CLockObject lock(m_mutex); + // find all devices that match the LA's of this client + CECDEVICEVEC devices; + m_busDevices->GetByLogicalAddresses(devices, client->GetConfiguration()->logicalAddresses); + for (CECDEVICEVEC::const_iterator it = devices.begin(); it != devices.end(); it++) { - if (msg.size() >= 2) - { - m_currentframe.push_back(msg[1]); - m_currentframe.eom = msg.eom(); - } - bEom = msg.eom(); + // find the client + map::iterator entry = m_clients.find((*it)->GetLogicalAddress()); + // unregister the client + if (entry != m_clients.end()) + m_clients.erase(entry); + + // reset the device status + (*it)->ResetDeviceStatus(); } - break; - default: - break; } - return bEom; + // set the new ackmask + return SetAckMask(GetLogicalAddresses().AckMask()); } -void CCECProcessor::ParseCommand(cec_command &command) +void CCECProcessor::UnregisterClients(void) { - CStdString dataStr; - dataStr.Format(">> %1x%1x:%02x", command.initiator, command.destination, command.opcode); - for (uint8_t iPtr = 0; iPtr < command.parameters.size; iPtr++) - dataStr.AppendFormat(":%02x", (unsigned int)command.parameters[iPtr]); - m_controller->AddLog(CEC_LOG_TRAFFIC, dataStr.c_str()); + m_libcec->AddLog(CEC_LOG_NOTICE, "unregistering all CEC clients"); + + vector clients = m_libcec->GetClients(); + for (vector::iterator client = clients.begin(); client != clients.end(); client++) + UnregisterClient(*client); - if (!m_bMonitor) - m_busDevices[(uint8_t)command.initiator]->HandleCommand(command); + CLockObject lock(m_mutex); + m_clients.clear(); } -uint16_t CCECProcessor::GetPhysicalAddress(void) const +CCECClient *CCECProcessor::GetClient(const cec_logical_address address) { - if (m_iLogicalAddress != CECDEVICE_UNKNOWN && m_busDevices[m_iLogicalAddress]) - return m_busDevices[m_iLogicalAddress]->GetPhysicalAddress(); - return false; + CLockObject lock(m_mutex); + map::const_iterator client = m_clients.find(address); + if (client != m_clients.end()) + return client->second; + return NULL; } -void CCECProcessor::SetCurrentButton(cec_user_control_code iButtonCode) +CCECClient *CCECProcessor::GetPrimaryClient(void) { - m_controller->SetCurrentButton(iButtonCode); + CLockObject lock(m_mutex); + map::const_iterator client = m_clients.begin(); + if (client != m_clients.end()) + return client->second; + return NULL; +} + +CCECBusDevice *CCECProcessor::GetPrimaryDevice(void) +{ + return m_busDevices->At(GetLogicalAddress()); } -void CCECProcessor::AddCommand(const cec_command &command) +cec_logical_address CCECProcessor::GetLogicalAddress(void) { - m_controller->AddCommand(command); + cec_logical_addresses addresses = GetLogicalAddresses(); + return addresses.primary; +} + +cec_logical_addresses CCECProcessor::GetLogicalAddresses(void) +{ + CLockObject lock(m_mutex); + cec_logical_addresses addresses; + addresses.Clear(); + for (map::const_iterator client = m_clients.begin(); client != m_clients.end(); client++) + addresses.Set(client->first); + + return addresses; } -void CCECProcessor::AddKey(void) +bool CCECProcessor::IsHandledByLibCEC(const cec_logical_address address) const { - m_controller->AddKey(); + CCECBusDevice *device = GetDevice(address); + return device && device->IsHandledByLibCEC(); } -void CCECProcessor::AddLog(cec_log_level level, const CStdString &strMessage) +bool CCECProcessor::IsRunningLatestFirmware(void) { - m_controller->AddLog(level, strMessage); + return m_communication && m_communication->IsOpen() ? + m_communication->IsRunningLatestFirmware() : + true; }