cec: ensure that the command handler of the tv is replaced before registering a clien...
[deb_libcec.git] / src / lib / CECProcessor.cpp
... / ...
CommitLineData
1/*
2 * This file is part of the libCEC(R) library.
3 *
4 * libCEC(R) is Copyright (C) 2011-2012 Pulse-Eight Limited. All rights reserved.
5 * libCEC(R) is an original work, containing original code.
6 *
7 * libCEC(R) is a trademark of Pulse-Eight Limited.
8 *
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.
13 *
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.
18 *
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.
22 *
23 *
24 * Alternatively, you can license this library under a commercial license,
25 * please contact Pulse-Eight Licensing for more information.
26 *
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/
31 */
32
33#include "env.h"
34#include "CECProcessor.h"
35
36#include "adapter/AdapterFactory.h"
37#include "devices/CECBusDevice.h"
38#include "devices/CECAudioSystem.h"
39#include "devices/CECPlaybackDevice.h"
40#include "devices/CECRecordingDevice.h"
41#include "devices/CECTuner.h"
42#include "devices/CECTV.h"
43#include "implementations/CECCommandHandler.h"
44#include "LibCEC.h"
45#include "CECClient.h"
46#include "CECTypeUtils.h"
47#include "platform/util/timeutils.h"
48#include "platform/util/util.h"
49
50using namespace CEC;
51using namespace std;
52using namespace PLATFORM;
53
54#define CEC_PROCESSOR_SIGNAL_WAIT_TIME 1000
55#define ACTIVE_SOURCE_CHECK_INTERVAL 500
56
57#define ToString(x) CCECTypeUtils::ToString(x)
58
59CCECProcessor::CCECProcessor(CLibCEC *libcec) :
60 m_bInitialised(false),
61 m_communication(NULL),
62 m_libcec(libcec),
63 m_iStandardLineTimeout(3),
64 m_iRetryLineTimeout(3),
65 m_iLastTransmission(0)
66{
67 m_busDevices = new CCECDeviceMap(this);
68}
69
70CCECProcessor::~CCECProcessor(void)
71{
72 Close();
73 DELETE_AND_NULL(m_busDevices);
74}
75
76bool CCECProcessor::Start(const char *strPort, uint16_t iBaudRate /* = CEC_SERIAL_DEFAULT_BAUDRATE */, uint32_t iTimeoutMs /* = CEC_DEFAULT_CONNECT_TIMEOUT */)
77{
78 CLockObject lock(m_mutex);
79 // open a connection
80 if (!OpenConnection(strPort, iBaudRate, iTimeoutMs))
81 return false;
82
83 // create the processor thread
84 if (!IsRunning())
85 {
86 if (!CreateThread())
87 {
88 m_libcec->AddLog(CEC_LOG_ERROR, "could not create a processor thread");
89 return false;
90 }
91 }
92
93 return true;
94}
95
96void CCECProcessor::Close(void)
97{
98 // mark as uninitialised
99 SetCECInitialised(false);
100
101 // stop the processor
102 StopThread();
103
104 // close the connection
105 DELETE_AND_NULL(m_communication);
106}
107
108void CCECProcessor::ResetMembers(void)
109{
110 // close the connection
111 DELETE_AND_NULL(m_communication);
112
113 // reset the other members to the initial state
114 m_iStandardLineTimeout = 3;
115 m_iRetryLineTimeout = 3;
116 m_iLastTransmission = 0;
117 m_busDevices->ResetDeviceStatus();
118}
119
120bool CCECProcessor::OpenConnection(const char *strPort, uint16_t iBaudRate, uint32_t iTimeoutMs, bool bStartListening /* = true */)
121{
122 bool bReturn(false);
123 CTimeout timeout(iTimeoutMs > 0 ? iTimeoutMs : CEC_DEFAULT_TRANSMIT_WAIT);
124
125 // ensure that a previous connection is closed
126 Close();
127
128 // reset all member to the initial state
129 ResetMembers();
130
131 // check whether the Close() method deleted any previous connection
132 if (m_communication)
133 {
134 m_libcec->AddLog(CEC_LOG_ERROR, "previous connection could not be closed");
135 return bReturn;
136 }
137
138 // create a new connection
139 m_communication = CAdapterFactory(this->m_libcec).GetInstance(strPort, iBaudRate);
140
141 // open a new connection
142 unsigned iConnectTry(0);
143 while (timeout.TimeLeft() > 0 && (bReturn = m_communication->Open((timeout.TimeLeft() / CEC_CONNECT_TRIES), false, bStartListening)) == false)
144 {
145 m_libcec->AddLog(CEC_LOG_ERROR, "could not open a connection (try %d)", ++iConnectTry);
146 m_communication->Close();
147 CEvent::Sleep(CEC_DEFAULT_CONNECT_RETRY_WAIT);
148 }
149
150 m_libcec->AddLog(CEC_LOG_NOTICE, "connection opened");
151
152 // mark as initialised
153 SetCECInitialised(true);
154
155 return bReturn;
156}
157
158bool CCECProcessor::CECInitialised(void)
159{
160 CLockObject lock(m_threadMutex);
161 return m_bInitialised;
162}
163
164void CCECProcessor::SetCECInitialised(bool bSetTo /* = true */)
165{
166 {
167 CLockObject lock(m_mutex);
168 m_bInitialised = bSetTo;
169 }
170 if (!bSetTo)
171 UnregisterClients();
172}
173
174bool CCECProcessor::TryLogicalAddress(cec_logical_address address, cec_version libCECSpecVersion /* = CEC_VERSION_1_4 */)
175{
176 // find the device
177 CCECBusDevice *device = m_busDevices->At(address);
178 if (device)
179 {
180 // check if it's already marked as present or used
181 if (device->IsPresent() || device->IsHandledByLibCEC())
182 return false;
183
184 // poll the LA if not
185 return device->TryLogicalAddress(libCECSpecVersion);
186 }
187
188 return false;
189}
190
191void CCECProcessor::ReplaceHandlers(void)
192{
193 if (!CECInitialised())
194 return;
195
196 // check each device
197 for (CECDEVICEMAP::iterator it = m_busDevices->Begin(); it != m_busDevices->End(); it++)
198 it->second->ReplaceHandler(true);
199}
200
201bool CCECProcessor::OnCommandReceived(const cec_command &command)
202{
203 return m_inBuffer.Push(command);
204}
205
206void *CCECProcessor::Process(void)
207{
208 m_libcec->AddLog(CEC_LOG_DEBUG, "processor thread started");
209
210 cec_command command; command.Clear();
211 CTimeout activeSourceCheck(ACTIVE_SOURCE_CHECK_INTERVAL);
212
213 // as long as we're not being stopped and the connection is open
214 while (!IsStopped() && m_communication->IsOpen())
215 {
216 // wait for a new incoming command, and process it
217 if (m_inBuffer.Pop(command, CEC_PROCESSOR_SIGNAL_WAIT_TIME))
218 ProcessCommand(command);
219
220 if (CECInitialised())
221 {
222 // check clients for keypress timeouts
223 m_libcec->CheckKeypressTimeout();
224
225 // check if we need to replace handlers
226 ReplaceHandlers();
227
228 // check whether we need to activate a source, if it failed before
229 if (activeSourceCheck.TimeLeft() == 0)
230 {
231 if (CECInitialised())
232 TransmitPendingActiveSourceCommands();
233 activeSourceCheck.Init(ACTIVE_SOURCE_CHECK_INTERVAL);
234 }
235 }
236 }
237
238 return NULL;
239}
240
241bool CCECProcessor::ActivateSource(uint16_t iStreamPath)
242{
243 bool bReturn(false);
244
245 // find the device with the given PA
246 CCECBusDevice *device = GetDeviceByPhysicalAddress(iStreamPath);
247 // and make it the active source when found
248 if (device)
249 bReturn = device->ActivateSource();
250 else
251 m_libcec->AddLog(CEC_LOG_DEBUG, "device with PA '%04x' not found", iStreamPath);
252
253 return bReturn;
254}
255
256void CCECProcessor::SetStandardLineTimeout(uint8_t iTimeout)
257{
258 CLockObject lock(m_mutex);
259 m_iStandardLineTimeout = iTimeout;
260}
261
262uint8_t CCECProcessor::GetStandardLineTimeout(void)
263{
264 CLockObject lock(m_mutex);
265 return m_iStandardLineTimeout;
266}
267
268void CCECProcessor::SetRetryLineTimeout(uint8_t iTimeout)
269{
270 CLockObject lock(m_mutex);
271 m_iRetryLineTimeout = iTimeout;
272}
273
274uint8_t CCECProcessor::GetRetryLineTimeout(void)
275{
276 CLockObject lock(m_mutex);
277 return m_iRetryLineTimeout;
278}
279
280bool CCECProcessor::PhysicalAddressInUse(uint16_t iPhysicalAddress)
281{
282 CCECBusDevice *device = GetDeviceByPhysicalAddress(iPhysicalAddress);
283 return device != NULL;
284}
285
286void CCECProcessor::LogOutput(const cec_command &data)
287{
288 CStdString strTx;
289
290 // initiator and destination
291 strTx.Format("<< %02x", ((uint8_t)data.initiator << 4) + (uint8_t)data.destination);
292
293 // append the opcode
294 if (data.opcode_set)
295 strTx.AppendFormat(":%02x", (uint8_t)data.opcode);
296
297 // append the parameters
298 for (uint8_t iPtr = 0; iPtr < data.parameters.size; iPtr++)
299 strTx.AppendFormat(":%02x", data.parameters[iPtr]);
300
301 // and log it
302 m_libcec->AddLog(CEC_LOG_TRAFFIC, strTx.c_str());
303}
304
305bool CCECProcessor::PollDevice(cec_logical_address iAddress)
306{
307 // try to find the primary device
308 CCECBusDevice *primary = GetPrimaryDevice();
309 // poll the destination, with the primary as source
310 if (primary)
311 return primary->TransmitPoll(iAddress, false);
312
313 CCECBusDevice *device = m_busDevices->At(CECDEVICE_UNREGISTERED);
314 if (device)
315 return device->TransmitPoll(iAddress, false);
316
317 return false;
318}
319
320CCECBusDevice *CCECProcessor::GetDeviceByPhysicalAddress(uint16_t iPhysicalAddress, bool bSuppressUpdate /* = true */)
321{
322 return m_busDevices ?
323 m_busDevices->GetDeviceByPhysicalAddress(iPhysicalAddress, bSuppressUpdate) :
324 NULL;
325}
326
327CCECBusDevice *CCECProcessor::GetDevice(cec_logical_address address) const
328{
329 return m_busDevices ?
330 m_busDevices->At(address) :
331 NULL;
332}
333
334cec_logical_address CCECProcessor::GetActiveSource(bool bRequestActiveSource /* = true */)
335{
336 // get the device that is marked as active source from the device map
337 CCECBusDevice *activeSource = m_busDevices->GetActiveSource();
338 if (activeSource)
339 return activeSource->GetLogicalAddress();
340
341 if (bRequestActiveSource)
342 {
343 // request the active source from the bus
344 CCECBusDevice *primary = GetPrimaryDevice();
345 if (primary)
346 {
347 primary->RequestActiveSource();
348 return GetActiveSource(false);
349 }
350 }
351
352 // unknown or none
353 return CECDEVICE_UNKNOWN;
354}
355
356bool CCECProcessor::IsActiveSource(cec_logical_address iAddress)
357{
358 CCECBusDevice *device = m_busDevices->At(iAddress);
359 return device && device->IsActiveSource();
360}
361
362bool CCECProcessor::Transmit(const cec_command &data, bool bIsReply)
363{
364 cec_command transmitData(data);
365 uint8_t iMaxTries(0);
366 bool bRetry(true);
367 uint8_t iTries(0);
368
369 // get the current timeout setting
370 uint8_t iLineTimeout(GetStandardLineTimeout());
371
372 // reset the state of this message to 'unknown'
373 cec_adapter_message_state adapterState = ADAPTER_MESSAGE_STATE_UNKNOWN;
374
375 if (!m_communication->SupportsSourceLogicalAddress(transmitData.initiator))
376 {
377 if (transmitData.initiator == CECDEVICE_UNREGISTERED && m_communication->SupportsSourceLogicalAddress(CECDEVICE_FREEUSE))
378 {
379 m_libcec->AddLog(CEC_LOG_DEBUG, "initiator '%s' is not supported by the CEC adapter. using '%s' instead", ToString(transmitData.initiator), ToString(CECDEVICE_FREEUSE));
380 transmitData.initiator = CECDEVICE_FREEUSE;
381 }
382 else
383 {
384 m_libcec->AddLog(CEC_LOG_DEBUG, "initiator '%s' is not supported by the CEC adapter", ToString(transmitData.initiator));
385 return false;
386 }
387 }
388
389 LogOutput(transmitData);
390
391 // find the initiator device
392 CCECBusDevice *initiator = m_busDevices->At(transmitData.initiator);
393 if (!initiator)
394 {
395 m_libcec->AddLog(CEC_LOG_WARNING, "invalid initiator");
396 return false;
397 }
398
399 // find the destination device, if it's not the broadcast address
400 if (transmitData.destination != CECDEVICE_BROADCAST)
401 {
402 // check if the device is marked as handled by libCEC
403 CCECBusDevice *destination = m_busDevices->At(transmitData.destination);
404 if (destination && destination->IsHandledByLibCEC())
405 {
406 // and reject the command if it's trying to send data to a device that is handled by libCEC
407 m_libcec->AddLog(CEC_LOG_WARNING, "not sending data to myself!");
408 return false;
409 }
410 }
411
412 {
413 CLockObject lock(m_mutex);
414 m_iLastTransmission = GetTimeMs();
415 // set the number of tries
416 iMaxTries = initiator->GetHandler()->GetTransmitRetries() + 1;
417 initiator->MarkHandlerReady();
418 }
419
420 // and try to send the command
421 while (bRetry && ++iTries < iMaxTries)
422 {
423 if (initiator->IsUnsupportedFeature(transmitData.opcode))
424 return false;
425
426 adapterState = !IsStopped() && m_communication && m_communication->IsOpen() ?
427 m_communication->Write(transmitData, bRetry, iLineTimeout, bIsReply) :
428 ADAPTER_MESSAGE_STATE_ERROR;
429 iLineTimeout = m_iRetryLineTimeout;
430 }
431
432 return adapterState == ADAPTER_MESSAGE_STATE_SENT_ACKED;
433}
434
435void CCECProcessor::TransmitAbort(cec_logical_address source, cec_logical_address destination, cec_opcode opcode, cec_abort_reason reason /* = CEC_ABORT_REASON_UNRECOGNIZED_OPCODE */)
436{
437 m_libcec->AddLog(CEC_LOG_DEBUG, "<< transmitting abort message");
438
439 cec_command command;
440 cec_command::Format(command, source, destination, CEC_OPCODE_FEATURE_ABORT);
441 command.parameters.PushBack((uint8_t)opcode);
442 command.parameters.PushBack((uint8_t)reason);
443
444 Transmit(command, true);
445}
446
447void CCECProcessor::ProcessCommand(const cec_command &command)
448{
449 // log the command
450 CStdString dataStr;
451 dataStr.Format(">> %1x%1x", command.initiator, command.destination);
452 if (command.opcode_set == 1)
453 dataStr.AppendFormat(":%02x", command.opcode);
454 for (uint8_t iPtr = 0; iPtr < command.parameters.size; iPtr++)
455 dataStr.AppendFormat(":%02x", (unsigned int)command.parameters[iPtr]);
456 m_libcec->AddLog(CEC_LOG_TRAFFIC, dataStr.c_str());
457
458 // find the initiator
459 CCECBusDevice *device = m_busDevices->At(command.initiator);
460
461 if (device)
462 device->HandleCommand(command);
463}
464
465bool CCECProcessor::IsPresentDevice(cec_logical_address address)
466{
467 CCECBusDevice *device = m_busDevices->At(address);
468 return device && device->GetStatus() == CEC_DEVICE_STATUS_PRESENT;
469}
470
471bool CCECProcessor::IsPresentDeviceType(cec_device_type type)
472{
473 CECDEVICEVEC devices;
474 m_busDevices->GetByType(type, devices);
475 CCECDeviceMap::FilterActive(devices);
476 return !devices.empty();
477}
478
479uint16_t CCECProcessor::GetDetectedPhysicalAddress(void) const
480{
481 return m_communication ? m_communication->GetPhysicalAddress() : CEC_INVALID_PHYSICAL_ADDRESS;
482}
483
484bool CCECProcessor::ClearLogicalAddresses(void)
485{
486 cec_logical_addresses addresses; addresses.Clear();
487 return SetLogicalAddresses(addresses);
488}
489
490bool CCECProcessor::SetLogicalAddresses(const cec_logical_addresses &addresses)
491{
492 return m_communication ? m_communication->SetLogicalAddresses(addresses) : false;
493}
494
495bool CCECProcessor::StandbyDevices(const cec_logical_address initiator, const CECDEVICEVEC &devices)
496{
497 bool bReturn(true);
498 for (CECDEVICEVEC::const_iterator it = devices.begin(); it != devices.end(); it++)
499 bReturn &= (*it)->Standby(initiator);
500 return bReturn;
501}
502
503bool CCECProcessor::StandbyDevice(const cec_logical_address initiator, cec_logical_address address)
504{
505 CCECBusDevice *device = m_busDevices->At(address);
506 return device ? device->Standby(initiator) : false;
507}
508
509bool CCECProcessor::PowerOnDevices(const cec_logical_address initiator, const CECDEVICEVEC &devices)
510{
511 bool bReturn(true);
512 for (CECDEVICEVEC::const_iterator it = devices.begin(); it != devices.end(); it++)
513 bReturn &= (*it)->PowerOn(initiator);
514 return bReturn;
515}
516
517bool CCECProcessor::PowerOnDevice(const cec_logical_address initiator, cec_logical_address address)
518{
519 CCECBusDevice *device = m_busDevices->At(address);
520 return device ? device->PowerOn(initiator) : false;
521}
522
523bool CCECProcessor::StartBootloader(const char *strPort /* = NULL */)
524{
525 bool bReturn(false);
526 // open a connection if no connection has been opened
527 if (!m_communication && strPort)
528 {
529 CAdapterFactory factory(this->m_libcec);
530 IAdapterCommunication *comm = factory.GetInstance(strPort);
531 CTimeout timeout(CEC_DEFAULT_CONNECT_TIMEOUT);
532 int iConnectTry(0);
533 while (timeout.TimeLeft() > 0 && (bReturn = comm->Open(timeout.TimeLeft() / CEC_CONNECT_TRIES, true)) == false)
534 {
535 m_libcec->AddLog(CEC_LOG_ERROR, "could not open a connection (try %d)", ++iConnectTry);
536 comm->Close();
537 Sleep(CEC_DEFAULT_TRANSMIT_RETRY_WAIT);
538 }
539 if (comm->IsOpen())
540 {
541 bReturn = comm->StartBootloader();
542 DELETE_AND_NULL(comm);
543 }
544 return bReturn;
545 }
546 else
547 {
548 m_communication->StartBootloader();
549 Close();
550 bReturn = true;
551 }
552
553 return bReturn;
554}
555
556bool CCECProcessor::PingAdapter(void)
557{
558 return m_communication->PingAdapter();
559}
560
561void CCECProcessor::HandlePoll(cec_logical_address initiator, cec_logical_address destination)
562{
563 CCECBusDevice *device = m_busDevices->At(destination);
564 if (device)
565 device->HandlePollFrom(initiator);
566}
567
568bool CCECProcessor::HandleReceiveFailed(cec_logical_address initiator)
569{
570 CCECBusDevice *device = m_busDevices->At(initiator);
571 return !device || !device->HandleReceiveFailed();
572}
573
574bool CCECProcessor::CanPersistConfiguration(void)
575{
576 return m_communication ? m_communication->GetFirmwareVersion() >= 2 : false;
577}
578
579bool CCECProcessor::PersistConfiguration(const libcec_configuration &configuration)
580{
581 libcec_configuration persistConfiguration = configuration;
582 if (!CLibCEC::IsValidPhysicalAddress(configuration.iPhysicalAddress))
583 {
584 CCECBusDevice *device = GetPrimaryDevice();
585 if (device)
586 persistConfiguration.iPhysicalAddress = device->GetCurrentPhysicalAddress();
587 }
588
589 return m_communication ? m_communication->PersistConfiguration(persistConfiguration) : false;
590}
591
592void CCECProcessor::RescanActiveDevices(void)
593{
594 for (CECDEVICEMAP::iterator it = m_busDevices->Begin(); it != m_busDevices->End(); it++)
595 it->second->GetStatus(true);
596}
597
598bool CCECProcessor::GetDeviceInformation(const char *strPort, libcec_configuration *config, uint32_t iTimeoutMs /* = CEC_DEFAULT_CONNECT_TIMEOUT */)
599{
600 if (!OpenConnection(strPort, CEC_SERIAL_DEFAULT_BAUDRATE, iTimeoutMs, false))
601 return false;
602
603 config->iFirmwareVersion = m_communication->GetFirmwareVersion();
604 config->iPhysicalAddress = m_communication->GetPhysicalAddress();
605 config->iFirmwareBuildDate = m_communication->GetFirmwareBuildDate();
606
607 return true;
608}
609
610bool CCECProcessor::TransmitPendingActiveSourceCommands(void)
611{
612 bool bReturn(true);
613 for (CECDEVICEMAP::iterator it = m_busDevices->Begin(); it != m_busDevices->End(); it++)
614 bReturn &= it->second->TransmitPendingActiveSourceCommands();
615 return bReturn;
616}
617
618CCECTV *CCECProcessor::GetTV(void) const
619{
620 return CCECBusDevice::AsTV(m_busDevices->At(CECDEVICE_TV));
621}
622
623CCECAudioSystem *CCECProcessor::GetAudioSystem(void) const
624{
625 return CCECBusDevice::AsAudioSystem(m_busDevices->At(CECDEVICE_AUDIOSYSTEM));
626}
627
628CCECPlaybackDevice *CCECProcessor::GetPlaybackDevice(cec_logical_address address) const
629{
630 return CCECBusDevice::AsPlaybackDevice(m_busDevices->At(address));
631}
632
633CCECRecordingDevice *CCECProcessor::GetRecordingDevice(cec_logical_address address) const
634{
635 return CCECBusDevice::AsRecordingDevice(m_busDevices->At(address));
636}
637
638CCECTuner *CCECProcessor::GetTuner(cec_logical_address address) const
639{
640 return CCECBusDevice::AsTuner(m_busDevices->At(address));
641}
642
643bool CCECProcessor::RegisterClient(CCECClient *client)
644{
645 if (!client)
646 return false;
647
648 libcec_configuration &configuration = *client->GetConfiguration();
649
650 if (configuration.clientVersion >= CEC_CLIENT_VERSION_1_6_3 && configuration.bMonitorOnly == 1)
651 return true;
652
653 if (!CECInitialised())
654 {
655 m_libcec->AddLog(CEC_LOG_ERROR, "failed to register a new CEC client: CEC processor is not initialised");
656 return false;
657 }
658
659 // unregister the client first if it's already been marked as registered
660 if (client->IsRegistered())
661 UnregisterClient(client);
662
663 // ensure that controlled mode is enabled
664 m_communication->SetControlledMode(true);
665
666 // ensure that we know the vendor id of the TV
667 CCECBusDevice *tv = GetTV();
668 cec_vendor_id tvVendor = CEC_VENDOR_UNKNOWN;
669 if (m_communication->SupportsSourceLogicalAddress(CECDEVICE_UNREGISTERED))
670 tvVendor = tv->GetVendorId(CECDEVICE_UNREGISTERED);
671 else if (m_communication->SupportsSourceLogicalAddress(CECDEVICE_FREEUSE))
672 tvVendor = tv->GetVendorId(CECDEVICE_FREEUSE);
673 if (tvVendor != CEC_VENDOR_UNKNOWN)
674 tv->ReplaceHandler(false);
675
676 // get the configuration from the client
677 m_libcec->AddLog(CEC_LOG_NOTICE, "registering new CEC client - v%s", ToString((cec_client_version)configuration.clientVersion));
678
679 // mark as uninitialised and unregistered
680 client->SetRegistered(false);
681 client->SetInitialised(false);
682
683 // get the current ackmask, so we can restore it if polling fails
684 cec_logical_addresses previousMask = GetLogicalAddresses();
685
686 // find logical addresses for this client
687 if (!client->AllocateLogicalAddresses())
688 {
689 m_libcec->AddLog(CEC_LOG_ERROR, "failed to register the new CEC client - cannot allocate the requested device types");
690 SetLogicalAddresses(previousMask);
691 return false;
692 }
693
694 // register this client on the new addresses
695 CECDEVICEVEC devices;
696 m_busDevices->GetByLogicalAddresses(devices, configuration.logicalAddresses);
697 for (CECDEVICEVEC::const_iterator it = devices.begin(); it != devices.end(); it++)
698 {
699 // set the physical address of the device at this LA
700 if (CLibCEC::IsValidPhysicalAddress(configuration.iPhysicalAddress))
701 (*it)->SetPhysicalAddress(configuration.iPhysicalAddress);
702
703 // replace a previous client
704 CLockObject lock(m_mutex);
705 m_clients.erase((*it)->GetLogicalAddress());
706 m_clients.insert(make_pair<cec_logical_address, CCECClient *>((*it)->GetLogicalAddress(), client));
707 }
708
709 // get the settings from the rom
710 if (configuration.bGetSettingsFromROM == 1)
711 {
712 libcec_configuration config; config.Clear();
713 m_communication->GetConfiguration(config);
714
715 CLockObject lock(m_mutex);
716 if (!config.deviceTypes.IsEmpty())
717 configuration.deviceTypes = config.deviceTypes;
718 if (CLibCEC::IsValidPhysicalAddress(config.iPhysicalAddress))
719 configuration.iPhysicalAddress = config.iPhysicalAddress;
720 snprintf(configuration.strDeviceName, 13, "%s", config.strDeviceName);
721 }
722
723 // set the firmware version and build date
724 configuration.serverVersion = LIBCEC_VERSION_CURRENT;
725 configuration.iFirmwareVersion = m_communication->GetFirmwareVersion();
726 configuration.iFirmwareBuildDate = m_communication->GetFirmwareBuildDate();
727
728 // mark the client as registered
729 client->SetRegistered(true);
730
731 // set the new ack mask
732 bool bReturn = SetLogicalAddresses(GetLogicalAddresses()) &&
733 // and initialise the client
734 client->OnRegister();
735
736 // log the new registration
737 CStdString strLog;
738 strLog.Format("%s: %s", bReturn ? "CEC client registered" : "failed to register the CEC client", client->GetConnectionInfo().c_str());
739 m_libcec->AddLog(bReturn ? CEC_LOG_NOTICE : CEC_LOG_ERROR, strLog);
740
741 // display a warning if the firmware can be upgraded
742 if (bReturn && !IsRunningLatestFirmware())
743 {
744 const char *strUpgradeMessage = "The firmware of this adapter can be upgraded. Please visit http://blog.pulse-eight.com/ for more information.";
745 m_libcec->AddLog(CEC_LOG_WARNING, strUpgradeMessage);
746 libcec_parameter param;
747 param.paramData = (void*)strUpgradeMessage; param.paramType = CEC_PARAMETER_TYPE_STRING;
748 client->Alert(CEC_ALERT_SERVICE_DEVICE, param);
749 }
750
751 // ensure that the command handler for the TV is initialised
752 if (bReturn)
753 {
754 CCECCommandHandler *handler = GetTV()->GetHandler();
755 if (handler)
756 handler->InitHandler();
757 GetTV()->MarkHandlerReady();
758 }
759
760 return bReturn;
761}
762
763bool CCECProcessor::UnregisterClient(CCECClient *client)
764{
765 if (!client)
766 return false;
767
768 if (client->IsRegistered())
769 m_libcec->AddLog(CEC_LOG_NOTICE, "unregistering client: %s", client->GetConnectionInfo().c_str());
770
771 // notify the client that it will be unregistered
772 client->OnUnregister();
773
774 {
775 CLockObject lock(m_mutex);
776 // find all devices that match the LA's of this client
777 CECDEVICEVEC devices;
778 m_busDevices->GetByLogicalAddresses(devices, client->GetConfiguration()->logicalAddresses);
779 for (CECDEVICEVEC::const_iterator it = devices.begin(); it != devices.end(); it++)
780 {
781 // find the client
782 map<cec_logical_address, CCECClient *>::iterator entry = m_clients.find((*it)->GetLogicalAddress());
783 // unregister the client
784 if (entry != m_clients.end())
785 m_clients.erase(entry);
786
787 // reset the device status
788 (*it)->ResetDeviceStatus();
789 }
790 }
791
792 // set the new ackmask
793 cec_logical_addresses addresses = GetLogicalAddresses();
794 if (SetLogicalAddresses(addresses))
795 {
796 // no more clients left, disable controlled mode
797 if (addresses.IsEmpty())
798 m_communication->SetControlledMode(false);
799
800 return true;
801 }
802
803 return false;
804}
805
806void CCECProcessor::UnregisterClients(void)
807{
808 m_libcec->AddLog(CEC_LOG_NOTICE, "unregistering all CEC clients");
809
810 vector<CCECClient *> clients = m_libcec->GetClients();
811 for (vector<CCECClient *>::iterator client = clients.begin(); client != clients.end(); client++)
812 UnregisterClient(*client);
813
814 CLockObject lock(m_mutex);
815 m_clients.clear();
816}
817
818CCECClient *CCECProcessor::GetClient(const cec_logical_address address)
819{
820 CLockObject lock(m_mutex);
821 map<cec_logical_address, CCECClient *>::const_iterator client = m_clients.find(address);
822 if (client != m_clients.end())
823 return client->second;
824 return NULL;
825}
826
827CCECClient *CCECProcessor::GetPrimaryClient(void)
828{
829 CLockObject lock(m_mutex);
830 map<cec_logical_address, CCECClient *>::const_iterator client = m_clients.begin();
831 if (client != m_clients.end())
832 return client->second;
833 return NULL;
834}
835
836CCECBusDevice *CCECProcessor::GetPrimaryDevice(void)
837{
838 return m_busDevices->At(GetLogicalAddress());
839}
840
841cec_logical_address CCECProcessor::GetLogicalAddress(void)
842{
843 cec_logical_addresses addresses = GetLogicalAddresses();
844 return addresses.primary;
845}
846
847cec_logical_addresses CCECProcessor::GetLogicalAddresses(void)
848{
849 CLockObject lock(m_mutex);
850 cec_logical_addresses addresses;
851 addresses.Clear();
852 for (map<cec_logical_address, CCECClient *>::const_iterator client = m_clients.begin(); client != m_clients.end(); client++)
853 addresses.Set(client->first);
854
855 return addresses;
856}
857
858bool CCECProcessor::IsHandledByLibCEC(const cec_logical_address address) const
859{
860 CCECBusDevice *device = GetDevice(address);
861 return device && device->IsHandledByLibCEC();
862}
863
864bool CCECProcessor::IsRunningLatestFirmware(void)
865{
866 return m_communication && m_communication->IsOpen() ?
867 m_communication->IsRunningLatestFirmware() :
868 true;
869}