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