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