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