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