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