cec: cleanups, documentation and some fixes for the last commits
[deb_libcec.git] / src / lib / CECProcessor.cpp
index 258e16419f9b79dd3b7cb3e413e651085329748c..0714d2a659b7f31c025d3ff15e6730465fdb10fb 100644 (file)
@@ -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.
 
 #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 "platform/util/timeutils.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 */, int iPhysicalAddress /* = CEC_DEFAULT_PHYSICAL_ADDRESS*/) :
-    m_physicaladdress(iPhysicalAddress),
-    m_iLogicalAddress(iLogicalAddress),
-    m_strDeviceName(strDeviceName),
-    m_communication(serComm),
-    m_controller(controller)
+#define CEC_PROCESSOR_SIGNAL_WAIT_TIME 1000
+
+#define ToString(x) m_libcec->ToString(x)
+
+CCECProcessor::CCECProcessor(CLibCEC *libcec) :
+    m_bInitialised(false),
+    m_communication(NULL),
+    m_libcec(libcec),
+    m_bMonitor(false),
+    m_iPreviousAckMask(0),
+    m_iStandardLineTimeout(3),
+    m_iRetryLineTimeout(3),
+    m_iLastTransmission(0)
 {
+  m_busDevices = new CCECDeviceMap(this);
 }
 
 CCECProcessor::~CCECProcessor(void)
 {
-  StopThread();
-  m_communication = NULL;
-  m_controller = NULL;
+  Close();
+  delete 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 */)
 {
-  if (!m_communication || !m_communication->IsOpen())
+  CLockObject lock(m_mutex);
+  // open a connection
+  if (!OpenConnection(strPort, iBaudRate, iTimeoutMs))
     return false;
 
-  if (!SetLogicalAddress(m_iLogicalAddress))
+  // create the processor thread
+  if (!IsRunning())
   {
-    m_controller->AddLog(CEC_LOG_ERROR, "could not set the logical address");
-    return false;
+    if (CreateThread())
+      m_libcec->AddLog(CEC_LOG_DEBUG, "processor thread started");
+    else
+    {
+      m_libcec->AddLog(CEC_LOG_ERROR, "could not create a processor thread");
+      return false;
+    }
   }
 
-  if (CreateThread())
-    return true;
-  else
-    m_controller->AddLog(CEC_LOG_ERROR, "could not create a processor thread");
+  // mark as initialised
+  SetCECInitialised(true);
 
-  return false;
+  return true;
 }
 
-void *CCECProcessor::Process(void)
+void CCECProcessor::Close(void)
 {
-  m_controller->AddLog(CEC_LOG_DEBUG, "processor thread started");
+  // mark as uninitialised
+  SetCECInitialised(false);
 
-  while (!m_bStop)
-  {
-    bool bParseFrame(false);
-    {
-      CLockObject lock(&m_mutex);
-      cec_frame msg;
-      if (!m_bStop && m_communication->IsOpen() && m_communication->Read(msg, CEC_BUTTON_TIMEOUT))
-        bParseFrame = ParseMessage(msg);
-    }
+  // stop the processor
+  StopThread();
 
-    if (!m_bStop && bParseFrame)
-      ParseCurrentFrame();
+  // close the connection
+  if (m_communication)
+  {
+    delete m_communication;
+    m_communication = NULL;
+  }
+}
 
-    if (!m_bStop)
-    {
-      m_controller->CheckKeypressTimeout();
-      CCondition::Sleep(50);
-    }
+void CCECProcessor::ResetMembers(void)
+{
+  // close the connection
+  if (m_communication)
+  {
+    delete m_communication;
+    m_communication = NULL;
   }
 
-  return NULL;
+  // reset the other members to the initial state
+  m_bMonitor = false;
+  m_iPreviousAckMask = 0;
+  m_iStandardLineTimeout = 3;
+  m_iRetryLineTimeout = 3;
+  m_iLastTransmission = 0;
+  m_busDevices->ResetDeviceStatus();
 }
 
-bool CCECProcessor::PowerOnDevices(cec_logical_address address /* = CECDEVICE_TV */)
+bool CCECProcessor::OpenConnection(const char *strPort, uint16_t iBaudRate, uint32_t iTimeoutMs, bool bStartListening /* = true */)
 {
-  if (!IsRunning())
-    return false;
+  bool bReturn(false);
+  CTimeout timeout(iTimeoutMs > 0 ? iTimeoutMs : CEC_DEFAULT_TRANSMIT_WAIT);
 
-  CStdString strLog;
-  strLog.Format("powering on devices with logical address %d", (int8_t)address);
-  m_controller->AddLog(CEC_LOG_DEBUG, strLog.c_str());
-  cec_frame frame;
-  frame.push_back(GetSourceDestination(address));
-  frame.push_back((uint8_t) CEC_OPCODE_TEXT_VIEW_ON);
-  return Transmit(frame);
+  // 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;
+  }
+
+  // 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");
+
+  return bReturn;
 }
 
