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