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