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();
205 bool bCommandReceived(false);
209 CLockObject
lock(m_mutex
);
211 bCommandReceived
= m_callback
&& Read(command
, 0);
214 /* push the next command to the callback method if there is one */
215 if (!IsStopped() && bCommandReceived
)
216 m_messageProcessor
->AddCommand(command
);
225 /* stop the message processor */
226 m_messageProcessor
->StopThread();
227 delete m_messageProcessor
;
229 /* notify all threads that are waiting on messages to be sent */
230 CCECAdapterMessage
*msg(NULL
);
231 while (m_outBuffer
.Pop(msg
))
232 msg
->event
.Broadcast();
234 /* set the ackmask to 0 before closing the connection */
235 SetAckMaskInternal(0, true);
246 cec_adapter_message_state
CUSBCECAdapterCommunication::Write(const cec_command
&data
, uint8_t iMaxTries
, uint8_t iLineTimeout
/* = 3 */, uint8_t iRetryLineTimeout
/* = 3 */)
248 cec_adapter_message_state
retVal(ADAPTER_MESSAGE_STATE_UNKNOWN
);
252 CCECAdapterMessage
*output
= new CCECAdapterMessage(data
);
254 /* set the number of retries */
255 if (data
.opcode
== CEC_OPCODE_NONE
) //TODO
256 output
->maxTries
= 1;
257 else if (data
.initiator
!= CECDEVICE_BROADCAST
)
258 output
->maxTries
= iMaxTries
;
260 output
->lineTimeout
= iLineTimeout
;
261 output
->retryTimeout
= iRetryLineTimeout
;
265 while (bRetry
&& ++output
->tries
< output
->maxTries
)
267 bRetry
= (!Write(output
) || output
->NeedsRetry()) && output
->transmit_timeout
> 0;
269 Sleep(CEC_DEFAULT_TRANSMIT_RETRY_WAIT
);
271 retVal
= output
->state
;
277 bool CUSBCECAdapterCommunication::Write(CCECAdapterMessage
*data
)
279 data
->state
= ADAPTER_MESSAGE_STATE_WAITING_TO_BE_SENT
;
280 m_outBuffer
.Push(data
);
281 data
->event
.Wait(5000);
283 if ((data
->expectControllerAck
&& data
->state
!= ADAPTER_MESSAGE_STATE_SENT_ACKED
) ||
284 (!data
->expectControllerAck
&& data
->state
!= ADAPTER_MESSAGE_STATE_SENT
))
286 CLibCEC::AddLog(CEC_LOG_DEBUG
, "command was not %s", data
->state
== ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED
? "acked" : "sent");
293 bool CUSBCECAdapterCommunication::Read(cec_command
&command
, uint32_t iTimeout
)
298 CCECAdapterMessage msg
;
299 if (Read(msg
, iTimeout
))
301 if (ParseMessage(msg
))
303 command
= m_currentframe
;
304 m_currentframe
.Clear();
311 bool CUSBCECAdapterCommunication::Read(CCECAdapterMessage
&msg
, uint32_t iTimeout
)
313 CLockObject
lock(m_mutex
);
316 CCECAdapterMessage
*buf(NULL
);
318 if (!m_inBuffer
.Pop(buf
))
320 if (iTimeout
== 0 || !m_rcvCondition
.Wait(m_mutex
, m_bHasData
, iTimeout
))
323 m_bHasData
= m_inBuffer
.Size() > 0;
328 msg
.packet
= buf
->packet
;
329 msg
.state
= ADAPTER_MESSAGE_STATE_INCOMING
;
336 CStdString
CUSBCECAdapterCommunication::GetError(void) const
339 strError
= m_port
->GetError();
343 bool CUSBCECAdapterCommunication::StartBootloader(void)
349 CLibCEC::AddLog(CEC_LOG_DEBUG
, "starting the bootloader");
350 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
352 output
->PushBack(MSGSTART
);
353 output
->PushEscaped(MSGCODE_START_BOOTLOADER
);
354 output
->PushBack(MSGEND
);
355 output
->isTransmission
= false;
356 output
->expectControllerAck
= false;
358 if ((bReturn
= Write(output
)) == false)
359 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not start the bootloader");
365 bool CUSBCECAdapterCommunication::PingAdapter(void)
371 CLibCEC::AddLog(CEC_LOG_DEBUG
, "sending ping");
372 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
374 output
->PushBack(MSGSTART
);
375 output
->PushEscaped(MSGCODE_PING
);
376 output
->PushBack(MSGEND
);
377 output
->isTransmission
= false;
379 if ((bReturn
= Write(output
)) == false)
380 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not ping the adapter");
386 bool CUSBCECAdapterCommunication::ParseMessage(const CCECAdapterMessage
&msg
)
389 bool bIsError(msg
.IsError());
394 CLockObject
adapterLock(m_mutex
);
395 switch(msg
.Message())
397 case MSGCODE_FRAME_START
:
399 m_currentframe
.Clear();
402 m_currentframe
.initiator
= msg
.Initiator();
403 m_currentframe
.destination
= msg
.Destination();
404 m_currentframe
.ack
= msg
.IsACK();
405 m_currentframe
.eom
= msg
.IsEOM();
407 if (m_currentframe
.ack
== 0x1)
409 m_lastInitiator
= m_currentframe
.initiator
;
410 m_processor
->HandlePoll(m_currentframe
.initiator
, m_currentframe
.destination
);
414 case MSGCODE_RECEIVE_FAILED
:
416 m_currentframe
.Clear();
417 if (m_lastInitiator
!= CECDEVICE_UNKNOWN
)
418 bIsError
= m_processor
->HandleReceiveFailed(m_lastInitiator
);
421 case MSGCODE_FRAME_DATA
:
425 m_currentframe
.PushBack(msg
[1]);
426 m_currentframe
.eom
= msg
.IsEOM();
435 CLibCEC::AddLog(bIsError
? CEC_LOG_WARNING
: CEC_LOG_DEBUG
, msg
.ToString());
439 uint16_t CUSBCECAdapterCommunication::GetFirmwareVersion(void)
441 uint16_t iReturn(m_iFirmwareVersion
);
445 if (iReturn
== CEC_FW_VERSION_UNKNOWN
)
447 CLockObject
lock(m_mutex
);
448 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting the firmware version");
449 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
451 output
->PushBack(MSGSTART
);
452 output
->PushEscaped(MSGCODE_FIRMWARE_VERSION
);
453 output
->PushBack(MSGEND
);
454 output
->isTransmission
= false;
455 output
->expectControllerAck
= false;
457 SendMessageToAdapter(output
);
458 bool bWriteOk
= output
->state
== ADAPTER_MESSAGE_STATE_SENT
;
462 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not request the firmware version");
466 Sleep(250); // TODO ReadFromDevice() isn't waiting for the timeout to pass on win32
467 ReadFromDevice(CEC_DEFAULT_TRANSMIT_WAIT
, 5 /* start + msgcode + 2 bytes for fw version + end */);
468 CCECAdapterMessage input
;
471 if (input
.Message() != MSGCODE_FIRMWARE_VERSION
|| input
.Size() != 3)
472 CLibCEC::AddLog(CEC_LOG_ERROR
, "invalid firmware version (size = %d, message = %d)", input
.Size(), input
.Message());
475 m_iFirmwareVersion
= (input
[1] << 8 | input
[2]);
476 iReturn
= m_iFirmwareVersion
;
481 CLibCEC::AddLog(CEC_LOG_ERROR
, "no firmware version received");
488 bool CUSBCECAdapterCommunication::SetLineTimeout(uint8_t iTimeout
)
490 m_iLineTimeout
= iTimeout
;
493 // bool bReturn(m_iLineTimeout != iTimeout);
497 // CCECAdapterMessage *output = new CCECAdapterMessage;
499 // output->PushBack(MSGSTART);
500 // output->PushEscaped(MSGCODE_TRANSMIT_IDLETIME);
501 // output->PushEscaped(iTimeout);
502 // output->PushBack(MSGEND);
503 // output->isTransmission = false;
505 // if ((bReturn = Write(output)) == false)
506 // CLibCEC::AddLog(CEC_LOG_ERROR, "could not set the idletime");
513 bool CUSBCECAdapterCommunication::SetAckMask(uint16_t iMask
)
515 return SetAckMaskInternal(iMask
, false);
518 bool CUSBCECAdapterCommunication::SetAckMaskInternal(uint16_t iMask
, bool bWriteDirectly
/* = false */)
521 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting ackmask to %2x", iMask
);
523 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
525 output
->PushBack(MSGSTART
);
526 output
->PushEscaped(MSGCODE_SET_ACK_MASK
);
527 output
->PushEscaped(iMask
>> 8);
528 output
->PushEscaped((uint8_t)iMask
);
529 output
->PushBack(MSGEND
);
530 output
->isTransmission
= false;
533 SendMessageToAdapter(output
);
534 else if ((bReturn
= Write(output
)) == false)
535 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not set the ackmask");
542 bool CUSBCECAdapterCommunication::SetControlledMode(bool controlled
)
545 CLibCEC::AddLog(CEC_LOG_DEBUG
, "turning controlled mode %s", controlled
? "on" : "off");
547 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
549 output
->PushBack(MSGSTART
);
550 output
->PushEscaped(MSGCODE_SET_CONTROLLED
);
551 output
->PushEscaped(controlled
);
552 output
->PushBack(MSGEND
);
553 output
->isTransmission
= false;
555 if ((bReturn
= Write(output
)) == false)
556 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not set controlled mode");
562 bool CUSBCECAdapterCommunication::IsOpen(void)
564 return !IsStopped() && m_port
->IsOpen() && IsRunning();
567 bool CUSBCECAdapterCommunication::WaitForAck(CCECAdapterMessage
&message
)
570 bool bTransmitSucceeded(false);
571 uint8_t iPacketsLeft(message
.Size() / 4);
573 int64_t iNow
= GetTimeMs();
574 int64_t iTargetTime
= iNow
+ (message
.transmit_timeout
<= 5 ? CEC_DEFAULT_TRANSMIT_WAIT
: message
.transmit_timeout
);
576 while (!bTransmitSucceeded
&& !bError
&& iNow
< iTargetTime
)
579 CCECAdapterMessage msg
;
586 if (msg
.Message() == MSGCODE_FRAME_START
&& msg
.IsACK())
588 m_processor
->HandlePoll(msg
.Initiator(), msg
.Destination());
589 m_lastInitiator
= msg
.Initiator();
594 if (msg
.Message() == MSGCODE_RECEIVE_FAILED
&&
595 m_lastInitiator
!= CECDEVICE_UNKNOWN
&&
596 m_processor
->HandleReceiveFailed(m_lastInitiator
))
602 bError
= msg
.IsError();
605 message
.reply
= msg
.Message();
606 CLibCEC::AddLog(CEC_LOG_DEBUG
, msg
.ToString());
610 switch(msg
.Message())
612 case MSGCODE_COMMAND_ACCEPTED
:
613 CLibCEC::AddLog(CEC_LOG_DEBUG
, msg
.ToString());
614 if (iPacketsLeft
> 0)
616 if (!message
.isTransmission
&& iPacketsLeft
== 0)
617 bTransmitSucceeded
= true;
619 case MSGCODE_TRANSMIT_SUCCEEDED
:
620 CLibCEC::AddLog(CEC_LOG_DEBUG
, msg
.ToString());
621 bTransmitSucceeded
= (iPacketsLeft
== 0);
622 bError
= !bTransmitSucceeded
;
623 message
.reply
= MSGCODE_TRANSMIT_SUCCEEDED
;
626 // ignore other data while waiting
634 message
.state
= bTransmitSucceeded
&& !bError
?
635 ADAPTER_MESSAGE_STATE_SENT_ACKED
:
636 ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED
;
638 return bTransmitSucceeded
&& !bError
;
641 void CUSBCECAdapterCommunication::AddData(uint8_t *data
, size_t iLen
)
643 CLockObject
lock(m_mutex
);
644 for (size_t iPtr
= 0; iPtr
< iLen
; iPtr
++)
648 if (data
[iPtr
] == MSGSTART
)
651 else if (data
[iPtr
] == MSGSTART
) //we found a msgstart before msgend, this is not right, remove
653 if (m_currentAdapterMessage
.Size() > 0)
654 CLibCEC::AddLog(CEC_LOG_WARNING
, "received MSGSTART before MSGEND, removing previous buffer contents");
655 m_currentAdapterMessage
.Clear();
658 else if (data
[iPtr
] == MSGEND
)
660 CCECAdapterMessage
*newMessage
= new CCECAdapterMessage
;
661 newMessage
->packet
= m_currentAdapterMessage
.packet
;
662 m_inBuffer
.Push(newMessage
);
663 m_currentAdapterMessage
.Clear();
665 m_bNextIsEscaped
= false;
667 m_rcvCondition
.Broadcast();
669 else if (m_bNextIsEscaped
)
671 m_currentAdapterMessage
.PushBack(data
[iPtr
] + (uint8_t)ESCOFFSET
);
672 m_bNextIsEscaped
= false;
674 else if (data
[iPtr
] == MSGESC
)
676 m_bNextIsEscaped
= true;
680 m_currentAdapterMessage
.PushBack(data
[iPtr
]);
685 bool CUSBCECAdapterCommunication::ReadFromDevice(uint32_t iTimeout
, size_t iSize
/* = 256 */)
694 CLockObject
lock(m_mutex
);
695 iBytesRead
= m_port
->Read(buff
, sizeof(uint8_t) * iSize
, iTimeout
);
696 if (iBytesRead
< 0 || iBytesRead
> 256)
698 CLibCEC::AddLog(CEC_LOG_ERROR
, "error reading from serial port: %s", m_port
->GetError().c_str());
702 else if (iBytesRead
> 0)
704 AddData(buff
, iBytesRead
);
707 return iBytesRead
> 0;
710 void CUSBCECAdapterCommunication::SendMessageToAdapter(CCECAdapterMessage
*msg
)
712 CLockObject
adapterLock(m_mutex
);
713 if (!m_port
->IsOpen())
715 CLibCEC::AddLog(CEC_LOG_ERROR
, "error writing to serial port: the connection is closed");
716 msg
->state
= ADAPTER_MESSAGE_STATE_ERROR
;
721 SetLineTimeout(msg
->lineTimeout
);
723 SetLineTimeout(msg
->retryTimeout
);
725 if (m_port
->Write(msg
->packet
.data
, msg
->Size()) != (ssize_t
) msg
->Size())
727 CLibCEC::AddLog(CEC_LOG_ERROR
, "error writing to serial port: %s", m_port
->GetError().c_str());
728 msg
->state
= ADAPTER_MESSAGE_STATE_ERROR
;
732 CLibCEC::AddLog(CEC_LOG_DEBUG
, "command sent");
733 msg
->state
= ADAPTER_MESSAGE_STATE_SENT
;
735 if (msg
->expectControllerAck
)
737 if (!WaitForAck(*msg
))
738 CLibCEC::AddLog(CEC_LOG_DEBUG
, "did not receive ack");
744 void CUSBCECAdapterCommunication::WriteNextCommand(void)
746 CCECAdapterMessage
*msg(NULL
);
747 if (m_outBuffer
.Pop(msg
))
748 SendMessageToAdapter(msg
);
751 CStdString
CUSBCECAdapterCommunication::GetPortName(void)
754 strName
= m_port
->GetName();