-bool CCECProcessor::StandbyDevices(cec_logical_address address /* = CECDEVICE_BROADCAST */)
+bool CCECProcessor::CECInitialised(void)
 {
-  if (!IsRunning())
-    return false;
+  CLockObject lock(m_threadMutex);
+  return m_bInitialised;
+}
 
-  CStdString strLog;
-  strLog.Format("putting all devices with logical address %d in standby mode", (int8_t)address);
-  m_controller->AddLog(CEC_LOG_DEBUG, strLog.c_str());
-  cec_frame frame;
-  frame.push_back(GetSourceDestination(address));
-  frame.push_back((uint8_t) CEC_OPCODE_STANDBY);
-  return Transmit(frame);
+void CCECProcessor::SetCECInitialised(bool bSetTo /* = true */)
+{
+  {
+    CLockObject lock(m_mutex);
+    m_bInitialised = bSetTo;
+  }
+  if (!bSetTo)
+    UnregisterClients();
 }
 
-bool CCECProcessor::SetActiveView(void)
+bool CCECProcessor::TryLogicalAddress(cec_logical_address address)
 {
-  if (!IsRunning())
-    return false;
+  // 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;
 
-  m_controller->AddLog(CEC_LOG_DEBUG, "setting active view");
-  cec_frame frame;
-  frame.push_back(GetSourceDestination(CECDEVICE_BROADCAST));
-  frame.push_back((uint8_t) CEC_OPCODE_ACTIVE_SOURCE);
-  frame.push_back((m_physicaladdress >> 8) & 0xFF);
-  frame.push_back(m_physicaladdress & 0xFF);
-  return Transmit(frame);
+    // poll the LA if not
+    SetAckMask(0);
+    return device->TryLogicalAddress();
+  }
+
+  return false;
 }
 
-bool CCECProcessor::SetInactiveView(void)
+void CCECProcessor::ReplaceHandlers(void)
 {
-  if (!IsRunning())
-    return false;
+  if (!CECInitialised())
+    return;
+
+  // check each device
+  for (CECDEVICEMAP::iterator it = m_busDevices->Begin(); it != m_busDevices->End(); it++)
+    it->second->ReplaceHandler(true);
+}
 
-  m_controller->AddLog(CEC_LOG_DEBUG, "setting inactive view");
-  cec_frame frame;
-  frame.push_back(GetSourceDestination(CECDEVICE_BROADCAST));
-  frame.push_back((uint8_t) CEC_OPCODE_INACTIVE_SOURCE);
-  frame.push_back((m_physicaladdress >> 8) & 0xFF);
-  frame.push_back(m_physicaladdress & 0xFF);
-  return Transmit(frame);
+bool CCECProcessor::OnCommandReceived(const cec_command &command)
+{
+  return m_inBuffer.Push(command);
 }
 
-bool CCECProcessor::Transmit(const cec_frame &data, bool bWaitForAck /* = true */)
+void *CCECProcessor::Process(void)
 {
-  CStdString txStr = "transmit ";
-  for (unsigned int i = 0; i < data.size(); i++)
-    txStr.AppendFormat(" %02x", data[i]);
-  m_controller->AddLog(CEC_LOG_DEBUG, txStr.c_str());
+  m_libcec->AddLog(CEC_LOG_DEBUG, "processor thread started");
+
+  cec_command command;
 
-  if (data.empty())
+  // as long as we're not being stopped and the connection is open
+  while (!IsStopped() && m_communication->IsOpen())
   {
-    m_controller->AddLog(CEC_LOG_WARNING, "transmit buffer is empty");
-    return false;
+    // wait for a new incoming command, and process it
+    if (m_inBuffer.Pop(command, CEC_PROCESSOR_SIGNAL_WAIT_TIME))
+      ProcessCommand(command);
+
+    if (CECInitialised())
+    {
+      // check clients for keypress timeouts
+      m_libcec->CheckKeypressTimeout();
+
+      // check if we need to replace handlers
+      ReplaceHandlers();
+    }
   }
 
-  cec_frame output;
+  return NULL;
+}
 
