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
),
73 m_port
= new PLATFORM::CSerialPort(strPort
, iBaudRate
);
76 CUSBCECAdapterCommunication::~CUSBCECAdapterCommunication(void)
81 bool CUSBCECAdapterCommunication::CheckAdapter(uint32_t iTimeoutMs
/* = 10000 */)
84 uint64_t iNow
= GetTimeMs();
85 uint64_t iTarget
= iTimeoutMs
> 0 ? iNow
+ iTimeoutMs
: iNow
+ CEC_DEFAULT_TRANSMIT_WAIT
;
87 /* try to ping the adapter */
90 while (iNow
< iTarget
&& (bPinged
= PingAdapter()) == false)
92 CLibCEC::AddLog(CEC_LOG_ERROR
, "the adapter did not respond correctly to a ping (try %d)", ++iPingTry
);
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
&& iFwVersionTry
< 3)
102 CLibCEC::AddLog(CEC_LOG_WARNING
, "the adapter did not respond with a correct firmware version (try %d)", ++iFwVersionTry
);
107 if (m_iFirmwareVersion
== CEC_FW_VERSION_UNKNOWN
)
109 CLibCEC::AddLog(CEC_LOG_DEBUG
, "defaulting to firmware version 1");
110 m_iFirmwareVersion
= 1;
113 if (m_iFirmwareVersion
>= 2)
115 /* try to set controlled mode */
116 unsigned iControlledTry(0);
117 bool bControlled(false);
118 while (iNow
< iTarget
&& (bControlled
= SetControlledMode(true)) == false)
120 CLibCEC::AddLog(CEC_LOG_ERROR
, "the adapter did not respond correctly to setting controlled mode (try %d)", ++iControlledTry
);
124 bReturn
= bControlled
;
130 CLockObject
lock(m_mutex
);
131 m_bInitialised
= bReturn
;
137 bool CUSBCECAdapterCommunication::Open(IAdapterCommunicationCallback
*cb
, uint32_t iTimeoutMs
/* = 10000 */, bool bSkipChecks
/* = false */)
139 uint64_t iNow
= GetTimeMs();
140 uint64_t iTimeout
= iNow
+ iTimeoutMs
;
143 CLockObject
lock(m_mutex
);
147 CLibCEC::AddLog(CEC_LOG_ERROR
, "port is NULL");
153 CLibCEC::AddLog(CEC_LOG_ERROR
, "port is already open");
159 bool bConnected(false);
160 while (!bConnected
&& iNow
< iTimeout
)
162 if ((bConnected
= m_port
->Open(iTimeout
)) == false)
164 strError
.Format("error opening serial port '%s': %s", m_port
->GetName().c_str(), m_port
->GetError().c_str());
172 CLibCEC::AddLog(CEC_LOG_ERROR
, strError
);
176 CLibCEC::AddLog(CEC_LOG_DEBUG
, "connection opened, clearing any previous input and waiting for active transmissions to end before starting");
180 //clear any input bytes
182 while (m_port
->Read(buff
, 1024, 100) > 0)
184 CLibCEC::AddLog(CEC_LOG_DEBUG
, "data received, clearing it");
190 if (!bSkipChecks
&& !CheckAdapter())
192 CLibCEC::AddLog(CEC_LOG_ERROR
, "the adapter failed to pass basic checks");
199 CLibCEC::AddLog(CEC_LOG_DEBUG
, "communication thread started");
204 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not create a communication thread");
211 void CUSBCECAdapterCommunication::Close(void)
216 void *CUSBCECAdapterCommunication::Process(void)
218 m_messageProcessor
= new CUSBCECAdapterProcessor(m_callback
);
219 m_messageProcessor
->CreateThread();
223 bool bCommandReceived(false);
227 CLockObject
lock(m_mutex
);
229 bCommandReceived
= m_callback
&& Read(command
, 0) && m_bInitialised
;
232 /* push the next command to the callback method if there is one */
233 if (!IsStopped() && bCommandReceived
)
234 m_messageProcessor
->AddCommand(command
);
243 /* stop the message processor */
244 m_messageProcessor
->StopThread();
245 delete m_messageProcessor
;
247 /* notify all threads that are waiting on messages to be sent */
248 CCECAdapterMessage
*msg(NULL
);
249 while (m_outBuffer
.Pop(msg
))
250 msg
->event
.Broadcast();
252 /* set the ackmask to 0 before closing the connection */
253 SetAckMaskInternal(0, true);
264 cec_adapter_message_state
CUSBCECAdapterCommunication::Write(const cec_command
&data
, uint8_t iMaxTries
, uint8_t iLineTimeout
/* = 3 */, uint8_t iRetryLineTimeout
/* = 3 */)
266 cec_adapter_message_state
retVal(ADAPTER_MESSAGE_STATE_UNKNOWN
);
270 CCECAdapterMessage
*output
= new CCECAdapterMessage(data
);
272 /* set the number of retries */
273 if (data
.opcode
== CEC_OPCODE_NONE
) //TODO
274 output
->maxTries
= 1;
275 else if (data
.initiator
!= CECDEVICE_BROADCAST
)
276 output
->maxTries
= iMaxTries
;
278 output
->lineTimeout
= iLineTimeout
;
279 output
->retryTimeout
= iRetryLineTimeout
;
283 while (bRetry
&& ++output
->tries
< output
->maxTries
)
285 bRetry
= (!Write(output
) || output
->NeedsRetry()) && output
->transmit_timeout
> 0;
287 Sleep(CEC_DEFAULT_TRANSMIT_RETRY_WAIT
);
289 retVal
= output
->state
;
295 bool CUSBCECAdapterCommunication::Write(CCECAdapterMessage
*data
)
297 data
->state
= ADAPTER_MESSAGE_STATE_WAITING_TO_BE_SENT
;
298 m_outBuffer
.Push(data
);
299 data
->event
.Wait(5000);
301 if ((data
->expectControllerAck
&& data
->state
!= ADAPTER_MESSAGE_STATE_SENT_ACKED
) ||
302 (!data
->expectControllerAck
&& data
->state
!= ADAPTER_MESSAGE_STATE_SENT
))
304 CLibCEC::AddLog(CEC_LOG_DEBUG
, "command was not %s", data
->state
== ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED
? "acked" : "sent");
311 bool CUSBCECAdapterCommunication::Read(cec_command
&command
, uint32_t iTimeout
)
316 CCECAdapterMessage msg
;
317 if (Read(msg
, iTimeout
))
319 if (ParseMessage(msg
))
321 command
= m_currentframe
;
322 m_currentframe
.Clear();
329 bool CUSBCECAdapterCommunication::Read(CCECAdapterMessage
&msg
, uint32_t iTimeout
)
331 CLockObject
lock(m_mutex
);
334 CCECAdapterMessage
*buf(NULL
);
336 if (!m_inBuffer
.Pop(buf
))
338 if (iTimeout
== 0 || !m_rcvCondition
.Wait(m_mutex
, m_bHasData
, iTimeout
))
341 m_bHasData
= !m_inBuffer
.IsEmpty();
346 msg
.packet
= buf
->packet
;
347 msg
.state
= ADAPTER_MESSAGE_STATE_INCOMING
;
354 CStdString
CUSBCECAdapterCommunication::GetError(void) const
357 strError
= m_port
->GetError();
361 bool CUSBCECAdapterCommunication::StartBootloader(void)
367 CLibCEC::AddLog(CEC_LOG_DEBUG
, "starting the bootloader");
368 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
370 output
->PushBack(MSGSTART
);
371 output
->PushEscaped(MSGCODE_START_BOOTLOADER
);
372 output
->PushBack(MSGEND
);
373 output
->isTransmission
= false;
374 output
->expectControllerAck
= false;
376 if ((bReturn
= Write(output
)) == false)
377 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not start the bootloader");
383 bool CUSBCECAdapterCommunication::PingAdapter(void)
385 CLockObject
lock(m_mutex
);
386 CLibCEC::AddLog(CEC_LOG_DEBUG
, "sending ping");
388 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
390 output
->PushBack(MSGSTART
);
391 output
->PushEscaped(MSGCODE_PING
);
392 output
->PushBack(MSGEND
);
393 output
->isTransmission
= false;
395 SendMessageToAdapter(output
);
396 bool bWriteOk
= output
->state
== ADAPTER_MESSAGE_STATE_SENT_ACKED
;
400 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not ping the adapter");
407 bool CUSBCECAdapterCommunication::ParseMessage(const CCECAdapterMessage
&msg
)
410 bool bIsError(msg
.IsError());
415 CLockObject
adapterLock(m_mutex
);
416 switch(msg
.Message())
418 case MSGCODE_FRAME_START
:
420 m_currentframe
.Clear();
423 m_currentframe
.initiator
= msg
.Initiator();
424 m_currentframe
.destination
= msg
.Destination();
425 m_currentframe
.ack
= msg
.IsACK();
426 m_currentframe
.eom
= msg
.IsEOM();
428 if (m_currentframe
.ack
== 0x1)
430 m_lastInitiator
= m_currentframe
.initiator
;
431 m_processor
->HandlePoll(m_currentframe
.initiator
, m_currentframe
.destination
);
435 case MSGCODE_RECEIVE_FAILED
:
437 m_currentframe
.Clear();
438 if (m_lastInitiator
!= CECDEVICE_UNKNOWN
)
439 bIsError
= m_processor
->HandleReceiveFailed(m_lastInitiator
);
442 case MSGCODE_FRAME_DATA
:
446 m_currentframe
.PushBack(msg
[1]);
447 m_currentframe
.eom
= msg
.IsEOM();
455 CLibCEC::AddLog(bIsError
? CEC_LOG_WARNING
: CEC_LOG_DEBUG
, msg
.ToString());
459 uint16_t CUSBCECAdapterCommunication::GetFirmwareVersion(void)
461 uint16_t iReturn(m_iFirmwareVersion
);
463 if (iReturn
== CEC_FW_VERSION_UNKNOWN
)
465 CLockObject
lock(m_mutex
);
466 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting the firmware version");
467 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
469 output
->PushBack(MSGSTART
);
470 output
->PushEscaped(MSGCODE_FIRMWARE_VERSION
);
471 output
->PushBack(MSGEND
);
472 output
->isTransmission
= false;
473 output
->expectControllerAck
= false;
475 SendMessageToAdapter(output
);
476 bool bWriteOk
= output
->state
== ADAPTER_MESSAGE_STATE_SENT
;
480 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not request the firmware version");
484 Sleep(250); // TODO ReadFromDevice() isn't waiting for the timeout to pass on win32
485 ReadFromDevice(CEC_DEFAULT_TRANSMIT_WAIT
, 5 /* start + msgcode + 2 bytes for fw version + end */);
486 CCECAdapterMessage input
;
489 if (input
.Message() != MSGCODE_FIRMWARE_VERSION
|| input
.Size() != 3)
490 CLibCEC::AddLog(CEC_LOG_ERROR
, "invalid firmware version (size = %d, message = %d)", input
.Size(), input
.Message());
493 m_iFirmwareVersion
= (input
[1] << 8 | input
[2]);
494 iReturn
= m_iFirmwareVersion
;
499 CLibCEC::AddLog(CEC_LOG_ERROR
, "no firmware version received");
506 bool CUSBCECAdapterCommunication::SetLineTimeout(uint8_t iTimeout
)
508 m_iLineTimeout
= iTimeout
;
511 // bool bReturn(m_iLineTimeout != iTimeout);
515 // CCECAdapterMessage *output = new CCECAdapterMessage;
517 // output->PushBack(MSGSTART);
518 // output->PushEscaped(MSGCODE_TRANSMIT_IDLETIME);
519 // output->PushEscaped(iTimeout);
520 // output->PushBack(MSGEND);
521 // output->isTransmission = false;
523 // if ((bReturn = Write(output)) == false)
524 // CLibCEC::AddLog(CEC_LOG_ERROR, "could not set the idletime");
531 bool CUSBCECAdapterCommunication::SetAckMask(uint16_t iMask
)
533 return SetAckMaskInternal(iMask
, false);
536 bool CUSBCECAdapterCommunication::SetAckMaskInternal(uint16_t iMask
, bool bWriteDirectly
/* = false */)
539 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting ackmask to %2x", iMask
);
541 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
543 output
->PushBack(MSGSTART
);
544 output
->PushEscaped(MSGCODE_SET_ACK_MASK
);
545 output
->PushEscaped(iMask
>> 8);
546 output
->PushEscaped((uint8_t)iMask
);
547 output
->PushBack(MSGEND
);
548 output
->isTransmission
= false;
551 SendMessageToAdapter(output
);
552 else if ((bReturn
= Write(output
)) == false)
553 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not set the ackmask");
560 bool CUSBCECAdapterCommunication::SetControlledMode(bool controlled
)
562 CLockObject
lock(m_mutex
);
563 CLibCEC::AddLog(CEC_LOG_DEBUG
, "turning controlled mode %s", controlled
? "on" : "off");
565 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
567 output
->PushBack(MSGSTART
);
568 output
->PushEscaped(MSGCODE_SET_CONTROLLED
);
569 output
->PushEscaped(controlled
);
570 output
->PushBack(MSGEND
);
571 output
->isTransmission
= false;
573 SendMessageToAdapter(output
);
574 bool bWriteOk
= output
->state
== ADAPTER_MESSAGE_STATE_SENT
;
578 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not set controlled mode");
585 bool CUSBCECAdapterCommunication::IsOpen(void)
587 return !IsStopped() && m_port
->IsOpen() && IsRunning();
590 bool CUSBCECAdapterCommunication::WaitForAck(CCECAdapterMessage
&message
)
593 bool bTransmitSucceeded(false);
594 uint8_t iPacketsLeft(message
.Size() / 4);
596 int64_t iNow
= GetTimeMs();
597 int64_t iTargetTime
= iNow
+ (message
.transmit_timeout
<= 5 ? CEC_DEFAULT_TRANSMIT_WAIT
: message
.transmit_timeout
);
599 while (!bTransmitSucceeded
&& !bError
&& iNow
< iTargetTime
)
602 CCECAdapterMessage msg
;
609 if (msg
.Message() == MSGCODE_FRAME_START
&& msg
.IsACK())
611 m_processor
->HandlePoll(msg
.Initiator(), msg
.Destination());
612 m_lastInitiator
= msg
.Initiator();
617 if (msg
.Message() == MSGCODE_RECEIVE_FAILED
&&
618 m_lastInitiator
!= CECDEVICE_UNKNOWN
&&
619 m_processor
->HandleReceiveFailed(m_lastInitiator
))
625 bError
= msg
.IsError();
628 message
.reply
= msg
.Message();
629 CLibCEC::AddLog(CEC_LOG_DEBUG
, msg
.ToString());
633 switch(msg
.Message())
635 case MSGCODE_COMMAND_ACCEPTED
:
636 if (iPacketsLeft
> 0)
638 if (!message
.isTransmission
&& iPacketsLeft
== 0)
639 bTransmitSucceeded
= true;
640 CLibCEC::AddLog(CEC_LOG_DEBUG
, "%s - waiting for %d more", msg
.ToString().c_str(), iPacketsLeft
);
642 case MSGCODE_TRANSMIT_SUCCEEDED
:
643 CLibCEC::AddLog(CEC_LOG_DEBUG
, msg
.ToString());
644 bTransmitSucceeded
= (iPacketsLeft
== 0);
645 bError
= !bTransmitSucceeded
;
646 message
.reply
= MSGCODE_TRANSMIT_SUCCEEDED
;
649 // ignore other data while waiting
657 message
.state
= bTransmitSucceeded
&& !bError
?
658 ADAPTER_MESSAGE_STATE_SENT_ACKED
:
659 ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED
;
661 return bTransmitSucceeded
&& !bError
;
664 void CUSBCECAdapterCommunication::AddData(uint8_t *data
, size_t iLen
)
666 CLockObject
lock(m_mutex
);
667 for (size_t iPtr
= 0; iPtr
< iLen
; iPtr
++)
671 if (data
[iPtr
] == MSGSTART
)
674 else if (data
[iPtr
] == MSGSTART
) //we found a msgstart before msgend, this is not right, remove
676 if (m_currentAdapterMessage
.Size() > 0)
677 CLibCEC::AddLog(CEC_LOG_WARNING
, "received MSGSTART before MSGEND, removing previous buffer contents");
678 m_currentAdapterMessage
.Clear();
681 else if (data
[iPtr
] == MSGEND
)
683 CCECAdapterMessage
*newMessage
= new CCECAdapterMessage
;
684 newMessage
->packet
= m_currentAdapterMessage
.packet
;
685 m_inBuffer
.Push(newMessage
);
686 m_currentAdapterMessage
.Clear();
688 m_bNextIsEscaped
= false;
690 m_rcvCondition
.Broadcast();
692 else if (m_bNextIsEscaped
)
694 m_currentAdapterMessage
.PushBack(data
[iPtr
] + (uint8_t)ESCOFFSET
);
695 m_bNextIsEscaped
= false;
697 else if (data
[iPtr
] == MSGESC
)
699 m_bNextIsEscaped
= true;
703 m_currentAdapterMessage
.PushBack(data
[iPtr
]);
708 bool CUSBCECAdapterCommunication::ReadFromDevice(uint32_t iTimeout
, size_t iSize
/* = 256 */)
717 CLockObject
lock(m_mutex
);
718 iBytesRead
= m_port
->Read(buff
, sizeof(uint8_t) * iSize
, iTimeout
);
719 if (iBytesRead
< 0 || iBytesRead
> 256)
721 CLibCEC::AddLog(CEC_LOG_ERROR
, "error reading from serial port: %s", m_port
->GetError().c_str());
725 else if (iBytesRead
> 0)
727 AddData(buff
, iBytesRead
);
730 return iBytesRead
> 0;
733 void CUSBCECAdapterCommunication::SendMessageToAdapter(CCECAdapterMessage
*msg
)
735 CLockObject
adapterLock(m_mutex
);
736 if (!m_port
->IsOpen())
738 CLibCEC::AddLog(CEC_LOG_ERROR
, "error writing to serial port: the connection is closed");
739 msg
->state
= ADAPTER_MESSAGE_STATE_ERROR
;
744 SetLineTimeout(msg
->lineTimeout
);
746 SetLineTimeout(msg
->retryTimeout
);
748 if (m_port
->Write(msg
->packet
.data
, msg
->Size()) != (ssize_t
) msg
->Size())
750 CLibCEC::AddLog(CEC_LOG_ERROR
, "error writing to serial port: %s", m_port
->GetError().c_str());
751 msg
->state
= ADAPTER_MESSAGE_STATE_ERROR
;
755 CLibCEC::AddLog(CEC_LOG_DEBUG
, "command sent");
756 msg
->state
= ADAPTER_MESSAGE_STATE_SENT
;
758 if (msg
->expectControllerAck
)
760 if (!WaitForAck(*msg
))
761 CLibCEC::AddLog(CEC_LOG_DEBUG
, "did not receive ack");
767 void CUSBCECAdapterCommunication::WriteNextCommand(void)
769 CCECAdapterMessage
*msg(NULL
);
770 if (m_outBuffer
.Pop(msg
))
771 SendMessageToAdapter(msg
);
774 CStdString
CUSBCECAdapterCommunication::GetPortName(void)
777 strName
= m_port
->GetName();