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
)
102 CLibCEC::AddLog(CEC_LOG_ERROR
, "the adapter did not respond with a correct firmware version (try %d)", ++iFwVersionTry
);
107 if (m_iFirmwareVersion
>= 2)
109 /* try to set controlled mode */
110 unsigned iControlledTry(0);
111 bool bControlled(false);
112 while (iNow
< iTarget
&& (bControlled
= SetControlledMode(true)) == false)
114 CLibCEC::AddLog(CEC_LOG_ERROR
, "the adapter did not respond correctly to setting controlled mode (try %d)", ++iControlledTry
);
118 bReturn
= bControlled
;
124 CLockObject
lock(m_mutex
);
125 m_bInitialised
= bReturn
;
131 bool CUSBCECAdapterCommunication::Open(IAdapterCommunicationCallback
*cb
, uint32_t iTimeoutMs
/* = 10000 */, bool bSkipChecks
/* = false */)
133 uint64_t iNow
= GetTimeMs();
134 uint64_t iTimeout
= iNow
+ iTimeoutMs
;
137 CLockObject
lock(m_mutex
);
141 CLibCEC::AddLog(CEC_LOG_ERROR
, "port is NULL");
147 CLibCEC::AddLog(CEC_LOG_ERROR
, "port is already open");
153 bool bConnected(false);
154 while (!bConnected
&& iNow
< iTimeout
)
156 if ((bConnected
= m_port
->Open(iTimeout
)) == false)
158 strError
.Format("error opening serial port '%s': %s", m_port
->GetName().c_str(), m_port
->GetError().c_str());
166 CLibCEC::AddLog(CEC_LOG_ERROR
, strError
);
170 CLibCEC::AddLog(CEC_LOG_DEBUG
, "connection opened, clearing any previous input and waiting for active transmissions to end before starting");
174 //clear any input bytes
176 while (m_port
->Read(buff
, 1024, 100) > 0)
178 CLibCEC::AddLog(CEC_LOG_DEBUG
, "data received, clearing it");
184 if (!bSkipChecks
&& !CheckAdapter())
186 CLibCEC::AddLog(CEC_LOG_ERROR
, "the adapter failed to pass basic checks");
193 CLibCEC::AddLog(CEC_LOG_DEBUG
, "communication thread started");
198 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not create a communication thread");
205 void CUSBCECAdapterCommunication::Close(void)
210 void *CUSBCECAdapterCommunication::Process(void)
212 m_messageProcessor
= new CUSBCECAdapterProcessor(m_callback
);
213 m_messageProcessor
->CreateThread();
217 bool bCommandReceived(false);
221 CLockObject
lock(m_mutex
);
223 bCommandReceived
= m_callback
&& Read(command
, 0) && m_bInitialised
;
226 /* push the next command to the callback method if there is one */
227 if (!IsStopped() && bCommandReceived
)
228 m_messageProcessor
->AddCommand(command
);
237 /* stop the message processor */
238 m_messageProcessor
->StopThread();
239 delete m_messageProcessor
;
241 /* notify all threads that are waiting on messages to be sent */
242 CCECAdapterMessage
*msg(NULL
);
243 while (m_outBuffer
.Pop(msg
))
244 msg
->event
.Broadcast();
246 /* set the ackmask to 0 before closing the connection */
247 SetAckMaskInternal(0, true);
258 cec_adapter_message_state
CUSBCECAdapterCommunication::Write(const cec_command
&data
, uint8_t iMaxTries
, uint8_t iLineTimeout
/* = 3 */, uint8_t iRetryLineTimeout
/* = 3 */)
260 cec_adapter_message_state
retVal(ADAPTER_MESSAGE_STATE_UNKNOWN
);
264 CCECAdapterMessage
*output
= new CCECAdapterMessage(data
);
266 /* set the number of retries */
267 if (data
.opcode
== CEC_OPCODE_NONE
) //TODO
268 output
->maxTries
= 1;
269 else if (data
.initiator
!= CECDEVICE_BROADCAST
)
270 output
->maxTries
= iMaxTries
;
272 output
->lineTimeout
= iLineTimeout
;
273 output
->retryTimeout
= iRetryLineTimeout
;
277 while (bRetry
&& ++output
->tries
< output
->maxTries
)
279 bRetry
= (!Write(output
) || output
->NeedsRetry()) && output
->transmit_timeout
> 0;
281 Sleep(CEC_DEFAULT_TRANSMIT_RETRY_WAIT
);
283 retVal
= output
->state
;
289 bool CUSBCECAdapterCommunication::Write(CCECAdapterMessage
*data
)
291 data
->state
= ADAPTER_MESSAGE_STATE_WAITING_TO_BE_SENT
;
292 m_outBuffer
.Push(data
);
293 data
->event
.Wait(5000);
295 if ((data
->expectControllerAck
&& data
->state
!= ADAPTER_MESSAGE_STATE_SENT_ACKED
) ||
296 (!data
->expectControllerAck
&& data
->state
!= ADAPTER_MESSAGE_STATE_SENT
))
298 CLibCEC::AddLog(CEC_LOG_DEBUG
, "command was not %s", data
->state
== ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED
? "acked" : "sent");
305 bool CUSBCECAdapterCommunication::Read(cec_command
&command
, uint32_t iTimeout
)
310 CCECAdapterMessage msg
;
311 if (Read(msg
, iTimeout
))
313 if (ParseMessage(msg
))
315 command
= m_currentframe
;
316 m_currentframe
.Clear();
323 bool CUSBCECAdapterCommunication::Read(CCECAdapterMessage
&msg
, uint32_t iTimeout
)
325 CLockObject
lock(m_mutex
);
328 CCECAdapterMessage
*buf(NULL
);
330 if (!m_inBuffer
.Pop(buf
))
332 if (iTimeout
== 0 || !m_rcvCondition
.Wait(m_mutex
, m_bHasData
, iTimeout
))
335 m_bHasData
= !m_inBuffer
.IsEmpty();
340 msg
.packet
= buf
->packet
;
341 msg
.state
= ADAPTER_MESSAGE_STATE_INCOMING
;
348 CStdString
CUSBCECAdapterCommunication::GetError(void) const
351 strError
= m_port
->GetError();
355 bool CUSBCECAdapterCommunication::StartBootloader(void)
361 CLibCEC::AddLog(CEC_LOG_DEBUG
, "starting the bootloader");
362 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
364 output
->PushBack(MSGSTART
);
365 output
->PushEscaped(MSGCODE_START_BOOTLOADER
);
366 output
->PushBack(MSGEND
);
367 output
->isTransmission
= false;
368 output
->expectControllerAck
= false;
370 if ((bReturn
= Write(output
)) == false)
371 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not start the bootloader");
377 bool CUSBCECAdapterCommunication::PingAdapter(void)
379 CLockObject
lock(m_mutex
);
380 CLibCEC::AddLog(CEC_LOG_DEBUG
, "sending ping");
382 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
384 output
->PushBack(MSGSTART
);
385 output
->PushEscaped(MSGCODE_PING
);
386 output
->PushBack(MSGEND
);
387 output
->isTransmission
= false;
389 SendMessageToAdapter(output
);
390 bool bWriteOk
= output
->state
== ADAPTER_MESSAGE_STATE_SENT_ACKED
;
394 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not ping the adapter");
401 bool CUSBCECAdapterCommunication::ParseMessage(const CCECAdapterMessage
&msg
)
404 bool bIsError(msg
.IsError());
409 CLockObject
adapterLock(m_mutex
);
410 switch(msg
.Message())
412 case MSGCODE_FRAME_START
:
414 m_currentframe
.Clear();
417 m_currentframe
.initiator
= msg
.Initiator();
418 m_currentframe
.destination
= msg
.Destination();
419 m_currentframe
.ack
= msg
.IsACK();
420 m_currentframe
.eom
= msg
.IsEOM();
422 if (m_currentframe
.ack
== 0x1)
424 m_lastInitiator
= m_currentframe
.initiator
;
425 m_processor
->HandlePoll(m_currentframe
.initiator
, m_currentframe
.destination
);
429 case MSGCODE_RECEIVE_FAILED
:
431 m_currentframe
.Clear();
432 if (m_lastInitiator
!= CECDEVICE_UNKNOWN
)
433 bIsError
= m_processor
->HandleReceiveFailed(m_lastInitiator
);
436 case MSGCODE_FRAME_DATA
:
440 m_currentframe
.PushBack(msg
[1]);
441 m_currentframe
.eom
= msg
.IsEOM();
449 CLibCEC::AddLog(bIsError
? CEC_LOG_WARNING
: CEC_LOG_DEBUG
, msg
.ToString());
453 uint16_t CUSBCECAdapterCommunication::GetFirmwareVersion(void)
455 uint16_t iReturn(m_iFirmwareVersion
);
457 if (iReturn
== CEC_FW_VERSION_UNKNOWN
)
459 CLockObject
lock(m_mutex
);
460 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting the firmware version");
461 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
463 output
->PushBack(MSGSTART
);
464 output
->PushEscaped(MSGCODE_FIRMWARE_VERSION
);
465 output
->PushBack(MSGEND
);
466 output
->isTransmission
= false;
467 output
->expectControllerAck
= false;
469 SendMessageToAdapter(output
);
470 bool bWriteOk
= output
->state
== ADAPTER_MESSAGE_STATE_SENT
;
474 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not request the firmware version");
478 Sleep(250); // TODO ReadFromDevice() isn't waiting for the timeout to pass on win32
479 ReadFromDevice(CEC_DEFAULT_TRANSMIT_WAIT
, 5 /* start + msgcode + 2 bytes for fw version + end */);
480 CCECAdapterMessage input
;
483 if (input
.Message() != MSGCODE_FIRMWARE_VERSION
|| input
.Size() != 3)
484 CLibCEC::AddLog(CEC_LOG_ERROR
, "invalid firmware version (size = %d, message = %d)", input
.Size(), input
.Message());
487 m_iFirmwareVersion
= (input
[1] << 8 | input
[2]);
488 iReturn
= m_iFirmwareVersion
;
493 CLibCEC::AddLog(CEC_LOG_ERROR
, "no firmware version received");
500 bool CUSBCECAdapterCommunication::SetLineTimeout(uint8_t iTimeout
)
502 m_iLineTimeout
= iTimeout
;
505 // bool bReturn(m_iLineTimeout != iTimeout);
509 // CCECAdapterMessage *output = new CCECAdapterMessage;
511 // output->PushBack(MSGSTART);
512 // output->PushEscaped(MSGCODE_TRANSMIT_IDLETIME);
513 // output->PushEscaped(iTimeout);
514 // output->PushBack(MSGEND);
515 // output->isTransmission = false;
517 // if ((bReturn = Write(output)) == false)
518 // CLibCEC::AddLog(CEC_LOG_ERROR, "could not set the idletime");
525 bool CUSBCECAdapterCommunication::SetAckMask(uint16_t iMask
)
527 return SetAckMaskInternal(iMask
, false);
530 bool CUSBCECAdapterCommunication::SetAckMaskInternal(uint16_t iMask
, bool bWriteDirectly
/* = false */)
533 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting ackmask to %2x", iMask
);
535 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
537 output
->PushBack(MSGSTART
);
538 output
->PushEscaped(MSGCODE_SET_ACK_MASK
);
539 output
->PushEscaped(iMask
>> 8);
540 output
->PushEscaped((uint8_t)iMask
);
541 output
->PushBack(MSGEND
);
542 output
->isTransmission
= false;
545 SendMessageToAdapter(output
);
546 else if ((bReturn
= Write(output
)) == false)
547 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not set the ackmask");
554 bool CUSBCECAdapterCommunication::SetControlledMode(bool controlled
)
556 CLockObject
lock(m_mutex
);
557 CLibCEC::AddLog(CEC_LOG_DEBUG
, "turning controlled mode %s", controlled
? "on" : "off");
559 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
561 output
->PushBack(MSGSTART
);
562 output
->PushEscaped(MSGCODE_SET_CONTROLLED
);
563 output
->PushEscaped(controlled
);
564 output
->PushBack(MSGEND
);
565 output
->isTransmission
= false;
567 SendMessageToAdapter(output
);
568 bool bWriteOk
= output
->state
== ADAPTER_MESSAGE_STATE_SENT
;
572 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not set controlled mode");
579 bool CUSBCECAdapterCommunication::IsOpen(void)
581 return !IsStopped() && m_port
->IsOpen() && IsRunning();
584 bool CUSBCECAdapterCommunication::WaitForAck(CCECAdapterMessage
&message
)
587 bool bTransmitSucceeded(false);
588 uint8_t iPacketsLeft(message
.Size() / 4);
590 int64_t iNow
= GetTimeMs();
591 int64_t iTargetTime
= iNow
+ (message
.transmit_timeout
<= 5 ? CEC_DEFAULT_TRANSMIT_WAIT
: message
.transmit_timeout
);
593 while (!bTransmitSucceeded
&& !bError
&& iNow
< iTargetTime
)
596 CCECAdapterMessage msg
;
603 if (msg
.Message() == MSGCODE_FRAME_START
&& msg
.IsACK())
605 m_processor
->HandlePoll(msg
.Initiator(), msg
.Destination());
606 m_lastInitiator
= msg
.Initiator();
611 if (msg
.Message() == MSGCODE_RECEIVE_FAILED
&&
612 m_lastInitiator
!= CECDEVICE_UNKNOWN
&&
613 m_processor
->HandleReceiveFailed(m_lastInitiator
))
619 bError
= msg
.IsError();
622 message
.reply
= msg
.Message();
623 CLibCEC::AddLog(CEC_LOG_DEBUG
, msg
.ToString());
627 switch(msg
.Message())
629 case MSGCODE_COMMAND_ACCEPTED
:
630 if (iPacketsLeft
> 0)
632 if (!message
.isTransmission
&& iPacketsLeft
== 0)
633 bTransmitSucceeded
= true;
634 CLibCEC::AddLog(CEC_LOG_DEBUG
, "%s - waiting for %d more", msg
.ToString().c_str(), iPacketsLeft
);
636 case MSGCODE_TRANSMIT_SUCCEEDED
:
637 CLibCEC::AddLog(CEC_LOG_DEBUG
, msg
.ToString());
638 bTransmitSucceeded
= (iPacketsLeft
== 0);
639 bError
= !bTransmitSucceeded
;
640 message
.reply
= MSGCODE_TRANSMIT_SUCCEEDED
;
643 // ignore other data while waiting
651 message
.state
= bTransmitSucceeded
&& !bError
?
652 ADAPTER_MESSAGE_STATE_SENT_ACKED
:
653 ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED
;
655 return bTransmitSucceeded
&& !bError
;
658 void CUSBCECAdapterCommunication::AddData(uint8_t *data
, size_t iLen
)
660 CLockObject
lock(m_mutex
);
661 for (size_t iPtr
= 0; iPtr
< iLen
; iPtr
++)
665 if (data
[iPtr
] == MSGSTART
)
668 else if (data
[iPtr
] == MSGSTART
) //we found a msgstart before msgend, this is not right, remove
670 if (m_currentAdapterMessage
.Size() > 0)
671 CLibCEC::AddLog(CEC_LOG_WARNING
, "received MSGSTART before MSGEND, removing previous buffer contents");
672 m_currentAdapterMessage
.Clear();
675 else if (data
[iPtr
] == MSGEND
)
677 CCECAdapterMessage
*newMessage
= new CCECAdapterMessage
;
678 newMessage
->packet
= m_currentAdapterMessage
.packet
;
679 m_inBuffer
.Push(newMessage
);
680 m_currentAdapterMessage
.Clear();
682 m_bNextIsEscaped
= false;
684 m_rcvCondition
.Broadcast();
686 else if (m_bNextIsEscaped
)
688 m_currentAdapterMessage
.PushBack(data
[iPtr
] + (uint8_t)ESCOFFSET
);
689 m_bNextIsEscaped
= false;
691 else if (data
[iPtr
] == MSGESC
)
693 m_bNextIsEscaped
= true;
697 m_currentAdapterMessage
.PushBack(data
[iPtr
]);
702 bool CUSBCECAdapterCommunication::ReadFromDevice(uint32_t iTimeout
, size_t iSize
/* = 256 */)
711 CLockObject
lock(m_mutex
);
712 iBytesRead
= m_port
->Read(buff
, sizeof(uint8_t) * iSize
, iTimeout
);
713 if (iBytesRead
< 0 || iBytesRead
> 256)
715 CLibCEC::AddLog(CEC_LOG_ERROR
, "error reading from serial port: %s", m_port
->GetError().c_str());
719 else if (iBytesRead
> 0)
721 AddData(buff
, iBytesRead
);
724 return iBytesRead
> 0;
727 void CUSBCECAdapterCommunication::SendMessageToAdapter(CCECAdapterMessage
*msg
)
729 CLockObject
adapterLock(m_mutex
);
730 if (!m_port
->IsOpen())
732 CLibCEC::AddLog(CEC_LOG_ERROR
, "error writing to serial port: the connection is closed");
733 msg
->state
= ADAPTER_MESSAGE_STATE_ERROR
;
738 SetLineTimeout(msg
->lineTimeout
);
740 SetLineTimeout(msg
->retryTimeout
);
742 if (m_port
->Write(msg
->packet
.data
, msg
->Size()) != (ssize_t
) msg
->Size())
744 CLibCEC::AddLog(CEC_LOG_ERROR
, "error writing to serial port: %s", m_port
->GetError().c_str());
745 msg
->state
= ADAPTER_MESSAGE_STATE_ERROR
;
749 CLibCEC::AddLog(CEC_LOG_DEBUG
, "command sent");
750 msg
->state
= ADAPTER_MESSAGE_STATE_SENT
;
752 if (msg
->expectControllerAck
)
754 if (!WaitForAck(*msg
))
755 CLibCEC::AddLog(CEC_LOG_DEBUG
, "did not receive ack");
761 void CUSBCECAdapterCommunication::WriteNextCommand(void)
763 CCECAdapterMessage
*msg(NULL
);
764 if (m_outBuffer
.Pop(msg
))
765 SendMessageToAdapter(msg
);
768 CStdString
CUSBCECAdapterCommunication::GetPortName(void)
771 strName
= m_port
->GetName();