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