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