73c921d8120f68c0ffff4f440e6e66e2e0443b07
[deb_libcec.git] / 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, true);
319
320 CCECBusDevice *device = m_busDevices->At(CECDEVICE_UNREGISTERED);
321 if (device)
322 return device->TransmitPoll(iAddress, true);
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 uint16_t CCECProcessor::GetPhysicalAddressFromEeprom(void)
705 {
706 libcec_configuration config; config.Clear();
707 if (m_communication)
708 m_communication->GetConfiguration(config);
709 return config.iPhysicalAddress;
710 }
711
712 bool CCECProcessor::RegisterClient(CCECClient *client)
713 {
714 if (!client)
715 return false;
716
717 libcec_configuration &configuration = *client->GetConfiguration();
718
719 if (configuration.clientVersion < CEC_CLIENT_VERSION_2_0_0)
720 {
721 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));
722 return false;
723 }
724
725 if (configuration.bMonitorOnly == 1)
726 return true;
727
728 if (!CECInitialised())
729 {
730 m_libcec->AddLog(CEC_LOG_ERROR, "failed to register a new CEC client: CEC processor is not initialised");
731 return false;
732 }
733
734 // unregister the client first if it's already been marked as registered
735 if (client->IsRegistered())
736 UnregisterClient(client);
737
738 // ensure that controlled mode is enabled
739 m_communication->SetControlledMode(true);
740
741 // source logical address for requests
742 cec_logical_address sourceAddress(CECDEVICE_UNREGISTERED);
743 if (!m_communication->SupportsSourceLogicalAddress(CECDEVICE_UNREGISTERED))
744 {
745 if (m_communication->SupportsSourceLogicalAddress(CECDEVICE_FREEUSE))
746 sourceAddress = CECDEVICE_FREEUSE;
747 else
748 {
749 m_libcec->AddLog(CEC_LOG_ERROR, "failed to register a new CEC client: both unregistered and free use are not supported by the device");
750 return false;
751 }
752 }
753
754 // ensure that we know the vendor id of the TV
755 CCECBusDevice *tv = GetTV();
756 cec_vendor_id tvVendor(tv->GetVendorId(sourceAddress));
757
758 // wait until the handler is replaced, to avoid double registrations
759 if (tvVendor != CEC_VENDOR_UNKNOWN &&
760 CCECCommandHandler::HasSpecificHandler(tvVendor))
761 {
762 while (!tv->ReplaceHandler(false))
763 CEvent::Sleep(5);
764 }
765
766 // get the configuration from the client
767 m_libcec->AddLog(CEC_LOG_NOTICE, "registering new CEC client - v%s", ToString((cec_client_version)configuration.clientVersion));
768
769 // get the current ackmask, so we can restore it if polling fails
770 cec_logical_addresses previousMask = GetLogicalAddresses();
771
772 // mark as uninitialised
773 client->SetInitialised(false);
774
775 // find logical addresses for this client
776 if (!AllocateLogicalAddresses(client))
777 {
778 m_libcec->AddLog(CEC_LOG_ERROR, "failed to register the new CEC client - cannot allocate the requested device types");
779 SetLogicalAddresses(previousMask);
780 return false;
781 }
782
783 // get the settings from the rom
784 if (configuration.bGetSettingsFromROM == 1)
785 {
786 libcec_configuration config; config.Clear();
787 m_communication->GetConfiguration(config);
788
789 CLockObject lock(m_mutex);
790 if (!config.deviceTypes.IsEmpty())
791 configuration.deviceTypes = config.deviceTypes;
792 if (CLibCEC::IsValidPhysicalAddress(config.iPhysicalAddress))
793 configuration.iPhysicalAddress = config.iPhysicalAddress;
794 snprintf(configuration.strDeviceName, 13, "%s", config.strDeviceName);
795 }
796
797 // set the firmware version and build date
798 configuration.serverVersion = LIBCEC_VERSION_CURRENT;
799 configuration.iFirmwareVersion = m_communication->GetFirmwareVersion();
800 configuration.iFirmwareBuildDate = m_communication->GetFirmwareBuildDate();
801 configuration.adapterType = m_communication->GetAdapterType();
802
803 // mark the client as registered
804 client->SetRegistered(true);
805
806 sourceAddress = client->GetPrimaryLogicalAdddress();
807
808 // initialise the client
809 bool bReturn = client->OnRegister();
810
811 // log the new registration
812 CStdString strLog;
813 strLog.Format("%s: %s", bReturn ? "CEC client registered" : "failed to register the CEC client", client->GetConnectionInfo().c_str());
814 m_libcec->AddLog(bReturn ? CEC_LOG_NOTICE : CEC_LOG_ERROR, strLog);
815
816 // display a warning if the firmware can be upgraded
817 if (bReturn && !IsRunningLatestFirmware())
818 {
819 const char *strUpgradeMessage = "The firmware of this adapter can be upgraded. Please visit http://blog.pulse-eight.com/ for more information.";
820 m_libcec->AddLog(CEC_LOG_WARNING, strUpgradeMessage);
821 libcec_parameter param;
822 param.paramData = (void*)strUpgradeMessage; param.paramType = CEC_PARAMETER_TYPE_STRING;
823 client->Alert(CEC_ALERT_SERVICE_DEVICE, param);
824 }
825
826 // ensure that the command handler for the TV is initialised
827 if (bReturn)
828 {
829 CCECCommandHandler *handler = GetTV()->GetHandler();
830 if (handler)
831 handler->InitHandler();
832 GetTV()->MarkHandlerReady();
833 }
834
835 // request the power status of the TV
836 tv->RequestPowerStatus(sourceAddress, true);
837
838 return bReturn;
839 }
840
841 bool CCECProcessor::UnregisterClient(CCECClient *client)
842 {
843 if (!client)
844 return false;
845
846 if (client->IsRegistered())
847 m_libcec->AddLog(CEC_LOG_NOTICE, "unregistering client: %s", client->GetConnectionInfo().c_str());
848
849 // notify the client that it will be unregistered
850 client->OnUnregister();
851
852 {
853 CLockObject lock(m_mutex);
854 // find all devices that match the LA's of this client
855 CECDEVICEVEC devices;
856 m_busDevices->GetByLogicalAddresses(devices, client->GetConfiguration()->logicalAddresses);
857 for (CECDEVICEVEC::const_iterator it = devices.begin(); it != devices.end(); it++)
858 {
859 // find the client
860 map<cec_logical_address, CCECClient *>::iterator entry = m_clients.find((*it)->GetLogicalAddress());
861 // unregister the client
862 if (entry != m_clients.end())
863 m_clients.erase(entry);
864
865 // reset the device status
866 (*it)->ResetDeviceStatus();
867 }
868 }
869
870 // set the new ackmask
871 cec_logical_addresses addresses = GetLogicalAddresses();
872 if (SetLogicalAddresses(addresses))
873 {
874 // no more clients left, disable controlled mode
875 if (addresses.IsEmpty() && !m_bMonitor)
876 m_communication->SetControlledMode(false);
877
878 return true;
879 }
880
881 return false;
882 }
883
884 void CCECProcessor::UnregisterClients(void)
885 {
886 m_libcec->AddLog(CEC_LOG_DEBUG, "unregistering all CEC clients");
887
888 vector<CCECClient *> clients = m_libcec->GetClients();
889 for (vector<CCECClient *>::iterator client = clients.begin(); client != clients.end(); client++)
890 UnregisterClient(*client);
891
892 CLockObject lock(m_mutex);
893 m_clients.clear();
894 }
895
896 CCECClient *CCECProcessor::GetClient(const cec_logical_address address)
897 {
898 CLockObject lock(m_mutex);
899 map<cec_logical_address, CCECClient *>::const_iterator client = m_clients.find(address);
900 if (client != m_clients.end())
901 return client->second;
902 return NULL;
903 }
904
905 CCECClient *CCECProcessor::GetPrimaryClient(void)
906 {
907 CLockObject lock(m_mutex);
908 map<cec_logical_address, CCECClient *>::const_iterator client = m_clients.begin();
909 if (client != m_clients.end())
910 return client->second;
911 return NULL;
912 }
913
914 CCECBusDevice *CCECProcessor::GetPrimaryDevice(void)
915 {
916 return m_busDevices->At(GetLogicalAddress());
917 }
918
919 cec_logical_address CCECProcessor::GetLogicalAddress(void)
920 {
921 cec_logical_addresses addresses = GetLogicalAddresses();
922 return addresses.primary;
923 }
924
925 cec_logical_addresses CCECProcessor::GetLogicalAddresses(void)
926 {
927 CLockObject lock(m_mutex);
928 cec_logical_addresses addresses;
929 addresses.Clear();
930 for (map<cec_logical_address, CCECClient *>::const_iterator client = m_clients.begin(); client != m_clients.end(); client++)
931 addresses.Set(client->first);
932
933 return addresses;
934 }
935
936 bool CCECProcessor::IsHandledByLibCEC(const cec_logical_address address) const
937 {
938 CCECBusDevice *device = GetDevice(address);
939 return device && device->IsHandledByLibCEC();
940 }
941
942 bool CCECProcessor::IsRunningLatestFirmware(void)
943 {
944 return m_communication && m_communication->IsOpen() ?
945 m_communication->IsRunningLatestFirmware() :
946 true;
947 }
948
949 void CCECProcessor::SwitchMonitoring(bool bSwitchTo)
950 {
951 {
952 CLockObject lock(m_mutex);
953 m_bMonitor = bSwitchTo;
954 }
955 if (bSwitchTo)
956 UnregisterClients();
957 }
958
959 void CCECProcessor::HandleLogicalAddressLost(cec_logical_address oldAddress)
960 {
961 // stall outgoing messages until we know our new LA
962 m_bStallCommunication = true;
963
964 m_libcec->AddLog(CEC_LOG_NOTICE, "logical address %x was taken by another device, allocating a new address", oldAddress);
965 CCECClient* client = GetClient(oldAddress);
966 if (!client)
967 client = GetPrimaryClient();
968 if (client)
969 {
970 if (m_addrAllocator)
971 while (m_addrAllocator->IsRunning()) Sleep(5);
972 delete m_addrAllocator;
973
974 m_addrAllocator = new CCECAllocateLogicalAddress(this, client);
975 m_addrAllocator->CreateThread();
976 }
977 }
978
979 uint16_t CCECProcessor::GetAdapterVendorId(void) const
980 {
981 return m_communication ? m_communication->GetAdapterVendorId() : 0;
982 }
983
984 uint16_t CCECProcessor::GetAdapterProductId(void) const
985 {
986 return m_communication ? m_communication->GetAdapterProductId() : 0;
987 }
988
989 CCECAllocateLogicalAddress::CCECAllocateLogicalAddress(CCECProcessor* processor, CCECClient* client) :
990 m_processor(processor),
991 m_client(client) { }
992
993 void* CCECAllocateLogicalAddress::Process(void)
994 {
995 m_processor->AllocateLogicalAddresses(m_client);
996 return NULL;
997 }