X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Flib%2FCECProcessor.cpp;h=8fc71dc31a2502e88e457c576063fac780414abe;hb=42d28d15d07f893b491051970ade1bd56bb596eb;hp=1bcba1893e60b728db5329a0d55e06e222c54d78;hpb=20b8870a99c4e141387dbf538a02c5b3527d8dc7;p=deb_libcec.git diff --git a/src/lib/CECProcessor.cpp b/src/lib/CECProcessor.cpp index 1bcba18..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,7 +32,7 @@ #include "CECProcessor.h" -#include "AdapterCommunication.h" +#include "adapter/USBCECAdapterCommunication.h" #include "devices/CECBusDevice.h" #include "devices/CECAudioSystem.h" #include "devices/CECPlaybackDevice.h" @@ -41,679 +41,793 @@ #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_bStarted(false), - m_strDeviceName(strDeviceName), - m_communication(serComm), - m_controller(controller), - m_bMonitor(false) -{ - m_logicalAddresses.Clear(); - m_logicalAddresses.Set(iLogicalAddress); - m_types.clear(); - for (int iPtr = 0; iPtr <= 16; iPtr++) - m_busDevices[iPtr] = new CCECBusDevice(this, (cec_logical_address) iPtr, iPtr == iLogicalAddress ? iPhysicalAddress : 0); -} - -CCECProcessor::CCECProcessor(CLibCEC *controller, CAdapterCommunication *serComm, const char *strDeviceName, const cec_device_type_list &types) : - m_bStarted(false), - m_strDeviceName(strDeviceName), - m_types(types), - m_communication(serComm), - m_controller(controller), - m_bMonitor(false) -{ - m_logicalAddresses.Clear(); - for (int iPtr = 0; iPtr < 16; iPtr++) - { - switch(iPtr) - { - case CECDEVICE_AUDIOSYSTEM: - m_busDevices[iPtr] = new CCECAudioSystem(this, (cec_logical_address) iPtr, 0xFFFF); - break; - case CECDEVICE_PLAYBACKDEVICE1: - case CECDEVICE_PLAYBACKDEVICE2: - case CECDEVICE_PLAYBACKDEVICE3: - m_busDevices[iPtr] = new CCECPlaybackDevice(this, (cec_logical_address) iPtr, 0xFFFF); - break; - case CECDEVICE_RECORDINGDEVICE1: - case CECDEVICE_RECORDINGDEVICE2: - case CECDEVICE_RECORDINGDEVICE3: - m_busDevices[iPtr] = new CCECRecordingDevice(this, (cec_logical_address) iPtr, 0xFFFF); - break; - case CECDEVICE_TUNER1: - case CECDEVICE_TUNER2: - case CECDEVICE_TUNER3: - case CECDEVICE_TUNER4: - m_busDevices[iPtr] = new CCECTuner(this, (cec_logical_address) iPtr, 0xFFFF); - break; - case CECDEVICE_TV: - m_busDevices[iPtr] = new CCECTV(this, (cec_logical_address) iPtr, 0); - break; - default: - m_busDevices[iPtr] = new CCECBusDevice(this, (cec_logical_address) iPtr, 0xFFFF); - break; - } - } +#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) +{ + m_busDevices = new CCECDeviceMap(this); } CCECProcessor::~CCECProcessor(void) { - m_startCondition.Broadcast(); - StopThread(); - m_communication = NULL; - m_controller = NULL; - for (unsigned int iPtr = 0; iPtr < 16; iPtr++) - delete m_busDevices[iPtr]; + Close(); + DELETE_AND_NULL(m_busDevices); } -bool CCECProcessor::Start(void) +bool CCECProcessor::Start(const char *strPort, uint16_t iBaudRate /* = CEC_SERIAL_DEFAULT_BAUDRATE */, uint32_t iTimeoutMs /* = CEC_DEFAULT_CONNECT_TIMEOUT */) { - CLockObject lock(&m_mutex); - if (!m_communication || !m_communication->IsOpen()) - { - m_controller->AddLog(CEC_LOG_ERROR, "connection is closed"); + CLockObject lock(m_mutex); + // open a connection + if (!OpenConnection(strPort, iBaudRate, iTimeoutMs)) return false; - } - if (CreateThread()) + // create the processor thread + if (!IsRunning()) { - if (!m_startCondition.Wait(&m_mutex) || !m_bStarted) + if (!CreateThread()) { - m_controller->AddLog(CEC_LOG_ERROR, "could not create a processor thread"); + m_libcec->AddLog(CEC_LOG_ERROR, "could not create a processor thread"); return false; } - return true; } - else - m_controller->AddLog(CEC_LOG_ERROR, "could not create a processor thread"); - return false; + return true; } -bool CCECProcessor::TryLogicalAddress(cec_logical_address address, unsigned int iIndex) +void CCECProcessor::Close(void) { - const char *strLabel = CCECCommandHandler::ToString(address); - CStdString strLog; - strLog.Format("trying logical address '%s'", strLabel); - AddLog(CEC_LOG_DEBUG, strLog); + // mark as uninitialised + SetCECInitialised(false); - SetAckMask(0x1 << address); - if (!m_busDevices[address]->TransmitPoll(address)) - { - strLog.Format("using logical address '%s'", strLabel); - AddLog(CEC_LOG_NOTICE, strLog); + // stop the processor + StopThread(); - /* only set our OSD name and active source for the primary device */ - if (m_logicalAddresses.IsEmpty()) - { - m_busDevices[address]->m_strDeviceName = m_strDeviceName; - m_busDevices[address]->m_bActiveSource = true; - } - m_busDevices[address]->m_powerStatus = CEC_POWER_STATUS_STANDBY; - m_busDevices[address]->m_cecVersion = CEC_VERSION_1_3A; + // close the connection + DELETE_AND_NULL(m_communication); +} - m_logicalAddresses.Set(address); +void CCECProcessor::ResetMembers(void) +{ + // close the connection + DELETE_AND_NULL(m_communication); - // TODO - m_busDevices[address]->SetPhysicalAddress((uint16_t)CEC_DEFAULT_PHYSICAL_ADDRESS + ((uint16_t)iIndex * 0x100)); + // reset the other members to the initial state + m_iStandardLineTimeout = 3; + m_iRetryLineTimeout = 3; + m_iLastTransmission = 0; + m_busDevices->ResetDeviceStatus(); +} - return true; +bool CCECProcessor::OpenConnection(const char *strPort, uint16_t iBaudRate, uint32_t iTimeoutMs, bool bStartListening /* = true */) +{ + 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_libcec->AddLog(CEC_LOG_ERROR, "previous connection could not be closed"); + return bReturn; } - strLog.Format("logical address '%s' already taken", strLabel); - AddLog(CEC_LOG_DEBUG, strLog); - return false; + // 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_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::FindLogicalAddressRecordingDevice(unsigned int iIndex) +bool CCECProcessor::CECInitialised(void) { - AddLog(CEC_LOG_DEBUG, "detecting logical address for type 'recording device'"); - return TryLogicalAddress(CECDEVICE_RECORDINGDEVICE1, iIndex) || - TryLogicalAddress(CECDEVICE_RECORDINGDEVICE2, iIndex) || - TryLogicalAddress(CECDEVICE_RECORDINGDEVICE3, iIndex); + CLockObject lock(m_threadMutex); + return m_bInitialised; } -bool CCECProcessor::FindLogicalAddressTuner(unsigned int iIndex) +void CCECProcessor::SetCECInitialised(bool bSetTo /* = true */) { - AddLog(CEC_LOG_DEBUG, "detecting logical address for type 'tuner'"); - return TryLogicalAddress(CECDEVICE_TUNER1, iIndex) || - TryLogicalAddress(CECDEVICE_TUNER2, iIndex) || - TryLogicalAddress(CECDEVICE_TUNER3, iIndex) || - TryLogicalAddress(CECDEVICE_TUNER4, iIndex); + { + CLockObject lock(m_mutex); + m_bInitialised = bSetTo; + } + if (!bSetTo) + UnregisterClients(); } -bool CCECProcessor::FindLogicalAddressPlaybackDevice(unsigned int iIndex) +bool CCECProcessor::TryLogicalAddress(cec_logical_address address) { - AddLog(CEC_LOG_DEBUG, "detecting logical address for type 'playback device'"); - return TryLogicalAddress(CECDEVICE_PLAYBACKDEVICE1, iIndex) || - TryLogicalAddress(CECDEVICE_PLAYBACKDEVICE2, iIndex) || - TryLogicalAddress(CECDEVICE_PLAYBACKDEVICE3, iIndex); + // find the device + CCECBusDevice *device = m_busDevices->At(address); + if (device) + { + // check if it's already marked as present or used + if (device->IsPresent() || device->IsHandledByLibCEC()) + return false; + + // poll the LA if not + SetAckMask(0); + return device->TryLogicalAddress(); + } + + return false; } -bool CCECProcessor::FindLogicalAddressAudioSystem(unsigned int iIndex) +void CCECProcessor::ReplaceHandlers(void) { - AddLog(CEC_LOG_DEBUG, "detecting logical address for type 'audio'"); - return TryLogicalAddress(CECDEVICE_AUDIOSYSTEM, iIndex); + if (!CECInitialised()) + return; + + // check each device + for (CECDEVICEMAP::iterator it = m_busDevices->Begin(); it != m_busDevices->End(); it++) + it->second->ReplaceHandler(true); } -bool CCECProcessor::FindLogicalAddresses(void) +void CCECProcessor::CheckPendingActiveSource(void) { - bool bReturn(true); - m_logicalAddresses.Clear(); - CStdString strLog; + if (!CECInitialised()) + return; - for (unsigned int iPtr = 0; iPtr < 5; iPtr++) + // check each device + for (CECDEVICEMAP::iterator it = m_busDevices->Begin(); it != m_busDevices->End(); it++) { - if (m_types.types[iPtr] == CEC_DEVICE_TYPE_RESERVED) - continue; - - strLog.Format("%s - device %d: type %d", __FUNCTION__, iPtr, m_types.types[iPtr]); - AddLog(CEC_LOG_DEBUG, strLog); - - if (m_types.types[iPtr] == CEC_DEVICE_TYPE_RECORDING_DEVICE) - bReturn &= FindLogicalAddressRecordingDevice(iPtr); - if (m_types.types[iPtr] == CEC_DEVICE_TYPE_TUNER) - bReturn &= FindLogicalAddressTuner(iPtr); - if (m_types.types[iPtr] == CEC_DEVICE_TYPE_PLAYBACK_DEVICE) - bReturn &= FindLogicalAddressPlaybackDevice(iPtr); - if (m_types.types[iPtr] == CEC_DEVICE_TYPE_AUDIO_SYSTEM) - bReturn &= FindLogicalAddressAudioSystem(iPtr); + if (it->second->GetHandler()->ActiveSourcePending()) + it->second->ActivateSource(); } +} - return bReturn; +bool CCECProcessor::OnCommandReceived(const cec_command &command) +{ + return m_inBuffer.Push(command); } void *CCECProcessor::Process(void) { - bool bParseFrame(false); - cec_command command; - CCECAdapterMessage msg; + m_libcec->AddLog(CEC_LOG_DEBUG, "processor thread started"); - { - if (m_logicalAddresses.IsEmpty() && !FindLogicalAddresses()) - { - CLockObject lock(&m_mutex); - m_controller->AddLog(CEC_LOG_ERROR, "could not detect our logical addressed"); - m_startCondition.Signal(); - return NULL; - } + cec_command command; + CTimeout activeSourceCheck(ACTIVE_SOURCE_CHECK_TIMEOUT); - SetAckMask(m_logicalAddresses.AckMask()); + // as long as we're not being stopped and the connection is open + while (!IsStopped() && m_communication->IsOpen()) + { + // 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); - m_controller->AddLog(CEC_LOG_DEBUG, "processor thread started"); - m_bStarted = true; - m_startCondition.Signal(); - } - } + // check clients for keypress timeouts + m_libcec->CheckKeypressTimeout(); - while (!IsStopped()) - { - command.Clear(); - msg.clear(); + // check if we need to replace handlers + ReplaceHandlers(); - { - CLockObject lock(&m_mutex); - if (m_commandBuffer.Pop(command)) + // check whether we need to activate a source, if it failed before + if (activeSourceCheck.TimeLeft() == 0) { - bParseFrame = true; - } - else if (m_communication->IsOpen() && m_communication->Read(msg, 50)) - { - m_controller->AddLog(msg.is_error() ? CEC_LOG_WARNING : CEC_LOG_DEBUG, msg.ToString()); - if ((bParseFrame = (ParseMessage(msg) && !IsStopped())) == true) - command = m_currentframe; + CheckPendingActiveSource(); + activeSourceCheck.Init(ACTIVE_SOURCE_CHECK_TIMEOUT); } } - - if (bParseFrame) - ParseCommand(command); - bParseFrame = false; - - Sleep(5); - - m_controller->CheckKeypressTimeout(); - - for (unsigned int iDevicePtr = 0; iDevicePtr < 16; iDevicePtr++) - m_busDevices[iDevicePtr]->PollVendorId(); - - Sleep(5); } return NULL; } -bool CCECProcessor::SetActiveSource(cec_device_type type /* = CEC_DEVICE_TYPE_RESERVED */) +bool CCECProcessor::ActivateSource(uint16_t iStreamPath) { bool bReturn(false); - if (!IsRunning()) - return bReturn; + // 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); + + return bReturn; +} - cec_logical_address addr = m_logicalAddresses.primary; +void CCECProcessor::SetStandardLineTimeout(uint8_t iTimeout) +{ + CLockObject lock(m_mutex); + m_iStandardLineTimeout = iTimeout; +} - if (type != CEC_DEVICE_TYPE_RESERVED) - { - for (uint8_t iPtr = 0; iPtr < 16; iPtr++) - { - if (m_logicalAddresses[iPtr] && m_busDevices[iPtr]->m_type == type) - { - addr = (cec_logical_address) iPtr; - break; - } - } - } +uint8_t CCECProcessor::GetStandardLineTimeout(void) +{ + CLockObject lock(m_mutex); + return m_iStandardLineTimeout; +} - return SetStreamPath(m_busDevices[addr]->GetPhysicalAddress()); +void CCECProcessor::SetRetryLineTimeout(uint8_t iTimeout) +{ + CLockObject lock(m_mutex); + m_iRetryLineTimeout = iTimeout; } -bool CCECProcessor::SetActiveView(void) +uint8_t CCECProcessor::GetRetryLineTimeout(void) { - return SetActiveSource(); + CLockObject lock(m_mutex); + return m_iRetryLineTimeout; } -bool CCECProcessor::SetDeckControlMode(cec_deck_control_mode mode, bool bSendUpdate /* = true */) +bool CCECProcessor::PhysicalAddressInUse(uint16_t iPhysicalAddress) { - bool bReturn(false); + CCECBusDevice *device = GetDeviceByPhysicalAddress(iPhysicalAddress); + return device != NULL; +} - CCECBusDevice *device = GetDeviceByType(CEC_DEVICE_TYPE_PLAYBACK_DEVICE); - if (device) - { - ((CCECPlaybackDevice *) device)->SetDeckControlMode(mode); - if (bSendUpdate) - ((CCECPlaybackDevice *) device)->TransmitDeckStatus(CECDEVICE_TV); - bReturn = true; - } +void CCECProcessor::LogOutput(const cec_command &data) +{ + CStdString strTx; - return bReturn; + // 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]); + + // and log it + m_libcec->AddLog(CEC_LOG_TRAFFIC, strTx.c_str()); } -bool CCECProcessor::SetDeckInfo(cec_deck_info info, bool bSendUpdate /* = true */) +bool CCECProcessor::PollDevice(cec_logical_address iAddress) { - bool bReturn(false); + // try to find the primary device + CCECBusDevice *primary = GetPrimaryDevice(); + // poll the destination, with the primary as source + if (primary) + return primary->TransmitPoll(iAddress); - CCECBusDevice *device = GetDeviceByType(CEC_DEVICE_TYPE_PLAYBACK_DEVICE); + // try to find the destination + CCECBusDevice *device = m_busDevices->At(iAddress); + // and poll the destination, with the same LA as source if (device) - { - ((CCECPlaybackDevice *) device)->SetDeckStatus(info); - if (bSendUpdate) - ((CCECPlaybackDevice *) device)->TransmitDeckStatus(CECDEVICE_TV); - bReturn = true; - } + return device->TransmitPoll(iAddress); - return bReturn; + return false; } -bool CCECProcessor::SetStreamPath(uint16_t iStreamPath) +CCECBusDevice *CCECProcessor::GetDeviceByPhysicalAddress(uint16_t iPhysicalAddress, bool bSuppressUpdate /* = true */) { - bool bReturn(false); + return m_busDevices ? + m_busDevices->GetDeviceByPhysicalAddress(iPhysicalAddress, bSuppressUpdate) : + NULL; +} - CCECBusDevice *device = GetDeviceByPhysicalAddress(iStreamPath); - if (device) - { - for (unsigned int iPtr = 0; iPtr < 16; iPtr++) - m_busDevices[iPtr]->m_bActiveSource = false; +CCECBusDevice *CCECProcessor::GetDevice(cec_logical_address address) const +{ + return m_busDevices ? + m_busDevices->At(address) : + NULL; +} - device->m_bActiveSource = true; - device->m_powerStatus = CEC_POWER_STATUS_ON; +cec_logical_address CCECProcessor::GetActiveSource(bool bRequestActiveSource /* = true */) +{ + // get the device that is marked as active source from the device map + CCECBusDevice *activeSource = m_busDevices->GetActiveSource(); + if (activeSource) + return activeSource->GetLogicalAddress(); - bReturn = true; + if (bRequestActiveSource) + { + // request the active source from the bus + CCECBusDevice *primary = GetPrimaryDevice(); + if (primary) + { + primary->RequestActiveSource(); + return GetActiveSource(false); + } } - return bReturn; + // unknown or none + return CECDEVICE_UNKNOWN; } -bool CCECProcessor::SetInactiveView(void) +bool CCECProcessor::IsActiveSource(cec_logical_address iAddress) { - if (!IsRunning()) + CCECBusDevice *device = m_busDevices->At(iAddress); + return device && device->IsActiveSource(); +} + +bool CCECProcessor::Transmit(const cec_command &data) +{ + 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_libcec->AddLog(CEC_LOG_WARNING, "invalid initiator"); return false; + } - if (!m_logicalAddresses.IsEmpty() && m_busDevices[m_logicalAddresses.primary]) - return m_busDevices[m_logicalAddresses.primary]->TransmitInactiveView(); - 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; } -void CCECProcessor::LogOutput(const cec_command &data) +void CCECProcessor::TransmitAbort(cec_logical_address source, cec_logical_address destination, cec_opcode opcode, cec_abort_reason reason /* = CEC_ABORT_REASON_UNRECOGNIZED_OPCODE */) { - CStdString strTx; - strTx.Format("<< %02x", ((uint8_t)data.initiator << 4) + (uint8_t)data.destination); - if (data.opcode_set) - strTx.AppendFormat(":%02x", (uint8_t)data.opcode); + m_libcec->AddLog(CEC_LOG_DEBUG, "<< transmitting abort message"); - 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()); + 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); } -bool CCECProcessor::SetLogicalAddress(cec_logical_address iLogicalAddress) +void CCECProcessor::ProcessCommand(const cec_command &command) { - if (m_logicalAddresses.primary != iLogicalAddress) - { - CStdString strLog; - strLog.Format("<< setting primary logical address to %1x", iLogicalAddress); - m_controller->AddLog(CEC_LOG_NOTICE, strLog.c_str()); - m_logicalAddresses.primary = iLogicalAddress; - m_logicalAddresses.Set(iLogicalAddress); - return SetAckMask(m_logicalAddresses.AckMask()); - } + // 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()); - return true; + // find the initiator + CCECBusDevice *device = m_busDevices->At(command.initiator); + + if (device) + device->HandleCommand(command); } -bool CCECProcessor::SetMenuState(cec_menu_state state, bool bSendUpdate /* = true */) +bool CCECProcessor::IsPresentDevice(cec_logical_address address) { - for (uint8_t iPtr = 0; iPtr < 16; iPtr++) - { - if (m_logicalAddresses[iPtr]) - m_busDevices[iPtr]->SetMenuState(state); - } + CCECBusDevice *device = m_busDevices->At(address); + return device && device->GetStatus() == CEC_DEVICE_STATUS_PRESENT; +} - if (bSendUpdate) - m_busDevices[m_logicalAddresses.primary]->TransmitMenuState(CECDEVICE_TV); +bool CCECProcessor::IsPresentDeviceType(cec_device_type type) +{ + CECDEVICEVEC devices; + m_busDevices->GetByType(type, devices); + CCECDeviceMap::FilterActive(devices); + return !devices.empty(); +} - return true; +uint16_t CCECProcessor::GetDetectedPhysicalAddress(void) const +{ + return m_communication ? m_communication->GetPhysicalAddress() : CEC_INVALID_PHYSICAL_ADDRESS; } -bool CCECProcessor::SetPhysicalAddress(uint16_t iPhysicalAddress) +bool CCECProcessor::SetAckMask(uint16_t iMask) { - if (!m_logicalAddresses.IsEmpty() && m_busDevices[m_logicalAddresses.primary]) - { - m_busDevices[m_logicalAddresses.primary]->SetPhysicalAddress(iPhysicalAddress); - return SetActiveView(); - } - return false; + return m_communication ? m_communication->SetAckMask(iMask) : false; } -bool CCECProcessor::SwitchMonitoring(bool bEnable) +bool CCECProcessor::StandbyDevices(const cec_logical_address initiator, const CECDEVICEVEC &devices) { - CStdString strLog; - strLog.Format("== %s monitoring mode ==", bEnable ? "enabling" : "disabling"); - m_controller->AddLog(CEC_LOG_NOTICE, strLog.c_str()); + bool bReturn(true); + for (CECDEVICEVEC::const_iterator it = devices.begin(); it != devices.end(); it++) + bReturn &= (*it)->Standby(initiator); + return bReturn; +} - m_bMonitor = bEnable; - if (bEnable) - return SetAckMask(0); - else - return SetAckMask(m_logicalAddresses.AckMask()); +bool CCECProcessor::StandbyDevice(const cec_logical_address initiator, cec_logical_address address) +{ + CCECBusDevice *device = m_busDevices->At(address); + return device ? device->Standby(initiator) : false; } -bool CCECProcessor::PollDevice(cec_logical_address iAddress) +bool CCECProcessor::PowerOnDevices(const cec_logical_address initiator, const CECDEVICEVEC &devices) { - if (iAddress != CECDEVICE_UNKNOWN && m_busDevices[iAddress]) - return m_busDevices[m_logicalAddresses.primary]->TransmitPoll(iAddress); - return false; + bool bReturn(true); + for (CECDEVICEVEC::const_iterator it = devices.begin(); it != devices.end(); it++) + bReturn &= (*it)->PowerOn(initiator); + return bReturn; } -CCECBusDevice *CCECProcessor::GetDeviceByPhysicalAddress(uint16_t iPhysicalAddress) const +bool CCECProcessor::PowerOnDevice(const cec_logical_address initiator, cec_logical_address address) { - CCECBusDevice *device = NULL; + CCECBusDevice *device = m_busDevices->At(address); + return device ? device->PowerOn(initiator) : false; +} - for (unsigned int iPtr = 0; iPtr < 16; iPtr++) +bool CCECProcessor::StartBootloader(const char *strPort /* = NULL */) +{ + bool bReturn(false); + // open a connection if no connection has been opened + if (!m_communication && strPort) { - if (m_busDevices[iPtr]->GetPhysicalAddress() == iPhysicalAddress) + 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) { - device = m_busDevices[iPtr]; - break; + m_libcec->AddLog(CEC_LOG_ERROR, "could not open a connection (try %d)", ++iConnectTry); + comm->Close(); + Sleep(CEC_DEFAULT_TRANSMIT_RETRY_WAIT); } + if (comm->IsOpen()) + { + bReturn = comm->StartBootloader(); + DELETE_AND_NULL(comm); + } + return bReturn; + } + else + { + m_communication->StartBootloader(); + Close(); + bReturn = true; } - return device; + return bReturn; } -CCECBusDevice *CCECProcessor::GetDeviceByType(cec_device_type type) const +bool CCECProcessor::PingAdapter(void) { - CCECBusDevice *device = NULL; + return m_communication->PingAdapter(); +} - for (unsigned int iPtr = 0; iPtr < 16; iPtr++) - { - if (m_busDevices[iPtr]->m_type == type) - { - device = m_busDevices[iPtr]; - break; - } - } +void CCECProcessor::HandlePoll(cec_logical_address initiator, cec_logical_address destination) +{ + CCECBusDevice *device = m_busDevices->At(destination); + if (device) + device->HandlePollFrom(initiator); +} - return device; +bool CCECProcessor::HandleReceiveFailed(cec_logical_address initiator) +{ + CCECBusDevice *device = m_busDevices->At(initiator); + return !device || !device->HandleReceiveFailed(); } -cec_version CCECProcessor::GetDeviceCecVersion(cec_logical_address iAddress) +bool CCECProcessor::SetStreamPath(uint16_t iPhysicalAddress) { - return m_busDevices[iAddress]->GetCecVersion(); + // stream path changes are sent by the TV + return GetTV()->GetHandler()->TransmitSetStreamPath(iPhysicalAddress); } -bool CCECProcessor::GetDeviceMenuLanguage(cec_logical_address iAddress, cec_menu_language *language) +bool CCECProcessor::CanPersistConfiguration(void) { - if (m_busDevices[iAddress]) - { - *language = m_busDevices[iAddress]->GetMenuLanguage(); - return (strcmp(language->language, "???") != 0); - } - return false; + return m_communication ? m_communication->GetFirmwareVersion() >= 2 : false; } -uint64_t CCECProcessor::GetDeviceVendorId(cec_logical_address iAddress) +bool CCECProcessor::PersistConfiguration(const libcec_configuration &configuration) { - if (m_busDevices[iAddress]) - return m_busDevices[iAddress]->GetVendorId(); - return false; + return m_communication ? m_communication->PersistConfiguration(configuration) : false; } -cec_power_status CCECProcessor::GetDevicePowerStatus(cec_logical_address iAddress) +void CCECProcessor::RescanActiveDevices(void) { - if (m_busDevices[iAddress]) - return m_busDevices[iAddress]->GetPowerStatus(); - return CEC_POWER_STATUS_UNKNOWN; + for (CECDEVICEMAP::iterator it = m_busDevices->Begin(); it != m_busDevices->End(); it++) + it->second->GetStatus(true); } -bool CCECProcessor::Transmit(const cec_command &data) +bool CCECProcessor::GetDeviceInformation(const char *strPort, libcec_configuration *config, uint32_t iTimeoutMs /* = CEC_DEFAULT_CONNECT_TIMEOUT */) { - bool bReturn(false); - LogOutput(data); + if (!OpenConnection(strPort, CEC_SERIAL_DEFAULT_BAUDRATE, iTimeoutMs, false)) + return false; - CCECAdapterMessage *output = new CCECAdapterMessage(data); - bReturn = Transmit(output); - delete output; + config->iFirmwareVersion = m_communication->GetFirmwareVersion(); + config->iPhysicalAddress = m_communication->GetPhysicalAddress(); + config->iFirmwareBuildDate = m_communication->GetFirmwareBuildDate(); - return bReturn; + return true; } -bool CCECProcessor::Transmit(CCECAdapterMessage *output) +bool CCECProcessor::TransmitPendingActiveSourceCommands(void) { - bool bReturn(false); - CLockObject lock(&m_mutex); - { - CLockObject msgLock(&output->mutex); - if (!m_communication || !m_communication->Write(output)) - return bReturn; - else - { - output->condition.Wait(&output->mutex); - if (output->state != ADAPTER_MESSAGE_STATE_SENT) - { - m_controller->AddLog(CEC_LOG_ERROR, "command was not sent"); - return bReturn; - } - } + bool bReturn(true); + for (CECDEVICEMAP::iterator it = m_busDevices->Begin(); it != m_busDevices->End(); it++) + bReturn &= it->second->TransmitPendingActiveSourceCommands(); + return bReturn; +} - if (output->transmit_timeout > 0) - { - if ((bReturn = WaitForTransmitSucceeded(output->size(), output->transmit_timeout)) == false) - m_controller->AddLog(CEC_LOG_DEBUG, "did not receive ack"); - } - else - bReturn = true; - } +CCECTV *CCECProcessor::GetTV(void) const +{ + return CCECBusDevice::AsTV(m_busDevices->At(CECDEVICE_TV)); +} - return bReturn; +CCECAudioSystem *CCECProcessor::GetAudioSystem(void) const +{ + return CCECBusDevice::AsAudioSystem(m_busDevices->At(CECDEVICE_AUDIOSYSTEM)); } -void CCECProcessor::TransmitAbort(cec_logical_address address, cec_opcode opcode, cec_abort_reason reason /* = CEC_ABORT_REASON_UNRECOGNIZED_OPCODE */) +CCECPlaybackDevice *CCECProcessor::GetPlaybackDevice(cec_logical_address address) const { - m_controller->AddLog(CEC_LOG_DEBUG, "<< transmitting abort message"); + return CCECBusDevice::AsPlaybackDevice(m_busDevices->At(address)); +} - cec_command command; - // TODO - cec_command::Format(command, m_logicalAddresses.primary, address, CEC_OPCODE_FEATURE_ABORT); - command.parameters.PushBack((uint8_t)opcode); - command.parameters.PushBack((uint8_t)reason); +CCECRecordingDevice *CCECProcessor::GetRecordingDevice(cec_logical_address address) const +{ + return CCECBusDevice::AsRecordingDevice(m_busDevices->At(address)); +} - Transmit(command); +CCECTuner *CCECProcessor::GetTuner(cec_logical_address address) const +{ + return CCECBusDevice::AsTuner(m_busDevices->At(address)); } -bool CCECProcessor::WaitForTransmitSucceeded(uint8_t iLength, uint32_t iTimeout /* = 1000 */) +bool CCECProcessor::RegisterClient(CCECClient *client) { - bool bError(false); - bool bTransmitSucceeded(false); - uint8_t iPacketsLeft(iLength / 4); + if (!client) + return false; - int64_t iNow = GetTimeMs(); - int64_t iTargetTime = iNow + (uint64_t) iTimeout; + libcec_configuration &configuration = *client->GetConfiguration(); - while (!bTransmitSucceeded && !bError && (iTimeout == 0 || iNow < iTargetTime)) + 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); - if ((bError = msg.is_error()) == false) - { - m_controller->AddLog(bError ? 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: - if (iPacketsLeft > 0) - iPacketsLeft--; - break; - case MSGCODE_TRANSMIT_SUCCEEDED: - bTransmitSucceeded = (iPacketsLeft == 0); - bError = !bTransmitSucceeded; - break; - default: - if (ParseMessage(msg)) - m_commandBuffer.Push(m_currentframe); - } + // get the configuration from the client + m_libcec->AddLog(CEC_LOG_NOTICE, "registering new CEC client - v%s", ToString((cec_client_version)configuration.clientVersion)); - iNow = GetTimeMs(); - } + // 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)); + } + + // 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); + } + + // 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); } - return bTransmitSucceeded && !bError; + // 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 (client->IsRegistered()) + m_libcec->AddLog(CEC_LOG_NOTICE, "unregistering client: %s", client->GetConnectionInfo().c_str()); - if (msg.empty()) - return bEom; + // 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.PushBack(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"); - if (!m_bMonitor && command.initiator >= CECDEVICE_TV && command.initiator <= CECDEVICE_BROADCAST) - m_busDevices[(uint8_t)command.initiator]->HandleCommand(command); + vector clients = m_libcec->GetClients(); + for (vector::iterator client = clients.begin(); client != clients.end(); client++) + UnregisterClient(*client); + + CLockObject lock(m_mutex); + m_clients.clear(); } -uint16_t CCECProcessor::GetPhysicalAddress(void) const +CCECClient *CCECProcessor::GetClient(const cec_logical_address address) { - if (!m_logicalAddresses.IsEmpty() && m_busDevices[m_logicalAddresses.primary]) - return m_busDevices[m_logicalAddresses.primary]->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; } -void CCECProcessor::AddCommand(const cec_command &command) +CCECBusDevice *CCECProcessor::GetPrimaryDevice(void) { - m_controller->AddCommand(command); + return m_busDevices->At(GetLogicalAddress()); } -void CCECProcessor::AddKey(cec_keypress &key) +cec_logical_address CCECProcessor::GetLogicalAddress(void) { - m_controller->AddKey(key); + cec_logical_addresses addresses = GetLogicalAddresses(); + return addresses.primary; } -void CCECProcessor::AddKey(void) +cec_logical_addresses CCECProcessor::GetLogicalAddresses(void) { - m_controller->AddKey(); + 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::AddLog(cec_log_level level, const CStdString &strMessage) +bool CCECProcessor::IsHandledByLibCEC(const cec_logical_address address) const { - m_controller->AddLog(level, strMessage); + CCECBusDevice *device = GetDevice(address); + return device && device->IsHandledByLibCEC(); } -bool CCECProcessor::SetAckMask(uint16_t iMask) +bool CCECProcessor::IsRunningLatestFirmware(void) { - bool bReturn(false); - CStdString strLog; - strLog.Format("setting ackmask to %2x", iMask); - m_controller->AddLog(CEC_LOG_DEBUG, strLog.c_str()); - - CCECAdapterMessage *output = new CCECAdapterMessage; - - output->push_back(MSGSTART); - output->push_escaped(MSGCODE_SET_ACK_MASK); - output->push_escaped(iMask >> 8); - output->push_escaped((uint8_t)iMask); - output->push_back(MSGEND); - - if ((bReturn = Transmit(output)) == false) - m_controller->AddLog(CEC_LOG_ERROR, "could not set the ackmask"); - - delete output; - - return bReturn; + return m_communication && m_communication->IsOpen() ? + m_communication->IsRunningLatestFirmware() : + true; }