-  //set ack polarity to high when transmitting to the broadcast address
-  //set ack polarity low when transmitting to any other address
-  output.push_back(MSGSTART);
-  CAdapterCommunication::PushEscaped(output, MSGCODE_TRANSMIT_ACK_POLARITY);
+bool CCECProcessor::ActivateSource(uint16_t iStreamPath)
+{
+  bool bReturn(false);
 
-  if ((data[0] & 0xF) == 0xF)
-    CAdapterCommunication::PushEscaped(output, CEC_TRUE);
+  // 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
-    CAdapterCommunication::PushEscaped(output, CEC_FALSE);
+    m_libcec->AddLog(CEC_LOG_DEBUG, "device with PA '%04x' not found", iStreamPath);
 
-  output.push_back(MSGEND);
+  return bReturn;
+}
 
-  for (unsigned int i = 0; i < data.size(); i++)
-  {
-    output.push_back(MSGSTART);
+void CCECProcessor::SetStandardLineTimeout(uint8_t iTimeout)
+{
+  CLockObject lock(m_mutex);
+  m_iStandardLineTimeout = iTimeout;
+}
 
-    if (i == data.size() - 1)
-      CAdapterCommunication::PushEscaped(output, MSGCODE_TRANSMIT_EOM);
-    else
-      CAdapterCommunication::PushEscaped(output, MSGCODE_TRANSMIT);
+uint8_t CCECProcessor::GetStandardLineTimeout(void)
+{
+  CLockObject lock(m_mutex);
+  return m_iStandardLineTimeout;
+}
 
-    CAdapterCommunication::PushEscaped(output, data[i]);
+void CCECProcessor::SetRetryLineTimeout(uint8_t iTimeout)
+{
+  CLockObject lock(m_mutex);
+  m_iRetryLineTimeout = iTimeout;
+}
 
-    output.push_back(MSGEND);
-  }
+uint8_t CCECProcessor::GetRetryLineTimeout(void)
+{
+  CLockObject lock(m_mutex);
+  return m_iRetryLineTimeout;
+}
 
-  return TransmitFormatted(output, bWaitForAck);
+bool CCECProcessor::PhysicalAddressInUse(uint16_t iPhysicalAddress)
+{
+  CCECBusDevice *device = GetDeviceByPhysicalAddress(iPhysicalAddress);
+  return device != NULL;
 }
 
