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