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