-bool CCECProcessor::SetLogicalAddress(cec_logical_address iLogicalAddress)
+void CCECProcessor::LogOutput(const cec_command &data)
 {
-  CStdString strLog;
-  strLog.Format("setting logical address to %d", iLogicalAddress);
-  m_controller->AddLog(CEC_LOG_NOTICE, strLog.c_str());
+  CStdString strTx;
+
+  // 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);
 
-  m_iLogicalAddress = iLogicalAddress;
-  return m_communication && m_communication->SetAckMask(0x1 << (uint8_t)m_iLogicalAddress);
+  // 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::TransmitFormatted(const cec_frame &data, bool bWaitForAck /* = true */)
+bool CCECProcessor::SwitchMonitoring(bool bEnable)
 {
-  CLockObject lock(&m_mutex);
-  if (!m_communication || !m_communication->Write(data))
-    return false;
+  m_libcec->AddLog(CEC_LOG_NOTICE, "== %s monitoring mode ==", bEnable ? "enabling" : "disabling");
 
-  if (bWaitForAck && !WaitForAck())
   {
-    m_controller->AddLog(CEC_LOG_DEBUG, "did not receive ACK");
-    return false;
+    CLockObject lock(m_mutex);
+    // switch to monitoring mode, which will stop processing of incoming messages
+    m_bMonitor = bEnable;
+    // and store the current ackmask
+    m_iPreviousAckMask = m_communication->GetAckMask();
   }
 
-  return true;
+  // set the mask to 0 when enabling monitor mode
+  if (bEnable)
+    return SetAckMask(0);
+  // and restore the previous mask otherwise
+  else
+    return SetAckMask(m_iPreviousAckMask);
 }
 
-void CCECProcessor::TransmitAbort(cec_logical_address address, cec_opcode opcode, ECecAbortReason reason /* = CEC_ABORT_REASON_UNRECOGNIZED_OPCODE */)
+bool CCECProcessor::PollDevice(cec_logical_address iAddress)
 {
-  m_controller->AddLog(CEC_LOG_DEBUG, "transmitting abort message");
-  cec_frame frame;
-  frame.push_back(GetSourceDestination(address));
-  frame.push_back((uint8_t) CEC_OPCODE_FEATURE_ABORT);
-  frame.push_back((uint8_t) opcode);
-  frame.push_back((uint8_t) reason);
-  Transmit(frame);
+  // 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;
 }
 
-void CCECProcessor::ReportCECVersion(cec_logical_address address /* = CECDEVICE_TV */)
+CCECBusDevice *CCECProcessor::GetDeviceByPhysicalAddress(uint16_t iPhysicalAddress, bool bSuppressUpdate /* = true */)
 {
-  cec_frame frame;
-  m_controller->AddLog(CEC_LOG_NOTICE, "reporting CEC version as 1.3a");
-  frame.push_back(GetSourceDestination(address));
-  frame.push_back((uint8_t) CEC_OPCODE_CEC_VERSION);
-  frame.push_back(CEC_VERSION_1_3A);
-  Transmit(frame);
+  return m_busDevices ?
+      m_busDevices->GetDeviceByPhysicalAddress(iPhysicalAddress, bSuppressUpdate) :
+      NULL;
 }
 
-void CCECProcessor::ReportPowerState(cec_logical_address address /*= CECDEVICE_TV */, bool bOn /* = true */)
+CCECBusDevice *CCECProcessor::GetDevice(cec_logical_address address) const
 {
-  cec_frame frame;
-  if (bOn)
-    m_controller->AddLog(CEC_LOG_NOTICE, "reporting \"On\" power status");
-  else
-    m_controller->AddLog(CEC_LOG_NOTICE, "reporting \"Off\" power status");
-
-  frame.push_back(GetSourceDestination(address));
-  frame.push_back((uint8_t) CEC_OPCODE_REPORT_POWER_STATUS);
-  frame.push_back(bOn ? (uint8_t) CEC_POWER_STATUS_ON : (uint8_t) CEC_POWER_STATUS_STANDBY);
-  Transmit(frame);
+  return m_busDevices ?
+      m_busDevices->At(address) :
+      NULL;
 }
 
-void CCECProcessor::ReportMenuState(cec_logical_address address /* = CECDEVICE_TV */, bool bActive /* = true */)
+cec_logical_address CCECProcessor::GetActiveSource(bool bRequestActiveSource /* = true */)
 {
-  cec_frame frame;
-  if (bActive)
-    m_controller->AddLog(CEC_LOG_NOTICE, "reporting menu state as active");
-  else
-    m_controller->AddLog(CEC_LOG_NOTICE, "reporting menu state as inactive");
+  // get the device that is marked as active source from the device map
+  CCECBusDevice *activeSource = m_busDevices->GetActiveSource();
+  if (activeSource)
+    return activeSource->GetLogicalAddress();
 
-  frame.push_back(GetSourceDestination(address));
-  frame.push_back((uint8_t) CEC_OPCODE_MENU_STATUS);
-  frame.push_back(bActive ? (uint8_t) CEC_MENU_STATE_ACTIVATED : (uint8_t) CEC_MENU_STATE_DEACTIVATED);
-  Transmit(frame);
+  if (bRequestActiveSource)
+  {
+    // request the active source from the bus
+    CCECBusDevice *primary = GetPrimaryDevice();
+    if (primary)
+    {
+      primary->RequestActiveSource();
+      return GetActiveSource(false);
+    }
+  }
+
+  // unknown or none
+  return CECDEVICE_UNKNOWN;
 }
 
-void CCECProcessor::ReportVendorID(cec_logical_address address /* = CECDEVICE_TV */)
+bool CCECProcessor::IsActiveSource(cec_logical_address iAddress)
 {
-  m_controller->AddLog(CEC_LOG_NOTICE, "vendor ID requested, feature abort");
-  TransmitAbort(address, CEC_OPCODE_GIVE_DEVICE_VENDOR_ID);
+  CCECBusDevice *device = m_busDevices->At(iAddress);
+  return device && device->IsActiveSource();
 }
 
-void CCECProcessor::ReportOSDName(cec_logical_address address /* = CECDEVICE_TV */)
+bool CCECProcessor::Transmit(const cec_command &data)
 {
-  cec_frame frame;
-  const char *osdname = m_strDeviceName.c_str();
-  CStdString strLog;
-  strLog.Format("reporting OSD name as %s", osdname);
-  m_controller->AddLog(CEC_LOG_NOTICE, strLog.c_str());
-  frame.push_back(GetSourceDestination(address));
-  frame.push_back((uint8_t) CEC_OPCODE_SET_OSD_NAME);
+  uint8_t iMaxTries(0);
+  bool bRetry(true);
+  uint8_t iTries(0);
+
+  // get the current timeout setting
+  uint8_t iLineTimeout(GetStandardLineTimeout());
 
-  for (unsigned int i = 0; i < strlen(osdname); i++)
-    frame.push_back(osdname[i]);
+  // reset the state of this message to 'unknown'
+  cec_adapter_message_state adapterState = ADAPTER_MESSAGE_STATE_UNKNOWN;
 
-  Transmit(frame);
+  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;
+  }
+
+  // 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::ReportPhysicalAddress(void)
+void CCECProcessor::TransmitAbort(cec_logical_address source, cec_logical_address destination, cec_opcode opcode, cec_abort_reason reason /* = CEC_ABORT_REASON_UNRECOGNIZED_OPCODE */)
 {
-  cec_frame frame;
-  CStdString strLog;
-  strLog.Format("reporting physical address as %04x", m_physicaladdress);
-  m_controller->AddLog(CEC_LOG_NOTICE, strLog.c_str());
-  frame.push_back(GetSourceDestination(CECDEVICE_BROADCAST));
-  frame.push_back((uint8_t) CEC_OPCODE_REPORT_PHYSICAL_ADDRESS);
-  frame.push_back((m_physicaladdress >> 8) & 0xFF);
-  frame.push_back(m_physicaladdress & 0xFF);
-  frame.push_back(CEC_DEVICE_TYPE_PLAYBACK_DEVICE);
-  Transmit(frame);
+  m_libcec->AddLog(CEC_LOG_DEBUG, "<< transmitting abort message");
+
+  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);
 }
 
