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