cec: don't keep the mutex locked while opening/closing a connection in CCECProcessor...
[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
83554890
LOK
43void *CUSBCECAdapterProcessor::Process(void)
44{
45 cec_command command;
46 while (!IsStopped())
47 {
48 if (m_inBuffer.Pop(command))
49 m_callback->OnCommandReceived(command);
50 Sleep(5);
51 }
52
53 return NULL;
54}
55
56void CUSBCECAdapterProcessor::AddCommand(cec_command command)
57{
58 m_inBuffer.Push(command);
59}
60
7bb4ed43 61CUSBCECAdapterCommunication::CUSBCECAdapterCommunication(CCECProcessor *processor, const char *strPort, uint16_t iBaudRate /* = 38400 */) :
12027dbe 62 m_port(NULL),
a171d2fd 63 m_processor(processor),
960f33c6 64 m_bHasData(false),
1fc16cfd 65 m_iLineTimeout(0),
7bb4ed43
LOK
66 m_iFirmwareVersion(CEC_FW_VERSION_UNKNOWN),
67 m_lastInitiator(CECDEVICE_UNKNOWN),
68 m_bNextIsEscaped(false),
83554890
LOK
69 m_bGotStart(false),
70 m_messageProcessor(NULL)
a8f0bd18 71{
99666519 72 m_port = new PLATFORM::CSerialPort(strPort, iBaudRate);
a8f0bd18
LOK
73}
74
7bb4ed43 75CUSBCECAdapterCommunication::~CUSBCECAdapterCommunication(void)
a8f0bd18 76{
12027dbe 77 Close();
a8f0bd18
LOK
78}
79
efed01e1 80bool CUSBCECAdapterCommunication::CheckAdapter(uint32_t iTimeoutMs /* = 10000 */)
a8f0bd18 81{
efed01e1 82 bool bReturn(false);
7b494bea 83 uint64_t iNow = GetTimeMs();
efed01e1 84 uint64_t iTarget = iTimeoutMs > 0 ? iNow + iTimeoutMs : iNow + CEC_DEFAULT_TRANSMIT_WAIT;
7b494bea 85
efed01e1
LOK
86 /* try to ping the adapter */
87 bool bPinged(false);
88 unsigned iPingTry(0);
89 while (iNow < iTarget && (bPinged = PingAdapter()) == false)
13fd6a66 90 {
efed01e1
LOK
91 CLibCEC::AddLog(CEC_LOG_ERROR, "the adapter did not respond correctly to a ping (try %d)", ++iPingTry);
92 Sleep(500);
93 iNow = GetTimeMs();
13fd6a66
LOK
94 }
95
efed01e1
LOK
96 /* try to read the firmware version */
97 m_iFirmwareVersion = CEC_FW_VERSION_UNKNOWN;
98 unsigned iFwVersionTry(0);
99 while (bPinged && iNow < iTarget && (m_iFirmwareVersion = GetFirmwareVersion()) == CEC_FW_VERSION_UNKNOWN)
13fd6a66 100 {
efed01e1
LOK
101 CLibCEC::AddLog(CEC_LOG_ERROR, "the adapter did not respond with a correct firmware version (try %d)", ++iFwVersionTry);
102 Sleep(500);
103 iNow = GetTimeMs();
13fd6a66 104 }
a8f0bd18 105
efed01e1 106 if (m_iFirmwareVersion >= 2)
7b494bea 107 {
efed01e1
LOK
108 /* try to set controlled mode */
109 unsigned iControlledTry(0);
110 bool bControlled(false);
111 while (iNow < iTarget && (bControlled = SetControlledMode(true)) == false)
7b494bea 112 {
efed01e1
LOK
113 CLibCEC::AddLog(CEC_LOG_ERROR, "the adapter did not respond correctly to setting controlled mode (try %d)", ++iControlledTry);
114 Sleep(500);
7b494bea
LOK
115 iNow = GetTimeMs();
116 }
efed01e1 117 bReturn = bControlled;
7b494bea 118 }
efed01e1
LOK
119 else
120 bReturn = true;
7b494bea 121
efed01e1
LOK
122 return bReturn;
123}
a8f0bd18 124
efed01e1
LOK
125bool CUSBCECAdapterCommunication::Open(IAdapterCommunicationCallback *cb, uint32_t iTimeoutMs /* = 10000 */)
126{
127 uint64_t iNow = GetTimeMs();
128 uint64_t iTimeout = iNow + iTimeoutMs;
a8f0bd18 129
2c780401 130 {
efed01e1
LOK
131 CLockObject lock(m_mutex);
132
133 if (!m_port)
134 {
135 CLibCEC::AddLog(CEC_LOG_ERROR, "port is NULL");
136 return false;
137 }
138
139 if (IsOpen())
140 {
141 CLibCEC::AddLog(CEC_LOG_ERROR, "port is already open");
142 return true;
143 }
144
145 m_callback = cb;
146 CStdString strError;
147 bool bConnected(false);
148 while (!bConnected && iNow < iTimeout)
149 {
150 if ((bConnected = m_port->Open(iTimeout)) == false)
151 {
152 strError.Format("error opening serial port '%s': %s", m_port->GetName().c_str(), m_port->GetError().c_str());
153 Sleep(250);
154 iNow = GetTimeMs();
155 }
156 }
157
158 if (!bConnected)
159 {
160 CLibCEC::AddLog(CEC_LOG_ERROR, strError);
161 return false;
162 }
163
164 CLibCEC::AddLog(CEC_LOG_DEBUG, "connection opened, clearing any previous input and waiting for active transmissions to end before starting");
165
166 //clear any input bytes
167 uint8_t buff[1024];
168 while (m_port->Read(buff, 1024, 100) > 0)
169 {
170 CLibCEC::AddLog(CEC_LOG_DEBUG, "data received, clearing it");
171 Sleep(250);
172 }
2c780401 173 }
a8f0bd18 174
828682d3 175 if (CreateThread())
a8f0bd18 176 {
efed01e1
LOK
177 if (!CheckAdapter())
178 {
179 StopThread();
180 CLibCEC::AddLog(CEC_LOG_ERROR, "the adapter failed to pass basic checks");
181 }
182 else
183 {
184 CLibCEC::AddLog(CEC_LOG_DEBUG, "communication thread started");
185 return true;
186 }
a8f0bd18 187 }
efed01e1 188 CLibCEC::AddLog(CEC_LOG_ERROR, "could not create a communication thread");
a8f0bd18
LOK
189
190 return false;
191}
192
7bb4ed43 193void CUSBCECAdapterCommunication::Close(void)
a8f0bd18 194{
b9eea66d 195 StopThread();
a8f0bd18
LOK
196}
197
7bb4ed43 198void *CUSBCECAdapterCommunication::Process(void)
a8f0bd18 199{
83554890
LOK
200 m_messageProcessor = new CUSBCECAdapterProcessor(m_callback);
201 m_messageProcessor->CreateThread();
202
b1f94db1 203 cec_command command;
32553784 204 command.Clear();
efed01e1 205 bool bCommandReceived(false);
13fd6a66 206 while (!IsStopped())
a8f0bd18 207 {
efed01e1
LOK
208 {
209 CLockObject lock(m_mutex);
210 ReadFromDevice(50);
211 bCommandReceived = m_callback && Read(command, 0);
212 }
b1f94db1
LOK
213
214 /* push the next command to the callback method if there is one */
efed01e1 215 if (!IsStopped() && bCommandReceived)
83554890 216 m_messageProcessor->AddCommand(command);
b1f94db1 217
efed01e1
LOK
218 if (!IsStopped())
219 {
220 Sleep(5);
221 WriteNextCommand();
222 }
a8f0bd18
LOK
223 }
224
83554890
LOK
225 /* stop the message processor */
226 m_messageProcessor->StopThread();
227 delete m_messageProcessor;
228
f9e01dac 229 /* notify all threads that are waiting on messages to be sent */
ef7696f5 230 CCECAdapterMessage *msg(NULL);
f9e01dac 231 while (m_outBuffer.Pop(msg))
960f33c6 232 msg->event.Broadcast();
a0878ee3 233
f9e01dac
LOK
234 /* set the ackmask to 0 before closing the connection */
235 SetAckMaskInternal(0, true);
236
9f9c8c82
LOK
237 if (m_port)
238 {
239 delete m_port;
240 m_port = NULL;
241 }
242
a8f0bd18
LOK
243 return NULL;
244}
245
7bb4ed43
LOK
246cec_adapter_message_state CUSBCECAdapterCommunication::Write(const cec_command &data, uint8_t iMaxTries, uint8_t iLineTimeout /* = 3 */, uint8_t iRetryLineTimeout /* = 3 */)
247{
248 cec_adapter_message_state retVal(ADAPTER_MESSAGE_STATE_UNKNOWN);
9f68cc28
LOK
249 if (!IsRunning())
250 return retVal;
7bb4ed43
LOK
251
252 CCECAdapterMessage *output = new CCECAdapterMessage(data);
253
254 /* set the number of retries */
255 if (data.opcode == CEC_OPCODE_NONE) //TODO
256 output->maxTries = 1;
257 else if (data.initiator != CECDEVICE_BROADCAST)
258 output->maxTries = iMaxTries;
259
260 output->lineTimeout = iLineTimeout;
261 output->retryTimeout = iRetryLineTimeout;
262 output->tries = 0;
263
264 bool bRetry(true);
265 while (bRetry && ++output->tries < output->maxTries)
266 {
267 bRetry = (!Write(output) || output->NeedsRetry()) && output->transmit_timeout > 0;
268 if (bRetry)
269 Sleep(CEC_DEFAULT_TRANSMIT_RETRY_WAIT);
270 }
271 retVal = output->state;
272
273 delete output;
274 return retVal;
275}
276
277bool CUSBCECAdapterCommunication::Write(CCECAdapterMessage *data)
3c53ac93 278{
5dcf9f25 279 data->state = ADAPTER_MESSAGE_STATE_WAITING_TO_BE_SENT;
3c53ac93 280 m_outBuffer.Push(data);
f9e01dac 281 data->event.Wait(5000);
5dcf9f25 282
b1f94db1
LOK
283 if ((data->expectControllerAck && data->state != ADAPTER_MESSAGE_STATE_SENT_ACKED) ||
284 (!data->expectControllerAck && data->state != ADAPTER_MESSAGE_STATE_SENT))
5dcf9f25 285 {
b1f94db1
LOK
286 CLibCEC::AddLog(CEC_LOG_DEBUG, "command was not %s", data->state == ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED ? "acked" : "sent");
287 return false;
5dcf9f25
LOK
288 }
289
b1f94db1 290 return true;
a8f0bd18
LOK
291}
292
7bb4ed43 293bool CUSBCECAdapterCommunication::Read(cec_command &command, uint32_t iTimeout)
a8f0bd18 294{
9f68cc28
LOK
295 if (!IsRunning())
296 return false;
297
7bb4ed43
LOK
298 CCECAdapterMessage msg;
299 if (Read(msg, iTimeout))
a8f0bd18 300 {
7bb4ed43 301 if (ParseMessage(msg))
a8f0bd18 302 {
7bb4ed43
LOK
303 command = m_currentframe;
304 m_currentframe.Clear();
305 return true;
a8f0bd18 306 }
7bb4ed43
LOK
307 }
308 return false;
309}
a8f0bd18 310
7bb4ed43
LOK
311bool CUSBCECAdapterCommunication::Read(CCECAdapterMessage &msg, uint32_t iTimeout)
312{
313 CLockObject lock(m_mutex);
a8f0bd18 314
7bb4ed43
LOK
315 msg.Clear();
316 CCECAdapterMessage *buf(NULL);
a8f0bd18 317
7bb4ed43
LOK
318 if (!m_inBuffer.Pop(buf))
319 {
960f33c6 320 if (iTimeout == 0 || !m_rcvCondition.Wait(m_mutex, m_bHasData, iTimeout))
7bb4ed43
LOK
321 return false;
322 m_inBuffer.Pop(buf);
960f33c6 323 m_bHasData = m_inBuffer.Size() > 0;
7bb4ed43 324 }
0e31a62c 325
7bb4ed43
LOK
326 if (buf)
327 {
328 msg.packet = buf->packet;
66e5bd72 329 msg.state = ADAPTER_MESSAGE_STATE_INCOMING;
7bb4ed43
LOK
330 delete buf;
331 return true;
332 }
333 return false;
a8f0bd18
LOK
334}
335
7bb4ed43 336CStdString CUSBCECAdapterCommunication::GetError(void) const
a8f0bd18 337{
ba65909d
LOK
338 CStdString strError;
339 strError = m_port->GetError();
340 return strError;
a8f0bd18 341}
2abe74eb 342
7bb4ed43 343bool CUSBCECAdapterCommunication::StartBootloader(void)
2abe74eb 344{
28352a04 345 bool bReturn(false);
2abe74eb 346 if (!IsRunning())
28352a04 347 return bReturn;
2abe74eb 348
5477a250 349 CLibCEC::AddLog(CEC_LOG_DEBUG, "starting the bootloader");
28352a04 350 CCECAdapterMessage *output = new CCECAdapterMessage;
25701fa6 351
ef7696f5
LOK
352 output->PushBack(MSGSTART);
353 output->PushEscaped(MSGCODE_START_BOOTLOADER);
354 output->PushBack(MSGEND);
5dcf9f25 355 output->isTransmission = false;
71c4a2f5 356 output->expectControllerAck = false;
2abe74eb 357
5dcf9f25 358 if ((bReturn = Write(output)) == false)
5477a250 359 CLibCEC::AddLog(CEC_LOG_ERROR, "could not start the bootloader");
28352a04
LOK
360 delete output;
361
362 return bReturn;
2abe74eb
LOK
363}
364
7bb4ed43 365bool CUSBCECAdapterCommunication::PingAdapter(void)
2abe74eb 366{
28352a04 367 bool bReturn(false);
2abe74eb 368 if (!IsRunning())
28352a04 369 return bReturn;
2abe74eb 370
5477a250 371 CLibCEC::AddLog(CEC_LOG_DEBUG, "sending ping");
28352a04 372 CCECAdapterMessage *output = new CCECAdapterMessage;
25701fa6 373
ef7696f5
LOK
374 output->PushBack(MSGSTART);
375 output->PushEscaped(MSGCODE_PING);
376 output->PushBack(MSGEND);
5dcf9f25 377 output->isTransmission = false;
2abe74eb 378
5dcf9f25 379 if ((bReturn = Write(output)) == false)
5477a250 380 CLibCEC::AddLog(CEC_LOG_ERROR, "could not ping the adapter");
28352a04
LOK
381 delete output;
382
383 return bReturn;
2abe74eb 384}
13fd6a66 385
7bb4ed43
LOK
386bool CUSBCECAdapterCommunication::ParseMessage(const CCECAdapterMessage &msg)
387{
388 bool bEom(false);
389 bool bIsError(msg.IsError());
390
391 if (msg.IsEmpty())
392 return bEom;
393
394 switch(msg.Message())
395 {
396 case MSGCODE_FRAME_START:
397 {
398 m_currentframe.Clear();
399 if (msg.Size() >= 2)
400 {
401 m_currentframe.initiator = msg.Initiator();
402 m_currentframe.destination = msg.Destination();
403 m_currentframe.ack = msg.IsACK();
404 m_currentframe.eom = msg.IsEOM();
405 }
406 if (m_currentframe.ack == 0x1)
407 {
408 m_lastInitiator = m_currentframe.initiator;
409 m_processor->HandlePoll(m_currentframe.initiator, m_currentframe.destination);
410 }
411 }
412 break;
413 case MSGCODE_RECEIVE_FAILED:
414 {
415 m_currentframe.Clear();
416 if (m_lastInitiator != CECDEVICE_UNKNOWN)
417 bIsError = m_processor->HandleReceiveFailed(m_lastInitiator);
418 }
419 break;
420 case MSGCODE_FRAME_DATA:
421 {
422 if (msg.Size() >= 2)
423 {
424 m_currentframe.PushBack(msg[1]);
425 m_currentframe.eom = msg.IsEOM();
426 }
427 bEom = msg.IsEOM();
428 }
429 break;
430 default:
431 break;
432 }
433
434 CLibCEC::AddLog(bIsError ? CEC_LOG_WARNING : CEC_LOG_DEBUG, msg.ToString());
435 return bEom;
436}
437
438uint16_t CUSBCECAdapterCommunication::GetFirmwareVersion(void)
1fc16cfd
LOK
439{
440 uint16_t iReturn(m_iFirmwareVersion);
441 if (!IsRunning())
442 return iReturn;
443
444 if (iReturn == CEC_FW_VERSION_UNKNOWN)
445 {
006b76b9 446 CLockObject lock(m_mutex);
5477a250 447 CLibCEC::AddLog(CEC_LOG_DEBUG, "requesting the firmware version");
1fc16cfd
LOK
448 CCECAdapterMessage *output = new CCECAdapterMessage;
449
450 output->PushBack(MSGSTART);
451 output->PushEscaped(MSGCODE_FIRMWARE_VERSION);
452 output->PushBack(MSGEND);
453 output->isTransmission = false;
454 output->expectControllerAck = false;
455
efed01e1
LOK
456 SendMessageToAdapter(output);
457 bool bWriteOk = output->state == ADAPTER_MESSAGE_STATE_SENT;
1fc16cfd 458 delete output;
b1f94db1
LOK
459 if (!bWriteOk)
460 {
461 CLibCEC::AddLog(CEC_LOG_ERROR, "could not request the firmware version");
efed01e1 462 return iReturn;
b1f94db1 463 }
efed01e1
LOK
464
465 Sleep(250); // TODO ReadFromDevice() isn't waiting for the timeout to pass on win32
466 ReadFromDevice(CEC_DEFAULT_TRANSMIT_WAIT, 5 /* start + msgcode + 2 bytes for fw version + end */);
467 CCECAdapterMessage input;
468 if (Read(input, 0))
1fc16cfd 469 {
efed01e1
LOK
470 if (input.Message() != MSGCODE_FIRMWARE_VERSION || input.Size() != 3)
471 CLibCEC::AddLog(CEC_LOG_ERROR, "invalid firmware version (size = %d, message = %d)", input.Size(), input.Message());
b1f94db1
LOK
472 else
473 {
474 m_iFirmwareVersion = (input[1] << 8 | input[2]);
475 iReturn = m_iFirmwareVersion;
476 }
1fc16cfd 477 }
efed01e1
LOK
478 else
479 {
480 CLibCEC::AddLog(CEC_LOG_ERROR, "no firmware version received");
481 }
1fc16cfd
LOK
482 }
483
484 return iReturn;
485}
486
7bb4ed43 487bool CUSBCECAdapterCommunication::SetLineTimeout(uint8_t iTimeout)
a171d2fd 488{
7bb4ed43
LOK
489 m_iLineTimeout = iTimeout;
490 return true;
491 //TODO
492// bool bReturn(m_iLineTimeout != iTimeout);
493//
494// if (!bReturn)
495// {
496// CCECAdapterMessage *output = new CCECAdapterMessage;
497//
498// output->PushBack(MSGSTART);
499// output->PushEscaped(MSGCODE_TRANSMIT_IDLETIME);
500// output->PushEscaped(iTimeout);
501// output->PushBack(MSGEND);
502// output->isTransmission = false;
503//
504// if ((bReturn = Write(output)) == false)
505// CLibCEC::AddLog(CEC_LOG_ERROR, "could not set the idletime");
506// delete output;
507// }
508//
509// return bReturn;
a171d2fd
LOK
510}
511
7bb4ed43 512bool CUSBCECAdapterCommunication::SetAckMask(uint16_t iMask)
f9e01dac
LOK
513{
514 return SetAckMaskInternal(iMask, false);
515}
516
517bool CUSBCECAdapterCommunication::SetAckMaskInternal(uint16_t iMask, bool bWriteDirectly /* = false */)
5dcf9f25
LOK
518{
519 bool bReturn(false);
bca69ca1 520 CLibCEC::AddLog(CEC_LOG_DEBUG, "setting ackmask to %2x", iMask);
5dcf9f25
LOK
521
522 CCECAdapterMessage *output = new CCECAdapterMessage;
523
524 output->PushBack(MSGSTART);
525 output->PushEscaped(MSGCODE_SET_ACK_MASK);
526 output->PushEscaped(iMask >> 8);
527 output->PushEscaped((uint8_t)iMask);
528 output->PushBack(MSGEND);
529 output->isTransmission = false;
530
f9e01dac
LOK
531 if (bWriteDirectly)
532 SendMessageToAdapter(output);
533 else if ((bReturn = Write(output)) == false)
5477a250 534 CLibCEC::AddLog(CEC_LOG_ERROR, "could not set the ackmask");
5dcf9f25
LOK
535 delete output;
536
537 return bReturn;
538}
539
b057edad
BL
540
541bool CUSBCECAdapterCommunication::SetControlledMode(bool controlled)
542{
543 bool bReturn(false);
bca69ca1 544 CLibCEC::AddLog(CEC_LOG_DEBUG, "turning controlled mode %s", controlled ? "on" : "off");
b057edad
BL
545
546 CCECAdapterMessage *output = new CCECAdapterMessage;
547
548 output->PushBack(MSGSTART);
549 output->PushEscaped(MSGCODE_SET_CONTROLLED);
550 output->PushEscaped(controlled);
551 output->PushBack(MSGEND);
552 output->isTransmission = false;
553
554 if ((bReturn = Write(output)) == false)
555 CLibCEC::AddLog(CEC_LOG_ERROR, "could not set controlled mode");
556 delete output;
557
558 return bReturn;
559}
560
7bb4ed43 561bool CUSBCECAdapterCommunication::IsOpen(void)
13fd6a66 562{
b9eea66d 563 return !IsStopped() && m_port->IsOpen() && IsRunning();
13fd6a66 564}
ef7696f5 565
7bb4ed43 566bool CUSBCECAdapterCommunication::WaitForAck(CCECAdapterMessage &message)
6729ac71
LOK
567{
568 bool bError(false);
569 bool bTransmitSucceeded(false);
b2f0b1ab 570 uint8_t iPacketsLeft(message.Size() / 4);
6729ac71
LOK
571
572 int64_t iNow = GetTimeMs();
b1f94db1 573 int64_t iTargetTime = iNow + (message.transmit_timeout <= 5 ? CEC_DEFAULT_TRANSMIT_WAIT : message.transmit_timeout);
6729ac71 574
b1f94db1 575 while (!bTransmitSucceeded && !bError && iNow < iTargetTime)
6729ac71 576 {
b1f94db1 577 ReadFromDevice(50);
6729ac71 578 CCECAdapterMessage msg;
b1f94db1 579 if (!Read(msg, 0))
6729ac71
LOK
580 {
581 iNow = GetTimeMs();
582 continue;
583 }
584
585 if (msg.Message() == MSGCODE_FRAME_START && msg.IsACK())
586 {
587 m_processor->HandlePoll(msg.Initiator(), msg.Destination());
7bb4ed43 588 m_lastInitiator = msg.Initiator();
6729ac71
LOK
589 iNow = GetTimeMs();
590 continue;
591 }
592
593 if (msg.Message() == MSGCODE_RECEIVE_FAILED &&
7bb4ed43
LOK
594 m_lastInitiator != CECDEVICE_UNKNOWN &&
595 m_processor->HandleReceiveFailed(m_lastInitiator))
6729ac71
LOK
596 {
597 iNow = GetTimeMs();
598 continue;
599 }
600
601 bError = msg.IsError();
602 if (bError)
603 {
b2f0b1ab 604 message.reply = msg.Message();
5477a250 605 CLibCEC::AddLog(CEC_LOG_DEBUG, msg.ToString());
6729ac71
LOK
606 }
607 else
608 {
609 switch(msg.Message())
610 {
611 case MSGCODE_COMMAND_ACCEPTED:
5477a250 612 CLibCEC::AddLog(CEC_LOG_DEBUG, msg.ToString());
6729ac71
LOK
613 if (iPacketsLeft > 0)
614 iPacketsLeft--;
b2f0b1ab 615 if (!message.isTransmission && iPacketsLeft == 0)
5dcf9f25 616 bTransmitSucceeded = true;
6729ac71
LOK
617 break;
618 case MSGCODE_TRANSMIT_SUCCEEDED:
5477a250 619 CLibCEC::AddLog(CEC_LOG_DEBUG, msg.ToString());
6729ac71
LOK
620 bTransmitSucceeded = (iPacketsLeft == 0);
621 bError = !bTransmitSucceeded;
b2f0b1ab 622 message.reply = MSGCODE_TRANSMIT_SUCCEEDED;
6729ac71
LOK
623 break;
624 default:
625 // ignore other data while waiting
626 break;
627 }
628
629 iNow = GetTimeMs();
630 }
631 }
632
b1f94db1
LOK
633 message.state = bTransmitSucceeded && !bError ?
634 ADAPTER_MESSAGE_STATE_SENT_ACKED :
635 ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED;
636
6729ac71
LOK
637 return bTransmitSucceeded && !bError;
638}
639
7bb4ed43 640void CUSBCECAdapterCommunication::AddData(uint8_t *data, size_t iLen)
ef7696f5
LOK
641{
642 CLockObject lock(m_mutex);
99666519 643 for (size_t iPtr = 0; iPtr < iLen; iPtr++)
7bb4ed43
LOK
644 {
645 if (!m_bGotStart)
646 {
647 if (data[iPtr] == MSGSTART)
648 m_bGotStart = true;
649 }
650 else if (data[iPtr] == MSGSTART) //we found a msgstart before msgend, this is not right, remove
651 {
652 if (m_currentAdapterMessage.Size() > 0)
653 CLibCEC::AddLog(CEC_LOG_WARNING, "received MSGSTART before MSGEND, removing previous buffer contents");
654 m_currentAdapterMessage.Clear();
655 m_bGotStart = true;
656 }
657 else if (data[iPtr] == MSGEND)
658 {
659 CCECAdapterMessage *newMessage = new CCECAdapterMessage;
660 newMessage->packet = m_currentAdapterMessage.packet;
661 m_inBuffer.Push(newMessage);
662 m_currentAdapterMessage.Clear();
663 m_bGotStart = false;
664 m_bNextIsEscaped = false;
960f33c6 665 m_bHasData = true;
7bb4ed43
LOK
666 m_rcvCondition.Signal();
667 }
668 else if (m_bNextIsEscaped)
669 {
670 m_currentAdapterMessage.PushBack(data[iPtr] + (uint8_t)ESCOFFSET);
671 m_bNextIsEscaped = false;
672 }
673 else if (data[iPtr] == MSGESC)
674 {
675 m_bNextIsEscaped = true;
676 }
677 else
678 {
679 m_currentAdapterMessage.PushBack(data[iPtr]);
680 }
681 }
ef7696f5
LOK
682}
683
b1f94db1 684bool CUSBCECAdapterCommunication::ReadFromDevice(uint32_t iTimeout, size_t iSize /* = 256 */)
ef7696f5 685{
99666519
LOK
686 ssize_t iBytesRead;
687 uint8_t buff[256];
ef7696f5
LOK
688 if (!m_port)
689 return false;
b1f94db1
LOK
690 if (iSize > 256)
691 iSize = 256;
ef7696f5 692
1fc16cfd 693 CLockObject lock(m_mutex);
b1f94db1 694 iBytesRead = m_port->Read(buff, sizeof(uint8_t) * iSize, iTimeout);
ef7696f5
LOK
695 if (iBytesRead < 0 || iBytesRead > 256)
696 {
99666519 697 CLibCEC::AddLog(CEC_LOG_ERROR, "error reading from serial port: %s", m_port->GetError().c_str());
60383b11 698 StopThread(false);
ef7696f5
LOK
699 return false;
700 }
701 else if (iBytesRead > 0)
99666519
LOK
702 {
703 AddData(buff, iBytesRead);
704 }
ef7696f5
LOK
705
706 return iBytesRead > 0;
707}
708
7bb4ed43 709void CUSBCECAdapterCommunication::SendMessageToAdapter(CCECAdapterMessage *msg)
ef7696f5 710{
1fc16cfd 711 CLockObject adapterLock(m_mutex);
f9e01dac
LOK
712 if (!m_port->IsOpen())
713 {
714 CLibCEC::AddLog(CEC_LOG_ERROR, "error writing to serial port: the connection is closed");
715 msg->state = ADAPTER_MESSAGE_STATE_ERROR;
716 return;
717 }
718
7bb4ed43
LOK
719 if (msg->tries == 1)
720 SetLineTimeout(msg->lineTimeout);
721 else
722 SetLineTimeout(msg->retryTimeout);
723
99666519 724 if (m_port->Write(msg->packet.data, msg->Size()) != (ssize_t) msg->Size())
ef7696f5 725 {
b74fd339 726 CLibCEC::AddLog(CEC_LOG_ERROR, "error writing to serial port: %s", m_port->GetError().c_str());
ef7696f5
LOK
727 msg->state = ADAPTER_MESSAGE_STATE_ERROR;
728 }
729 else
730 {
5477a250 731 CLibCEC::AddLog(CEC_LOG_DEBUG, "command sent");
ef7696f5 732 msg->state = ADAPTER_MESSAGE_STATE_SENT;
b1f94db1
LOK
733
734 if (msg->expectControllerAck)
735 {
736 if (!WaitForAck(*msg))
737 CLibCEC::AddLog(CEC_LOG_DEBUG, "did not receive ack");
738 }
ef7696f5 739 }
960f33c6 740 msg->event.Signal();
ef7696f5
LOK
741}
742
7bb4ed43 743void CUSBCECAdapterCommunication::WriteNextCommand(void)
ef7696f5
LOK
744{
745 CCECAdapterMessage *msg(NULL);
746 if (m_outBuffer.Pop(msg))
747 SendMessageToAdapter(msg);
748}
cba904a6
LOK
749
750CStdString CUSBCECAdapterCommunication::GetPortName(void)
751{
752 CStdString strName;
753 strName = m_port->GetName();
754 return strName;
755}