-void CCECProcessor::BroadcastActiveSource(void)
+void CCECProcessor::ProcessCommand(const cec_command &command)
 {
-  cec_frame frame;
-  m_controller->AddLog(CEC_LOG_NOTICE, "broadcasting active source");
-  frame.push_back(GetSourceDestination(CECDEVICE_BROADCAST));
-  frame.push_back((uint8_t) CEC_OPCODE_ACTIVE_SOURCE);
-  frame.push_back((m_physicaladdress >> 8) & 0xFF);
-  frame.push_back(m_physicaladdress & 0xFF);
-  Transmit(frame);
+  // 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());
+
+  // if we're not in monitor mode
+  if (!m_bMonitor)
+  {
+    // find the initiator
+    CCECBusDevice *device = m_busDevices->At(command.initiator);
+    // and "handle" the command
+    if (device)
+      device->HandleCommand(command);
+  }
 }
 
-uint8_t CCECProcessor::GetSourceDestination(cec_logical_address destination /* = CECDEVICE_BROADCAST */) const
+bool CCECProcessor::IsPresentDevice(cec_logical_address address)
 {
-  return ((uint8_t)m_iLogicalAddress << 4) + (uint8_t)destination;
+  CCECBusDevice *device = m_busDevices->At(address);
+  return device && device->GetStatus() == CEC_DEVICE_STATUS_PRESENT;
 }
 
-bool CCECProcessor::WaitForAck(int iTimeout /* = 1000 */)
+bool CCECProcessor::IsPresentDeviceType(cec_device_type type)
 {
-  bool bGotAck(false);
-  bool bError(false);
+  CECDEVICEVEC devices;
+  m_busDevices->GetByType(type, devices);
+  CCECDeviceMap::FilterActive(devices);
+  return !devices.empty();
+}
 
-  int64_t iNow = GetTimeMs();
-  int64_t iTargetTime = iNow + (int64_t) iTimeout;
+uint16_t CCECProcessor::GetDetectedPhysicalAddress(void) const
+{
+  return m_communication ? m_communication->GetPhysicalAddress() : CEC_INVALID_PHYSICAL_ADDRESS;
+}
 
