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