12b8eacde7f70b2197656cf78d8a6cd7c33576d5
[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 CUSBCECAdapterCommunication::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
55 CUSBCECAdapterCommunication::~CUSBCECAdapterCommunication(void)
56 {
57 Close();
58 }
59
60 bool CUSBCECAdapterCommunication::Open(uint32_t iTimeoutMs /* = 10000 */)
61 {
62 uint64_t iNow = GetTimeMs();
63 uint64_t iTimeout = iNow + iTimeoutMs;
64
65 CLockObject lock(m_mutex);
66
67 if (!m_port)
68 {
69 CLibCEC::AddLog(CEC_LOG_ERROR, "port is NULL");
70 return false;
71 }
72
73 if (IsOpen())
74 {
75 CLibCEC::AddLog(CEC_LOG_ERROR, "port is already open");
76 return true;
77 }
78
79 CStdString strError;
80 bool bConnected(false);
81 while (!bConnected && iNow < iTimeout)
82 {
83 if ((bConnected = m_port->Open(iTimeout)) == false)
84 {
85 strError.Format("error opening serial port '%s': %s", m_port->GetName().c_str(), m_port->GetError().c_str());
86 Sleep(250);
87 iNow = GetTimeMs();
88 }
89 }
90
91 if (!bConnected)
92 {
93 CLibCEC::AddLog(CEC_LOG_ERROR, strError);
94 return false;
95 }
96
97 CLibCEC::AddLog(CEC_LOG_DEBUG, "connection opened, clearing any previous input and waiting for active transmissions to end before starting");
98
99 //clear any input bytes
100 uint8_t buff[1024];
101 while (m_port->Read(buff, 1024, 100) > 0)
102 {
103 CLibCEC::AddLog(CEC_LOG_DEBUG, "data received, clearing it");
104 Sleep(250);
105 }
106
107 if (CreateThread())
108 {
109 CLibCEC::AddLog(CEC_LOG_DEBUG, "communication thread started");
110 return true;
111 }
112 else
113 {
114 CLibCEC::AddLog(CEC_LOG_ERROR, "could not create a communication thread");
115 }
116
117 return false;
118 }
119
120 void CUSBCECAdapterCommunication::Close(void)
121 {
122 CLockObject lock(m_mutex);
123 m_rcvCondition.Broadcast();
124 StopThread();
125 }
126
127 void *CUSBCECAdapterCommunication::Process(void)
128 {
129 while (!IsStopped())
130 {
131 ReadFromDevice(50);
132 Sleep(5);
133 WriteNextCommand();
134 }
135
136 CCECAdapterMessage *msg(NULL);
137 if (m_outBuffer.Pop(msg))
138 msg->condition.Broadcast();
139
140 if (m_port)
141 {
142 delete m_port;
143 m_port = NULL;
144 }
145
146 return NULL;
147 }
148
149 cec_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
178 bool 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
213 bool 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
228 bool 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
252 CStdString CUSBCECAdapterCommunication::GetError(void) const
253 {
254 CStdString strError;
255 strError = m_port->GetError();
256 return strError;
257 }
258
259 bool 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
281 bool 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
302 bool 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
354 uint16_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
387 bool 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
412 bool CUSBCECAdapterCommunication::SetAckMask(uint16_t iMask)
413 {
414 bool bReturn(false);
415 CLibCEC::AddLog(CEC_LOG_DEBUG, "setting ackmask to %2x", iMask);
416
417 CCECAdapterMessage *output = new CCECAdapterMessage;
418
419 output->PushBack(MSGSTART);
420 output->PushEscaped(MSGCODE_SET_ACK_MASK);
421 output->PushEscaped(iMask >> 8);
422 output->PushEscaped((uint8_t)iMask);
423 output->PushBack(MSGEND);
424 output->isTransmission = false;
425
426 if ((bReturn = Write(output)) == false)
427 CLibCEC::AddLog(CEC_LOG_ERROR, "could not set the ackmask");
428 delete output;
429
430 return bReturn;
431 }
432
433
434 bool CUSBCECAdapterCommunication::SetControlledMode(bool controlled)
435 {
436 bool bReturn(false);
437 CLibCEC::AddLog(CEC_LOG_DEBUG, "turning controlled mode %s", controlled ? "on" : "off");
438
439 CCECAdapterMessage *output = new CCECAdapterMessage;
440
441 output->PushBack(MSGSTART);
442 output->PushEscaped(MSGCODE_SET_CONTROLLED);
443 output->PushEscaped(controlled);
444 output->PushBack(MSGEND);
445 output->isTransmission = false;
446
447 if ((bReturn = Write(output)) == false)
448 CLibCEC::AddLog(CEC_LOG_ERROR, "could not set controlled mode");
449 delete output;
450
451 return bReturn;
452 }
453
454 bool CUSBCECAdapterCommunication::IsOpen(void)
455 {
456 return !IsStopped() && m_port->IsOpen() && IsRunning();
457 }
458
459 bool CUSBCECAdapterCommunication::WaitForAck(CCECAdapterMessage &message)
460 {
461 bool bError(false);
462 bool bTransmitSucceeded(false);
463 uint8_t iPacketsLeft(message.Size() / 4);
464
465 int64_t iNow = GetTimeMs();
466 int64_t iTargetTime = iNow + message.transmit_timeout;
467
468 while (!bTransmitSucceeded && !bError && (message.transmit_timeout == 0 || iNow < iTargetTime))
469 {
470 CCECAdapterMessage msg;
471 int32_t iWait = (int32_t)(iTargetTime - iNow);
472 if (iWait <= 5 || message.transmit_timeout <= 5)
473 iWait = CEC_DEFAULT_TRANSMIT_WAIT;
474
475 if (!Read(msg, iWait))
476 {
477 iNow = GetTimeMs();
478 continue;
479 }
480
481 if (msg.Message() == MSGCODE_FRAME_START && msg.IsACK())
482 {
483 m_processor->HandlePoll(msg.Initiator(), msg.Destination());
484 m_lastInitiator = msg.Initiator();
485 iNow = GetTimeMs();
486 continue;
487 }
488
489 if (msg.Message() == MSGCODE_RECEIVE_FAILED &&
490 m_lastInitiator != CECDEVICE_UNKNOWN &&
491 m_processor->HandleReceiveFailed(m_lastInitiator))
492 {
493 iNow = GetTimeMs();
494 continue;
495 }
496
497 bError = msg.IsError();
498 if (bError)
499 {
500 message.reply = msg.Message();
501 CLibCEC::AddLog(CEC_LOG_DEBUG, msg.ToString());
502 }
503 else
504 {
505 switch(msg.Message())
506 {
507 case MSGCODE_COMMAND_ACCEPTED:
508 CLibCEC::AddLog(CEC_LOG_DEBUG, msg.ToString());
509 if (iPacketsLeft > 0)
510 iPacketsLeft--;
511 if (!message.isTransmission && iPacketsLeft == 0)
512 bTransmitSucceeded = true;
513 break;
514 case MSGCODE_TRANSMIT_SUCCEEDED:
515 CLibCEC::AddLog(CEC_LOG_DEBUG, msg.ToString());
516 bTransmitSucceeded = (iPacketsLeft == 0);
517 bError = !bTransmitSucceeded;
518 message.reply = MSGCODE_TRANSMIT_SUCCEEDED;
519 break;
520 default:
521 // ignore other data while waiting
522 break;
523 }
524
525 iNow = GetTimeMs();
526 }
527 }
528
529 return bTransmitSucceeded && !bError;
530 }
531
532 void CUSBCECAdapterCommunication::AddData(uint8_t *data, size_t iLen)
533 {
534 CLockObject lock(m_mutex);
535 for (size_t iPtr = 0; iPtr < iLen; iPtr++)
536 {
537 if (!m_bGotStart)
538 {
539 if (data[iPtr] == MSGSTART)
540 m_bGotStart = true;
541 }
542 else if (data[iPtr] == MSGSTART) //we found a msgstart before msgend, this is not right, remove
543 {
544 if (m_currentAdapterMessage.Size() > 0)
545 CLibCEC::AddLog(CEC_LOG_WARNING, "received MSGSTART before MSGEND, removing previous buffer contents");
546 m_currentAdapterMessage.Clear();
547 m_bGotStart = true;
548 }
549 else if (data[iPtr] == MSGEND)
550 {
551 CCECAdapterMessage *newMessage = new CCECAdapterMessage;
552 newMessage->packet = m_currentAdapterMessage.packet;
553 m_inBuffer.Push(newMessage);
554 m_currentAdapterMessage.Clear();
555 m_bGotStart = false;
556 m_bNextIsEscaped = false;
557 m_rcvCondition.Signal();
558 }
559 else if (m_bNextIsEscaped)
560 {
561 m_currentAdapterMessage.PushBack(data[iPtr] + (uint8_t)ESCOFFSET);
562 m_bNextIsEscaped = false;
563 }
564 else if (data[iPtr] == MSGESC)
565 {
566 m_bNextIsEscaped = true;
567 }
568 else
569 {
570 m_currentAdapterMessage.PushBack(data[iPtr]);
571 }
572 }
573 }
574
575 bool CUSBCECAdapterCommunication::ReadFromDevice(uint32_t iTimeout)
576 {
577 ssize_t iBytesRead;
578 uint8_t buff[256];
579 if (!m_port)
580 return false;
581
582 CLockObject lock(m_mutex);
583 iBytesRead = m_port->Read(buff, sizeof(buff), iTimeout);
584 if (iBytesRead < 0 || iBytesRead > 256)
585 {
586 CLibCEC::AddLog(CEC_LOG_ERROR, "error reading from serial port: %s", m_port->GetError().c_str());
587 return false;
588 }
589 else if (iBytesRead > 0)
590 {
591 AddData(buff, iBytesRead);
592 }
593
594 return iBytesRead > 0;
595 }
596
597 void CUSBCECAdapterCommunication::SendMessageToAdapter(CCECAdapterMessage *msg)
598 {
599 CLockObject adapterLock(m_mutex);
600 CLockObject lock(msg->mutex);
601 if (msg->tries == 1)
602 SetLineTimeout(msg->lineTimeout);
603 else
604 SetLineTimeout(msg->retryTimeout);
605
606 if (m_port->Write(msg->packet.data, msg->Size()) != (ssize_t) msg->Size())
607 {
608 CLibCEC::AddLog(CEC_LOG_ERROR, "error writing to serial port: %s", m_port->GetError().c_str());
609 msg->state = ADAPTER_MESSAGE_STATE_ERROR;
610 }
611 else
612 {
613 CLibCEC::AddLog(CEC_LOG_DEBUG, "command sent");
614 msg->state = ADAPTER_MESSAGE_STATE_SENT;
615 }
616 msg->condition.Signal();
617 }
618
619 void CUSBCECAdapterCommunication::WriteNextCommand(void)
620 {
621 CCECAdapterMessage *msg(NULL);
622 if (m_outBuffer.Pop(msg))
623 SendMessageToAdapter(msg);
624 }