-  while (!bGotAck && !bError && (iTimeout <= 0 || iNow < iTargetTime))
-  {
-    cec_frame msg;
-    while (!bGotAck && !bError && m_communication->Read(msg, iTimeout))
-    {
-      uint8_t iCode = msg[0] & ~(MSGCODE_FRAME_EOM | MSGCODE_FRAME_ACK);
-
-      switch (iCode)
-      {
-      case MSGCODE_COMMAND_ACCEPTED:
-        m_controller->AddLog(CEC_LOG_DEBUG, "MSGCODE_COMMAND_ACCEPTED");
-        break;
-      case MSGCODE_TRANSMIT_SUCCEEDED:
-        m_controller->AddLog(CEC_LOG_DEBUG, "MSGCODE_TRANSMIT_SUCCEEDED");
-        // TODO
-        bGotAck = true;
-        break;
-      case MSGCODE_RECEIVE_FAILED:
-        m_controller->AddLog(CEC_LOG_WARNING, "MSGCODE_RECEIVE_FAILED");
-        bError = true;
-        break;
-      case MSGCODE_COMMAND_REJECTED:
-        m_controller->AddLog(CEC_LOG_WARNING, "MSGCODE_COMMAND_REJECTED");
-        bError = true;
-        break;
-      case MSGCODE_TRANSMIT_FAILED_LINE:
-        m_controller->AddLog(CEC_LOG_WARNING, "MSGCODE_TRANSMIT_FAILED_LINE");
-        bError = true;
-        break;
-      case MSGCODE_TRANSMIT_FAILED_ACK:
-        m_controller->AddLog(CEC_LOG_WARNING, "MSGCODE_TRANSMIT_FAILED_ACK");
-        bError = true;
-        break;
-      case MSGCODE_TRANSMIT_FAILED_TIMEOUT_DATA:
-        m_controller->AddLog(CEC_LOG_WARNING, "MSGCODE_TRANSMIT_FAILED_TIMEOUT_DATA");
-        bError = true;
-        break;
-      case MSGCODE_TRANSMIT_FAILED_TIMEOUT_LINE:
-        m_controller->AddLog(CEC_LOG_WARNING, "MSGCODE_TRANSMIT_FAILED_TIMEOUT_LINE");
-        bError = true;
-        break;
-      default:
-        m_frameBuffer.Push(msg);
-        bGotAck = (msg[0] & MSGCODE_FRAME_ACK) != 0;
-        break;
-      }
-      iNow = GetTimeMs();
-    }
-  }
+bool CCECProcessor::SetAckMask(uint16_t iMask)
+{
+  return m_communication ? m_communication->SetAckMask(iMask) : false;
+}
 
-  return bGotAck && !bError;
+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;
 }
 
-bool CCECProcessor::ParseMessage(cec_frame &msg)
+bool CCECProcessor::StandbyDevice(const cec_logical_address initiator, cec_logical_address address)
 {
-  bool bReturn(false);
+  CCECBusDevice *device = m_busDevices->At(address);
+  return device ? device->Standby(initiator) : false;
+}
 
-  if (msg.empty())
-    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;
+}
 
-  CStdString logStr;
-  uint8_t iCode = msg[0] & ~(MSGCODE_FRAME_EOM | MSGCODE_FRAME_ACK);
-  bool    bEom  = (msg[0] & MSGCODE_FRAME_EOM) != 0;
-  bool    bAck  = (msg[0] & MSGCODE_FRAME_ACK) != 0;
+bool CCECProcessor::PowerOnDevice(const cec_logical_address initiator, cec_logical_address address)
+{
+  CCECBusDevice *device = m_busDevices->At(address);
+  return device ? device->PowerOn(initiator) : false;
+}
 
-  switch(iCode)
+bool CCECProcessor::StartBootloader(const char *strPort /* = NULL */)
+{
+  bool bReturn(false);
+  // open a connection if no connection has been opened
+  if (!m_communication && strPort)
   {
-  case MSGCODE_NOTHING:
-    m_controller->AddLog(CEC_LOG_DEBUG, "MSGCODE_NOTHING");
-    break;
-  case MSGCODE_TIMEOUT_ERROR:
-  case MSGCODE_HIGH_ERROR:
-  case MSGCODE_LOW_ERROR:
-    {
-      if (iCode == MSGCODE_TIMEOUT_ERROR)
-        logStr = "MSGCODE_TIMEOUT";
-      else if (iCode == MSGCODE_HIGH_ERROR)
-        logStr = "MSGCODE_HIGH_ERROR";
-      else
-        logStr = "MSGCODE_LOW_ERROR";
-
-      int iLine      = (msg.size() >= 3) ? (msg[1] << 8) | (msg[2]) : 0;
-      uint32_t iTime = (msg.size() >= 7) ? (msg[3] << 24) | (msg[4] << 16) | (msg[5] << 8) | (msg[6]) : 0;
-      logStr.AppendFormat(" line:%i", iLine);
-      logStr.AppendFormat(" time:%u", iTime);
-      m_controller->AddLog(CEC_LOG_WARNING, logStr.c_str());
-    }
-    break;
-  case MSGCODE_FRAME_START:
+    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)
     {
-      logStr = "MSGCODE_FRAME_START";
-      m_currentframe.clear();
-      if (msg.size() >= 2)
-      {
-        int iInitiator = msg[1] >> 4;
-        int iDestination = msg[1] & 0xF;
-        logStr.AppendFormat(" initiator:%u destination:%u ack:%s %s", iInitiator, iDestination, bAck ? "high" : "low", bEom ? "eom" : "");
-
-        m_currentframe.push_back(msg[1]);
-      }
-      m_controller->AddLog(CEC_LOG_DEBUG, logStr.c_str());
+      m_libcec->AddLog(CEC_LOG_ERROR, "could not open a connection (try %d)", ++iConnectTry);
+      comm->Close();
+      Sleep(CEC_DEFAULT_TRANSMIT_RETRY_WAIT);
     }
-    break;
-  case MSGCODE_FRAME_DATA:
+    if (comm->IsOpen())
     {
-      logStr = "MSGCODE_FRAME_DATA";
-      if (msg.size() >= 2)
-      {
-        uint8_t iData = msg[1];
-        logStr.AppendFormat(" %02x", iData);
-        m_currentframe.push_back(iData);
-      }
-      m_controller->AddLog(CEC_LOG_DEBUG, logStr.c_str());
+      bReturn = comm->StartBootloader();
+      delete comm;
     }
-    if (bEom)
-      bReturn = true;
-    break;
-  default:
-    break;
+    return bReturn;
+  }
+  else
+  {
+    m_communication->StartBootloader();
+    Close();
+    bReturn = true;
   }
 
   return bReturn;
 }
 
