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