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