added protection against standby without a notification from XBMC and clock changes...
[deb_libcec.git] / src / lib / CECProcessor.cpp
index 3bfa061548c0e4b74d4811e7296790a6849b2630..63e481551457682c0e58545b37272028a56979f0 100644 (file)
@@ -1,7 +1,7 @@
 /*
  * This file is part of the libCEC(R) library.
  *
- * libCEC(R) is Copyright (C) 2011-2012 Pulse-Eight Limited.  All rights reserved.
+ * libCEC(R) is Copyright (C) 2011-2013 Pulse-Eight Limited.  All rights reserved.
  * libCEC(R) is an original work, containing original code.
  *
  * libCEC(R) is a trademark of Pulse-Eight Limited.
  *     http://www.pulse-eight.net/
  */
 
+#include "env.h"
 #include "CECProcessor.h"
 
-#include "adapter/USBCECAdapterCommunication.h"
+#include "adapter/AdapterFactory.h"
 #include "devices/CECBusDevice.h"
 #include "devices/CECAudioSystem.h"
 #include "devices/CECPlaybackDevice.h"
 #include "implementations/CECCommandHandler.h"
 #include "LibCEC.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;
 
 #define CEC_PROCESSOR_SIGNAL_WAIT_TIME 1000
+#define ACTIVE_SOURCE_CHECK_INTERVAL   500
+#define TV_PRESENT_CHECK_INTERVAL      30000
 
-#define ToString(x) m_libcec->ToString(x)
+#define ToString(x) CCECTypeUtils::ToString(x)
+
+CCECStandbyProtection::CCECStandbyProtection(CCECProcessor* processor) :
+    m_processor(processor) {}
+CCECStandbyProtection::~CCECStandbyProtection(void) {}
+
+void* CCECStandbyProtection::Process(void)
+{
+  int64_t last = GetTimeMs();
+  int64_t next;
+  while (!IsStopped())
+  {
+    PLATFORM::CEvent::Sleep(1000);
+
+    next = GetTimeMs();
+
+    // reset the connection if the clock changed
+    if (next < last || next - last > 10000)
+    {
+      libcec_parameter param;
+      param.paramData = NULL; param.paramType = CEC_PARAMETER_TYPE_UNKOWN;
+      m_processor->GetLib()->Alert(CEC_ALERT_CONNECTION_LOST, param);
+      break;
+    }
+
+    last = next;
+  }
+  return NULL;
+}
 
 CCECProcessor::CCECProcessor(CLibCEC *libcec) :
     m_bInitialised(false),
@@ -58,15 +91,21 @@ CCECProcessor::CCECProcessor(CLibCEC *libcec) :
     m_libcec(libcec),
     m_iStandardLineTimeout(3),
     m_iRetryLineTimeout(3),
-    m_iLastTransmission(0)
+    m_iLastTransmission(0),
+    m_bMonitor(true),
+    m_addrAllocator(NULL),
+    m_bStallCommunication(false),
+    m_connCheck(NULL)
 {
   m_busDevices = new CCECDeviceMap(this);
 }
 
 CCECProcessor::~CCECProcessor(void)
 {
+  m_bStallCommunication = false;
+  DELETE_AND_NULL(m_addrAllocator);
   Close();
-  delete m_busDevices;
+  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 */)
@@ -95,24 +134,19 @@ void CCECProcessor::Close(void)
   SetCECInitialised(false);
 
   // stop the processor
+  DELETE_AND_NULL(m_connCheck);
+  StopThread(-1);
+  m_inBuffer.Broadcast();
   StopThread();
 
   // close the connection