-void CCECProcessor::ParseCurrentFrame(void)
+bool CCECProcessor::PingAdapter(void)
 {
-  uint8_t initiator = m_currentframe[0] >> 4;
-  uint8_t destination = m_currentframe[0] & 0xF;
+  return m_communication->PingAdapter();
+}
 
-  CStdString dataStr;
-  dataStr.Format("received frame: initiator: %u destination: %u", initiator, destination);
+void CCECProcessor::HandlePoll(cec_logical_address initiator, cec_logical_address destination)
+{
+  CCECBusDevice *device = m_busDevices->At(destination);
+  if (device)
+    device->HandlePollFrom(initiator);
+}
 
-  if (m_currentframe.size() > 1)
+bool CCECProcessor::HandleReceiveFailed(cec_logical_address initiator)
+{
+  CCECBusDevice *device = m_busDevices->At(initiator);
+  return !device || !device->HandleReceiveFailed();
+}
+
+bool CCECProcessor::SetStreamPath(uint16_t iPhysicalAddress)
+{
+  // 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;
+}
+
+bool CCECProcessor::PersistConfiguration(const libcec_configuration &configuration)
+{
+  return m_communication ? m_communication->PersistConfiguration(configuration) : false;
+}
+
+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;
+
+  // unregister the client first if it's already been marked as registered
+  if (client->IsRegistered())
+    UnregisterClient(client);
+
+  // get the configuration from the client
+  libcec_configuration &configuration = *client->GetConfiguration();
+  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())
   {
-    dataStr += " data:";
-    for (unsigned int i = 1; i < m_currentframe.size(); i++)
-      dataStr.AppendFormat(" %02x", m_currentframe[i]);
+    m_libcec->AddLog(CEC_LOG_ERROR, "failed to register the new CEC client - cannot allocate the requested device types");
+    SetAckMask(iPreviousMask);
+    return false;
   }
-  m_controller->AddLog(CEC_LOG_DEBUG, dataStr.c_str());
 
-  if (m_currentframe.size() <= 1)
-    return;
+  // 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<cec_logical_address, CCECClient *>((*it)->GetLogicalAddress(), client));
+  }
 
-  vector<uint8_t> tx;
-  cec_opcode opCode = (cec_opcode) m_currentframe[1];
-  if (destination == (uint16_t) m_iLogicalAddress)
+  // get the settings from the rom
+  if (configuration.bGetSettingsFromROM == 1)
   {
-    switch(opCode)
-    {
-    case CEC_OPCODE_GIVE_PHYSICAL_ADDRESS:
-      ReportPhysicalAddress();
-      SetActiveView();
-      break;
-    case CEC_OPCODE_GIVE_OSD_NAME:
-      ReportOSDName((cec_logical_address)initiator);
-      break;
-    case CEC_OPCODE_GIVE_DEVICE_VENDOR_ID:
-      ReportVendorID((cec_logical_address)initiator);
-      break;
-    case CEC_OPCODE_MENU_REQUEST:
-      ReportMenuState((cec_logical_address)initiator);
-      break;
-    case CEC_OPCODE_GIVE_DEVICE_POWER_STATUS:
-      ReportPowerState((cec_logical_address)initiator);
-      break;
-    case CEC_OPCODE_GET_CEC_VERSION:
-      ReportCECVersion((cec_logical_address)initiator);
-      break;
-    case CEC_OPCODE_USER_CONTROL_PRESSED:
-      if (m_currentframe.size() > 2)
-      {
-        m_controller->AddKey();
-
-        if (m_currentframe[2] <= CEC_USER_CONTROL_CODE_MAX)
-          m_controller->SetCurrentButton((cec_user_control_code) m_currentframe[2]);
-      }
-      break;
-    case CEC_OPCODE_USER_CONTROL_RELEASE:
-      m_controller->AddKey();
-      break;
-    default:
-      cec_frame params = m_currentframe;
-      params.erase(params.begin(), params.begin() + 2);
-      m_controller->AddCommand((cec_logical_address) initiator, (cec_logical_address) destination, opCode, &params);
-      break;
-    }
+    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);
   }
