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