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