added: new enum values
[deb_libcec.git] / src / lib / adapter / USBCECAdapterCommunication.cpp
... / ...
CommitLineData
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
39using namespace std;
40using namespace CEC;
41using namespace PLATFORM;
42
43CUSBCECAdapterCommunication::CUSBCECAdapterCommunication(CCECProcessor *processor, const char *strPort, uint16_t iBaudRate /* = 38400 */) :
44 m_port(NULL),
45 m_processor(processor),
46 m_iLineTimeout(0),
47 m_iFirmwareVersion(CEC_FW_VERSION_UNKNOWN),
48 m_lastInitiator(CECDEVICE_UNKNOWN),
49 m_bNextIsEscaped(false),
50 m_bGotStart(false)
51{
52 m_port = new PLATFORM::CSerialPort(strPort, iBaudRate);
53}
54
55CUSBCECAdapterCommunication::~CUSBCECAdapterCommunication(void)
56{
57 Close();
58
59 if (m_port)
60 {
61 delete m_port;
62 m_port = NULL;
63 }
64}
65
66bool CUSBCECAdapterCommunication::Open(uint32_t iTimeoutMs /* = 10000 */)
67{
68 uint64_t iNow = GetTimeMs();
69 uint64_t iTimeout = iNow + iTimeoutMs;
70
71 CLockObject lock(m_mutex);
72
73 if (!m_port)
74 {
75 CLibCEC::AddLog(CEC_LOG_ERROR, "port is NULL");
76 return false;
77 }
78
79 if (IsOpen())
80 {
81 CLibCEC::AddLog(CEC_LOG_ERROR, "port is already open");
82 return true;
83 }
84
85 CStdString strError;
86 bool bConnected(false);
87 while (!bConnected && iNow < iTimeout)
88 {
89 if ((bConnected = m_port->Open(iTimeout)) == false)
90 {
91 strError.Format("error opening serial port '%s': %s", m_port->GetName().c_str(), m_port->GetError().c_str());
92 Sleep(250);
93 iNow = GetTimeMs();
94 }
95 }
96
97 if (!bConnected)
98 {
99 CLibCEC::AddLog(CEC_LOG_ERROR, strError);
100 return false;
101 }
102
103 CLibCEC::AddLog(CEC_LOG_DEBUG, "connection opened, clearing any previous input and waiting for active transmissions to end before starting");
104
105 //clear any input bytes
106 uint8_t buff[1024];
107 while (m_port->Read(buff, 1024, 100) > 0)
108 {
109 CLibCEC::AddLog(CEC_LOG_DEBUG, "data received, clearing it");
110 Sleep(250);
111 }
112
113 if (CreateThread())
114 {
115 CLibCEC::AddLog(CEC_LOG_DEBUG, "communication thread started");
116 return true;
117 }
118 else
119 {
120 CLibCEC::AddLog(CEC_LOG_ERROR, "could not create a communication thread");
121 }
122
123 return false;
124}
125
126void CUSBCECAdapterCommunication::Close(void)
127{
128 CLockObject lock(m_mutex);
129 m_rcvCondition.Broadcast();
130 StopThread();
131}
132
133void *CUSBCECAdapterCommunication::Process(void)
134{
135 while (!IsStopped())
136 {
137 ReadFromDevice(50);
138 Sleep(5);
139 WriteNextCommand();
140 }
141
142 CCECAdapterMessage *msg(NULL);
143 if (m_outBuffer.Pop(msg))
144 msg->condition.Broadcast();
145
146 return NULL;
147}
148
149cec_adapter_message_state CUSBCECAdapterCommunication::Write(const cec_command &data, uint8_t iMaxTries, uint8_t iLineTimeout /* = 3 */, uint8_t iRetryLineTimeout /* = 3 */)
150{
151 cec_adapter_message_state retVal(ADAPTER_MESSAGE_STATE_UNKNOWN);
152
153 CCECAdapterMessage *output = new CCECAdapterMessage(data);
154
155 /* set the number of retries */
156 if (data.opcode == CEC_OPCODE_NONE) //TODO
157 output->maxTries = 1;
158 else if (data.initiator != CECDEVICE_BROADCAST)
159 output->maxTries = iMaxTries;
160
161 output->lineTimeout = iLineTimeout;
162 output->retryTimeout = iRetryLineTimeout;
163 output->tries = 0;
164
165 bool bRetry(true);
166 while (bRetry && ++output->tries < output->maxTries)
167 {
168 bRetry = (!Write(output) || output->NeedsRetry()) && output->transmit_timeout > 0;
169 if (bRetry)
170 Sleep(CEC_DEFAULT_TRANSMIT_RETRY_WAIT);
171 }
172 retVal = output->state;
173
174 delete output;
175 return retVal;
176}
177
178bool CUSBCECAdapterCommunication::Write(CCECAdapterMessage *data)
179{
180 bool bReturn(false);
181
182 CLockObject lock(data->mutex);
183 data->state = ADAPTER_MESSAGE_STATE_WAITING_TO_BE_SENT;
184 m_outBuffer.Push(data);
185 data->condition.Wait(data->mutex);
186
187 if (data->state != ADAPTER_MESSAGE_STATE_SENT)
188 {
189 CLibCEC::AddLog(CEC_LOG_ERROR, "command was not sent");
190 }
191 else if (data->expectControllerAck)
192 {
193 bReturn = WaitForAck(*data);
194 if (bReturn)
195 {
196 if (data->isTransmission)
197 data->state = ADAPTER_MESSAGE_STATE_SENT_ACKED;
198 }
199 else
200 {
201 data->state = ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED;
202 CLibCEC::AddLog(CEC_LOG_DEBUG, "did not receive ack");
203 }
204 }
205 else
206 {
207 bReturn = true;
208 }
209
210 return bReturn;
211}
212
213bool CUSBCECAdapterCommunication::Read(cec_command &command, uint32_t iTimeout)
214{
215 CCECAdapterMessage msg;
216 if (Read(msg, iTimeout))
217 {
218 if (ParseMessage(msg))
219 {
220 command = m_currentframe;
221 m_currentframe.Clear();
222 return true;
223 }
224 }
225 return false;
226}
227
228bool CUSBCECAdapterCommunication::Read(CCECAdapterMessage &msg, uint32_t iTimeout)
229{
230 CLockObject lock(m_mutex);
231
232 msg.Clear();
233 CCECAdapterMessage *buf(NULL);
234
235 if (!m_inBuffer.Pop(buf))
236 {
237 if (!m_rcvCondition.Wait(m_mutex, iTimeout))
238 return false;
239 m_inBuffer.Pop(buf);
240 }
241
242 if (buf)
243 {
244 msg.packet = buf->packet;
245 msg.state = msg.state = ADAPTER_MESSAGE_STATE_INCOMING;
246 delete buf;
247 return true;
248 }
249 return false;
250}
251
252CStdString CUSBCECAdapterCommunication::GetError(void) const
253{
254 CStdString strError;
255 strError = m_port->GetError();
256 return strError;
257}
258
259bool CUSBCECAdapterCommunication::StartBootloader(void)
260{
261 bool bReturn(false);
262 if (!IsRunning())
263 return bReturn;
264
265 CLibCEC::AddLog(CEC_LOG_DEBUG, "starting the bootloader");
266 CCECAdapterMessage *output = new CCECAdapterMessage;
267
268 output->PushBack(MSGSTART);
269 output->PushEscaped(MSGCODE_START_BOOTLOADER);
270 output->PushBack(MSGEND);
271 output->isTransmission = false;
272 output->expectControllerAck = false;
273
274 if ((bReturn = Write(output)) == false)
275 CLibCEC::AddLog(CEC_LOG_ERROR, "could not start the bootloader");
276 delete output;
277
278 return bReturn;
279}
280
281bool CUSBCECAdapterCommunication::PingAdapter(void)
282{
283 bool bReturn(false);
284 if (!IsRunning())
285 return bReturn;
286
287 CLibCEC::AddLog(CEC_LOG_DEBUG, "sending ping");
288 CCECAdapterMessage *output = new CCECAdapterMessage;
289
290 output->PushBack(MSGSTART);
291 output->PushEscaped(MSGCODE_PING);
292 output->PushBack(MSGEND);
293 output->isTransmission = false;
294
295 if ((bReturn = Write(output)) == false)
296 CLibCEC::AddLog(CEC_LOG_ERROR, "could not ping the adapter");
297 delete output;
298
299 return bReturn;
300}
301
302bool CUSBCECAdapterCommunication::ParseMessage(const CCECAdapterMessage &msg)
303{
304 bool bEom(false);
305 bool bIsError(msg.IsError());
306
307 if (msg.IsEmpty())
308 return bEom;
309
310 switch(msg.Message())
311 {
312 case MSGCODE_FRAME_START:
313 {
314 m_currentframe.Clear();
315 if (msg.Size() >= 2)
316 {
317 m_currentframe.initiator = msg.Initiator();
318 m_currentframe.destination = msg.Destination();
319 m_currentframe.ack = msg.IsACK();
320 m_currentframe.eom = msg.IsEOM();
321 }
322 if (m_currentframe.ack == 0x1)
323 {
324 m_lastInitiator = m_currentframe.initiator;
325 m_processor->HandlePoll(m_currentframe.initiator, m_currentframe.destination);
326 }
327 }
328 break;
329 case MSGCODE_RECEIVE_FAILED:
330 {
331 m_currentframe.Clear();
332 if (m_lastInitiator != CECDEVICE_UNKNOWN)
333 bIsError = m_processor->HandleReceiveFailed(m_lastInitiator);
334 }
335 break;
336 case MSGCODE_FRAME_DATA:
337 {
338 if (msg.Size() >= 2)
339 {
340 m_currentframe.PushBack(msg[1]);
341 m_currentframe.eom = msg.IsEOM();
342 }
343 bEom = msg.IsEOM();
344 }
345 break;
346 default:
347 break;
348 }
349
350 CLibCEC::AddLog(bIsError ? CEC_LOG_WARNING : CEC_LOG_DEBUG, msg.ToString());
351 return bEom;
352}
353
354uint16_t CUSBCECAdapterCommunication::GetFirmwareVersion(void)
355{
356 uint16_t iReturn(m_iFirmwareVersion);
357 if (!IsRunning())
358 return iReturn;
359
360 if (iReturn == CEC_FW_VERSION_UNKNOWN)
361 {
362 CLibCEC::AddLog(CEC_LOG_DEBUG, "requesting the firmware version");
363 CCECAdapterMessage *output = new CCECAdapterMessage;
364
365 output->PushBack(MSGSTART);
366 output->PushEscaped(MSGCODE_FIRMWARE_VERSION);
367 output->PushBack(MSGEND);
368 output->isTransmission = false;
369 output->expectControllerAck = false;
370
371 SendMessageToAdapter(output);
372 delete output;
373
374 CCECAdapterMessage input;
375 if (!Read(input, CEC_DEFAULT_TRANSMIT_WAIT) || input.Message() != MSGCODE_FIRMWARE_VERSION || input.Size() != 3)
376 CLibCEC::AddLog(CEC_LOG_ERROR, "no or invalid firmware version (size = %d, message = %d)", input.Size(), input.Message());
377 else
378 {
379 m_iFirmwareVersion = (input[1] << 8 | input[2]);
380 iReturn = m_iFirmwareVersion;
381 }
382 }
383
384 return iReturn;
385}
386
387bool CUSBCECAdapterCommunication::SetLineTimeout(uint8_t iTimeout)
388{
389 m_iLineTimeout = iTimeout;
390 return true;
391 //TODO
392// bool bReturn(m_iLineTimeout != iTimeout);
393//
394// if (!bReturn)
395// {
396// CCECAdapterMessage *output = new CCECAdapterMessage;
397//
398// output->PushBack(MSGSTART);
399// output->PushEscaped(MSGCODE_TRANSMIT_IDLETIME);
400// output->PushEscaped(iTimeout);
401// output->PushBack(MSGEND);
402// output->isTransmission = false;
403//
404// if ((bReturn = Write(output)) == false)
405// CLibCEC::AddLog(CEC_LOG_ERROR, "could not set the idletime");
406// delete output;
407// }
408//
409// return bReturn;
410}
411
412bool CUSBCECAdapterCommunication::SetAckMask(uint16_t iMask)
413{
414 bool bReturn(false);
415 CStdString strLog;
416 strLog.Format("setting ackmask to %2x", iMask);
417 CLibCEC::AddLog(CEC_LOG_DEBUG, strLog.c_str());
418
419 CCECAdapterMessage *output = new CCECAdapterMessage;
420
421 output->PushBack(MSGSTART);
422 output->PushEscaped(MSGCODE_SET_ACK_MASK);
423 output->PushEscaped(iMask >> 8);
424 output->PushEscaped((uint8_t)iMask);
425 output->PushBack(MSGEND);
426 output->isTransmission = false;
427
428 if ((bReturn = Write(output)) == false)
429 CLibCEC::AddLog(CEC_LOG_ERROR, "could not set the ackmask");
430 delete output;
431
432 return bReturn;
433}
434
435bool CUSBCECAdapterCommunication::IsOpen(void)
436{
437 return !IsStopped() && m_port->IsOpen() && IsRunning();
438}
439
440bool CUSBCECAdapterCommunication::WaitForAck(CCECAdapterMessage &message)
441{
442 bool bError(false);
443 bool bTransmitSucceeded(false);
444 uint8_t iPacketsLeft(message.Size() / 4);
445
446 int64_t iNow = GetTimeMs();
447 int64_t iTargetTime = iNow + message.transmit_timeout;
448
449 while (!bTransmitSucceeded && !bError && (message.transmit_timeout == 0 || iNow < iTargetTime))
450 {
451 CCECAdapterMessage msg;
452 int32_t iWait = (int32_t)(iTargetTime - iNow);
453 if (iWait <= 5 || message.transmit_timeout <= 5)
454 iWait = CEC_DEFAULT_TRANSMIT_WAIT;
455
456 if (!Read(msg, iWait))
457 {
458 iNow = GetTimeMs();
459 continue;
460 }
461
462 if (msg.Message() == MSGCODE_FRAME_START && msg.IsACK())
463 {
464 m_processor->HandlePoll(msg.Initiator(), msg.Destination());
465 m_lastInitiator = msg.Initiator();
466 iNow = GetTimeMs();
467 continue;
468 }
469
470 if (msg.Message() == MSGCODE_RECEIVE_FAILED &&
471 m_lastInitiator != CECDEVICE_UNKNOWN &&
472 m_processor->HandleReceiveFailed(m_lastInitiator))
473 {
474 iNow = GetTimeMs();
475 continue;
476 }
477
478 bError = msg.IsError();
479 if (bError)
480 {
481 message.reply = msg.Message();
482 CLibCEC::AddLog(CEC_LOG_DEBUG, msg.ToString());
483 }
484 else
485 {
486 switch(msg.Message())
487 {
488 case MSGCODE_COMMAND_ACCEPTED:
489 CLibCEC::AddLog(CEC_LOG_DEBUG, msg.ToString());
490 if (iPacketsLeft > 0)
491 iPacketsLeft--;
492 if (!message.isTransmission && iPacketsLeft == 0)
493 bTransmitSucceeded = true;
494 break;
495 case MSGCODE_TRANSMIT_SUCCEEDED:
496 CLibCEC::AddLog(CEC_LOG_DEBUG, msg.ToString());
497 bTransmitSucceeded = (iPacketsLeft == 0);
498 bError = !bTransmitSucceeded;
499 message.reply = MSGCODE_TRANSMIT_SUCCEEDED;
500 break;
501 default:
502 // ignore other data while waiting
503 break;
504 }
505
506 iNow = GetTimeMs();
507 }
508 }
509
510 return bTransmitSucceeded && !bError;
511}
512
513void CUSBCECAdapterCommunication::AddData(uint8_t *data, size_t iLen)
514{
515 CLockObject lock(m_mutex);
516 for (size_t iPtr = 0; iPtr < iLen; iPtr++)
517 {
518 if (!m_bGotStart)
519 {
520 if (data[iPtr] == MSGSTART)
521 m_bGotStart = true;
522 }
523 else if (data[iPtr] == MSGSTART) //we found a msgstart before msgend, this is not right, remove
524 {
525 if (m_currentAdapterMessage.Size() > 0)
526 CLibCEC::AddLog(CEC_LOG_WARNING, "received MSGSTART before MSGEND, removing previous buffer contents");
527 m_currentAdapterMessage.Clear();
528 m_bGotStart = true;
529 }
530 else if (data[iPtr] == MSGEND)
531 {
532 CCECAdapterMessage *newMessage = new CCECAdapterMessage;
533 newMessage->packet = m_currentAdapterMessage.packet;
534 m_inBuffer.Push(newMessage);
535 m_currentAdapterMessage.Clear();
536 m_bGotStart = false;
537 m_bNextIsEscaped = false;
538 m_rcvCondition.Signal();
539 }
540 else if (m_bNextIsEscaped)
541 {
542 m_currentAdapterMessage.PushBack(data[iPtr] + (uint8_t)ESCOFFSET);
543 m_bNextIsEscaped = false;
544 }
545 else if (data[iPtr] == MSGESC)
546 {
547 m_bNextIsEscaped = true;
548 }
549 else
550 {
551 m_currentAdapterMessage.PushBack(data[iPtr]);
552 }
553 }
554}
555
556bool CUSBCECAdapterCommunication::ReadFromDevice(uint32_t iTimeout)
557{
558 ssize_t iBytesRead;
559 uint8_t buff[256];
560 if (!m_port)
561 return false;
562
563 CLockObject lock(m_mutex);
564 iBytesRead = m_port->Read(buff, sizeof(buff), iTimeout);
565 if (iBytesRead < 0 || iBytesRead > 256)
566 {
567 CLibCEC::AddLog(CEC_LOG_ERROR, "error reading from serial port: %s", m_port->GetError().c_str());
568 return false;
569 }
570 else if (iBytesRead > 0)
571 {
572 AddData(buff, iBytesRead);
573 }
574
575 return iBytesRead > 0;
576}
577
578void CUSBCECAdapterCommunication::SendMessageToAdapter(CCECAdapterMessage *msg)
579{
580 CLockObject adapterLock(m_mutex);
581 CLockObject lock(msg->mutex);
582 if (msg->tries == 1)
583 SetLineTimeout(msg->lineTimeout);
584 else
585 SetLineTimeout(msg->retryTimeout);
586
587 if (m_port->Write(msg->packet.data, msg->Size()) != (ssize_t) msg->Size())
588 {
589 CStdString strError;
590 strError.Format("error writing to serial port: %s", m_port->GetError().c_str());
591 CLibCEC::AddLog(CEC_LOG_ERROR, strError);
592 msg->state = ADAPTER_MESSAGE_STATE_ERROR;
593 }
594 else
595 {
596 CLibCEC::AddLog(CEC_LOG_DEBUG, "command sent");
597 msg->state = ADAPTER_MESSAGE_STATE_SENT;
598 }
599 msg->condition.Signal();
600}
601
602void CUSBCECAdapterCommunication::WriteNextCommand(void)
603{
604 CCECAdapterMessage *msg(NULL);
605 if (m_outBuffer.Pop(msg))
606 SendMessageToAdapter(msg);
607}