2 * This file is part of the libCEC(R) library.
4 * libCEC(R) is Copyright (C) 2011-2012 Pulse-Eight Limited. All rights reserved.
5 * libCEC(R) is an original work, containing original code.
7 * libCEC(R) is a trademark of Pulse-Eight Limited.
9 * This program is dual-licensed; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
24 * Alternatively, you can license this library under a commercial license,
25 * please contact Pulse-Eight Licensing for more information.
27 * For more information contact:
28 * Pulse-Eight Licensing <license@pulse-eight.com>
29 * http://www.pulse-eight.com/
30 * http://www.pulse-eight.net/
33 #include "CECProcessor.h"
35 #include "adapter/USBCECAdapterCommunication.h"
36 #include "devices/CECBusDevice.h"
37 #include "devices/CECAudioSystem.h"
38 #include "devices/CECPlaybackDevice.h"
39 #include "devices/CECRecordingDevice.h"
40 #include "devices/CECTuner.h"
41 #include "devices/CECTV.h"
42 #include "implementations/CECCommandHandler.h"
44 #include "CECClient.h"
45 #include "platform/util/timeutils.h"
49 using namespace PLATFORM
;
51 #define CEC_PROCESSOR_SIGNAL_WAIT_TIME 1000
53 #define ToString(x) m_libcec->ToString(x)
55 CCECProcessor::CCECProcessor(CLibCEC
*libcec
) :
56 m_bInitialised(false),
57 m_communication(NULL
),
60 m_iPreviousAckMask(0),
61 m_iStandardLineTimeout(3),
62 m_iRetryLineTimeout(3),
63 m_iLastTransmission(0)
65 m_busDevices
= new CCECDeviceMap(this);
68 CCECProcessor::~CCECProcessor(void)
74 bool CCECProcessor::Start(const char *strPort
, uint16_t iBaudRate
/* = CEC_SERIAL_DEFAULT_BAUDRATE */, uint32_t iTimeoutMs
/* = CEC_DEFAULT_CONNECT_TIMEOUT */)
76 CLockObject
lock(m_mutex
);
77 if (!OpenConnection(strPort
, iBaudRate
, iTimeoutMs
))
80 /* create the processor thread */
84 m_libcec
->AddLog(CEC_LOG_DEBUG
, "processor thread started");
87 m_libcec
->AddLog(CEC_LOG_ERROR
, "could not create a processor thread");
92 SetCECInitialised(true);
97 void CCECProcessor::Close(void)
99 SetCECInitialised(false);
104 delete m_communication
;
105 m_communication
= NULL
;
109 bool CCECProcessor::OpenConnection(const char *strPort
, uint16_t iBaudRate
, uint32_t iTimeoutMs
, bool bStartListening
/* = true */)
115 CLockObject
lock(m_mutex
);
116 if (m_communication
&& m_communication
->IsOpen())
118 m_libcec
->AddLog(CEC_LOG_ERROR
, "connection already opened");
121 else if (!m_communication
)
122 m_communication
= new CUSBCECAdapterCommunication(this, strPort
, iBaudRate
);
125 CTimeout
timeout(iTimeoutMs
> 0 ? iTimeoutMs
: CEC_DEFAULT_TRANSMIT_WAIT
);
127 /* open a new connection */
128 unsigned iConnectTry(0);
129 while (timeout
.TimeLeft() > 0 && (bReturn
= m_communication
->Open((timeout
.TimeLeft() / CEC_CONNECT_TRIES
), false, bStartListening
)) == false)
131 m_libcec
->AddLog(CEC_LOG_ERROR
, "could not open a connection (try %d)", ++iConnectTry
);
132 m_communication
->Close();
133 CEvent::Sleep(CEC_DEFAULT_CONNECT_RETRY_WAIT
);
136 m_libcec
->AddLog(CEC_LOG_NOTICE
, "connection opened");
141 bool CCECProcessor::CECInitialised(void)
143 CLockObject
lock(m_threadMutex
);
144 return m_bInitialised
;
147 void CCECProcessor::SetCECInitialised(bool bSetTo
/* = true */)
149 CLockObject
lock(m_mutex
);
150 m_bInitialised
= bSetTo
;
155 bool CCECProcessor::TryLogicalAddress(cec_logical_address address
)
157 CCECBusDevice
*device
= m_busDevices
->At(address
);
160 if (device
->IsPresent() || device
->IsHandledByLibCEC())
164 return device
->TryLogicalAddress();
170 void CCECProcessor::ReplaceHandlers(void)
172 if (!CECInitialised())
175 for (CECDEVICEMAP::iterator it
= m_busDevices
->Begin(); it
!= m_busDevices
->End(); it
++)
176 it
->second
->ReplaceHandler(true);
179 bool CCECProcessor::OnCommandReceived(const cec_command
&command
)
181 return m_inBuffer
.Push(command
);
184 void *CCECProcessor::Process(void)
186 m_libcec
->AddLog(CEC_LOG_DEBUG
, "processor thread started");
191 while (!IsStopped() && m_communication
->IsOpen())
193 if (m_inBuffer
.Pop(command
, CEC_PROCESSOR_SIGNAL_WAIT_TIME
))
194 ParseCommand(command
);
196 if (CECInitialised())
200 m_libcec
->CheckKeypressTimeout();
207 bool CCECProcessor::SetActiveSource(uint16_t iStreamPath
)
211 CCECBusDevice
*device
= GetDeviceByPhysicalAddress(iStreamPath
);
213 bReturn
= device
->ActivateSource();
215 m_libcec
->AddLog(CEC_LOG_DEBUG
, "device with PA '%04x' not found", iStreamPath
);
220 void CCECProcessor::SetStandardLineTimeout(uint8_t iTimeout
)
222 CLockObject
lock(m_mutex
);
223 m_iStandardLineTimeout
= iTimeout
;
226 void CCECProcessor::SetRetryLineTimeout(uint8_t iTimeout
)
228 CLockObject
lock(m_mutex
);
229 m_iRetryLineTimeout
= iTimeout
;
232 bool CCECProcessor::PhysicalAddressInUse(uint16_t iPhysicalAddress
)
234 CCECBusDevice
*device
= GetDeviceByPhysicalAddress(iPhysicalAddress
);
235 return device
!= NULL
;
238 void CCECProcessor::LogOutput(const cec_command
&data
)
241 strTx
.Format("<< %02x", ((uint8_t)data
.initiator
<< 4) + (uint8_t)data
.destination
);
243 strTx
.AppendFormat(":%02x", (uint8_t)data
.opcode
);
245 for (uint8_t iPtr
= 0; iPtr
< data
.parameters
.size
; iPtr
++)
246 strTx
.AppendFormat(":%02x", data
.parameters
[iPtr
]);
247 m_libcec
->AddLog(CEC_LOG_TRAFFIC
, strTx
.c_str());
250 bool CCECProcessor::SwitchMonitoring(bool bEnable
)
252 m_libcec
->AddLog(CEC_LOG_NOTICE
, "== %s monitoring mode ==", bEnable
? "enabling" : "disabling");
255 CLockObject
lock(m_mutex
);
256 m_bMonitor
= bEnable
;
257 m_iPreviousAckMask
= m_communication
->GetAckMask();
261 return SetAckMask(0);
263 return SetAckMask(m_iPreviousAckMask
);
266 bool CCECProcessor::PollDevice(cec_logical_address iAddress
)
268 CCECBusDevice
*device
= m_busDevices
->At(iAddress
);
269 CCECBusDevice
*primary
= GetPrimaryDevice();
273 primary
->TransmitPoll(iAddress
) :
274 device
->TransmitPoll(iAddress
);
279 CCECBusDevice
*CCECProcessor::GetDeviceByPhysicalAddress(uint16_t iPhysicalAddress
, bool bSuppressUpdate
/* = true */)
281 return m_busDevices
?
282 m_busDevices
->GetDeviceByPhysicalAddress(iPhysicalAddress
, bSuppressUpdate
) :
286 CCECBusDevice
*CCECProcessor::GetDevice(cec_logical_address address
) const
288 return m_busDevices
?
289 m_busDevices
->At(address
) :
293 cec_logical_address
CCECProcessor::GetActiveSource(bool bRequestActiveSource
/* = true */)
295 // get the device that is marked as active source from the device map
296 CCECBusDevice
*activeSource
= m_busDevices
->GetActiveSource();
298 return activeSource
->GetLogicalAddress();
300 if (bRequestActiveSource
)
302 // request the active source from the bus
303 CCECBusDevice
*primary
= GetPrimaryDevice();
306 primary
->RequestActiveSource();
307 return GetActiveSource(false);
312 return CECDEVICE_UNKNOWN
;
315 bool CCECProcessor::IsActiveSource(cec_logical_address iAddress
)
317 CCECBusDevice
*device
= m_busDevices
->At(iAddress
);
318 return device
&& device
->IsActiveSource();
321 bool CCECProcessor::Transmit(const cec_command
&data
)
323 CCECBusDevice
*initiator
= m_busDevices
->At(data
.initiator
);
326 m_libcec
->AddLog(CEC_LOG_WARNING
, "invalid initiator");
330 if (data
.destination
!= CECDEVICE_BROADCAST
)
332 CCECBusDevice
*destination
= m_busDevices
->At(data
.destination
);
333 if (destination
&& destination
->IsHandledByLibCEC())
335 m_libcec
->AddLog(CEC_LOG_WARNING
, "not sending data to myself!");
340 uint8_t iMaxTries(0);
342 CLockObject
lock(m_mutex
);
346 m_iLastTransmission
= GetTimeMs();
347 if (!m_communication
|| !m_communication
->IsOpen())
349 m_libcec
->AddLog(CEC_LOG_ERROR
, "cannot transmit command: connection closed");
352 iMaxTries
= initiator
->GetHandler()->GetTransmitRetries() + 1;
357 uint8_t iLineTimeout
= m_iStandardLineTimeout
;
358 cec_adapter_message_state adapterState
= ADAPTER_MESSAGE_STATE_UNKNOWN
;
360 while (bRetry
&& ++iTries
< iMaxTries
)
362 if (initiator
->IsUnsupportedFeature(data
.opcode
))
365 adapterState
= m_communication
->Write(data
, bRetry
, iLineTimeout
);
366 iLineTimeout
= m_iRetryLineTimeout
;
369 return adapterState
== ADAPTER_MESSAGE_STATE_SENT_ACKED
;
372 void CCECProcessor::TransmitAbort(cec_logical_address source
, cec_logical_address destination
, cec_opcode opcode
, cec_abort_reason reason
/* = CEC_ABORT_REASON_UNRECOGNIZED_OPCODE */)
374 m_libcec
->AddLog(CEC_LOG_DEBUG
, "<< transmitting abort message");
377 cec_command::Format(command
, source
, destination
, CEC_OPCODE_FEATURE_ABORT
);
378 command
.parameters
.PushBack((uint8_t)opcode
);
379 command
.parameters
.PushBack((uint8_t)reason
);
384 void CCECProcessor::ParseCommand(const cec_command
&command
)
387 dataStr
.Format(">> %1x%1x", command
.initiator
, command
.destination
);
388 if (command
.opcode_set
== 1)
389 dataStr
.AppendFormat(":%02x", command
.opcode
);
390 for (uint8_t iPtr
= 0; iPtr
< command
.parameters
.size
; iPtr
++)
391 dataStr
.AppendFormat(":%02x", (unsigned int)command
.parameters
[iPtr
]);
392 m_libcec
->AddLog(CEC_LOG_TRAFFIC
, dataStr
.c_str());
396 CCECBusDevice
*device
= m_busDevices
->At(command
.initiator
);
398 device
->HandleCommand(command
);
402 bool CCECProcessor::IsPresentDevice(cec_logical_address address
)
404 CCECBusDevice
*device
= m_busDevices
->At(address
);
405 return device
&& device
->GetStatus() == CEC_DEVICE_STATUS_PRESENT
;
408 bool CCECProcessor::IsPresentDeviceType(cec_device_type type
)
410 CECDEVICEVEC devices
;
411 m_busDevices
->GetByType(type
, devices
);
412 CCECDeviceMap::FilterActive(devices
);
413 return !devices
.empty();
416 uint16_t CCECProcessor::GetDetectedPhysicalAddress(void) const
418 return m_communication
? m_communication
->GetPhysicalAddress() : CEC_INVALID_PHYSICAL_ADDRESS
;
421 bool CCECProcessor::SetAckMask(uint16_t iMask
)
423 return m_communication
? m_communication
->SetAckMask(iMask
) : false;
426 bool CCECProcessor::StandbyDevices(const cec_logical_address initiator
, const CECDEVICEVEC
&devices
)
429 for (CECDEVICEVEC::const_iterator it
= devices
.begin(); it
!= devices
.end(); it
++)
430 bReturn
&= (*it
)->Standby(initiator
);
434 bool CCECProcessor::StandbyDevice(const cec_logical_address initiator
, cec_logical_address address
)
436 CCECBusDevice
*device
= m_busDevices
->At(address
);
437 return device
? device
->Standby(initiator
) : false;
440 bool CCECProcessor::PowerOnDevices(const cec_logical_address initiator
, const CECDEVICEVEC
&devices
)
443 for (CECDEVICEVEC::const_iterator it
= devices
.begin(); it
!= devices
.end(); it
++)
444 bReturn
&= (*it
)->PowerOn(initiator
);
448 bool CCECProcessor::PowerOnDevice(const cec_logical_address initiator
, cec_logical_address address
)
450 CCECBusDevice
*device
= m_busDevices
->At(address
);
451 return device
? device
->PowerOn(initiator
) : false;
454 bool CCECProcessor::StartBootloader(const char *strPort
/* = NULL */)
457 if (!m_communication
&& strPort
)
459 IAdapterCommunication
*comm
= new CUSBCECAdapterCommunication(this, strPort
);
460 CTimeout
timeout(CEC_DEFAULT_CONNECT_TIMEOUT
);
462 while (timeout
.TimeLeft() > 0 && (bReturn
= comm
->Open(timeout
.TimeLeft() / CEC_CONNECT_TRIES
, true)) == false)
464 m_libcec
->AddLog(CEC_LOG_ERROR
, "could not open a connection (try %d)", ++iConnectTry
);
466 Sleep(CEC_DEFAULT_TRANSMIT_RETRY_WAIT
);
470 bReturn
= comm
->StartBootloader();
477 m_communication
->StartBootloader();
485 bool CCECProcessor::PingAdapter(void)
487 return m_communication
->PingAdapter();
490 void CCECProcessor::HandlePoll(cec_logical_address initiator
, cec_logical_address destination
)
492 CCECBusDevice
*device
= m_busDevices
->At(destination
);
494 device
->HandlePollFrom(initiator
);
497 bool CCECProcessor::HandleReceiveFailed(cec_logical_address initiator
)
499 CCECBusDevice
*device
= m_busDevices
->At(initiator
);
500 return !device
|| !device
->HandleReceiveFailed();
503 bool CCECProcessor::SetStreamPath(uint16_t iPhysicalAddress
)
505 // stream path changes are sent by the TV
506 return GetTV()->GetHandler()->TransmitSetStreamPath(iPhysicalAddress
);
509 bool CCECProcessor::CanPersistConfiguration(void)
511 return m_communication
? m_communication
->GetFirmwareVersion() >= 2 : false;
514 bool CCECProcessor::PersistConfiguration(libcec_configuration
*configuration
)
516 return m_communication
? m_communication
->PersistConfiguration(configuration
) : false;
519 void CCECProcessor::RescanActiveDevices(void)
521 for (CECDEVICEMAP::iterator it
= m_busDevices
->Begin(); it
!= m_busDevices
->End(); it
++)
522 it
->second
->GetStatus(true);
525 bool CCECProcessor::GetDeviceInformation(const char *strPort
, libcec_configuration
*config
, uint32_t iTimeoutMs
/* = CEC_DEFAULT_CONNECT_TIMEOUT */)
527 if (!OpenConnection(strPort
, CEC_SERIAL_DEFAULT_BAUDRATE
, iTimeoutMs
, false))
530 config
->iFirmwareVersion
= m_communication
->GetFirmwareVersion();
531 config
->iPhysicalAddress
= m_communication
->GetPhysicalAddress();
532 config
->iFirmwareBuildDate
= m_communication
->GetFirmwareBuildDate();
537 bool CCECProcessor::TransmitPendingActiveSourceCommands(void)
540 for (CECDEVICEMAP::iterator it
= m_busDevices
->Begin(); it
!= m_busDevices
->End(); it
++)
541 bReturn
&= it
->second
->TransmitPendingActiveSourceCommands();
545 CCECTV
*CCECProcessor::GetTV(void) const
547 return CCECBusDevice::AsTV(m_busDevices
->At(CECDEVICE_TV
));
550 CCECAudioSystem
*CCECProcessor::GetAudioSystem(void) const
552 return CCECBusDevice::AsAudioSystem(m_busDevices
->At(CECDEVICE_AUDIOSYSTEM
));
555 CCECPlaybackDevice
*CCECProcessor::GetPlaybackDevice(cec_logical_address address
) const
557 return CCECBusDevice::AsPlaybackDevice(m_busDevices
->At(address
));
560 CCECRecordingDevice
*CCECProcessor::GetRecordingDevice(cec_logical_address address
) const
562 return CCECBusDevice::AsRecordingDevice(m_busDevices
->At(address
));
565 CCECTuner
*CCECProcessor::GetTuner(cec_logical_address address
) const
567 return CCECBusDevice::AsTuner(m_busDevices
->At(address
));
570 bool CCECProcessor::RegisterClient(CCECClient
*client
)
575 libcec_configuration
&configuration
= *client
->GetConfiguration();
576 m_libcec
->AddLog(CEC_LOG_NOTICE
, "registering new CEC client - v%s", ToString((cec_client_version
)configuration
.clientVersion
));
578 client
->SetRegistered(false);
579 client
->SetInitialised(false);
581 uint16_t iPreviousMask(m_communication
->GetAckMask());
583 // find logical addresses for this client
584 if (!client
->FindLogicalAddresses())
586 SetAckMask(iPreviousMask
);
590 // register this client on the new addresses
591 CECDEVICEVEC devices
;
592 m_busDevices
->GetByLogicalAddresses(devices
, configuration
.logicalAddresses
);
593 for (CECDEVICEVEC::const_iterator it
= devices
.begin(); it
!= devices
.end(); it
++)
595 CLockObject
lock(m_mutex
);
596 m_clients
.erase((*it
)->GetLogicalAddress());
597 m_clients
.insert(make_pair
<cec_logical_address
, CCECClient
*>((*it
)->GetLogicalAddress(), client
));
598 client
->SetRegistered(true);
601 // get the settings from the rom
602 if (configuration
.bGetSettingsFromROM
== 1)
604 libcec_configuration config
;
605 m_communication
->GetConfiguration(&config
);
607 CLockObject
lock(m_mutex
);
608 if (!config
.deviceTypes
.IsEmpty())
609 configuration
.deviceTypes
= config
.deviceTypes
;
610 if (CLibCEC::IsValidPhysicalAddress(config
.iPhysicalAddress
))
611 configuration
.iPhysicalAddress
= config
.iPhysicalAddress
;
612 snprintf(configuration
.strDeviceName
, 13, "%s", config
.strDeviceName
);
615 // set the new ack mask
616 bool bReturn
= SetAckMask(GetLogicalAddresses().AckMask()) &&
617 client
->Initialise();
619 // set the firmware version and build date
620 configuration
.iFirmwareVersion
= m_communication
->GetFirmwareVersion();
621 configuration
.iFirmwareBuildDate
= m_communication
->GetFirmwareBuildDate();
625 strLog
= "CEC client registered.";
627 strLog
= "failed to register the CEC client.";
628 strLog
.AppendFormat(" libCEC version = %s, client version = %s, firmware version = %d", ToString((cec_server_version
)configuration
.serverVersion
), ToString((cec_client_version
)configuration
.clientVersion
), configuration
.iFirmwareVersion
);
629 if (configuration
.iFirmwareBuildDate
!= CEC_FW_BUILD_UNKNOWN
)
631 time_t buildTime
= (time_t)configuration
.iFirmwareBuildDate
;
632 strLog
.AppendFormat(", firmware build date: %s", asctime(gmtime(&buildTime
)));
633 strLog
= strLog
.Left((int)strLog
.length() - 1); // strip \n added by asctime
634 strLog
.append(" +0000");
637 m_libcec
->AddLog(bReturn
? CEC_LOG_NOTICE
: CEC_LOG_ERROR
, strLog
);
641 strLog
= "Using logical address(es): ";
642 CECDEVICEVEC devices
;
643 m_busDevices
->GetByLogicalAddresses(devices
, configuration
.logicalAddresses
);
644 for (CECDEVICEVEC::iterator it
= devices
.begin(); it
!= devices
.end(); it
++)
645 strLog
.AppendFormat("%s (%X) ", (*it
)->GetLogicalAddressName(), (*it
)->GetLogicalAddress());
646 m_libcec
->AddLog(CEC_LOG_NOTICE
, strLog
);
649 // display a warning if the firmware can be upgraded
650 if (!m_communication
->IsRunningLatestFirmware())
652 const char *strUpgradeMessage
= "The firmware of this adapter can be upgraded. Please visit http://blog.pulse-eight.com/ for more information.";
653 m_libcec
->AddLog(CEC_LOG_WARNING
, strUpgradeMessage
);
654 client
->Alert(CEC_ALERT_SERVICE_DEVICE
, libcec_parameter(strUpgradeMessage
));
658 m_libcec
->AddLog(CEC_LOG_DEBUG
, "the adapter is using the latest (known) firmware version");
663 /* get the vendor id from the TV, so we are using the correct handler */
664 GetTV()->GetVendorId(configuration
.logicalAddresses
.primary
);
670 void CCECProcessor::UnregisterClient(CCECClient
*client
)
672 CLockObject
lock(m_mutex
);
673 libcec_configuration
&configuration
= *client
->GetConfiguration();
674 CECDEVICEVEC devices
;
675 m_busDevices
->GetByLogicalAddresses(devices
, configuration
.logicalAddresses
);
676 for (CECDEVICEVEC::const_iterator it
= devices
.begin(); it
!= devices
.end(); it
++)
678 map
<cec_logical_address
, CCECClient
*>::iterator entry
= m_clients
.find((*it
)->GetLogicalAddress());
679 if (entry
!= m_clients
.end())
680 m_clients
.erase(entry
);
684 void CCECProcessor::UnregisterClients(void)
686 CLockObject
lock(m_mutex
);
687 for (map
<cec_logical_address
, CCECClient
*>::iterator client
= m_clients
.begin(); client
!= m_clients
.end(); client
++)
688 client
->second
->OnUnregister();
692 CCECClient
*CCECProcessor::GetClient(const cec_logical_address address
)
694 CLockObject
lock(m_mutex
);
695 map
<cec_logical_address
, CCECClient
*>::const_iterator client
= m_clients
.find(address
);
696 if (client
!= m_clients
.end())
697 return client
->second
;
701 CCECClient
*CCECProcessor::GetPrimaryClient(void)
703 CLockObject
lock(m_mutex
);
704 map
<cec_logical_address
, CCECClient
*>::const_iterator client
= m_clients
.begin();
705 if (client
!= m_clients
.end())
706 return client
->second
;
710 CCECBusDevice
*CCECProcessor::GetPrimaryDevice(void) const
712 return m_busDevices
->At(GetLogicalAddress());
715 cec_logical_address
CCECProcessor::GetLogicalAddress(void) const
717 cec_logical_addresses addresses
= GetLogicalAddresses();
718 return addresses
.primary
;
721 cec_logical_addresses
CCECProcessor::GetLogicalAddresses(void) const
723 cec_logical_addresses addresses
;
724 for (map
<cec_logical_address
, CCECClient
*>::const_iterator client
= m_clients
.begin(); client
!= m_clients
.end(); client
++)
725 addresses
.Set(client
->first
);
730 bool CCECProcessor::IsHandledByLibCEC(const cec_logical_address address
) const
732 CCECBusDevice
*device
= GetDevice(address
);
733 return device
&& device
->IsHandledByLibCEC();