cec: don't return from the Close() method in CUSBCECAdapterCommunication, because...
[deb_libcec.git] / src / lib / adapter / USBCECAdapterCommunication.cpp
CommitLineData
a8f0bd18
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.
a8f0bd18
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
7bb4ed43 33#include "USBCECAdapterCommunication.h"
ba65909d
LOK
34#include "../platform/sockets/serialport.h"
35#include "../platform/util/timeutils.h"
5477a250 36#include "../LibCEC.h"
7bb4ed43 37#include "../CECProcessor.h"
a8f0bd18
LOK
38
39using namespace std;
40using namespace CEC;
f00ff009 41using namespace PLATFORM;
a8f0bd18 42
ae54110f
LOK
43#define CEC_ADAPTER_PING_TIMEOUT 15000
44
83554890
LOK
45void *CUSBCECAdapterProcessor::Process(void)
46{
47 cec_command command;
48 while (!IsStopped())
49 {
50 if (m_inBuffer.Pop(command))
51 m_callback->OnCommandReceived(command);
52 Sleep(5);
53 }
54
55 return NULL;
56}
57
58void CUSBCECAdapterProcessor::AddCommand(cec_command command)
59{
60 m_inBuffer.Push(command);
61}
62
7bb4ed43 63CUSBCECAdapterCommunication::CUSBCECAdapterCommunication(CCECProcessor *processor, const char *strPort, uint16_t iBaudRate /* = 38400 */) :
12027dbe 64 m_port(NULL),
a171d2fd 65 m_processor(processor),
960f33c6 66 m_bHasData(false),
1fc16cfd 67 m_iLineTimeout(0),
7bb4ed43 68 m_iFirmwareVersion(CEC_FW_VERSION_UNKNOWN),
eb965473 69 m_lastDestination(CECDEVICE_UNKNOWN),
7bb4ed43 70 m_bNextIsEscaped(false),
83554890 71 m_bGotStart(false),
cccd2724
LOK
72 m_messageProcessor(NULL),
73 m_bInitialised(false)
a8f0bd18 74{
4164923b
LOK
75 for (unsigned int iPtr = 0; iPtr < 15; iPtr++)
76 m_bWaitingForAck[iPtr] = false;
089f0e9d 77 m_port = new CSerialPort(strPort, iBaudRate);
a8f0bd18
LOK
78}
79
efed01e1 80bool CUSBCECAdapterCommunication::CheckAdapter(uint32_t iTimeoutMs /* = 10000 */)
a8f0bd18 81{
efed01e1 82 bool bReturn(false);
7b494bea 83 uint64_t iNow = GetTimeMs();
efed01e1 84 uint64_t iTarget = iTimeoutMs > 0 ? iNow + iTimeoutMs : iNow + CEC_DEFAULT_TRANSMIT_WAIT;
7b494bea 85
efed01e1
LOK
86 /* try to ping the adapter */
87 bool bPinged(false);
88 unsigned iPingTry(0);
89 while (iNow < iTarget && (bPinged = PingAdapter()) == false)
13fd6a66 90 {
efed01e1 91 CLibCEC::AddLog(CEC_LOG_ERROR, "the adapter did not respond correctly to a ping (try %d)", ++iPingTry);
befa3a23 92 CEvent::Sleep(500);
efed01e1 93 iNow = GetTimeMs();
13fd6a66
LOK
94 }
95
efed01e1
LOK
96 /* try to read the firmware version */
97 m_iFirmwareVersion = CEC_FW_VERSION_UNKNOWN;
98 unsigned iFwVersionTry(0);
9aae458a 99 while (bPinged && iNow < iTarget && (m_iFirmwareVersion = GetFirmwareVersion()) == CEC_FW_VERSION_UNKNOWN && iFwVersionTry < 3)
13fd6a66 100 {
9aae458a 101 CLibCEC::AddLog(CEC_LOG_WARNING, "the adapter did not respond with a correct firmware version (try %d)", ++iFwVersionTry);
befa3a23 102 CEvent::Sleep(500);
efed01e1 103 iNow = GetTimeMs();
13fd6a66 104 }
a8f0bd18 105
9aae458a
LOK
106 if (m_iFirmwareVersion == CEC_FW_VERSION_UNKNOWN)
107 {
108 CLibCEC::AddLog(CEC_LOG_DEBUG, "defaulting to firmware version 1");
109 m_iFirmwareVersion = 1;
110 }
111
efed01e1 112 if (m_iFirmwareVersion >= 2)
7b494bea 113 {
efed01e1
LOK
114 /* try to set controlled mode */
115 unsigned iControlledTry(0);
116 bool bControlled(false);
117 while (iNow < iTarget && (bControlled = SetControlledMode(true)) == false)
7b494bea 118 {
efed01e1 119 CLibCEC::AddLog(CEC_LOG_ERROR, "the adapter did not respond correctly to setting controlled mode (try %d)", ++iControlledTry);
befa3a23 120 CEvent::Sleep(500);
7b494bea
LOK
121 iNow = GetTimeMs();
122 }
efed01e1 123 bReturn = bControlled;
7b494bea 124 }
efed01e1
LOK
125 else
126 bReturn = true;
7b494bea 127
cccd2724
LOK
128 {
129 CLockObject lock(m_mutex);
130 m_bInitialised = bReturn;
131 }
132
efed01e1
LOK
133 return bReturn;
134}
a8f0bd18 135
a2198e5e 136bool CUSBCECAdapterCommunication::Open(IAdapterCommunicationCallback *cb, uint32_t iTimeoutMs /* = 10000 */, bool bSkipChecks /* = false */)
efed01e1
LOK
137{
138 uint64_t iNow = GetTimeMs();
139 uint64_t iTimeout = iNow + iTimeoutMs;
a8f0bd18 140
2c780401 141 {
efed01e1
LOK
142 CLockObject lock(m_mutex);
143
144 if (!m_port)
145 {
146 CLibCEC::AddLog(CEC_LOG_ERROR, "port is NULL");
147 return false;
148 }
149
150 if (IsOpen())
151 {
152 CLibCEC::AddLog(CEC_LOG_ERROR, "port is already open");
153 return true;
154 }
155
156 m_callback = cb;
157 CStdString strError;
158 bool bConnected(false);
159 while (!bConnected && iNow < iTimeout)
160 {
161 if ((bConnected = m_port->Open(iTimeout)) == false)
162 {
163 strError.Format("error opening serial port '%s': %s", m_port->GetName().c_str(), m_port->GetError().c_str());
164 Sleep(250);
165 iNow = GetTimeMs();
166 }
167 }
168
169 if (!bConnected)
170 {
171 CLibCEC::AddLog(CEC_LOG_ERROR, strError);
172 return false;
173 }
174
175 CLibCEC::AddLog(CEC_LOG_DEBUG, "connection opened, clearing any previous input and waiting for active transmissions to end before starting");
176
a2198e5e 177 if (!bSkipChecks)
efed01e1 178 {
a2198e5e
LOK
179 //clear any input bytes
180 uint8_t buff[1024];
053ecec4
LOK
181 ssize_t iBytesRead(0);
182 bool bGotMsgStart(false), bGotMsgEnd(false);
183 while ((iBytesRead = m_port->Read(buff, 1024, 100)) > 0 || (bGotMsgStart && !bGotMsgEnd))
a2198e5e 184 {
053ecec4
LOK
185 if (!bGotMsgStart)
186 CLibCEC::AddLog(CEC_LOG_DEBUG, "data received, clearing it");
187 // if something was received, wait for MSGEND
188 for (ssize_t iPtr = 0; iPtr < iBytesRead; iPtr++)
189 {
190 if (buff[iPtr] == MSGSTART)
191 bGotMsgStart = true;
192 else if (buff[iPtr] == MSGEND)
193 bGotMsgEnd = true;
194 }
a2198e5e
LOK
195 Sleep(250);
196 }
efed01e1 197 }
2c780401 198 }
a8f0bd18 199
befa3a23 200 if (!bSkipChecks && !CheckAdapter())
a8f0bd18 201 {
befa3a23
LOK
202 CLibCEC::AddLog(CEC_LOG_ERROR, "the adapter failed to pass basic checks");
203 return false;
204 }
205 else
206 {
207 if (CreateThread())
efed01e1 208 {
befa3a23
LOK
209 CLibCEC::AddLog(CEC_LOG_DEBUG, "communication thread started");
210 return true;
efed01e1
LOK
211 }
212 else
213 {
befa3a23 214 CLibCEC::AddLog(CEC_LOG_ERROR, "could not create a communication thread");
efed01e1 215 }
a8f0bd18
LOK
216 }
217
218 return false;
219}
220
7bb4ed43 221void CUSBCECAdapterCommunication::Close(void)
a8f0bd18 222{
26516f2f 223 StopThread(0);
a8f0bd18
LOK
224}
225
7bb4ed43 226void *CUSBCECAdapterCommunication::Process(void)
a8f0bd18 227{
83554890
LOK
228 m_messageProcessor = new CUSBCECAdapterProcessor(m_callback);
229 m_messageProcessor->CreateThread();
230
b1f94db1 231 cec_command command;
32553784 232 command.Clear();
efed01e1 233 bool bCommandReceived(false);
ae54110f 234 CTimeout pingTimeout(CEC_ADAPTER_PING_TIMEOUT);
13fd6a66 235 while (!IsStopped())
a8f0bd18 236 {
efed01e1
LOK
237 {
238 CLockObject lock(m_mutex);
239 ReadFromDevice(50);
cccd2724 240 bCommandReceived = m_callback && Read(command, 0) && m_bInitialised;
efed01e1 241 }
b1f94db1
LOK
242
243 /* push the next command to the callback method if there is one */
efed01e1 244 if (!IsStopped() && bCommandReceived)
83554890 245 m_messageProcessor->AddCommand(command);
b1f94db1 246
ae54110f
LOK
247 /* ping the adapter every 15 seconds */
248 if (pingTimeout.TimeLeft() == 0)
249 {
250 pingTimeout.Init(CEC_ADAPTER_PING_TIMEOUT);
251 PingAdapter();
252 }
253
efed01e1
LOK
254 if (!IsStopped())
255 {
256 Sleep(5);
257 WriteNextCommand();
258 }
a8f0bd18
LOK
259 }
260
83554890
LOK
261 /* stop the message processor */
262 m_messageProcessor->StopThread();
263 delete m_messageProcessor;
264
f9e01dac 265 /* notify all threads that are waiting on messages to be sent */
ef7696f5 266 CCECAdapterMessage *msg(NULL);
f9e01dac 267 while (m_outBuffer.Pop(msg))
960f33c6 268 msg->event.Broadcast();
a0878ee3 269
f9e01dac
LOK
270 /* set the ackmask to 0 before closing the connection */
271 SetAckMaskInternal(0, true);
272
3c30c490
LOK
273 if (m_iFirmwareVersion >= 2)
274 SetControlledMode(false);
275
9f9c8c82
LOK
276 if (m_port)
277 {
278 delete m_port;
279 m_port = NULL;
280 }
281
a8f0bd18
LOK
282 return NULL;
283}
284
7bb4ed43
LOK
285cec_adapter_message_state CUSBCECAdapterCommunication::Write(const cec_command &data, uint8_t iMaxTries, uint8_t iLineTimeout /* = 3 */, uint8_t iRetryLineTimeout /* = 3 */)
286{
287 cec_adapter_message_state retVal(ADAPTER_MESSAGE_STATE_UNKNOWN);
9f68cc28
LOK
288 if (!IsRunning())
289 return retVal;
7bb4ed43
LOK
290
291 CCECAdapterMessage *output = new CCECAdapterMessage(data);
292
293 /* set the number of retries */
294 if (data.opcode == CEC_OPCODE_NONE) //TODO
295 output->maxTries = 1;
296 else if (data.initiator != CECDEVICE_BROADCAST)
297 output->maxTries = iMaxTries;
298
299 output->lineTimeout = iLineTimeout;
300 output->retryTimeout = iRetryLineTimeout;
301 output->tries = 0;
302
4164923b
LOK
303 {
304 CLockObject lock(m_mutex);
305 m_bWaitingForAck[data.destination] = true;
306 }
307
7bb4ed43
LOK
308 bool bRetry(true);
309 while (bRetry && ++output->tries < output->maxTries)
310 {
311 bRetry = (!Write(output) || output->NeedsRetry()) && output->transmit_timeout > 0;
312 if (bRetry)
313 Sleep(CEC_DEFAULT_TRANSMIT_RETRY_WAIT);
314 }
315 retVal = output->state;
316
317 delete output;
318 return retVal;
319}
320
321bool CUSBCECAdapterCommunication::Write(CCECAdapterMessage *data)
3c53ac93 322{
5dcf9f25 323 data->state = ADAPTER_MESSAGE_STATE_WAITING_TO_BE_SENT;
3c53ac93 324 m_outBuffer.Push(data);
f9e01dac 325 data->event.Wait(5000);
5dcf9f25 326
b1f94db1
LOK
327 if ((data->expectControllerAck && data->state != ADAPTER_MESSAGE_STATE_SENT_ACKED) ||
328 (!data->expectControllerAck && data->state != ADAPTER_MESSAGE_STATE_SENT))
5dcf9f25 329 {
b1f94db1
LOK
330 CLibCEC::AddLog(CEC_LOG_DEBUG, "command was not %s", data->state == ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED ? "acked" : "sent");
331 return false;
5dcf9f25
LOK
332 }
333
b1f94db1 334 return true;
a8f0bd18
LOK
335}
336
7bb4ed43 337bool CUSBCECAdapterCommunication::Read(cec_command &command, uint32_t iTimeout)
a8f0bd18 338{
9f68cc28
LOK
339 if (!IsRunning())
340 return false;
341
7bb4ed43
LOK
342 CCECAdapterMessage msg;
343 if (Read(msg, iTimeout))
a8f0bd18 344 {
7bb4ed43 345 if (ParseMessage(msg))
a8f0bd18 346 {
7bb4ed43
LOK
347 command = m_currentframe;
348 m_currentframe.Clear();
349 return true;
a8f0bd18 350 }
7bb4ed43
LOK
351 }
352 return false;
353}
a8f0bd18 354
7bb4ed43
LOK
355bool CUSBCECAdapterCommunication::Read(CCECAdapterMessage &msg, uint32_t iTimeout)
356{
357 CLockObject lock(m_mutex);
a8f0bd18 358
7bb4ed43
LOK
359 msg.Clear();
360 CCECAdapterMessage *buf(NULL);
a8f0bd18 361
7bb4ed43
LOK
362 if (!m_inBuffer.Pop(buf))
363 {
960f33c6 364 if (iTimeout == 0 || !m_rcvCondition.Wait(m_mutex, m_bHasData, iTimeout))
7bb4ed43
LOK
365 return false;
366 m_inBuffer.Pop(buf);
120d4ca8 367 m_bHasData = !m_inBuffer.IsEmpty();
7bb4ed43 368 }
0e31a62c 369
7bb4ed43
LOK
370 if (buf)
371 {
372 msg.packet = buf->packet;
66e5bd72 373 msg.state = ADAPTER_MESSAGE_STATE_INCOMING;
7bb4ed43
LOK
374 delete buf;
375 return true;
376 }
377 return false;
a8f0bd18
LOK
378}
379
7bb4ed43 380CStdString CUSBCECAdapterCommunication::GetError(void) const
a8f0bd18 381{
ba65909d
LOK
382 CStdString strError;
383 strError = m_port->GetError();
384 return strError;
a8f0bd18 385}
2abe74eb 386
7bb4ed43 387bool CUSBCECAdapterCommunication::StartBootloader(void)
2abe74eb 388{
28352a04 389 bool bReturn(false);
2abe74eb 390 if (!IsRunning())
28352a04 391 return bReturn;
2abe74eb 392
5477a250 393 CLibCEC::AddLog(CEC_LOG_DEBUG, "starting the bootloader");
2abe74eb 394
089f0e9d
LOK
395 CCECAdapterMessage params;
396 return SendCommand(MSGCODE_START_BOOTLOADER, params, false);
2abe74eb
LOK
397}
398
7bb4ed43 399bool CUSBCECAdapterCommunication::PingAdapter(void)
2abe74eb 400{
befa3a23 401 CLockObject lock(m_mutex);
5477a250 402 CLibCEC::AddLog(CEC_LOG_DEBUG, "sending ping");
befa3a23 403
089f0e9d
LOK
404 CCECAdapterMessage params;
405 return SendCommand(MSGCODE_PING, params);
2abe74eb 406}
13fd6a66 407
7bb4ed43
LOK
408bool CUSBCECAdapterCommunication::ParseMessage(const CCECAdapterMessage &msg)
409{
410 bool bEom(false);
411 bool bIsError(msg.IsError());
412
413 if (msg.IsEmpty())
414 return bEom;
415
24dd566c 416 CLockObject adapterLock(m_mutex);
7bb4ed43
LOK
417 switch(msg.Message())
418 {
419 case MSGCODE_FRAME_START:
420 {
421 m_currentframe.Clear();
422 if (msg.Size() >= 2)
423 {
424 m_currentframe.initiator = msg.Initiator();
425 m_currentframe.destination = msg.Destination();
426 m_currentframe.ack = msg.IsACK();
427 m_currentframe.eom = msg.IsEOM();
428 }
429 if (m_currentframe.ack == 0x1)
430 {
eb965473 431 m_lastDestination = m_currentframe.destination;
4164923b 432 if (!m_bWaitingForAck[m_currentframe.destination])
eb965473 433 m_processor->HandlePoll(m_currentframe.initiator, m_currentframe.destination);
4164923b 434 else
4164923b 435 m_bWaitingForAck[m_currentframe.destination] = false;
7bb4ed43
LOK
436 }
437 }
438 break;
439 case MSGCODE_RECEIVE_FAILED:
440 {
441 m_currentframe.Clear();
eb965473
LOK
442 if (m_lastDestination != CECDEVICE_UNKNOWN)
443 bIsError = m_processor->HandleReceiveFailed(m_lastDestination);
7bb4ed43
LOK
444 }
445 break;
446 case MSGCODE_FRAME_DATA:
447 {
448 if (msg.Size() >= 2)
449 {
450 m_currentframe.PushBack(msg[1]);
451 m_currentframe.eom = msg.IsEOM();
452 }
7bb4ed43
LOK
453 }
454 break;
455 default:
456 break;
457 }
458
459 CLibCEC::AddLog(bIsError ? CEC_LOG_WARNING : CEC_LOG_DEBUG, msg.ToString());
eb965473 460 return msg.IsEOM();
7bb4ed43
LOK
461}
462
463uint16_t CUSBCECAdapterCommunication::GetFirmwareVersion(void)
1fc16cfd
LOK
464{
465 uint16_t iReturn(m_iFirmwareVersion);
1fc16cfd
LOK
466
467 if (iReturn == CEC_FW_VERSION_UNKNOWN)
468 {
006b76b9 469 CLockObject lock(m_mutex);
5477a250 470 CLibCEC::AddLog(CEC_LOG_DEBUG, "requesting the firmware version");
90008d10 471 cec_datapacket response = GetSetting(MSGCODE_FIRMWARE_VERSION, 2);
d4db0c6f 472 if (response.size == 2)
1fc16cfd 473 {
d4db0c6f
LOK
474 m_iFirmwareVersion = (response[0] << 8 | response[1]);
475 iReturn = m_iFirmwareVersion;
476 CLibCEC::AddLog(CEC_LOG_DEBUG, "firmware version %d", m_iFirmwareVersion);
efed01e1 477 }
1fc16cfd
LOK
478 }
479
480 return iReturn;
481}
482
7bb4ed43 483bool CUSBCECAdapterCommunication::SetLineTimeout(uint8_t iTimeout)
a171d2fd 484{
16459df9 485 bool bReturn(true);
089f0e9d 486
16459df9 487 if (m_iLineTimeout != iTimeout)
089f0e9d
LOK
488 {
489 CLibCEC::AddLog(CEC_LOG_DEBUG, "setting the line timeout to %d", iTimeout);
490 CCECAdapterMessage params;
491 params.PushEscaped(iTimeout);
492 bReturn = SendCommand(MSGCODE_TRANSMIT_IDLETIME, params);
16459df9
LOK
493 if (bReturn)
494 m_iLineTimeout = iTimeout;
089f0e9d
LOK
495 }
496
497 return bReturn;
a171d2fd
LOK
498}
499
7bb4ed43 500bool CUSBCECAdapterCommunication::SetAckMask(uint16_t iMask)
f9e01dac 501{
089f0e9d 502 return SetAckMaskInternal(iMask, IsRunning());
f9e01dac
LOK
503}
504
505bool CUSBCECAdapterCommunication::SetAckMaskInternal(uint16_t iMask, bool bWriteDirectly /* = false */)
5dcf9f25 506{
bca69ca1 507 CLibCEC::AddLog(CEC_LOG_DEBUG, "setting ackmask to %2x", iMask);
5dcf9f25 508
089f0e9d
LOK
509 CCECAdapterMessage params;
510 params.PushEscaped(iMask >> 8);
511 params.PushEscaped((uint8_t)iMask);
512 return SendCommand(MSGCODE_SET_ACK_MASK, params, true, false, bWriteDirectly);
5dcf9f25
LOK
513}
514
c214d197
LOK
515bool CUSBCECAdapterCommunication::PersistConfiguration(libcec_configuration *configuration)
516{
cb4ee028
LOK
517 if (m_iFirmwareVersion < 2)
518 return false;
519
ffdfabf0 520 bool bReturn(true);
12a36be9
LOK
521 bReturn &= SetSettingAutoEnabled(true);
522 bReturn &= SetSettingDeviceType(CLibCEC::GetType(configuration->logicalAddresses.primary));
523 bReturn &= SetSettingDefaultLogicalAddress(configuration->logicalAddresses.primary);
524 bReturn &= SetSettingLogicalAddressMask(CLibCEC::GetMaskForType(configuration->logicalAddresses.primary));
525 bReturn &= SetSettingPhysicalAddress(configuration->iPhysicalAddress);
526 bReturn &= SetSettingCECVersion(CEC_VERSION_1_3A);
527 bReturn &= SetSettingOSDName(configuration->strDeviceName);
ffdfabf0
LOK
528 if (bReturn)
529 bReturn = WriteEEPROM();
530 return bReturn;
c214d197 531}
b057edad 532
12a36be9
LOK
533bool CUSBCECAdapterCommunication::GetConfiguration(libcec_configuration *configuration)
534{
535 if (m_iFirmwareVersion < 2)
536 return false;
537
538 bool bReturn(true);
539 cec_device_type type;
540 if (GetSettingDeviceType(type))
541 {
542 CLibCEC::AddLog(CEC_LOG_DEBUG, "using persisted device type setting %s", m_processor->ToString(type));
543 configuration->deviceTypes.Clear();
544 configuration->deviceTypes.Add(type);
545 }
546 else
547 {
548 CLibCEC::AddLog(CEC_LOG_DEBUG, "no persisted device type setting");
549 bReturn = false;
550 }
551
552 if (GetSettingPhysicalAddress(configuration->iPhysicalAddress))
553 {
554 CLibCEC::AddLog(CEC_LOG_DEBUG, "using persisted physical address setting %4x", configuration->iPhysicalAddress);
555 }
556 else
557 {
558 CLibCEC::AddLog(CEC_LOG_DEBUG, "no persisted physical address setting");
559 bReturn = false;
560 }
561
562 CStdString strDeviceName;
563 if (GetSettingOSDName(strDeviceName))
564 {
565 snprintf(configuration->strDeviceName, 13, "%s", strDeviceName.c_str());
566 CLibCEC::AddLog(CEC_LOG_DEBUG, "using persisted device name setting %s", configuration->strDeviceName);
567 }
568 else
569 {
570 CLibCEC::AddLog(CEC_LOG_DEBUG, "no persisted device name setting");
571 bReturn = false;
572 }
573
574 // don't read the following settings:
575 // - auto enabled (always enabled)
576 // - default logical address (autodetected)
577 // - logical address mask (autodetected)
578 // - CEC version (1.3a)
579
580 // TODO to be added to the firmware:
d28b4393
LOK
581 // - base device (4 bits)
582 // - HDMI port number (4 bits)
583 // - TV vendor id (12 bits)
584 // - wake devices (8 bits)
585 // - standby devices (8 bits)
12a36be9
LOK
586 // - use TV menu language (1 bit)
587 // - activate source (1 bit)
588 // - power off screensaver (1 bit)
589 // - power off on standby (1 bit)
590 // - send inactive source (1 bit)
591 return bReturn;
592}
593
b057edad
BL
594bool CUSBCECAdapterCommunication::SetControlledMode(bool controlled)
595{
befa3a23 596 CLockObject lock(m_mutex);
bca69ca1 597 CLibCEC::AddLog(CEC_LOG_DEBUG, "turning controlled mode %s", controlled ? "on" : "off");
b057edad 598
089f0e9d
LOK
599 CCECAdapterMessage params;
600 params.PushEscaped(controlled ? 1 : 0);
601 return SendCommand(MSGCODE_SET_CONTROLLED, params);
b057edad
BL
602}
603
12a36be9 604bool CUSBCECAdapterCommunication::SetSettingAutoEnabled(bool enabled)
c214d197
LOK
605{
606 CLockObject lock(m_mutex);
607 CLibCEC::AddLog(CEC_LOG_DEBUG, "turning autonomous mode %s", enabled ? "on" : "off");
608
c9c282a4
LOK
609 CCECAdapterMessage params;
610 params.PushEscaped(enabled ? 1 : 0);
611 return SendCommand(MSGCODE_SET_AUTO_ENABLED, params);
c214d197
LOK
612}
613
12a36be9
LOK
614bool CUSBCECAdapterCommunication::GetSettingAutoEnabled(bool &enabled)
615{
616 CLockObject lock(m_mutex);
617 CLibCEC::AddLog(CEC_LOG_DEBUG, "requesting autonomous mode setting");
618
90008d10 619 cec_datapacket response = GetSetting(MSGCODE_GET_AUTO_ENABLED, 1);
12a36be9
LOK
620 if (response.size == 1)
621 {
622 enabled = response[0] == 1;
623 return true;
624 }
625 return false;
626}
627
628bool CUSBCECAdapterCommunication::SetSettingDeviceType(cec_device_type type)
9878069e
LOK
629{
630 CLockObject lock(m_mutex);
631 CLibCEC::AddLog(CEC_LOG_DEBUG, "setting the device type to %1X", (uint8_t)type);
632
c9c282a4
LOK
633 CCECAdapterMessage params;
634 params.PushEscaped((uint8_t)type);
635 return SendCommand(MSGCODE_SET_DEVICE_TYPE, params);
9878069e
LOK
636}
637
12a36be9
LOK
638bool CUSBCECAdapterCommunication::GetSettingDeviceType(cec_device_type &value)
639{
640 CLockObject lock(m_mutex);
641 CLibCEC::AddLog(CEC_LOG_DEBUG, "requesting device type setting");
642
90008d10 643 cec_datapacket response = GetSetting(MSGCODE_GET_DEVICE_TYPE, 1);
12a36be9
LOK
644 if (response.size == 1)
645 {
646 value = (cec_device_type)response[0];
647 return true;
648 }
649 return false;
650}
651
652bool CUSBCECAdapterCommunication::SetSettingDefaultLogicalAddress(cec_logical_address address)
c214d197
LOK
653{
654 CLockObject lock(m_mutex);
655 CLibCEC::AddLog(CEC_LOG_DEBUG, "setting the default logical address to %1X", address);
656
c9c282a4
LOK
657 CCECAdapterMessage params;
658 params.PushEscaped((uint8_t)address);
659 return SendCommand(MSGCODE_SET_DEFAULT_LOGICAL_ADDRESS, params);
c214d197
LOK
660}
661
12a36be9
LOK
662bool CUSBCECAdapterCommunication::GetSettingDefaultLogicalAddress(cec_logical_address &address)
663{
664 CLockObject lock(m_mutex);
665 CLibCEC::AddLog(CEC_LOG_DEBUG, "requesting default logical address setting");
666
90008d10 667 cec_datapacket response = GetSetting(MSGCODE_GET_DEFAULT_LOGICAL_ADDRESS, 1);
12a36be9
LOK
668 if (response.size == 1)
669 {
670 address = (cec_logical_address)response[0];
671 return true;
672 }
673 return false;
674}
675
676bool CUSBCECAdapterCommunication::SetSettingLogicalAddressMask(uint16_t iMask)
c214d197
LOK
677{
678 CLockObject lock(m_mutex);
679 CLibCEC::AddLog(CEC_LOG_DEBUG, "setting the logical address mask to %2X", iMask);
680
c9c282a4
LOK
681 CCECAdapterMessage params;
682 params.PushEscaped(iMask >> 8);
683 params.PushEscaped((uint8_t)iMask);
684 return SendCommand(MSGCODE_SET_LOGICAL_ADDRESS_MASK, params);
c214d197
LOK
685}
686
12a36be9
LOK
687bool CUSBCECAdapterCommunication::GetSettingLogicalAddressMask(uint16_t &iMask)
688{
689 CLockObject lock(m_mutex);
690 CLibCEC::AddLog(CEC_LOG_DEBUG, "requesting logical address mask setting");
691
90008d10 692 cec_datapacket response = GetSetting(MSGCODE_GET_LOGICAL_ADDRESS_MASK, 2);
12a36be9
LOK
693 if (response.size == 2)
694 {
695 iMask = ((uint16_t)response[0] << 8) | ((uint16_t)response[1]);
696 return true;
697 }
698 return false;
699}
700
701bool CUSBCECAdapterCommunication::SetSettingPhysicalAddress(uint16_t iPhysicalAddress)
c214d197
LOK
702{
703 CLockObject lock(m_mutex);
9ff1aa80 704 CLibCEC::AddLog(CEC_LOG_DEBUG, "setting the physical address to %04X", iPhysicalAddress);
c214d197 705
c9c282a4
LOK
706 CCECAdapterMessage params;
707 params.PushEscaped(iPhysicalAddress >> 8);
708 params.PushEscaped((uint8_t)iPhysicalAddress);
709 return SendCommand(MSGCODE_SET_PHYSICAL_ADDRESS, params);
c214d197
LOK
710}
711
12a36be9
LOK
712bool CUSBCECAdapterCommunication::GetSettingPhysicalAddress(uint16_t &iPhysicalAddress)
713{
714 CLockObject lock(m_mutex);
715 CLibCEC::AddLog(CEC_LOG_DEBUG, "requesting physical address setting");
716
90008d10 717 cec_datapacket response = GetSetting(MSGCODE_GET_PHYSICAL_ADDRESS, 2);
12a36be9
LOK
718 if (response.size == 2)
719 {
720 iPhysicalAddress = ((uint16_t)response[0] << 8) | ((uint16_t)response[1]);
721 return true;
722 }
723 return false;
724}
725
726bool CUSBCECAdapterCommunication::SetSettingCECVersion(cec_version version)
c214d197
LOK
727{
728 CLockObject lock(m_mutex);
729 CLibCEC::AddLog(CEC_LOG_DEBUG, "setting the CEC version to %s", CLibCEC::GetInstance()->ToString(version));
730
c9c282a4
LOK
731 CCECAdapterMessage params;
732 params.PushEscaped((uint8_t)version);
733 return SendCommand(MSGCODE_SET_HDMI_VERSION, params);
c214d197
LOK
734}
735
12a36be9
LOK
736bool CUSBCECAdapterCommunication::GetSettingCECVersion(cec_version &version)
737{
738 CLockObject lock(m_mutex);
739 CLibCEC::AddLog(CEC_LOG_DEBUG, "requesting CEC version setting");
740
90008d10 741 cec_datapacket response = GetSetting(MSGCODE_GET_HDMI_VERSION, 1);
12a36be9
LOK
742 if (response.size == 1)
743 {
744 version = (cec_version)response[0];
745 return true;
746 }
747 return false;
748}
749
750bool CUSBCECAdapterCommunication::SetSettingOSDName(const char *strOSDName)
c214d197
LOK
751{
752 CLockObject lock(m_mutex);
753 CLibCEC::AddLog(CEC_LOG_DEBUG, "setting the OSD name to %s", strOSDName);
754
c9c282a4 755 CCECAdapterMessage params;
c214d197 756 for (size_t iPtr = 0; iPtr < strlen(strOSDName); iPtr++)
c9c282a4
LOK
757 params.PushEscaped(strOSDName[iPtr]);
758 return SendCommand(MSGCODE_SET_OSD_NAME, params);
c214d197
LOK
759}
760
12a36be9
LOK
761bool CUSBCECAdapterCommunication::GetSettingOSDName(CStdString &strOSDName)
762{
763 CLockObject lock(m_mutex);
764 CLibCEC::AddLog(CEC_LOG_DEBUG, "requesting OSD name setting");
765
90008d10 766 cec_datapacket response = GetSetting(MSGCODE_GET_OSD_NAME, 13);
12a36be9
LOK
767 if (response.size == 0)
768 return false;
769
90008d10
LOK
770 char buf[14];
771 for (uint8_t iPtr = 0; iPtr < response.size && iPtr < 13; iPtr++)
12a36be9
LOK
772 buf[iPtr] = (char)response[iPtr];
773 buf[response.size] = 0;
774
775 strOSDName.Format("%s", buf);
776 return true;
777}
778
c214d197
LOK
779bool CUSBCECAdapterCommunication::WriteEEPROM(void)
780{
781 CLockObject lock(m_mutex);
782 CLibCEC::AddLog(CEC_LOG_DEBUG, "writing settings in the EEPROM");
783
c9c282a4
LOK
784 CCECAdapterMessage params;
785 return SendCommand(MSGCODE_WRITE_EEPROM, params);
c214d197
LOK
786}
787
7bb4ed43 788bool CUSBCECAdapterCommunication::IsOpen(void)
13fd6a66 789{
b9eea66d 790 return !IsStopped() && m_port->IsOpen() && IsRunning();
13fd6a66 791}
ef7696f5 792
7bb4ed43 793bool CUSBCECAdapterCommunication::WaitForAck(CCECAdapterMessage &message)
6729ac71
LOK
794{
795 bool bError(false);
796 bool bTransmitSucceeded(false);
99f1d66e 797 uint8_t iPacketsLeft(message.isTransmission ? message.Size() / 4 : 1);
6729ac71
LOK
798
799 int64_t iNow = GetTimeMs();
b1f94db1 800 int64_t iTargetTime = iNow + (message.transmit_timeout <= 5 ? CEC_DEFAULT_TRANSMIT_WAIT : message.transmit_timeout);
6729ac71 801
b1f94db1 802 while (!bTransmitSucceeded && !bError && iNow < iTargetTime)
6729ac71 803 {
b1f94db1 804 ReadFromDevice(50);
6729ac71 805 CCECAdapterMessage msg;
b1f94db1 806 if (!Read(msg, 0))
6729ac71
LOK
807 {
808 iNow = GetTimeMs();
809 continue;
810 }
811
812 if (msg.Message() == MSGCODE_FRAME_START && msg.IsACK())
813 {
4164923b
LOK
814 if (m_bWaitingForAck[msg.Initiator()])
815 m_bWaitingForAck[msg.Initiator()] = false;
816 else
817 {
818 m_processor->HandlePoll(msg.Initiator(), msg.Destination());
eb965473 819 m_lastDestination = msg.Initiator();
4164923b 820 }
6729ac71
LOK
821 iNow = GetTimeMs();
822 continue;
823 }
824
825 if (msg.Message() == MSGCODE_RECEIVE_FAILED &&
eb965473
LOK
826 m_lastDestination != CECDEVICE_UNKNOWN &&
827 m_processor->HandleReceiveFailed(m_lastDestination))
6729ac71
LOK
828 {
829 iNow = GetTimeMs();
830 continue;
831 }
832
833 bError = msg.IsError();
834 if (bError)
835 {
b2f0b1ab 836 message.reply = msg.Message();
5477a250 837 CLibCEC::AddLog(CEC_LOG_DEBUG, msg.ToString());
6729ac71
LOK
838 }
839 else
840 {
841 switch(msg.Message())
842 {
843 case MSGCODE_COMMAND_ACCEPTED:
6729ac71
LOK
844 if (iPacketsLeft > 0)
845 iPacketsLeft--;
b2f0b1ab 846 if (!message.isTransmission && iPacketsLeft == 0)
5dcf9f25 847 bTransmitSucceeded = true;
befa3a23 848 CLibCEC::AddLog(CEC_LOG_DEBUG, "%s - waiting for %d more", msg.ToString().c_str(), iPacketsLeft);
6729ac71
LOK
849 break;
850 case MSGCODE_TRANSMIT_SUCCEEDED:
5477a250 851 CLibCEC::AddLog(CEC_LOG_DEBUG, msg.ToString());
6729ac71
LOK
852 bTransmitSucceeded = (iPacketsLeft == 0);
853 bError = !bTransmitSucceeded;
b2f0b1ab 854 message.reply = MSGCODE_TRANSMIT_SUCCEEDED;
6729ac71
LOK
855 break;
856 default:
857 // ignore other data while waiting
858 break;
859 }
860
861 iNow = GetTimeMs();
862 }
863 }
864
b1f94db1
LOK
865 message.state = bTransmitSucceeded && !bError ?
866 ADAPTER_MESSAGE_STATE_SENT_ACKED :
867 ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED;
868
6729ac71
LOK
869 return bTransmitSucceeded && !bError;
870}
871
7bb4ed43 872void CUSBCECAdapterCommunication::AddData(uint8_t *data, size_t iLen)
ef7696f5
LOK
873{
874 CLockObject lock(m_mutex);
99666519 875 for (size_t iPtr = 0; iPtr < iLen; iPtr++)
7bb4ed43
LOK
876 {
877 if (!m_bGotStart)
878 {
879 if (data[iPtr] == MSGSTART)
880 m_bGotStart = true;
881 }
882 else if (data[iPtr] == MSGSTART) //we found a msgstart before msgend, this is not right, remove
883 {
884 if (m_currentAdapterMessage.Size() > 0)
885 CLibCEC::AddLog(CEC_LOG_WARNING, "received MSGSTART before MSGEND, removing previous buffer contents");
886 m_currentAdapterMessage.Clear();
887 m_bGotStart = true;
888 }
889 else if (data[iPtr] == MSGEND)
890 {
891 CCECAdapterMessage *newMessage = new CCECAdapterMessage;
892 newMessage->packet = m_currentAdapterMessage.packet;
893 m_inBuffer.Push(newMessage);
894 m_currentAdapterMessage.Clear();
895 m_bGotStart = false;
896 m_bNextIsEscaped = false;
960f33c6 897 m_bHasData = true;
24dd566c 898 m_rcvCondition.Broadcast();
7bb4ed43
LOK
899 }
900 else if (m_bNextIsEscaped)
901 {
902 m_currentAdapterMessage.PushBack(data[iPtr] + (uint8_t)ESCOFFSET);
903 m_bNextIsEscaped = false;
904 }
905 else if (data[iPtr] == MSGESC)
906 {
907 m_bNextIsEscaped = true;
908 }
909 else
910 {
911 m_currentAdapterMessage.PushBack(data[iPtr]);
912 }
913 }
ef7696f5
LOK
914}
915
b1f94db1 916bool CUSBCECAdapterCommunication::ReadFromDevice(uint32_t iTimeout, size_t iSize /* = 256 */)
ef7696f5 917{
99666519
LOK
918 ssize_t iBytesRead;
919 uint8_t buff[256];
ef7696f5
LOK
920 if (!m_port)
921 return false;
b1f94db1
LOK
922 if (iSize > 256)
923 iSize = 256;
ef7696f5 924
1fc16cfd 925 CLockObject lock(m_mutex);
b1f94db1 926 iBytesRead = m_port->Read(buff, sizeof(uint8_t) * iSize, iTimeout);
ef7696f5
LOK
927 if (iBytesRead < 0 || iBytesRead > 256)
928 {
99666519 929 CLibCEC::AddLog(CEC_LOG_ERROR, "error reading from serial port: %s", m_port->GetError().c_str());
60383b11 930 StopThread(false);
ef7696f5
LOK
931 return false;
932 }
933 else if (iBytesRead > 0)
99666519
LOK
934 {
935 AddData(buff, iBytesRead);
936 }
ef7696f5
LOK
937
938 return iBytesRead > 0;
939}
940
7bb4ed43 941void CUSBCECAdapterCommunication::SendMessageToAdapter(CCECAdapterMessage *msg)
ef7696f5 942{
1fc16cfd 943 CLockObject adapterLock(m_mutex);
f9e01dac
LOK
944 if (!m_port->IsOpen())
945 {
946 CLibCEC::AddLog(CEC_LOG_ERROR, "error writing to serial port: the connection is closed");
947 msg->state = ADAPTER_MESSAGE_STATE_ERROR;
948 return;
949 }
950
089f0e9d
LOK
951 if (msg->isTransmission && (msg->Size() < 2 || msg->At(1) != MSGCODE_TRANSMIT_IDLETIME))
952 {
953 if (msg->tries == 1)
954 SetLineTimeout(msg->lineTimeout);
955 else
956 SetLineTimeout(msg->retryTimeout);
957 }
7bb4ed43 958
99666519 959 if (m_port->Write(msg->packet.data, msg->Size()) != (ssize_t) msg->Size())
ef7696f5 960 {
b74fd339 961 CLibCEC::AddLog(CEC_LOG_ERROR, "error writing to serial port: %s", m_port->GetError().c_str());
ef7696f5
LOK
962 msg->state = ADAPTER_MESSAGE_STATE_ERROR;
963 }
964 else
965 {
5477a250 966 CLibCEC::AddLog(CEC_LOG_DEBUG, "command sent");
ef7696f5 967 msg->state = ADAPTER_MESSAGE_STATE_SENT;
b1f94db1
LOK
968
969 if (msg->expectControllerAck)
970 {
971 if (!WaitForAck(*msg))
972 CLibCEC::AddLog(CEC_LOG_DEBUG, "did not receive ack");
973 }
ef7696f5 974 }
960f33c6 975 msg->event.Signal();
ef7696f5
LOK
976}
977
7bb4ed43 978void CUSBCECAdapterCommunication::WriteNextCommand(void)
ef7696f5
LOK
979{
980 CCECAdapterMessage *msg(NULL);
981 if (m_outBuffer.Pop(msg))
982 SendMessageToAdapter(msg);
983}
cba904a6
LOK
984
985CStdString CUSBCECAdapterCommunication::GetPortName(void)
986{
987 CStdString strName;
988 strName = m_port->GetName();
989 return strName;
990}
c9c282a4 991
9b175d9c 992bool CUSBCECAdapterCommunication::SendCommand(cec_adapter_messagecode msgCode, CCECAdapterMessage &params, bool bExpectAck /* = true */, bool bIsTransmission /* = false */, bool bSendDirectly /* = true */, bool bIsRetry /* = false */)
c9c282a4
LOK
993{
994 CLockObject lock(m_mutex);
995
996 CCECAdapterMessage *output = new CCECAdapterMessage;
997
998 output->PushBack(MSGSTART);
edd18f05 999 output->PushEscaped((uint8_t)msgCode);
c9c282a4
LOK
1000 output->Append(params);
1001 output->PushBack(MSGEND);
089f0e9d
LOK
1002 output->isTransmission = bIsTransmission;
1003 output->expectControllerAck = bExpectAck;
1004
1005 if (bSendDirectly)
1006 SendMessageToAdapter(output);
1007 else
1008 Write(output);
c9c282a4 1009
089f0e9d 1010 bool bWriteOk = output->state == (output->expectControllerAck ? ADAPTER_MESSAGE_STATE_SENT_ACKED : ADAPTER_MESSAGE_STATE_SENT);
c9c282a4
LOK
1011 if (!bWriteOk)
1012 {
7a87e02e 1013 CLibCEC::AddLog(CEC_LOG_ERROR, "'%s' failed", CCECAdapterMessage::ToString(msgCode));
c9c282a4 1014 delete output;
9b175d9c
LOK
1015
1016 if (!bIsRetry && output->reply == MSGCODE_COMMAND_REJECTED && msgCode != MSGCODE_SET_CONTROLLED)
1017 {
1018 CLibCEC::AddLog(CEC_LOG_DEBUG, "setting controlled mode and retrying");
1019 if (SetControlledMode(true))
1020 return SendCommand(msgCode, params, bExpectAck, bIsTransmission, bSendDirectly, true);
1021 }
c9c282a4
LOK
1022 return false;
1023 }
1024
1025 delete output;
1026 return true;
1027}
d4db0c6f 1028
90008d10 1029cec_datapacket CUSBCECAdapterCommunication::GetSetting(cec_adapter_messagecode msgCode, uint8_t iResponseLength)
d4db0c6f
LOK
1030{
1031 cec_datapacket retVal;
1032 retVal.Clear();
1033
1034 CCECAdapterMessage params;
1035 if (!SendCommand(msgCode, params, false))
1036 {
1037 CLibCEC::AddLog(CEC_LOG_ERROR, "%s failed", CCECAdapterMessage::ToString(msgCode));
1038 return retVal;
1039 }
1040
1041 Sleep(250); // TODO ReadFromDevice() isn't waiting for the timeout to pass on win32
90008d10 1042 ReadFromDevice(CEC_DEFAULT_TRANSMIT_WAIT, iResponseLength + 3 /* start + msgcode + iResponseLength + end */);
d4db0c6f
LOK
1043 CCECAdapterMessage input;
1044 if (Read(input, 0))
1045 {
1046 if (input.Message() != msgCode)
1047 CLibCEC::AddLog(CEC_LOG_ERROR, "invalid response to %s received (%s)", CCECAdapterMessage::ToString(msgCode), CCECAdapterMessage::ToString(input.Message()));
1048 else
1049 {
1050 for (uint8_t iPtr = 1; iPtr < input.Size(); iPtr++)
1051 retVal.PushBack(input[iPtr]);
1052 }
1053 }
1054 else
1055 {
1056 CLibCEC::AddLog(CEC_LOG_ERROR, "no response to %s received", CCECAdapterMessage::ToString(msgCode));
1057 }
1058
1059 return retVal;
1060}