-  else if (destination == (uint8_t) CECDEVICE_BROADCAST)
+
+  // 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())
   {
-    if (opCode == CEC_OPCODE_REQUEST_ACTIVE_SOURCE)
-    {
-      BroadcastActiveSource();
-    }
-    else if (opCode == CEC_OPCODE_SET_STREAM_PATH)
-    {
-      if (m_currentframe.size() >= 4)
-      {
-        int streamaddr = ((int)m_currentframe[2] << 8) | ((int)m_currentframe[3]);
-        CStdString strLog;
-        strLog.Format("%i requests stream path from physical address %04x", initiator, streamaddr);
-        m_controller->AddLog(CEC_LOG_DEBUG, strLog.c_str());
-        if (streamaddr == m_physicaladdress)
-          BroadcastActiveSource();
-      }
-    }
-    else
-    {
-      cec_frame params = m_currentframe;
-      params.erase(params.begin(), params.begin() + 2);
-      m_controller->AddCommand((cec_logical_address) initiator, (cec_logical_address) destination, opCode, &params);
-    }
+    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);
   }
-  else
+
+  return bReturn;
+}
+
+void CCECProcessor::UnregisterClient(CCECClient *client)
+{
+  if (!client)
+    return;
+
+  m_libcec->AddLog(CEC_LOG_NOTICE, "unregistering client: %s", client->GetConnectionInfo().c_str());
+
+  // notify the client that it will be unregistered
+  client->OnUnregister();
+
   {
-    CStdString strLog;
-    strLog.Format("ignoring frame: destination: %u != %u", destination, (uint16_t)m_iLogicalAddress);
-    m_controller->AddLog(CEC_LOG_DEBUG, strLog.c_str());
+    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++)
+    {
+      // find the client
+      map<cec_logical_address, CCECClient *>::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();
+    }
   }
+
+  // set the new ackmask
+  SetAckMask(GetLogicalAddresses().AckMask());
+}
+
+void CCECProcessor::UnregisterClients(void)
+{
+  m_libcec->AddLog(CEC_LOG_NOTICE, "unregistering all CEC clients");
+
+  vector<CCECClient *> clients = m_libcec->GetClients();
+  for (vector<CCECClient *>::iterator client = clients.begin(); client != clients.end(); client++)
+    UnregisterClient(*client);
+
+  CLockObject lock(m_mutex);
+  m_clients.clear();
+}
+
+CCECClient *CCECProcessor::GetClient(const cec_logical_address address)
+{
+  CLockObject lock(m_mutex);
+  map<cec_logical_address, CCECClient *>::const_iterator client = m_clients.find(address);
+  if (client != m_clients.end())
+    return client->second;
+  return NULL;
+}
+
+CCECClient *CCECProcessor::GetPrimaryClient(void)
+{
+  CLockObject lock(m_mutex);
+  map<cec_logical_address, CCECClient *>::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());
+}
+
+cec_logical_address CCECProcessor::GetLogicalAddress(void)
+{
+  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<cec_logical_address, CCECClient *>::const_iterator client = m_clients.begin(); client != m_clients.end(); client++)
+    addresses.Set(client->first);
+
+  return addresses;
+}
+
+bool CCECProcessor::IsHandledByLibCEC(const cec_logical_address address) const
+{
+  CCECBusDevice *device = GetDevice(address);
+  return device && device->IsHandledByLibCEC();
+}
+
+bool CCECProcessor::IsRunningLatestFirmware(void)
+{
+  return m_communication && m_communication->IsOpen() ?
+      m_communication->IsRunningLatestFirmware() :
+      true;
 }