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