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