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