cec: lock in SyncedBuffer
[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);
120d4ca8 323 m_bHasData = !m_inBuffer.IsEmpty();
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
24dd566c 394 CLockObject adapterLock(m_mutex);
7bb4ed43
LOK
395 switch(msg.Message())
396 {
397 case MSGCODE_FRAME_START:
398 {
399 m_currentframe.Clear();
400 if (msg.Size() >= 2)
401 {
402 m_currentframe.initiator = msg.Initiator();
403 m_currentframe.destination = msg.Destination();
404 m_currentframe.ack = msg.IsACK();
405 m_currentframe.eom = msg.IsEOM();
406 }
407 if (m_currentframe.ack == 0x1)
408 {
409 m_lastInitiator = m_currentframe.initiator;
410 m_processor->HandlePoll(m_currentframe.initiator, m_currentframe.destination);
411 }
412 }
413 break;
414 case MSGCODE_RECEIVE_FAILED:
415 {
416 m_currentframe.Clear();
417 if (m_lastInitiator != CECDEVICE_UNKNOWN)
418 bIsError = m_processor->HandleReceiveFailed(m_lastInitiator);
419 }
420 break;
421 case MSGCODE_FRAME_DATA:
422 {
423 if (msg.Size() >= 2)
424 {
425 m_currentframe.PushBack(msg[1]);
426 m_currentframe.eom = msg.IsEOM();
427 }
428 bEom = msg.IsEOM();
429 }
430 break;
431 default:
432 break;
433 }
434
435 CLibCEC::AddLog(bIsError ? CEC_LOG_WARNING : CEC_LOG_DEBUG, msg.ToString());
436 return bEom;
437}
438
439uint16_t CUSBCECAdapterCommunication::GetFirmwareVersion(void)
1fc16cfd
LOK
440{
441 uint16_t iReturn(m_iFirmwareVersion);
442 if (!IsRunning())
443 return iReturn;
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");
1fc16cfd
LOK
449 CCECAdapterMessage *output = new CCECAdapterMessage;
450
451 output->PushBack(MSGSTART);
452 output->PushEscaped(MSGCODE_FIRMWARE_VERSION);
453 output->PushBack(MSGEND);
454 output->isTransmission = false;
455 output->expectControllerAck = false;
456
efed01e1
LOK
457 SendMessageToAdapter(output);
458 bool bWriteOk = output->state == ADAPTER_MESSAGE_STATE_SENT;
1fc16cfd 459 delete output;
b1f94db1
LOK
460 if (!bWriteOk)
461 {
462 CLibCEC::AddLog(CEC_LOG_ERROR, "could not request the firmware version");
efed01e1 463 return iReturn;
b1f94db1 464 }
efed01e1
LOK
465
466 Sleep(250); // TODO ReadFromDevice() isn't waiting for the timeout to pass on win32
467 ReadFromDevice(CEC_DEFAULT_TRANSMIT_WAIT, 5 /* start + msgcode + 2 bytes for fw version + end */);
468 CCECAdapterMessage input;
469 if (Read(input, 0))
1fc16cfd 470 {
efed01e1
LOK
471 if (input.Message() != MSGCODE_FIRMWARE_VERSION || input.Size() != 3)
472 CLibCEC::AddLog(CEC_LOG_ERROR, "invalid firmware version (size = %d, message = %d)", input.Size(), input.Message());
b1f94db1
LOK
473 else
474 {
475 m_iFirmwareVersion = (input[1] << 8 | input[2]);
476 iReturn = m_iFirmwareVersion;
477 }
1fc16cfd 478 }
efed01e1
LOK
479 else
480 {
481 CLibCEC::AddLog(CEC_LOG_ERROR, "no firmware version received");
482 }
1fc16cfd
LOK
483 }
484
485 return iReturn;
486}
487
7bb4ed43 488bool CUSBCECAdapterCommunication::SetLineTimeout(uint8_t iTimeout)
a171d2fd 489{
7bb4ed43
LOK
490 m_iLineTimeout = iTimeout;
491 return true;
492 //TODO
493// bool bReturn(m_iLineTimeout != iTimeout);
494//
495// if (!bReturn)
496// {
497// CCECAdapterMessage *output = new CCECAdapterMessage;
498//
499// output->PushBack(MSGSTART);
500// output->PushEscaped(MSGCODE_TRANSMIT_IDLETIME);
501// output->PushEscaped(iTimeout);
502// output->PushBack(MSGEND);
503// output->isTransmission = false;
504//
505// if ((bReturn = Write(output)) == false)
506// CLibCEC::AddLog(CEC_LOG_ERROR, "could not set the idletime");
507// delete output;
508// }
509//
510// return bReturn;
a171d2fd
LOK
511}
512
7bb4ed43 513bool CUSBCECAdapterCommunication::SetAckMask(uint16_t iMask)
f9e01dac
LOK
514{
515 return SetAckMaskInternal(iMask, false);
516}
517
518bool CUSBCECAdapterCommunication::SetAckMaskInternal(uint16_t iMask, bool bWriteDirectly /* = false */)
5dcf9f25
LOK
519{
520 bool bReturn(false);
bca69ca1 521 CLibCEC::AddLog(CEC_LOG_DEBUG, "setting ackmask to %2x", iMask);
5dcf9f25
LOK
522
523 CCECAdapterMessage *output = new CCECAdapterMessage;
524
525 output->PushBack(MSGSTART);
526 output->PushEscaped(MSGCODE_SET_ACK_MASK);
527 output->PushEscaped(iMask >> 8);
528 output->PushEscaped((uint8_t)iMask);
529 output->PushBack(MSGEND);
530 output->isTransmission = false;
531
f9e01dac
LOK
532 if (bWriteDirectly)
533 SendMessageToAdapter(output);
534 else if ((bReturn = Write(output)) == false)
5477a250 535 CLibCEC::AddLog(CEC_LOG_ERROR, "could not set the ackmask");
5dcf9f25
LOK
536 delete output;
537
538 return bReturn;
539}
540
b057edad
BL
541
542bool CUSBCECAdapterCommunication::SetControlledMode(bool controlled)
543{
544 bool bReturn(false);
bca69ca1 545 CLibCEC::AddLog(CEC_LOG_DEBUG, "turning controlled mode %s", controlled ? "on" : "off");
b057edad
BL
546
547 CCECAdapterMessage *output = new CCECAdapterMessage;
548
549 output->PushBack(MSGSTART);
550 output->PushEscaped(MSGCODE_SET_CONTROLLED);
551 output->PushEscaped(controlled);
552 output->PushBack(MSGEND);
553 output->isTransmission = false;
554
555 if ((bReturn = Write(output)) == false)
556 CLibCEC::AddLog(CEC_LOG_ERROR, "could not set controlled mode");
557 delete output;
558
559 return bReturn;
560}
561
7bb4ed43 562bool CUSBCECAdapterCommunication::IsOpen(void)
13fd6a66 563{
b9eea66d 564 return !IsStopped() && m_port->IsOpen() && IsRunning();
13fd6a66 565}
ef7696f5 566
7bb4ed43 567bool CUSBCECAdapterCommunication::WaitForAck(CCECAdapterMessage &message)
6729ac71
LOK
568{
569 bool bError(false);
570 bool bTransmitSucceeded(false);
b2f0b1ab 571 uint8_t iPacketsLeft(message.Size() / 4);
6729ac71
LOK
572
573 int64_t iNow = GetTimeMs();
b1f94db1 574 int64_t iTargetTime = iNow + (message.transmit_timeout <= 5 ? CEC_DEFAULT_TRANSMIT_WAIT : message.transmit_timeout);
6729ac71 575
b1f94db1 576 while (!bTransmitSucceeded && !bError && iNow < iTargetTime)
6729ac71 577 {
b1f94db1 578 ReadFromDevice(50);
6729ac71 579 CCECAdapterMessage msg;
b1f94db1 580 if (!Read(msg, 0))
6729ac71
LOK
581 {
582 iNow = GetTimeMs();
583 continue;
584 }
585
586 if (msg.Message() == MSGCODE_FRAME_START && msg.IsACK())
587 {
588 m_processor->HandlePoll(msg.Initiator(), msg.Destination());
7bb4ed43 589 m_lastInitiator = msg.Initiator();
6729ac71
LOK
590 iNow = GetTimeMs();
591 continue;
592 }
593
594 if (msg.Message() == MSGCODE_RECEIVE_FAILED &&
7bb4ed43
LOK
595 m_lastInitiator != CECDEVICE_UNKNOWN &&
596 m_processor->HandleReceiveFailed(m_lastInitiator))
6729ac71
LOK
597 {
598 iNow = GetTimeMs();
599 continue;
600 }
601
602 bError = msg.IsError();
603 if (bError)
604 {
b2f0b1ab 605 message.reply = msg.Message();
5477a250 606 CLibCEC::AddLog(CEC_LOG_DEBUG, msg.ToString());
6729ac71
LOK
607 }
608 else
609 {
610 switch(msg.Message())
611 {
612 case MSGCODE_COMMAND_ACCEPTED:
5477a250 613 CLibCEC::AddLog(CEC_LOG_DEBUG, msg.ToString());
6729ac71
LOK
614 if (iPacketsLeft > 0)
615 iPacketsLeft--;
b2f0b1ab 616 if (!message.isTransmission && iPacketsLeft == 0)
5dcf9f25 617 bTransmitSucceeded = true;
6729ac71
LOK
618 break;
619 case MSGCODE_TRANSMIT_SUCCEEDED:
5477a250 620 CLibCEC::AddLog(CEC_LOG_DEBUG, msg.ToString());
6729ac71
LOK
621 bTransmitSucceeded = (iPacketsLeft == 0);
622 bError = !bTransmitSucceeded;
b2f0b1ab 623 message.reply = MSGCODE_TRANSMIT_SUCCEEDED;
6729ac71
LOK
624 break;
625 default:
626 // ignore other data while waiting
627 break;
628 }
629
630 iNow = GetTimeMs();
631 }
632 }
633
b1f94db1
LOK
634 message.state = bTransmitSucceeded && !bError ?
635 ADAPTER_MESSAGE_STATE_SENT_ACKED :
636 ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED;
637
6729ac71
LOK
638 return bTransmitSucceeded && !bError;
639}
640
7bb4ed43 641void CUSBCECAdapterCommunication::AddData(uint8_t *data, size_t iLen)
ef7696f5
LOK
642{
643 CLockObject lock(m_mutex);
99666519 644 for (size_t iPtr = 0; iPtr < iLen; iPtr++)
7bb4ed43
LOK
645 {
646 if (!m_bGotStart)
647 {
648 if (data[iPtr] == MSGSTART)
649 m_bGotStart = true;
650 }
651 else if (data[iPtr] == MSGSTART) //we found a msgstart before msgend, this is not right, remove
652 {
653 if (m_currentAdapterMessage.Size() > 0)
654 CLibCEC::AddLog(CEC_LOG_WARNING, "received MSGSTART before MSGEND, removing previous buffer contents");
655 m_currentAdapterMessage.Clear();
656 m_bGotStart = true;
657 }
658 else if (data[iPtr] == MSGEND)
659 {
660 CCECAdapterMessage *newMessage = new CCECAdapterMessage;
661 newMessage->packet = m_currentAdapterMessage.packet;
662 m_inBuffer.Push(newMessage);
663 m_currentAdapterMessage.Clear();
664 m_bGotStart = false;
665 m_bNextIsEscaped = false;
960f33c6 666 m_bHasData = true;
24dd566c 667 m_rcvCondition.Broadcast();
7bb4ed43
LOK
668 }
669 else if (m_bNextIsEscaped)
670 {
671 m_currentAdapterMessage.PushBack(data[iPtr] + (uint8_t)ESCOFFSET);
672 m_bNextIsEscaped = false;
673 }
674 else if (data[iPtr] == MSGESC)
675 {
676 m_bNextIsEscaped = true;
677 }
678 else
679 {
680 m_currentAdapterMessage.PushBack(data[iPtr]);
681 }
682 }
ef7696f5
LOK
683}
684
b1f94db1 685bool CUSBCECAdapterCommunication::ReadFromDevice(uint32_t iTimeout, size_t iSize /* = 256 */)
ef7696f5 686{
99666519
LOK
687 ssize_t iBytesRead;
688 uint8_t buff[256];
ef7696f5
LOK
689 if (!m_port)
690 return false;
b1f94db1
LOK
691 if (iSize > 256)
692 iSize = 256;
ef7696f5 693
1fc16cfd 694 CLockObject lock(m_mutex);
b1f94db1 695 iBytesRead = m_port->Read(buff, sizeof(uint8_t) * iSize, iTimeout);
ef7696f5
LOK
696 if (iBytesRead < 0 || iBytesRead > 256)
697 {
99666519 698 CLibCEC::AddLog(CEC_LOG_ERROR, "error reading from serial port: %s", m_port->GetError().c_str());
60383b11 699 StopThread(false);
ef7696f5
LOK
700 return false;
701 }
702 else if (iBytesRead > 0)
99666519
LOK
703 {
704 AddData(buff, iBytesRead);
705 }
ef7696f5
LOK
706
707 return iBytesRead > 0;
708}
709
7bb4ed43 710void CUSBCECAdapterCommunication::SendMessageToAdapter(CCECAdapterMessage *msg)
ef7696f5 711{
1fc16cfd 712 CLockObject adapterLock(m_mutex);
f9e01dac
LOK
713 if (!m_port->IsOpen())
714 {
715 CLibCEC::AddLog(CEC_LOG_ERROR, "error writing to serial port: the connection is closed");
716 msg->state = ADAPTER_MESSAGE_STATE_ERROR;
717 return;
718 }
719
7bb4ed43
LOK
720 if (msg->tries == 1)
721 SetLineTimeout(msg->lineTimeout);
722 else
723 SetLineTimeout(msg->retryTimeout);
724
99666519 725 if (m_port->Write(msg->packet.data, msg->Size()) != (ssize_t) msg->Size())
ef7696f5 726 {
b74fd339 727 CLibCEC::AddLog(CEC_LOG_ERROR, "error writing to serial port: %s", m_port->GetError().c_str());
ef7696f5
LOK
728 msg->state = ADAPTER_MESSAGE_STATE_ERROR;
729 }
730 else
731 {
5477a250 732 CLibCEC::AddLog(CEC_LOG_DEBUG, "command sent");
ef7696f5 733 msg->state = ADAPTER_MESSAGE_STATE_SENT;
b1f94db1
LOK
734
735 if (msg->expectControllerAck)
736 {
737 if (!WaitForAck(*msg))
738 CLibCEC::AddLog(CEC_LOG_DEBUG, "did not receive ack");
739 }
ef7696f5 740 }
960f33c6 741 msg->event.Signal();
ef7696f5
LOK
742}
743
7bb4ed43 744void CUSBCECAdapterCommunication::WriteNextCommand(void)
ef7696f5
LOK
745{
746 CCECAdapterMessage *msg(NULL);
747 if (m_outBuffer.Pop(msg))
748 SendMessageToAdapter(msg);
749}
cba904a6
LOK
750
751CStdString CUSBCECAdapterCommunication::GetPortName(void)
752{
753 CStdString strName;
754 strName = m_port->GetName();
755 return strName;
756}