-  if (m_communication)
-  {
-    delete m_communication;
-    m_communication = NULL;
-  }
+  DELETE_AND_NULL(m_communication);
 }
 
 void CCECProcessor::ResetMembers(void)
 {
   // close the connection
-  if (m_communication)
-  {
-    delete m_communication;
-    m_communication = NULL;
-  }
+  DELETE_AND_NULL(m_communication);
 
   // reset the other members to the initial state
   m_iStandardLineTimeout = 3;
@@ -140,7 +174,7 @@ bool CCECProcessor::OpenConnection(const char *strPort, uint16_t iBaudRate, uint
   }
 
   // create a new connection
-  m_communication = new CUSBCECAdapterCommunication(this, strPort, iBaudRate);
+  m_communication = CAdapterFactory(this->m_libcec).GetInstance(strPort, iBaudRate);
 
   // open a new connection
   unsigned iConnectTry(0);
@@ -153,9 +187,6 @@ bool CCECProcessor::OpenConnection(const char *strPort, uint16_t iBaudRate, uint
 
   m_libcec->AddLog(CEC_LOG_NOTICE, "connection opened");
 
-  // always start by setting the ackmask to 0, to clear previous values
-  SetAckMask(0);
-
   // mark as initialised
   SetCECInitialised(true);
 
@@ -178,7 +209,7 @@ void CCECProcessor::SetCECInitialised(bool bSetTo /* = true */)
     UnregisterClients();
 }
 
-bool CCECProcessor::TryLogicalAddress(cec_logical_address address)
+bool CCECProcessor::TryLogicalAddress(cec_logical_address address, cec_version libCECSpecVersion /* = CEC_VERSION_1_4 */)
 {
   // find the device
   CCECBusDevice *device = m_busDevices->At(address);
@@ -189,8 +220,7 @@ bool CCECProcessor::TryLogicalAddress(cec_logical_address address)
       return false;
 
     // poll the LA if not
-    SetAckMask(0);
-    return device->TryLogicalAddress();
+    return device->TryLogicalAddress(libCECSpecVersion);
   }
 
   return false;
@@ -215,7 +245,13 @@ void *CCECProcessor::Process(void)
 {
   m_libcec->AddLog(CEC_LOG_DEBUG, "processor thread started");
 
-  cec_command command;
+  if (!m_connCheck)
+    m_connCheck = new CCECStandbyProtection(this);
+  m_connCheck->CreateThread();
+
+  cec_command command; command.Clear();
+  CTimeout activeSourceCheck(ACTIVE_SOURCE_CHECK_INTERVAL);
+  CTimeout tvPresentCheck(TV_PRESENT_CHECK_INTERVAL);
 
   // as long as we're not being stopped and the connection is open
   while (!IsStopped() && m_communication->IsOpen())
@@ -224,13 +260,39 @@ void *CCECProcessor::Process(void)
     if (m_inBuffer.Pop(command, CEC_PROCESSOR_SIGNAL_WAIT_TIME))
       ProcessCommand(command);
 
-    if (CECInitialised())
+    if (CECInitialised() && !IsStopped())
     {
       // check clients for keypress timeouts
       m_libcec->CheckKeypressTimeout();
 
       // check if we need to replace handlers
       ReplaceHandlers();
+
+      // check whether we need to activate a source, if it failed before
+      if (activeSourceCheck.TimeLeft() == 0)
+      {
+        if (CECInitialised())
+          TransmitPendingActiveSourceCommands();
+        activeSourceCheck.Init(ACTIVE_SOURCE_CHECK_INTERVAL);
+      }
+
+      // check whether the TV is present and responding
+      if (tvPresentCheck.TimeLeft() == 0)
+      {
+        CCECClient *primary = GetPrimaryClient();
+        // only check whether the tv responds to polls when a client is connected and not in monitoring mode
+        if (primary && primary->GetConfiguration()->bMonitorOnly != 1)
+        {
+          if (!m_busDevices->At(CECDEVICE_TV)->IsPresent())
+          {
+            libcec_parameter param;
+            param.paramType = CEC_PARAMETER_TYPE_STRING;
+            param.paramData = (void*)"TV does not respond to CEC polls";
+            primary->Alert(CEC_ALERT_TV_POLL_FAILED, param);
+          }
+        }
+        tvPresentCheck.Init(TV_PRESENT_CHECK_INTERVAL);
+      }
     }
   }
 
@@ -252,6 +314,12 @@ bool CCECProcessor::ActivateSource(uint16_t iStreamPath)
   return bReturn;
 }
 
