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