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 void *CUSBCECAdapterProcessor::Process(void)
48 if (m_inBuffer
.Pop(command
))
49 m_callback
->OnCommandReceived(command
);
56 void CUSBCECAdapterProcessor::AddCommand(cec_command command
)
58 m_inBuffer
.Push(command
);
61 CUSBCECAdapterCommunication::CUSBCECAdapterCommunication(CCECProcessor
*processor
, const char *strPort
, uint16_t iBaudRate
/* = 38400 */) :
63 m_processor(processor
),
66 m_iFirmwareVersion(CEC_FW_VERSION_UNKNOWN
),
67 m_lastInitiator(CECDEVICE_UNKNOWN
),
68 m_bNextIsEscaped(false),
70 m_messageProcessor(NULL
)
72 m_port
= new PLATFORM::CSerialPort(strPort
, iBaudRate
);
75 CUSBCECAdapterCommunication::~CUSBCECAdapterCommunication(void)
80 bool CUSBCECAdapterCommunication::CheckAdapter(uint32_t iTimeoutMs
/* = 10000 */)
83 uint64_t iNow
= GetTimeMs();
84 uint64_t iTarget
= iTimeoutMs
> 0 ? iNow
+ iTimeoutMs
: iNow
+ CEC_DEFAULT_TRANSMIT_WAIT
;
86 /* try to ping the adapter */
89 while (iNow
< iTarget
&& (bPinged
= PingAdapter()) == false)
91 CLibCEC::AddLog(CEC_LOG_ERROR
, "the adapter did not respond correctly to a ping (try %d)", ++iPingTry
);
96 /* try to read the firmware version */
97 m_iFirmwareVersion
= CEC_FW_VERSION_UNKNOWN
;
98 unsigned iFwVersionTry(0);
99 while (bPinged
&& iNow
< iTarget
&& (m_iFirmwareVersion
= GetFirmwareVersion()) == CEC_FW_VERSION_UNKNOWN
)
101 CLibCEC::AddLog(CEC_LOG_ERROR
, "the adapter did not respond with a correct firmware version (try %d)", ++iFwVersionTry
);
106 if (m_iFirmwareVersion
>= 2)
108 /* try to set controlled mode */
109 unsigned iControlledTry(0);
110 bool bControlled(false);
111 while (iNow
< iTarget
&& (bControlled
= SetControlledMode(true)) == false)
113 CLibCEC::AddLog(CEC_LOG_ERROR
, "the adapter did not respond correctly to setting controlled mode (try %d)", ++iControlledTry
);
117 bReturn
= bControlled
;
125 bool CUSBCECAdapterCommunication::Open(IAdapterCommunicationCallback
*cb
, uint32_t iTimeoutMs
/* = 10000 */)
127 uint64_t iNow
= GetTimeMs();
128 uint64_t iTimeout
= iNow
+ iTimeoutMs
;
131 CLockObject
lock(m_mutex
);
135 CLibCEC::AddLog(CEC_LOG_ERROR
, "port is NULL");
141 CLibCEC::AddLog(CEC_LOG_ERROR
, "port is already open");
147 bool bConnected(false);
148 while (!bConnected
&& iNow
< iTimeout
)
150 if ((bConnected
= m_port
->Open(iTimeout
)) == false)
152 strError
.Format("error opening serial port '%s': %s", m_port
->GetName().c_str(), m_port
->GetError().c_str());
160 CLibCEC::AddLog(CEC_LOG_ERROR
, strError
);
164 CLibCEC::AddLog(CEC_LOG_DEBUG
, "connection opened, clearing any previous input and waiting for active transmissions to end before starting");
166 //clear any input bytes
168 while (m_port
->Read(buff
, 1024, 100) > 0)
170 CLibCEC::AddLog(CEC_LOG_DEBUG
, "data received, clearing it");
180 CLibCEC::AddLog(CEC_LOG_ERROR
, "the adapter failed to pass basic checks");
184 CLibCEC::AddLog(CEC_LOG_DEBUG
, "communication thread started");
188 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not create a communication thread");
193 void CUSBCECAdapterCommunication::Close(void)
198 void *CUSBCECAdapterCommunication::Process(void)
200 m_messageProcessor
= new CUSBCECAdapterProcessor(m_callback
);
201 m_messageProcessor
->CreateThread();
204 bool bCommandReceived(false);
208 CLockObject
lock(m_mutex
);
210 bCommandReceived
= m_callback
&& Read(command
, 0);
213 /* push the next command to the callback method if there is one */
214 if (!IsStopped() && bCommandReceived
)
215 m_messageProcessor
->AddCommand(command
);
224 /* stop the message processor */
225 m_messageProcessor
->StopThread();
226 delete m_messageProcessor
;
228 /* notify all threads that are waiting on messages to be sent */
229 CCECAdapterMessage
*msg(NULL
);
230 while (m_outBuffer
.Pop(msg
))
231 msg
->event
.Broadcast();
233 /* set the ackmask to 0 before closing the connection */
234 SetAckMaskInternal(0, true);
245 cec_adapter_message_state
CUSBCECAdapterCommunication::Write(const cec_command
&data
, uint8_t iMaxTries
, uint8_t iLineTimeout
/* = 3 */, uint8_t iRetryLineTimeout
/* = 3 */)
247 cec_adapter_message_state
retVal(ADAPTER_MESSAGE_STATE_UNKNOWN
);
251 CCECAdapterMessage
*output
= new CCECAdapterMessage(data
);
253 /* set the number of retries */
254 if (data
.opcode
== CEC_OPCODE_NONE
) //TODO
255 output
->maxTries
= 1;
256 else if (data
.initiator
!= CECDEVICE_BROADCAST
)
257 output
->maxTries
= iMaxTries
;
259 output
->lineTimeout
= iLineTimeout
;
260 output
->retryTimeout
= iRetryLineTimeout
;
264 while (bRetry
&& ++output
->tries
< output
->maxTries
)
266 bRetry
= (!Write(output
) || output
->NeedsRetry()) && output
->transmit_timeout
> 0;
268 Sleep(CEC_DEFAULT_TRANSMIT_RETRY_WAIT
);
270 retVal
= output
->state
;
276 bool CUSBCECAdapterCommunication::Write(CCECAdapterMessage
*data
)
278 data
->state
= ADAPTER_MESSAGE_STATE_WAITING_TO_BE_SENT
;
279 m_outBuffer
.Push(data
);
280 data
->event
.Wait(5000);
282 if ((data
->expectControllerAck
&& data
->state
!= ADAPTER_MESSAGE_STATE_SENT_ACKED
) ||
283 (!data
->expectControllerAck
&& data
->state
!= ADAPTER_MESSAGE_STATE_SENT
))
285 CLibCEC::AddLog(CEC_LOG_DEBUG
, "command was not %s", data
->state
== ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED
? "acked" : "sent");
292 bool CUSBCECAdapterCommunication::Read(cec_command
&command
, uint32_t iTimeout
)
297 CCECAdapterMessage msg
;
298 if (Read(msg
, iTimeout
))
300 if (ParseMessage(msg
))
302 command
= m_currentframe
;
303 m_currentframe
.Clear();
310 bool CUSBCECAdapterCommunication::Read(CCECAdapterMessage
&msg
, uint32_t iTimeout
)
312 CLockObject
lock(m_mutex
);
315 CCECAdapterMessage
*buf(NULL
);
317 if (!m_inBuffer
.Pop(buf
))
319 if (iTimeout
== 0 || !m_rcvCondition
.Wait(m_mutex
, m_bHasData
, iTimeout
))
322 m_bHasData
= m_inBuffer
.Size() > 0;
327 msg
.packet
= buf
->packet
;
328 msg
.state
= ADAPTER_MESSAGE_STATE_INCOMING
;
335 CStdString
CUSBCECAdapterCommunication::GetError(void) const
338 strError
= m_port
->GetError();
342 bool CUSBCECAdapterCommunication::StartBootloader(void)
348 CLibCEC::AddLog(CEC_LOG_DEBUG
, "starting the bootloader");
349 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
351 output
->PushBack(MSGSTART
);
352 output
->PushEscaped(MSGCODE_START_BOOTLOADER
);
353 output
->PushBack(MSGEND
);
354 output
->isTransmission
= false;
355 output
->expectControllerAck
= false;
357 if ((bReturn
= Write(output
)) == false)
358 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not start the bootloader");
364 bool CUSBCECAdapterCommunication::PingAdapter(void)
370 CLibCEC::AddLog(CEC_LOG_DEBUG
, "sending ping");
371 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
373 output
->PushBack(MSGSTART
);
374 output
->PushEscaped(MSGCODE_PING
);
375 output
->PushBack(MSGEND
);
376 output
->isTransmission
= false;
378 if ((bReturn
= Write(output
)) == false)
379 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not ping the adapter");
385 bool CUSBCECAdapterCommunication::ParseMessage(const CCECAdapterMessage
&msg
)
388 bool bIsError(msg
.IsError());
393 switch(msg
.Message())
395 case MSGCODE_FRAME_START
:
397 m_currentframe
.Clear();
400 m_currentframe
.initiator
= msg
.Initiator();
401 m_currentframe
.destination
= msg
.Destination();
402 m_currentframe
.ack
= msg
.IsACK();
403 m_currentframe
.eom
= msg
.IsEOM();
405 if (m_currentframe
.ack
== 0x1)
407 m_lastInitiator
= m_currentframe
.initiator
;
408 m_processor
->HandlePoll(m_currentframe
.initiator
, m_currentframe
.destination
);
412 case MSGCODE_RECEIVE_FAILED
:
414 m_currentframe
.Clear();
415 if (m_lastInitiator
!= CECDEVICE_UNKNOWN
)
416 bIsError
= m_processor
->HandleReceiveFailed(m_lastInitiator
);
419 case MSGCODE_FRAME_DATA
:
423 m_currentframe
.PushBack(msg
[1]);
424 m_currentframe
.eom
= msg
.IsEOM();
433 CLibCEC::AddLog(bIsError
? CEC_LOG_WARNING
: CEC_LOG_DEBUG
, msg
.ToString());
437 uint16_t CUSBCECAdapterCommunication::GetFirmwareVersion(void)
439 uint16_t iReturn(m_iFirmwareVersion
);
443 if (iReturn
== CEC_FW_VERSION_UNKNOWN
)
445 CLockObject
lock(m_mutex
);
446 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting the firmware version");
447 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
449 output
->PushBack(MSGSTART
);
450 output
->PushEscaped(MSGCODE_FIRMWARE_VERSION
);
451 output
->PushBack(MSGEND
);
452 output
->isTransmission
= false;
453 output
->expectControllerAck
= false;
455 SendMessageToAdapter(output
);
456 bool bWriteOk
= output
->state
== ADAPTER_MESSAGE_STATE_SENT
;
460 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not request the firmware version");
464 Sleep(250); // TODO ReadFromDevice() isn't waiting for the timeout to pass on win32
465 ReadFromDevice(CEC_DEFAULT_TRANSMIT_WAIT
, 5 /* start + msgcode + 2 bytes for fw version + end */);
466 CCECAdapterMessage input
;
469 if (input
.Message() != MSGCODE_FIRMWARE_VERSION
|| input
.Size() != 3)
470 CLibCEC::AddLog(CEC_LOG_ERROR
, "invalid firmware version (size = %d, message = %d)", input
.Size(), input
.Message());
473 m_iFirmwareVersion
= (input
[1] << 8 | input
[2]);
474 iReturn
= m_iFirmwareVersion
;
479 CLibCEC::AddLog(CEC_LOG_ERROR
, "no firmware version received");
486 bool CUSBCECAdapterCommunication::SetLineTimeout(uint8_t iTimeout
)
488 m_iLineTimeout
= iTimeout
;
491 // bool bReturn(m_iLineTimeout != iTimeout);
495 // CCECAdapterMessage *output = new CCECAdapterMessage;
497 // output->PushBack(MSGSTART);
498 // output->PushEscaped(MSGCODE_TRANSMIT_IDLETIME);
499 // output->PushEscaped(iTimeout);
500 // output->PushBack(MSGEND);
501 // output->isTransmission = false;
503 // if ((bReturn = Write(output)) == false)
504 // CLibCEC::AddLog(CEC_LOG_ERROR, "could not set the idletime");
511 bool CUSBCECAdapterCommunication::SetAckMask(uint16_t iMask
)
513 return SetAckMaskInternal(iMask
, false);
516 bool CUSBCECAdapterCommunication::SetAckMaskInternal(uint16_t iMask
, bool bWriteDirectly
/* = false */)
519 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting ackmask to %2x", iMask
);
521 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
523 output
->PushBack(MSGSTART
);
524 output
->PushEscaped(MSGCODE_SET_ACK_MASK
);
525 output
->PushEscaped(iMask
>> 8);
526 output
->PushEscaped((uint8_t)iMask
);
527 output
->PushBack(MSGEND
);
528 output
->isTransmission
= false;
531 SendMessageToAdapter(output
);
532 else if ((bReturn
= Write(output
)) == false)
533 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not set the ackmask");
540 bool CUSBCECAdapterCommunication::SetControlledMode(bool controlled
)
543 CLibCEC::AddLog(CEC_LOG_DEBUG
, "turning controlled mode %s", controlled
? "on" : "off");
545 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
547 output
->PushBack(MSGSTART
);
548 output
->PushEscaped(MSGCODE_SET_CONTROLLED
);
549 output
->PushEscaped(controlled
);
550 output
->PushBack(MSGEND
);
551 output
->isTransmission
= false;
553 if ((bReturn
= Write(output
)) == false)
554 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not set controlled mode");
560 bool CUSBCECAdapterCommunication::IsOpen(void)
562 return !IsStopped() && m_port
->IsOpen() && IsRunning();
565 bool CUSBCECAdapterCommunication::WaitForAck(CCECAdapterMessage
&message
)
568 bool bTransmitSucceeded(false);
569 uint8_t iPacketsLeft(message
.Size() / 4);
571 int64_t iNow
= GetTimeMs();
572 int64_t iTargetTime
= iNow
+ (message
.transmit_timeout
<= 5 ? CEC_DEFAULT_TRANSMIT_WAIT
: message
.transmit_timeout
);
574 while (!bTransmitSucceeded
&& !bError
&& iNow
< iTargetTime
)
577 CCECAdapterMessage msg
;
584 if (msg
.Message() == MSGCODE_FRAME_START
&& msg
.IsACK())
586 m_processor
->HandlePoll(msg
.Initiator(), msg
.Destination());
587 m_lastInitiator
= msg
.Initiator();
592 if (msg
.Message() == MSGCODE_RECEIVE_FAILED
&&
593 m_lastInitiator
!= CECDEVICE_UNKNOWN
&&
594 m_processor
->HandleReceiveFailed(m_lastInitiator
))
600 bError
= msg
.IsError();
603 message
.reply
= msg
.Message();
604 CLibCEC::AddLog(CEC_LOG_DEBUG
, msg
.ToString());
608 switch(msg
.Message())
610 case MSGCODE_COMMAND_ACCEPTED
:
611 CLibCEC::AddLog(CEC_LOG_DEBUG
, msg
.ToString());
612 if (iPacketsLeft
> 0)
614 if (!message
.isTransmission
&& iPacketsLeft
== 0)
615 bTransmitSucceeded
= true;
617 case MSGCODE_TRANSMIT_SUCCEEDED
:
618 CLibCEC::AddLog(CEC_LOG_DEBUG
, msg
.ToString());
619 bTransmitSucceeded
= (iPacketsLeft
== 0);
620 bError
= !bTransmitSucceeded
;
621 message
.reply
= MSGCODE_TRANSMIT_SUCCEEDED
;
624 // ignore other data while waiting
632 message
.state
= bTransmitSucceeded
&& !bError
?
633 ADAPTER_MESSAGE_STATE_SENT_ACKED
:
634 ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED
;
636 return bTransmitSucceeded
&& !bError
;
639 void CUSBCECAdapterCommunication::AddData(uint8_t *data
, size_t iLen
)
641 CLockObject
lock(m_mutex
);
642 for (size_t iPtr
= 0; iPtr
< iLen
; iPtr
++)
646 if (data
[iPtr
] == MSGSTART
)
649 else if (data
[iPtr
] == MSGSTART
) //we found a msgstart before msgend, this is not right, remove
651 if (m_currentAdapterMessage
.Size() > 0)
652 CLibCEC::AddLog(CEC_LOG_WARNING
, "received MSGSTART before MSGEND, removing previous buffer contents");
653 m_currentAdapterMessage
.Clear();
656 else if (data
[iPtr
] == MSGEND
)
658 CCECAdapterMessage
*newMessage
= new CCECAdapterMessage
;
659 newMessage
->packet
= m_currentAdapterMessage
.packet
;
660 m_inBuffer
.Push(newMessage
);
661 m_currentAdapterMessage
.Clear();
663 m_bNextIsEscaped
= false;
665 m_rcvCondition
.Signal();
667 else if (m_bNextIsEscaped
)
669 m_currentAdapterMessage
.PushBack(data
[iPtr
] + (uint8_t)ESCOFFSET
);
670 m_bNextIsEscaped
= false;
672 else if (data
[iPtr
] == MSGESC
)
674 m_bNextIsEscaped
= true;
678 m_currentAdapterMessage
.PushBack(data
[iPtr
]);
683 bool CUSBCECAdapterCommunication::ReadFromDevice(uint32_t iTimeout
, size_t iSize
/* = 256 */)
692 CLockObject
lock(m_mutex
);
693 iBytesRead
= m_port
->Read(buff
, sizeof(uint8_t) * iSize
, iTimeout
);
694 if (iBytesRead
< 0 || iBytesRead
> 256)
696 CLibCEC::AddLog(CEC_LOG_ERROR
, "error reading from serial port: %s", m_port
->GetError().c_str());
700 else if (iBytesRead
> 0)
702 AddData(buff
, iBytesRead
);
705 return iBytesRead
> 0;
708 void CUSBCECAdapterCommunication::SendMessageToAdapter(CCECAdapterMessage
*msg
)
710 CLockObject
adapterLock(m_mutex
);
711 if (!m_port
->IsOpen())
713 CLibCEC::AddLog(CEC_LOG_ERROR
, "error writing to serial port: the connection is closed");
714 msg
->state
= ADAPTER_MESSAGE_STATE_ERROR
;
719 SetLineTimeout(msg
->lineTimeout
);
721 SetLineTimeout(msg
->retryTimeout
);
723 if (m_port
->Write(msg
->packet
.data
, msg
->Size()) != (ssize_t
) msg
->Size())
725 CLibCEC::AddLog(CEC_LOG_ERROR
, "error writing to serial port: %s", m_port
->GetError().c_str());
726 msg
->state
= ADAPTER_MESSAGE_STATE_ERROR
;
730 CLibCEC::AddLog(CEC_LOG_DEBUG
, "command sent");
731 msg
->state
= ADAPTER_MESSAGE_STATE_SENT
;
733 if (msg
->expectControllerAck
)
735 if (!WaitForAck(*msg
))
736 CLibCEC::AddLog(CEC_LOG_DEBUG
, "did not receive ack");
742 void CUSBCECAdapterCommunication::WriteNextCommand(void)
744 CCECAdapterMessage
*msg(NULL
);
745 if (m_outBuffer
.Pop(msg
))
746 SendMessageToAdapter(msg
);
749 CStdString
CUSBCECAdapterCommunication::GetPortName(void)
752 strName
= m_port
->GetName();