+void CCECProcessor::SetActiveSource(bool bSetTo, bool bClientUnregistered)
+{
+  if (m_communication)
+    m_communication->SetActiveSource(bSetTo, bClientUnregistered);
+}
+
 void CCECProcessor::SetStandardLineTimeout(uint8_t iTimeout)
 {
   CLockObject lock(m_mutex);
@@ -307,13 +375,11 @@ bool CCECProcessor::PollDevice(cec_logical_address iAddress)
   CCECBusDevice *primary = GetPrimaryDevice();
   // poll the destination, with the primary as source
   if (primary)
-    return primary->TransmitPoll(iAddress);
+    return primary->TransmitPoll(iAddress, true);
 
-  // try to find the destination
-  CCECBusDevice *device = m_busDevices->At(iAddress);
-  // and poll the destination, with the same LA as source
+  CCECBusDevice *device = m_busDevices->At(CECDEVICE_UNREGISTERED);
   if (device)
-    return device->TransmitPoll(iAddress);
+    return device->TransmitPoll(iAddress, true);
 
   return false;
 }
@@ -360,8 +426,9 @@ bool CCECProcessor::IsActiveSource(cec_logical_address iAddress)
   return device && device->IsActiveSource();
 }
 
-bool CCECProcessor::Transmit(const cec_command &data)
+bool CCECProcessor::Transmit(const cec_command &data, bool bIsReply)
 {
+  cec_command transmitData(data);
   uint8_t iMaxTries(0);
   bool bRetry(true);
   uint8_t iTries(0);
@@ -372,10 +439,24 @@ bool CCECProcessor::Transmit(const cec_command &data)
   // reset the state of this message to 'unknown'
   cec_adapter_message_state adapterState = ADAPTER_MESSAGE_STATE_UNKNOWN;
 
-  LogOutput(data);
+  if (!m_communication->SupportsSourceLogicalAddress(transmitData.initiator))
+  {
+    if (transmitData.initiator == CECDEVICE_UNREGISTERED && m_communication->SupportsSourceLogicalAddress(CECDEVICE_FREEUSE))
+    {
+      m_libcec->AddLog(CEC_LOG_DEBUG, "initiator '%s' is not supported by the CEC adapter. using '%s' instead", ToString(transmitData.initiator), ToString(CECDEVICE_FREEUSE));
+      transmitData.initiator = CECDEVICE_FREEUSE;
+    }
+    else
+    {
+      m_libcec->AddLog(CEC_LOG_DEBUG, "initiator '%s' is not supported by the CEC adapter", ToString(transmitData.initiator));
+      return false;
+    }
+  }
+
+  LogOutput(transmitData);
 
   // find the initiator device
-  CCECBusDevice *initiator = m_busDevices->At(data.initiator);
+  CCECBusDevice *initiator = m_busDevices->At(transmitData.initiator);
   if (!initiator)
   {
     m_libcec->AddLog(CEC_LOG_WARNING, "invalid initiator");
@@ -383,10 +464,10 @@ bool CCECProcessor::Transmit(const cec_command &data)
   }
 
   // find the destination device, if it's not the broadcast address
-  if (data.destination != CECDEVICE_BROADCAST)
+  if (transmitData.destination != CECDEVICE_BROADCAST)
   {
     // check if the device is marked as handled by libCEC
-    CCECBusDevice *destination = m_busDevices->At(data.destination);
+    CCECBusDevice *destination = m_busDevices->At(transmitData.destination);
     if (destination && destination->IsHandledByLibCEC())
     {
       // and reject the command if it's trying to send data to a device that is handled by libCEC
@@ -395,26 +476,32 @@ bool CCECProcessor::Transmit(const cec_command &data)
     }
   }
 
+  // wait until we finished allocating a new LA if it got lost
+  while (m_bStallCommunication) Sleep(5);
+
   {
     CLockObject lock(m_mutex);
     m_iLastTransmission = GetTimeMs();
     // set the number of tries
     iMaxTries = initiator->GetHandler()->GetTransmitRetries() + 1;
+    initiator->MarkHandlerReady();
   }
 
   // and try to send the command
   while (bRetry && ++iTries < iMaxTries)
   {
-    if (initiator->IsUnsupportedFeature(data.opcode))
+    if (initiator->IsUnsupportedFeature(transmitData.opcode))
       return false;
 
     adapterState = !IsStopped() && m_communication && m_communication->IsOpen() ?
-        m_communication->Write(data, bRetry, iLineTimeout) :
+        m_communication->Write(transmitData, bRetry, iLineTimeout, bIsReply) :
         ADAPTER_MESSAGE_STATE_ERROR;
     iLineTimeout = m_iRetryLineTimeout;
   }
 
-  return adapterState == ADAPTER_MESSAGE_STATE_SENT_ACKED;
+  return bIsReply ?
+      adapterState == ADAPTER_MESSAGE_STATE_SENT_ACKED || adapterState == ADAPTER_MESSAGE_STATE_SENT || adapterState == ADAPTER_MESSAGE_STATE_WAITING_TO_BE_SENT :
+      adapterState == ADAPTER_MESSAGE_STATE_SENT_ACKED;
 }
 
 void CCECProcessor::TransmitAbort(cec_logical_address source, cec_logical_address destination, cec_opcode opcode, cec_abort_reason reason /* = CEC_ABORT_REASON_UNRECOGNIZED_OPCODE */)
