stall outgoing messages when the logical address was lost, until we got a new address
[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 adapterState == ADAPTER_MESSAGE_STATE_SENT_ACKED;
441 }
442
443 void CCECProcessor::TransmitAbort(cec_logical_address source, cec_logical_address destination, cec_opcode opcode, cec_abort_reason reason /* = CEC_ABORT_REASON_UNRECOGNIZED_OPCODE */)
444 {
445 m_libcec->AddLog(CEC_LOG_DEBUG, "<< transmitting abort message");
446
447 cec_command command;
448 cec_command::Format(command, source, destination, CEC_OPCODE_FEATURE_ABORT);
449 command.parameters.PushBack((uint8_t)opcode);
450 command.parameters.PushBack((uint8_t)reason);
451
452 Transmit(command, true);
453 }
454
455 void CCECProcessor::ProcessCommand(const cec_command &command)
456 {
457 // log the command
458 CStdString dataStr;
459 dataStr.Format(">> %1x%1x", command.initiator, command.destination);
460 if (command.opcode_set == 1)
461 dataStr.AppendFormat(":%02x", command.opcode);
462 for (uint8_t iPtr = 0; iPtr < command.parameters.size; iPtr++)
463 dataStr.AppendFormat(":%02x", (unsigned int)command.parameters[iPtr]);
464 m_libcec->AddLog(CEC_LOG_TRAFFIC, dataStr.c_str());
465
466 // find the initiator
467 CCECBusDevice *device = m_busDevices->At(command.initiator);
468
469 if (device)
470 device->HandleCommand(command);
471 }
472
473 bool CCECProcessor::IsPresentDevice(cec_logical_address address)
474 {
475 CCECBusDevice *device = m_busDevices->At(address);
476 return device && device->GetStatus() == CEC_DEVICE_STATUS_PRESENT;
477 }
478
479 bool CCECProcessor::IsPresentDeviceType(cec_device_type type)
480 {
481 CECDEVICEVEC devices;
482 m_busDevices->GetByType(type, devices);
483 CCECDeviceMap::FilterActive(devices);
484 return !devices.empty();
485 }
486
487 uint16_t CCECProcessor::GetDetectedPhysicalAddress(void) const
488 {
489 return m_communication ? m_communication->GetPhysicalAddress() : CEC_INVALID_PHYSICAL_ADDRESS;
490 }
491
492 bool CCECProcessor::ClearLogicalAddresses(void)
493 {
494 cec_logical_addresses addresses; addresses.Clear();
495 return SetLogicalAddresses(addresses);
496 }
497
498 bool CCECProcessor::SetLogicalAddresses(const cec_logical_addresses &addresses)
499 {
500 return m_communication ? m_communication->SetLogicalAddresses(addresses) : false;
501 }
502
503 bool CCECProcessor::StandbyDevices(const cec_logical_address initiator, const CECDEVICEVEC &devices)
504 {
505 bool bReturn(true);
506 for (CECDEVICEVEC::const_iterator it = devices.begin(); it != devices.end(); it++)
507 bReturn &= (*it)->Standby(initiator);
508 return bReturn;
509 }
510
511 bool CCECProcessor::StandbyDevice(const cec_logical_address initiator, cec_logical_address address)
512 {
513 CCECBusDevice *device = m_busDevices->At(address);
514 return device ? device->Standby(initiator) : false;
515 }
516
517 bool CCECProcessor::PowerOnDevices(const cec_logical_address initiator, const CECDEVICEVEC &devices)
518 {
519 bool bReturn(true);
520 for (CECDEVICEVEC::const_iterator it = devices.begin(); it != devices.end(); it++)
521 bReturn &= (*it)->PowerOn(initiator);
522 return bReturn;
523 }
524
525 bool CCECProcessor::PowerOnDevice(const cec_logical_address initiator, cec_logical_address address)
526 {
527 CCECBusDevice *device = m_busDevices->At(address);
528 return device ? device->PowerOn(initiator) : false;
529 }
530
531 bool CCECProcessor::StartBootloader(const char *strPort /* = NULL */)
532 {
533 bool bReturn(false);
534 // open a connection if no connection has been opened
535 if (!m_communication && strPort)
536 {
537 CAdapterFactory factory(this->m_libcec);
538 IAdapterCommunication *comm = factory.GetInstance(strPort);
539 CTimeout timeout(CEC_DEFAULT_CONNECT_TIMEOUT);
540 int iConnectTry(0);
541 while (timeout.TimeLeft() > 0 && (bReturn = comm->Open(timeout.TimeLeft() / CEC_CONNECT_TRIES, true)) == false)
542 {
543 m_libcec->AddLog(CEC_LOG_ERROR, "could not open a connection (try %d)", ++iConnectTry);
544 comm->Close();
545 Sleep(CEC_DEFAULT_TRANSMIT_RETRY_WAIT);
546 }
547 if (comm->IsOpen())
548 {
549 bReturn = comm->StartBootloader();
550 DELETE_AND_NULL(comm);
551 }
552 return bReturn;
553 }
554 else
555 {
556 m_communication->StartBootloader();
557 Close();
558 bReturn = true;
559 }
560
561 return bReturn;
562 }
563
564 bool CCECProcessor::PingAdapter(void)
565 {
566 return m_communication->PingAdapter();
567 }
568
569 void CCECProcessor::HandlePoll(cec_logical_address initiator, cec_logical_address destination)
570 {
571 CCECBusDevice *device = m_busDevices->At(destination);
572 if (device)
573 device->HandlePollFrom(initiator);
574 }
575
576 bool CCECProcessor::HandleReceiveFailed(cec_logical_address initiator)
577 {
578 CCECBusDevice *device = m_busDevices->At(initiator);
579 return !device || !device->HandleReceiveFailed();
580 }
581
582 bool CCECProcessor::CanPersistConfiguration(void)
583 {
584 return m_communication ? m_communication->GetFirmwareVersion() >= 2 : false;
585 }
586
587 bool CCECProcessor::PersistConfiguration(const libcec_configuration &configuration)
588 {
589 libcec_configuration persistConfiguration = configuration;
590 if (!CLibCEC::IsValidPhysicalAddress(configuration.iPhysicalAddress))
591 {
592 CCECBusDevice *device = GetPrimaryDevice();
593 if (device)
594 persistConfiguration.iPhysicalAddress = device->GetCurrentPhysicalAddress();
595 }
596
597 return m_communication ? m_communication->PersistConfiguration(persistConfiguration) : false;
598 }
599
600 void CCECProcessor::RescanActiveDevices(void)
601 {
602 for (CECDEVICEMAP::iterator it = m_busDevices->Begin(); it != m_busDevices->End(); it++)
603 it->second->GetStatus(true);
604 }
605
606 bool CCECProcessor::GetDeviceInformation(const char *strPort, libcec_configuration *config, uint32_t iTimeoutMs /* = CEC_DEFAULT_CONNECT_TIMEOUT */)
607 {
608 if (!OpenConnection(strPort, CEC_SERIAL_DEFAULT_BAUDRATE, iTimeoutMs, false))
609 return false;
610
611 config->iFirmwareVersion = m_communication->GetFirmwareVersion();
612 config->iPhysicalAddress = m_communication->GetPhysicalAddress();
613 config->iFirmwareBuildDate = m_communication->GetFirmwareBuildDate();
614 config->adapterType = m_communication->GetAdapterType();
615
616 return true;
617 }
618
619 bool CCECProcessor::TransmitPendingActiveSourceCommands(void)
620 {
621 bool bReturn(true);
622 for (CECDEVICEMAP::iterator it = m_busDevices->Begin(); it != m_busDevices->End(); it++)
623 bReturn &= it->second->TransmitPendingActiveSourceCommands();
624 return bReturn;
625 }
626
627 CCECTV *CCECProcessor::GetTV(void) const
628 {
629 return CCECBusDevice::AsTV(m_busDevices->At(CECDEVICE_TV));
630 }
631
632 CCECAudioSystem *CCECProcessor::GetAudioSystem(void) const
633 {
634 return CCECBusDevice::AsAudioSystem(m_busDevices->At(CECDEVICE_AUDIOSYSTEM));
635 }
636
637 CCECPlaybackDevice *CCECProcessor::GetPlaybackDevice(cec_logical_address address) const
638 {
639 return CCECBusDevice::AsPlaybackDevice(m_busDevices->At(address));
640 }
641
642 CCECRecordingDevice *CCECProcessor::GetRecordingDevice(cec_logical_address address) const
643 {
644 return CCECBusDevice::AsRecordingDevice(m_busDevices->At(address));
645 }
646
647 CCECTuner *CCECProcessor::GetTuner(cec_logical_address address) const
648 {
649 return CCECBusDevice::AsTuner(m_busDevices->At(address));
650 }
651
652 bool CCECProcessor::AllocateLogicalAddresses(CCECClient* client)
653 {
654 libcec_configuration &configuration = *client->GetConfiguration();
655
656 // mark as unregistered
657 client->SetRegistered(false);
658
659 // unregister this client from the old addresses
660 CECDEVICEVEC devices;
661 m_busDevices->GetByLogicalAddresses(devices, configuration.logicalAddresses);
662 for (CECDEVICEVEC::const_iterator it = devices.begin(); it != devices.end(); it++)
663 {
664 // remove client entry
665 CLockObject lock(m_mutex);
666 m_clients.erase((*it)->GetLogicalAddress());
667 }
668
669 // find logical addresses for this client
670 if (!client->AllocateLogicalAddresses())
671 {
672 m_libcec->AddLog(CEC_LOG_ERROR, "failed to find a free logical address for the client");
673 return false;
674 }
675
676 // register this client on the new addresses
677 devices.clear();
678 m_busDevices->GetByLogicalAddresses(devices, configuration.logicalAddresses);
679 for (CECDEVICEVEC::const_iterator it = devices.begin(); it != devices.end(); it++)
680 {
681 // set the physical address of the device at this LA
682 if (CLibCEC::IsValidPhysicalAddress(configuration.iPhysicalAddress))
683 (*it)->SetPhysicalAddress(configuration.iPhysicalAddress);
684
685 // replace a previous client
686 CLockObject lock(m_mutex);
687 m_clients.erase((*it)->GetLogicalAddress());
688 m_clients.insert(make_pair<cec_logical_address, CCECClient *>((*it)->GetLogicalAddress(), client));
689 }
690
691 // set the new ackmask
692 SetLogicalAddresses(GetLogicalAddresses());
693
694 // resume outgoing communication
695 m_bStallCommunication = false;
696
697 return true;
698 }
699
700 bool CCECProcessor::RegisterClient(CCECClient *client)
701 {
702 if (!client)
703 return false;
704
705 libcec_configuration &configuration = *client->GetConfiguration();
706
707 if (configuration.clientVersion >= CEC_CLIENT_VERSION_1_6_3 && configuration.bMonitorOnly == 1)
708 return true;
709
710 if (!CECInitialised())
711 {
712 m_libcec->AddLog(CEC_LOG_ERROR, "failed to register a new CEC client: CEC processor is not initialised");
713 return false;
714 }
715
716 // unregister the client first if it's already been marked as registered
717 if (client->IsRegistered())
718 UnregisterClient(client);
719
720 // ensure that controlled mode is enabled
721 m_communication->SetControlledMode(true);
722
723 // ensure that we know the vendor id of the TV
724 CCECBusDevice *tv = GetTV();
725 cec_vendor_id tvVendor = CEC_VENDOR_UNKNOWN;
726 if (m_communication->SupportsSourceLogicalAddress(CECDEVICE_UNREGISTERED))
727 tvVendor = tv->GetVendorId(CECDEVICE_UNREGISTERED);
728 else if (m_communication->SupportsSourceLogicalAddress(CECDEVICE_FREEUSE))
729 tvVendor = tv->GetVendorId(CECDEVICE_FREEUSE);
730
731 // wait until the handler is replaced, to avoid double registrations
732 if (tvVendor != CEC_VENDOR_UNKNOWN &&
733 CCECCommandHandler::HasSpecificHandler(tvVendor))
734 {
735 while (!tv->ReplaceHandler(false))
736 CEvent::Sleep(5);
737 }
738
739 // get the configuration from the client
740 m_libcec->AddLog(CEC_LOG_NOTICE, "registering new CEC client - v%s", ToString((cec_client_version)configuration.clientVersion));
741
742 // get the current ackmask, so we can restore it if polling fails
743 cec_logical_addresses previousMask = GetLogicalAddresses();
744
745 // mark as uninitialised
746 client->SetInitialised(false);
747
748 // find logical addresses for this client
749 if (!AllocateLogicalAddresses(client))
750 {
751 m_libcec->AddLog(CEC_LOG_ERROR, "failed to register the new CEC client - cannot allocate the requested device types");
752 SetLogicalAddresses(previousMask);
753 return false;
754 }
755
756 // get the settings from the rom
757 if (configuration.bGetSettingsFromROM == 1)
758 {
759 libcec_configuration config; config.Clear();
760 m_communication->GetConfiguration(config);
761
762 CLockObject lock(m_mutex);
763 if (!config.deviceTypes.IsEmpty())
764 configuration.deviceTypes = config.deviceTypes;
765 if (CLibCEC::IsValidPhysicalAddress(config.iPhysicalAddress))
766 configuration.iPhysicalAddress = config.iPhysicalAddress;
767 snprintf(configuration.strDeviceName, 13, "%s", config.strDeviceName);
768 }
769
770 // set the firmware version and build date
771 configuration.serverVersion = LIBCEC_VERSION_CURRENT;
772 configuration.iFirmwareVersion = m_communication->GetFirmwareVersion();
773 configuration.iFirmwareBuildDate = m_communication->GetFirmwareBuildDate();
774 configuration.adapterType = m_communication->GetAdapterType();
775
776 // mark the client as registered
777 client->SetRegistered(true);
778
779 // initialise the client
780 bool bReturn = client->OnRegister();
781
782 // log the new registration
783 CStdString strLog;
784 strLog.Format("%s: %s", bReturn ? "CEC client registered" : "failed to register the CEC client", client->GetConnectionInfo().c_str());
785 m_libcec->AddLog(bReturn ? CEC_LOG_NOTICE : CEC_LOG_ERROR, strLog);
786
787 // display a warning if the firmware can be upgraded
788 if (bReturn && !IsRunningLatestFirmware())
789 {
790 const char *strUpgradeMessage = "The firmware of this adapter can be upgraded. Please visit http://blog.pulse-eight.com/ for more information.";
791 m_libcec->AddLog(CEC_LOG_WARNING, strUpgradeMessage);
792 libcec_parameter param;
793 param.paramData = (void*)strUpgradeMessage; param.paramType = CEC_PARAMETER_TYPE_STRING;
794 client->Alert(CEC_ALERT_SERVICE_DEVICE, param);
795 }
796
797 // ensure that the command handler for the TV is initialised
798 if (bReturn)
799 {
800 CCECCommandHandler *handler = GetTV()->GetHandler();
801 if (handler)
802 handler->InitHandler();
803 GetTV()->MarkHandlerReady();
804 }
805
806 return bReturn;
807 }
808
809 bool CCECProcessor::UnregisterClient(CCECClient *client)
810 {
811 if (!client)
812 return false;
813
814 if (client->IsRegistered())
815 m_libcec->AddLog(CEC_LOG_NOTICE, "unregistering client: %s", client->GetConnectionInfo().c_str());
816
817 // notify the client that it will be unregistered
818 client->OnUnregister();
819
820 {
821 CLockObject lock(m_mutex);
822 // find all devices that match the LA's of this client
823 CECDEVICEVEC devices;
824 m_busDevices->GetByLogicalAddresses(devices, client->GetConfiguration()->logicalAddresses);
825 for (CECDEVICEVEC::const_iterator it = devices.begin(); it != devices.end(); it++)
826 {
827 // find the client
828 map<cec_logical_address, CCECClient *>::iterator entry = m_clients.find((*it)->GetLogicalAddress());
829 // unregister the client
830 if (entry != m_clients.end())
831 m_clients.erase(entry);
832
833 // reset the device status
834 (*it)->ResetDeviceStatus();
835 }
836 }
837
838 // set the new ackmask
839 cec_logical_addresses addresses = GetLogicalAddresses();
840 if (SetLogicalAddresses(addresses))
841 {
842 // no more clients left, disable controlled mode
843 if (addresses.IsEmpty() && !m_bMonitor)
844 m_communication->SetControlledMode(false);
845
846 return true;
847 }
848
849 return false;
850 }
851
852 void CCECProcessor::UnregisterClients(void)
853 {
854 m_libcec->AddLog(CEC_LOG_NOTICE, "unregistering all CEC clients");
855
856 vector<CCECClient *> clients = m_libcec->GetClients();
857 for (vector<CCECClient *>::iterator client = clients.begin(); client != clients.end(); client++)
858 UnregisterClient(*client);
859
860 CLockObject lock(m_mutex);
861 m_clients.clear();
862 }
863
864 CCECClient *CCECProcessor::GetClient(const cec_logical_address address)
865 {
866 CLockObject lock(m_mutex);
867 map<cec_logical_address, CCECClient *>::const_iterator client = m_clients.find(address);
868 if (client != m_clients.end())
869 return client->second;
870 return NULL;
871 }
872
873 CCECClient *CCECProcessor::GetPrimaryClient(void)
874 {
875 CLockObject lock(m_mutex);
876 map<cec_logical_address, CCECClient *>::const_iterator client = m_clients.begin();
877 if (client != m_clients.end())
878 return client->second;
879 return NULL;
880 }
881
882 CCECBusDevice *CCECProcessor::GetPrimaryDevice(void)
883 {
884 return m_busDevices->At(GetLogicalAddress());
885 }
886
887 cec_logical_address CCECProcessor::GetLogicalAddress(void)
888 {
889 cec_logical_addresses addresses = GetLogicalAddresses();
890 return addresses.primary;
891 }
892
893 cec_logical_addresses CCECProcessor::GetLogicalAddresses(void)
894 {
895 CLockObject lock(m_mutex);
896 cec_logical_addresses addresses;
897 addresses.Clear();
898 for (map<cec_logical_address, CCECClient *>::const_iterator client = m_clients.begin(); client != m_clients.end(); client++)
899 addresses.Set(client->first);
900
901 return addresses;
902 }
903
904 bool CCECProcessor::IsHandledByLibCEC(const cec_logical_address address) const
905 {
906 CCECBusDevice *device = GetDevice(address);
907 return device && device->IsHandledByLibCEC();
908 }
909
910 bool CCECProcessor::IsRunningLatestFirmware(void)
911 {
912 return m_communication && m_communication->IsOpen() ?
913 m_communication->IsRunningLatestFirmware() :
914 true;
915 }
916
917 void CCECProcessor::SwitchMonitoring(bool bSwitchTo)
918 {
919 {
920 CLockObject lock(m_mutex);
921 m_bMonitor = bSwitchTo;
922 }
923 if (bSwitchTo)
924 UnregisterClients();
925 }
926
927 void CCECProcessor::HandleLogicalAddressLost(cec_logical_address oldAddress)
928 {
929 // stall outgoing messages until we know our new LA
930 m_bStallCommunication = true;
931
932 m_libcec->AddLog(CEC_LOG_NOTICE, "logical address %x was taken by another device, allocating a new address", oldAddress);
933 CCECClient* client = GetClient(oldAddress);
934 if (client)
935 {
936 if (m_addrAllocator)
937 while (m_addrAllocator->IsRunning()) Sleep(5);
938 delete m_addrAllocator;
939
940 m_addrAllocator = new CCECAllocateLogicalAddress(this, client);
941 m_addrAllocator->CreateThread();
942 }
943 }
944
945 CCECAllocateLogicalAddress::CCECAllocateLogicalAddress(CCECProcessor* processor, CCECClient* client) :
946 m_processor(processor),
947 m_client(client) { }
948
949 void* CCECAllocateLogicalAddress::Process(void)
950 {
951 m_processor->AllocateLogicalAddresses(m_client);
952 return NULL;
953 }