2 * This file is part of the libCEC(R) library.
4 * libCEC(R) is Copyright (C) 2011-2012 Pulse-Eight Limited. All rights reserved.
5 * libCEC(R) is an original work, containing original code.
7 * libCEC(R) is a trademark of Pulse-Eight Limited.
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.
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.
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.
24 * Alternatively, you can license this library under a commercial license,
25 * please contact Pulse-Eight Licensing for more information.
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/
33 #include "USBCECAdapterCommunication.h"
34 #include "../platform/sockets/serialport.h"
35 #include "../platform/util/timeutils.h"
36 #include "../LibCEC.h"
37 #include "../CECProcessor.h"
41 using namespace PLATFORM
;
43 CUSBCECAdapterCommunication::CUSBCECAdapterCommunication(CCECProcessor
*processor
, const char *strPort
, uint16_t iBaudRate
/* = 38400 */) :
45 m_processor(processor
),
47 m_iFirmwareVersion(CEC_FW_VERSION_UNKNOWN
),
48 m_lastInitiator(CECDEVICE_UNKNOWN
),
49 m_bNextIsEscaped(false),
52 m_port
= new PLATFORM::CSerialPort(strPort
, iBaudRate
);
55 CUSBCECAdapterCommunication::~CUSBCECAdapterCommunication(void)
60 bool CUSBCECAdapterCommunication::Open(uint32_t iTimeoutMs
/* = 10000 */)
62 uint64_t iNow
= GetTimeMs();
63 uint64_t iTimeout
= iNow
+ iTimeoutMs
;
65 CLockObject
lock(m_mutex
);
69 CLibCEC::AddLog(CEC_LOG_ERROR
, "port is NULL");
75 CLibCEC::AddLog(CEC_LOG_ERROR
, "port is already open");
80 bool bConnected(false);
81 while (!bConnected
&& iNow
< iTimeout
)
83 if ((bConnected
= m_port
->Open(iTimeout
)) == false)
85 strError
.Format("error opening serial port '%s': %s", m_port
->GetName().c_str(), m_port
->GetError().c_str());
93 CLibCEC::AddLog(CEC_LOG_ERROR
, strError
);
97 CLibCEC::AddLog(CEC_LOG_DEBUG
, "connection opened, clearing any previous input and waiting for active transmissions to end before starting");
99 //clear any input bytes
101 while (m_port
->Read(buff
, 1024, 100) > 0)
103 CLibCEC::AddLog(CEC_LOG_DEBUG
, "data received, clearing it");
109 CLibCEC::AddLog(CEC_LOG_DEBUG
, "communication thread started");
114 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not create a communication thread");
120 void CUSBCECAdapterCommunication::Close(void)
122 CLockObject
lock(m_mutex
);
123 m_rcvCondition
.Broadcast();
127 void *CUSBCECAdapterCommunication::Process(void)
136 CCECAdapterMessage
*msg(NULL
);
137 if (m_outBuffer
.Pop(msg
))
138 msg
->condition
.Broadcast();
149 cec_adapter_message_state
CUSBCECAdapterCommunication::Write(const cec_command
&data
, uint8_t iMaxTries
, uint8_t iLineTimeout
/* = 3 */, uint8_t iRetryLineTimeout
/* = 3 */)
151 cec_adapter_message_state
retVal(ADAPTER_MESSAGE_STATE_UNKNOWN
);
153 CCECAdapterMessage
*output
= new CCECAdapterMessage(data
);
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
;
161 output
->lineTimeout
= iLineTimeout
;
162 output
->retryTimeout
= iRetryLineTimeout
;
166 while (bRetry
&& ++output
->tries
< output
->maxTries
)
168 bRetry
= (!Write(output
) || output
->NeedsRetry()) && output
->transmit_timeout
> 0;
170 Sleep(CEC_DEFAULT_TRANSMIT_RETRY_WAIT
);
172 retVal
= output
->state
;
178 bool CUSBCECAdapterCommunication::Write(CCECAdapterMessage
*data
)
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
);
187 if (data
->state
!= ADAPTER_MESSAGE_STATE_SENT
)
189 CLibCEC::AddLog(CEC_LOG_ERROR
, "command was not sent");
191 else if (data
->expectControllerAck
)
193 bReturn
= WaitForAck(*data
);
196 if (data
->isTransmission
)
197 data
->state
= ADAPTER_MESSAGE_STATE_SENT_ACKED
;
201 data
->state
= ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED
;
202 CLibCEC::AddLog(CEC_LOG_DEBUG
, "did not receive ack");
213 bool CUSBCECAdapterCommunication::Read(cec_command
&command
, uint32_t iTimeout
)
215 CCECAdapterMessage msg
;
216 if (Read(msg
, iTimeout
))
218 if (ParseMessage(msg
))
220 command
= m_currentframe
;
221 m_currentframe
.Clear();
228 bool CUSBCECAdapterCommunication::Read(CCECAdapterMessage
&msg
, uint32_t iTimeout
)
230 CLockObject
lock(m_mutex
);
233 CCECAdapterMessage
*buf(NULL
);
235 if (!m_inBuffer
.Pop(buf
))
237 if (!m_rcvCondition
.Wait(m_mutex
, iTimeout
))
244 msg
.packet
= buf
->packet
;
245 msg
.state
= msg
.state
= ADAPTER_MESSAGE_STATE_INCOMING
;
252 CStdString
CUSBCECAdapterCommunication::GetError(void) const
255 strError
= m_port
->GetError();
259 bool CUSBCECAdapterCommunication::StartBootloader(void)
265 CLibCEC::AddLog(CEC_LOG_DEBUG
, "starting the bootloader");
266 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
268 output
->PushBack(MSGSTART
);
269 output
->PushEscaped(MSGCODE_START_BOOTLOADER
);
270 output
->PushBack(MSGEND
);
271 output
->isTransmission
= false;
272 output
->expectControllerAck
= false;
274 if ((bReturn
= Write(output
)) == false)
275 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not start the bootloader");
281 bool CUSBCECAdapterCommunication::PingAdapter(void)
287 CLibCEC::AddLog(CEC_LOG_DEBUG
, "sending ping");
288 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
290 output
->PushBack(MSGSTART
);
291 output
->PushEscaped(MSGCODE_PING
);
292 output
->PushBack(MSGEND
);
293 output
->isTransmission
= false;
295 if ((bReturn
= Write(output
)) == false)
296 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not ping the adapter");
302 bool CUSBCECAdapterCommunication::ParseMessage(const CCECAdapterMessage
&msg
)
305 bool bIsError(msg
.IsError());
310 switch(msg
.Message())
312 case MSGCODE_FRAME_START
:
314 m_currentframe
.Clear();
317 m_currentframe
.initiator
= msg
.Initiator();
318 m_currentframe
.destination
= msg
.Destination();
319 m_currentframe
.ack
= msg
.IsACK();
320 m_currentframe
.eom
= msg
.IsEOM();
322 if (m_currentframe
.ack
== 0x1)
324 m_lastInitiator
= m_currentframe
.initiator
;
325 m_processor
->HandlePoll(m_currentframe
.initiator
, m_currentframe
.destination
);
329 case MSGCODE_RECEIVE_FAILED
:
331 m_currentframe
.Clear();
332 if (m_lastInitiator
!= CECDEVICE_UNKNOWN
)
333 bIsError
= m_processor
->HandleReceiveFailed(m_lastInitiator
);
336 case MSGCODE_FRAME_DATA
:
340 m_currentframe
.PushBack(msg
[1]);
341 m_currentframe
.eom
= msg
.IsEOM();
350 CLibCEC::AddLog(bIsError
? CEC_LOG_WARNING
: CEC_LOG_DEBUG
, msg
.ToString());
354 uint16_t CUSBCECAdapterCommunication::GetFirmwareVersion(void)
356 uint16_t iReturn(m_iFirmwareVersion
);
360 if (iReturn
== CEC_FW_VERSION_UNKNOWN
)
362 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting the firmware version");
363 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
365 output
->PushBack(MSGSTART
);
366 output
->PushEscaped(MSGCODE_FIRMWARE_VERSION
);
367 output
->PushBack(MSGEND
);
368 output
->isTransmission
= false;
369 output
->expectControllerAck
= false;
371 SendMessageToAdapter(output
);
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());
379 m_iFirmwareVersion
= (input
[1] << 8 | input
[2]);
380 iReturn
= m_iFirmwareVersion
;
387 bool CUSBCECAdapterCommunication::SetLineTimeout(uint8_t iTimeout
)
389 m_iLineTimeout
= iTimeout
;
392 // bool bReturn(m_iLineTimeout != iTimeout);
396 // CCECAdapterMessage *output = new CCECAdapterMessage;
398 // output->PushBack(MSGSTART);
399 // output->PushEscaped(MSGCODE_TRANSMIT_IDLETIME);
400 // output->PushEscaped(iTimeout);
401 // output->PushBack(MSGEND);
402 // output->isTransmission = false;
404 // if ((bReturn = Write(output)) == false)
405 // CLibCEC::AddLog(CEC_LOG_ERROR, "could not set the idletime");
412 bool CUSBCECAdapterCommunication::SetAckMask(uint16_t iMask
)
416 strLog
.Format("setting ackmask to %2x", iMask
);
417 CLibCEC::AddLog(CEC_LOG_DEBUG
, strLog
.c_str());
419 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
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;
428 if ((bReturn
= Write(output
)) == false)
429 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not set the ackmask");
436 bool CUSBCECAdapterCommunication::SetControlledMode(bool controlled
)
440 strLog
.Format("turning controlled mode %s", controlled
? "on" : "off");
441 CLibCEC::AddLog(CEC_LOG_DEBUG
, strLog
.c_str());
443 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
445 output
->PushBack(MSGSTART
);
446 output
->PushEscaped(MSGCODE_SET_CONTROLLED
);
447 output
->PushEscaped(controlled
);
448 output
->PushBack(MSGEND
);
449 output
->isTransmission
= false;
451 if ((bReturn
= Write(output
)) == false)
452 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not set controlled mode");
458 bool CUSBCECAdapterCommunication::IsOpen(void)
460 return !IsStopped() && m_port
->IsOpen() && IsRunning();
463 bool CUSBCECAdapterCommunication::WaitForAck(CCECAdapterMessage
&message
)
466 bool bTransmitSucceeded(false);
467 uint8_t iPacketsLeft(message
.Size() / 4);
469 int64_t iNow
= GetTimeMs();
470 int64_t iTargetTime
= iNow
+ message
.transmit_timeout
;
472 while (!bTransmitSucceeded
&& !bError
&& (message
.transmit_timeout
== 0 || iNow
< iTargetTime
))
474 CCECAdapterMessage msg
;
475 int32_t iWait
= (int32_t)(iTargetTime
- iNow
);
476 if (iWait
<= 5 || message
.transmit_timeout
<= 5)
477 iWait
= CEC_DEFAULT_TRANSMIT_WAIT
;
479 if (!Read(msg
, iWait
))
485 if (msg
.Message() == MSGCODE_FRAME_START
&& msg
.IsACK())
487 m_processor
->HandlePoll(msg
.Initiator(), msg
.Destination());
488 m_lastInitiator
= msg
.Initiator();
493 if (msg
.Message() == MSGCODE_RECEIVE_FAILED
&&
494 m_lastInitiator
!= CECDEVICE_UNKNOWN
&&
495 m_processor
->HandleReceiveFailed(m_lastInitiator
))
501 bError
= msg
.IsError();
504 message
.reply
= msg
.Message();
505 CLibCEC::AddLog(CEC_LOG_DEBUG
, msg
.ToString());
509 switch(msg
.Message())
511 case MSGCODE_COMMAND_ACCEPTED
:
512 CLibCEC::AddLog(CEC_LOG_DEBUG
, msg
.ToString());
513 if (iPacketsLeft
> 0)
515 if (!message
.isTransmission
&& iPacketsLeft
== 0)
516 bTransmitSucceeded
= true;
518 case MSGCODE_TRANSMIT_SUCCEEDED
:
519 CLibCEC::AddLog(CEC_LOG_DEBUG
, msg
.ToString());
520 bTransmitSucceeded
= (iPacketsLeft
== 0);
521 bError
= !bTransmitSucceeded
;
522 message
.reply
= MSGCODE_TRANSMIT_SUCCEEDED
;
525 // ignore other data while waiting
533 return bTransmitSucceeded
&& !bError
;
536 void CUSBCECAdapterCommunication::AddData(uint8_t *data
, size_t iLen
)
538 CLockObject
lock(m_mutex
);
539 for (size_t iPtr
= 0; iPtr
< iLen
; iPtr
++)
543 if (data
[iPtr
] == MSGSTART
)
546 else if (data
[iPtr
] == MSGSTART
) //we found a msgstart before msgend, this is not right, remove
548 if (m_currentAdapterMessage
.Size() > 0)
549 CLibCEC::AddLog(CEC_LOG_WARNING
, "received MSGSTART before MSGEND, removing previous buffer contents");
550 m_currentAdapterMessage
.Clear();
553 else if (data
[iPtr
] == MSGEND
)
555 CCECAdapterMessage
*newMessage
= new CCECAdapterMessage
;
556 newMessage
->packet
= m_currentAdapterMessage
.packet
;
557 m_inBuffer
.Push(newMessage
);
558 m_currentAdapterMessage
.Clear();
560 m_bNextIsEscaped
= false;
561 m_rcvCondition
.Signal();
563 else if (m_bNextIsEscaped
)
565 m_currentAdapterMessage
.PushBack(data
[iPtr
] + (uint8_t)ESCOFFSET
);
566 m_bNextIsEscaped
= false;
568 else if (data
[iPtr
] == MSGESC
)
570 m_bNextIsEscaped
= true;
574 m_currentAdapterMessage
.PushBack(data
[iPtr
]);
579 bool CUSBCECAdapterCommunication::ReadFromDevice(uint32_t iTimeout
)
586 CLockObject
lock(m_mutex
);
587 iBytesRead
= m_port
->Read(buff
, sizeof(buff
), iTimeout
);
588 if (iBytesRead
< 0 || iBytesRead
> 256)
590 CLibCEC::AddLog(CEC_LOG_ERROR
, "error reading from serial port: %s", m_port
->GetError().c_str());
593 else if (iBytesRead
> 0)
595 AddData(buff
, iBytesRead
);
598 return iBytesRead
> 0;
601 void CUSBCECAdapterCommunication::SendMessageToAdapter(CCECAdapterMessage
*msg
)
603 CLockObject
adapterLock(m_mutex
);
604 CLockObject
lock(msg
->mutex
);
606 SetLineTimeout(msg
->lineTimeout
);
608 SetLineTimeout(msg
->retryTimeout
);
610 if (m_port
->Write(msg
->packet
.data
, msg
->Size()) != (ssize_t
) msg
->Size())
613 strError
.Format("error writing to serial port: %s", m_port
->GetError().c_str());
614 CLibCEC::AddLog(CEC_LOG_ERROR
, strError
);
615 msg
->state
= ADAPTER_MESSAGE_STATE_ERROR
;
619 CLibCEC::AddLog(CEC_LOG_DEBUG
, "command sent");
620 msg
->state
= ADAPTER_MESSAGE_STATE_SENT
;
622 msg
->condition
.Signal();
625 void CUSBCECAdapterCommunication::WriteNextCommand(void)
627 CCECAdapterMessage
*msg(NULL
);
628 if (m_outBuffer
.Pop(msg
))
629 SendMessageToAdapter(msg
);