@@ -426,19 +513,13 @@ void CCECProcessor::TransmitAbort(cec_logical_address source, cec_logical_addres
   command.parameters.PushBack((uint8_t)opcode);
   command.parameters.PushBack((uint8_t)reason);
 
-  Transmit(command);
+  Transmit(command, true);
 }
 
 void CCECProcessor::ProcessCommand(const cec_command &command)
 {
   // 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());
+  m_libcec->AddLog(CEC_LOG_TRAFFIC, ToString(command).c_str());
 
   // find the initiator
   CCECBusDevice *device = m_busDevices->At(command.initiator);
@@ -466,9 +547,15 @@ uint16_t CCECProcessor::GetDetectedPhysicalAddress(void) const
   return m_communication ? m_communication->GetPhysicalAddress() : CEC_INVALID_PHYSICAL_ADDRESS;
 }
 
-bool CCECProcessor::SetAckMask(uint16_t iMask)
+bool CCECProcessor::ClearLogicalAddresses(void)
 {
-  return m_communication ? m_communication->SetAckMask(iMask) : false;
+  cec_logical_addresses addresses; addresses.Clear();
+  return SetLogicalAddresses(addresses);
+}
+
+bool CCECProcessor::SetLogicalAddresses(const cec_logical_addresses &addresses)
+{
+  return m_communication ? m_communication->SetLogicalAddresses(addresses) : false;
 }
 
 bool CCECProcessor::StandbyDevices(const cec_logical_address initiator, const CECDEVICEVEC &devices)
@@ -505,7 +592,8 @@ bool CCECProcessor::StartBootloader(const char *strPort /* = NULL */)
   // open a connection if no connection has been opened
   if (!m_communication && strPort)
   {
-    IAdapterCommunication *comm = new CUSBCECAdapterCommunication(this, strPort);
+    CAdapterFactory factory(this->m_libcec);
+    IAdapterCommunication *comm = factory.GetInstance(strPort);
     CTimeout timeout(CEC_DEFAULT_CONNECT_TIMEOUT);
     int iConnectTry(0);
     while (timeout.TimeLeft() > 0 && (bReturn = comm->Open(timeout.TimeLeft() / CEC_CONNECT_TRIES, true)) == false)
@@ -517,7 +605,7 @@ bool CCECProcessor::StartBootloader(const char *strPort /* = NULL */)
     if (comm->IsOpen())
     {
       bReturn = comm->StartBootloader();
-      delete comm;
+      DELETE_AND_NULL(comm);
     }
     return bReturn;
   }
