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