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