@@ -549,12 +637,6 @@ bool CCECProcessor::HandleReceiveFailed(cec_logical_address 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;
@@ -562,7 +644,15 @@ bool CCECProcessor::CanPersistConfiguration(void)
 
 bool CCECProcessor::PersistConfiguration(const libcec_configuration &configuration)
 {
-  return m_communication ? m_communication->PersistConfiguration(configuration) : false;
+  libcec_configuration persistConfiguration = configuration;
+  if (!CLibCEC::IsValidPhysicalAddress(configuration.iPhysicalAddress))
+  {
+    CCECBusDevice *device = GetPrimaryDevice();
+    if (device)
+      persistConfiguration.iPhysicalAddress = device->GetCurrentPhysicalAddress();
+  }
+
+  return m_communication ? m_communication->PersistConfiguration(persistConfiguration) : false;
 }
 
 void CCECProcessor::RescanActiveDevices(void)
@@ -579,6 +669,9 @@ bool CCECProcessor::GetDeviceInformation(const char *strPort, libcec_configurati
   config->iFirmwareVersion   = m_communication->GetFirmwareVersion();
   config->iPhysicalAddress   = m_communication->GetPhysicalAddress();
   config->iFirmwareBuildDate = m_communication->GetFirmwareBuildDate();
+  config->adapterType        = m_communication->GetAdapterType();
+
+  Close();
 
   return true;
 }
@@ -616,6 +709,62 @@ CCECTuner *CCECProcessor::GetTuner(cec_logical_address address) const
   return CCECBusDevice::AsTuner(m_busDevices->At(address));
 }
 
