76c2465fb2dd74419822d63cf5991e4c4814af95
[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 {
67 m_busDevices = new CCECDeviceMap(this);
68 }
69
70 CCECProcessor::~CCECProcessor(void)
71 {
72 Close();
73 DELETE_AND_NULL(m_busDevices);
74 }
75
76 bool 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
96 void 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
108 void 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
120 bool 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
158 bool CCECProcessor::CECInitialised(void)
159 {
160 CLockObject lock(m_threadMutex);
161 return m_bInitialised;
162 }
163
164 void CCECProcessor::SetCECInitialised(bool bSetTo /* = true */)
165 {
166 {
167 CLockObject lock(m_mutex);
168 m_bInitialised = bSetTo;
169 }
170 if (!bSetTo)
171 UnregisterClients();
172 }
173
174 bool 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
191 void 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
201 bool CCECProcessor::OnCommandReceived(const cec_command &command)
202 {
203 return m_inBuffer.Push(command);
204 }
205
206 void *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
241 bool 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
256 void CCECProcessor::SetStandardLineTimeout(uint8_t iTimeout)
257 {
258 CLockObject lock(m_mutex);
259 m_iStandardLineTimeout = iTimeout;
260 }
261
262 uint8_t CCECProcessor::GetStandardLineTimeout(void)
263 {
264 CLockObject lock(m_mutex);
265 return m_iStandardLineTimeout;
266 }
267
268 void CCECProcessor::SetRetryLineTimeout(uint8_t iTimeout)
269 {
270 CLockObject lock(m_mutex);
271 m_iRetryLineTimeout = iTimeout;
272 }
273
274 uint8_t CCECProcessor::GetRetryLineTimeout(void)
275 {
276 CLockObject lock(m_mutex);
277 return m_iRetryLineTimeout;
278 }
279
280 bool CCECProcessor::PhysicalAddressInUse(uint16_t iPhysicalAddress)
281 {
282 CCECBusDevice *device = GetDeviceByPhysicalAddress(iPhysicalAddress);
283 return device != NULL;
284 }
285
286 void 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
305 bool 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
320 CCECBusDevice *CCECProcessor::GetDeviceByPhysicalAddress(uint16_t iPhysicalAddress, bool bSuppressUpdate /* = true */)
321 {
322 return m_busDevices ?
323 m_busDevices->GetDeviceByPhysicalAddress(iPhysicalAddress, bSuppressUpdate) :
324 NULL;
325 }
326
327 CCECBusDevice *CCECProcessor::GetDevice(cec_logical_address address) const
328 {
329 return m_busDevices ?
330 m_busDevices->At(address) :
331 NULL;
332 }
333
334 cec_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
356 bool CCECProcessor::IsActiveSource(cec_logical_address iAddress)
357 {
358 CCECBusDevice *device = m_busDevices->At(iAddress);
359 return device && device->IsActiveSource();
360 }
361
362 bool 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
435 void 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
447 void 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
465 bool 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
471 bool 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
479 uint16_t CCECProcessor::GetDetectedPhysicalAddress(void) const
480 {
481 return m_communication ? m_communication->GetPhysicalAddress() : CEC_INVALID_PHYSICAL_ADDRESS;
482 }
483
484 bool CCECProcessor::ClearLogicalAddresses(void)
485 {
486 cec_logical_addresses addresses; addresses.Clear();
487 return SetLogicalAddresses(addresses);
488 }
489
490 bool CCECProcessor::SetLogicalAddresses(const cec_logical_addresses &addresses)
491 {
492 return m_communication ? m_communication->SetLogicalAddresses(addresses) : false;
493 }
494
495 bool 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
503 bool 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
509 bool 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
517 bool 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
523 bool 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
556 bool CCECProcessor::PingAdapter(void)
557 {
558 return m_communication->PingAdapter();
559 }
560
561 void 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
568 bool CCECProcessor::HandleReceiveFailed(cec_logical_address initiator)
569 {
570 CCECBusDevice *device = m_busDevices->At(initiator);
571 return !device || !device->HandleReceiveFailed();
572 }
573
574 bool CCECProcessor::CanPersistConfiguration(void)
575 {
576 return m_communication ? m_communication->GetFirmwareVersion() >= 2 : false;
577 }
578
579 bool 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
592 void CCECProcessor::RescanActiveDevices(void)
593 {
594 for (CECDEVICEMAP::iterator it = m_busDevices->Begin(); it != m_busDevices->End(); it++)
595 it->second->GetStatus(true);
596 }
597
598 bool 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
610 bool 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
618 CCECTV *CCECProcessor::GetTV(void) const
619 {
620 return CCECBusDevice::AsTV(m_busDevices->At(CECDEVICE_TV));
621 }
622
623 CCECAudioSystem *CCECProcessor::GetAudioSystem(void) const
624 {
625 return CCECBusDevice::AsAudioSystem(m_busDevices->At(CECDEVICE_AUDIOSYSTEM));
626 }
627
628 CCECPlaybackDevice *CCECProcessor::GetPlaybackDevice(cec_logical_address address) const
629 {
630 return CCECBusDevice::AsPlaybackDevice(m_busDevices->At(address));
631 }
632
633 CCECRecordingDevice *CCECProcessor::GetRecordingDevice(cec_logical_address address) const
634 {
635 return CCECBusDevice::AsRecordingDevice(m_busDevices->At(address));
636 }
637
638 CCECTuner *CCECProcessor::GetTuner(cec_logical_address address) const
639 {
640 return CCECBusDevice::AsTuner(m_busDevices->At(address));
641 }
642
643 bool 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 if (m_communication->SupportsSourceLogicalAddress(CECDEVICE_UNREGISTERED))
669 tv->GetVendorId(CECDEVICE_UNREGISTERED);
670 else if (m_communication->SupportsSourceLogicalAddress(CECDEVICE_FREEUSE))
671 tv->GetVendorId(CECDEVICE_FREEUSE);
672
673 // get the configuration from the client
674 m_libcec->AddLog(CEC_LOG_NOTICE, "registering new CEC client - v%s", ToString((cec_client_version)configuration.clientVersion));
675
676 // mark as uninitialised and unregistered
677 client->SetRegistered(false);
678 client->SetInitialised(false);
679
680 // get the current ackmask, so we can restore it if polling fails
681 cec_logical_addresses previousMask = GetLogicalAddresses();
682
683 // find logical addresses for this client
684 if (!client->AllocateLogicalAddresses())
685 {
686 m_libcec->AddLog(CEC_LOG_ERROR, "failed to register the new CEC client - cannot allocate the requested device types");
687 SetLogicalAddresses(previousMask);
688 return false;
689 }
690
691 // register this client on the new addresses
692 CECDEVICEVEC devices;
693 m_busDevices->GetByLogicalAddresses(devices, configuration.logicalAddresses);
694 for (CECDEVICEVEC::const_iterator it = devices.begin(); it != devices.end(); it++)
695 {
696 // set the physical address of the device at this LA
697 if (CLibCEC::IsValidPhysicalAddress(configuration.iPhysicalAddress))
698 (*it)->SetPhysicalAddress(configuration.iPhysicalAddress);
699
700 // replace a previous client
701 CLockObject lock(m_mutex);
702 m_clients.erase((*it)->GetLogicalAddress());
703 m_clients.insert(make_pair<cec_logical_address, CCECClient *>((*it)->GetLogicalAddress(), client));
704 }
705
706 // get the settings from the rom
707 if (configuration.bGetSettingsFromROM == 1)
708 {
709 libcec_configuration config; config.Clear();
710 m_communication->GetConfiguration(config);
711
712 CLockObject lock(m_mutex);
713 if (!config.deviceTypes.IsEmpty())
714 configuration.deviceTypes = config.deviceTypes;
715 if (CLibCEC::IsValidPhysicalAddress(config.iPhysicalAddress))
716 configuration.iPhysicalAddress = config.iPhysicalAddress;
717 snprintf(configuration.strDeviceName, 13, "%s", config.strDeviceName);
718 }
719
720 // set the firmware version and build date
721 configuration.serverVersion = LIBCEC_VERSION_CURRENT;
722 configuration.iFirmwareVersion = m_communication->GetFirmwareVersion();
723 configuration.iFirmwareBuildDate = m_communication->GetFirmwareBuildDate();
724
725 // mark the client as registered
726 client->SetRegistered(true);
727
728 // set the new ack mask
729 bool bReturn = SetLogicalAddresses(GetLogicalAddresses()) &&
730 // and initialise the client
731 client->OnRegister();
732
733 // log the new registration
734 CStdString strLog;
735 strLog.Format("%s: %s", bReturn ? "CEC client registered" : "failed to register the CEC client", client->GetConnectionInfo().c_str());
736 m_libcec->AddLog(bReturn ? CEC_LOG_NOTICE : CEC_LOG_ERROR, strLog);
737
738 // display a warning if the firmware can be upgraded
739 if (bReturn && !IsRunningLatestFirmware())
740 {
741 const char *strUpgradeMessage = "The firmware of this adapter can be upgraded. Please visit http://blog.pulse-eight.com/ for more information.";
742 m_libcec->AddLog(CEC_LOG_WARNING, strUpgradeMessage);
743 libcec_parameter param;
744 param.paramData = (void*)strUpgradeMessage; param.paramType = CEC_PARAMETER_TYPE_STRING;
745 client->Alert(CEC_ALERT_SERVICE_DEVICE, param);
746 }
747
748 // ensure that the command handler for the TV is initialised
749 if (bReturn)
750 {
751 CCECCommandHandler *handler = GetTV()->GetHandler();
752 if (handler)
753 handler->InitHandler();
754 GetTV()->MarkHandlerReady();
755 }
756
757 return bReturn;
758 }
759
760 bool CCECProcessor::UnregisterClient(CCECClient *client)
761 {
762 if (!client)
763 return false;
764
765 if (client->IsRegistered())
766 m_libcec->AddLog(CEC_LOG_NOTICE, "unregistering client: %s", client->GetConnectionInfo().c_str());
767
768 // notify the client that it will be unregistered
769 client->OnUnregister();
770
771 {
772 CLockObject lock(m_mutex);
773 // find all devices that match the LA's of this client
774 CECDEVICEVEC devices;
775 m_busDevices->GetByLogicalAddresses(devices, client->GetConfiguration()->logicalAddresses);
776 for (CECDEVICEVEC::const_iterator it = devices.begin(); it != devices.end(); it++)
777 {
778 // find the client
779 map<cec_logical_address, CCECClient *>::iterator entry = m_clients.find((*it)->GetLogicalAddress());
780 // unregister the client
781 if (entry != m_clients.end())
782 m_clients.erase(entry);
783
784 // reset the device status
785 (*it)->ResetDeviceStatus();
786 }
787 }
788
789 // set the new ackmask
790 cec_logical_addresses addresses = GetLogicalAddresses();
791 if (SetLogicalAddresses(addresses))
792 {
793 // no more clients left, disable controlled mode
794 if (addresses.IsEmpty())
795 m_communication->SetControlledMode(false);
796
797 return true;
798 }
799
800 return false;
801 }
802
803 void CCECProcessor::UnregisterClients(void)
804 {
805 m_libcec->AddLog(CEC_LOG_NOTICE, "unregistering all CEC clients");
806
807 vector<CCECClient *> clients = m_libcec->GetClients();
808 for (vector<CCECClient *>::iterator client = clients.begin(); client != clients.end(); client++)
809 UnregisterClient(*client);
810
811 CLockObject lock(m_mutex);
812 m_clients.clear();
813 }
814
815 CCECClient *CCECProcessor::GetClient(const cec_logical_address address)
816 {
817 CLockObject lock(m_mutex);
818 map<cec_logical_address, CCECClient *>::const_iterator client = m_clients.find(address);
819 if (client != m_clients.end())
820 return client->second;
821 return NULL;
822 }
823
824 CCECClient *CCECProcessor::GetPrimaryClient(void)
825 {
826 CLockObject lock(m_mutex);
827 map<cec_logical_address, CCECClient *>::const_iterator client = m_clients.begin();
828 if (client != m_clients.end())
829 return client->second;
830 return NULL;
831 }
832
833 CCECBusDevice *CCECProcessor::GetPrimaryDevice(void)
834 {
835 return m_busDevices->At(GetLogicalAddress());
836 }
837
838 cec_logical_address CCECProcessor::GetLogicalAddress(void)
839 {
840 cec_logical_addresses addresses = GetLogicalAddresses();
841 return addresses.primary;
842 }
843
844 cec_logical_addresses CCECProcessor::GetLogicalAddresses(void)
845 {
846 CLockObject lock(m_mutex);
847 cec_logical_addresses addresses;
848 addresses.Clear();
849 for (map<cec_logical_address, CCECClient *>::const_iterator client = m_clients.begin(); client != m_clients.end(); client++)
850 addresses.Set(client->first);
851
852 return addresses;
853 }
854
855 bool CCECProcessor::IsHandledByLibCEC(const cec_logical_address address) const
856 {
857 CCECBusDevice *device = GetDevice(address);
858 return device && device->IsHandledByLibCEC();
859 }
860
861 bool CCECProcessor::IsRunningLatestFirmware(void)
862 {
863 return m_communication && m_communication->IsOpen() ?
864 m_communication->IsRunningLatestFirmware() :
865 true;
866 }