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