+bool CCECProcessor::AllocateLogicalAddresses(CCECClient* client)
+{
+  libcec_configuration &configuration = *client->GetConfiguration();
+
+  // mark as unregistered
+  client->SetRegistered(false);
+
+  // unregister this client from the old addresses
+  CECDEVICEVEC devices;
+  m_busDevices->GetByLogicalAddresses(devices, configuration.logicalAddresses);
+  for (CECDEVICEVEC::const_iterator it = devices.begin(); it != devices.end(); it++)
+  {
+    // remove client entry
+    CLockObject lock(m_mutex);
+    m_clients.erase((*it)->GetLogicalAddress());
+  }
+
+  // find logical addresses for this client
+  if (!client->AllocateLogicalAddresses())
+  {
+    m_libcec->AddLog(CEC_LOG_ERROR, "failed to find a free logical address for the client");
+    return false;
+  }
+
+  // register this client on the new addresses
+  devices.clear();
+  m_busDevices->GetByLogicalAddresses(devices, configuration.logicalAddresses);
+  for (CECDEVICEVEC::const_iterator it = devices.begin(); it != devices.end(); it++)
+  {
+    // set the physical address of the device at this LA
+    if (CLibCEC::IsValidPhysicalAddress(configuration.iPhysicalAddress))
+      (*it)->SetPhysicalAddress(configuration.iPhysicalAddress);
+
+    // replace a previous client
+    CLockObject lock(m_mutex);
+    m_clients.erase((*it)->GetLogicalAddress());
+    m_clients.insert(make_pair((*it)->GetLogicalAddress(), client));
+  }
+
+  // set the new ackmask
+  SetLogicalAddresses(GetLogicalAddresses());
+
+  // resume outgoing communication
+  m_bStallCommunication = false;
+
+  return true;
+}
+
+uint16_t CCECProcessor::GetPhysicalAddressFromEeprom(void)
+{
+  libcec_configuration config; config.Clear();
+  if (m_communication)
+    m_communication->GetConfiguration(config);
+  return config.iPhysicalAddress;
+}
+
 bool CCECProcessor::RegisterClient(CCECClient *client)
 {
   if (!client)
@@ -623,7 +772,13 @@ bool CCECProcessor::RegisterClient(CCECClient *client)
 
   libcec_configuration &configuration = *client->GetConfiguration();
 
-  if (configuration.clientVersion >= CEC_CLIENT_VERSION_1_6_3 && configuration.bMonitorOnly == 1)
+  if (configuration.clientVersion < CEC_CLIENT_VERSION_2_0_0)
+  {
+    m_libcec->AddLog(CEC_LOG_ERROR, "failed to register a new CEC client: client version %s is no longer supported", ToString((cec_client_version)configuration.clientVersion));
+    return false;
+  }
+
+  if (configuration.bMonitorOnly == 1)
     return true;
 
   if (!CECInitialised())
@@ -636,39 +791,56 @@ bool CCECProcessor::RegisterClient(CCECClient *client)
   if (client->IsRegistered())
     UnregisterClient(client);
 
+  // ensure that controlled mode is enabled
+  m_communication->SetControlledMode(true);
+  m_bMonitor = false;
+
+  // source logical address for requests
+  cec_logical_address sourceAddress(CECDEVICE_UNREGISTERED);
+  if (!m_communication->SupportsSourceLogicalAddress(CECDEVICE_UNREGISTERED))
+  {
+    if (m_communication->SupportsSourceLogicalAddress(CECDEVICE_FREEUSE))
+      sourceAddress = CECDEVICE_FREEUSE;
+    else
+    {
+      m_libcec->AddLog(CEC_LOG_ERROR, "failed to register a new CEC client: both unregistered and free use are not supported by the device");
+      return false;
+    }
+  }
+
+  // ensure that we know the vendor id of the TV
+  CCECBusDevice *tv = GetTV();
+  cec_vendor_id tvVendor(tv->GetVendorId(sourceAddress));
+
+  // wait until the handler is replaced, to avoid double registrations
+  if (tvVendor != CEC_VENDOR_UNKNOWN &&
+      CCECCommandHandler::HasSpecificHandler(tvVendor))
+  {
+    while (!tv->ReplaceHandler(false))
+      CEvent::Sleep(5);
+  }
+
   // 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());
+  cec_logical_addresses previousMask = GetLogicalAddresses();
+
+  // mark as uninitialised
+  client->SetInitialised(false);
 
   // find logical addresses for this client
-  if (!client->AllocateLogicalAddresses())
+  if (!AllocateLogicalAddresses(client))
   {
     m_libcec->AddLog(CEC_LOG_ERROR, "failed to register the new CEC client - cannot allocate the requested device types");
-    SetAckMask(iPreviousMask);
+    SetLogicalAddresses(previousMask);
     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<cec_logical_address, CCECClient *>((*it)->GetLogicalAddress(), client));
-  }
-
   // get the settings from the rom
   if (configuration.bGetSettingsFromROM == 1)
   {
-    libcec_configuration config;
+    libcec_configuration config; config.Clear();
     m_communication->GetConfiguration(config);
 
     CLockObject lock(m_mutex);
@@ -683,14 +855,15 @@ bool CCECProcessor::RegisterClient(CCECClient *client)
   configuration.serverVersion      = LIBCEC_VERSION_CURRENT;
   configuration.iFirmwareVersion   = m_communication->GetFirmwareVersion();
   configuration.iFirmwareBuildDate = m_communication->GetFirmwareBuildDate();
+  configuration.adapterType        = m_communication->GetAdapterType();
 
   // mark the client as registered
   client->SetRegistered(true);
 
-  // set the new ack mask
-  bool bReturn = SetAckMask(GetLogicalAddresses().AckMask()) &&
-      // and initialise the client
-      client->OnRegister();
+  sourceAddress = client->GetPrimaryLogicalAdddress();
+
+  // initialise the client
+  bool bReturn = client->OnRegister();
 
   // log the new registration
   CStdString strLog;
@@ -707,6 +880,21 @@ bool CCECProcessor::RegisterClient(CCECClient *client)
     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();
+    GetTV()->MarkHandlerReady();
+  }
+
+  // report our OSD name to the TV, since some TVs don't request it
+  client->GetPrimaryDevice()->TransmitOSDName(CECDEVICE_TV, false);
+
+  // request the power status of the TV
+  tv->RequestPowerStatus(sourceAddress, true, true);
+
   return bReturn;
 }
 
