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