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