@@ -735,17 +923,27 @@ bool CCECProcessor::UnregisterClient(CCECClient *client)
         m_clients.erase(entry);
 
       // reset the device status
-      (*it)->ResetDeviceStatus();
+      (*it)->ResetDeviceStatus(true);
     }
   }
 
   // set the new ackmask
-  return SetAckMask(GetLogicalAddresses().AckMask());
+  cec_logical_addresses addresses = GetLogicalAddresses();
+  if (SetLogicalAddresses(addresses))
+  {
+    // no more clients left, disable controlled mode
+    if (addresses.IsEmpty() && !m_bMonitor)
+      m_communication->SetControlledMode(false);
+
+    return true;
+  }
+
+  return false;
 }
 
 void CCECProcessor::UnregisterClients(void)
 {
-  m_libcec->AddLog(CEC_LOG_NOTICE, "unregistering all CEC clients");
+  m_libcec->AddLog(CEC_LOG_DEBUG, "unregistering all CEC clients");
 
   vector<CCECClient *> clients = m_libcec->GetClients();
   for (vector<CCECClient *>::iterator client = clients.begin(); client != clients.end(); client++)
@@ -807,3 +1005,61 @@ bool CCECProcessor::IsRunningLatestFirmware(void)
       m_communication->IsRunningLatestFirmware() :
       true;
 }
+
+void CCECProcessor::SwitchMonitoring(bool bSwitchTo)
+{
+  {
+    CLockObject lock(m_mutex);
+    m_bMonitor = bSwitchTo;
+  }
+  if (bSwitchTo)
+    UnregisterClients();
+}
+
+void CCECProcessor::HandleLogicalAddressLost(cec_logical_address oldAddress)
+{
+  // stall outgoing messages until we know our new LA
+  m_bStallCommunication = true;
+
+  m_libcec->AddLog(CEC_LOG_NOTICE, "logical address %x was taken by another device, allocating a new address", oldAddress);
+  CCECClient* client = GetClient(oldAddress);
+  if (!client)
+    client = GetPrimaryClient();
+  if (client)
+  {
+    if (m_addrAllocator)
+      while (m_addrAllocator->IsRunning()) Sleep(5);
+    delete m_addrAllocator;
+
+    m_addrAllocator = new CCECAllocateLogicalAddress(this, client);
+    m_addrAllocator->CreateThread();
+  }
+}
+
+void CCECProcessor::HandlePhysicalAddressChanged(uint16_t iNewAddress)
+{
+  m_libcec->AddLog(CEC_LOG_NOTICE, "physical address changed to %04x", iNewAddress);
+  CCECClient* client = GetPrimaryClient();
+  if (client)
+    client->SetPhysicalAddress(iNewAddress);
+}
+
+uint16_t CCECProcessor::GetAdapterVendorId(void) const
+{
+  return m_communication ? m_communication->GetAdapterVendorId() : 0;
+}
+
+uint16_t CCECProcessor::GetAdapterProductId(void) const
+{
+  return m_communication ? m_communication->GetAdapterProductId() : 0;
+}
+
+CCECAllocateLogicalAddress::CCECAllocateLogicalAddress(CCECProcessor* processor, CCECClient* client) :
+    m_processor(processor),
+    m_client(client) { }
+
+void* CCECAllocateLogicalAddress::Process(void)
+{
+  m_processor->AllocateLogicalAddresses(m_client);
+  return NULL;
+}