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");
186 if (!bSkipChecks
&& !CheckAdapter())
189 CLibCEC::AddLog(CEC_LOG_ERROR
, "the adapter failed to pass basic checks");
194 CLibCEC::AddLog(CEC_LOG_DEBUG
, "communication thread started");
198 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not create a communication thread");
203 void CUSBCECAdapterCommunication::Close(void)
208 void *CUSBCECAdapterCommunication::Process(void)
210 m_messageProcessor
= new CUSBCECAdapterProcessor(m_callback
);
211 m_messageProcessor
->CreateThread();
215 bool bCommandReceived(false);
219 CLockObject
lock(m_mutex
);
221 bCommandReceived
= m_callback
&& Read(command
, 0) && m_bInitialised
;
224 /* push the next command to the callback method if there is one */
225 if (!IsStopped() && bCommandReceived
)
226 m_messageProcessor
->AddCommand(command
);
235 /* stop the message processor */
236 m_messageProcessor
->StopThread();
237 delete m_messageProcessor
;
239 /* notify all threads that are waiting on messages to be sent */
240 CCECAdapterMessage
*msg(NULL
);
241 while (m_outBuffer
.Pop(msg
))
242 msg
->event
.Broadcast();
244 /* set the ackmask to 0 before closing the connection */
245 SetAckMaskInternal(0, true);
256 cec_adapter_message_state
CUSBCECAdapterCommunication::Write(const cec_command
&data
, uint8_t iMaxTries
, uint8_t iLineTimeout
/* = 3 */, uint8_t iRetryLineTimeout
/* = 3 */)
258 cec_adapter_message_state
retVal(ADAPTER_MESSAGE_STATE_UNKNOWN
);
262 CCECAdapterMessage
*output
= new CCECAdapterMessage(data
);
264 /* set the number of retries */
265 if (data
.opcode
== CEC_OPCODE_NONE
) //TODO
266 output
->maxTries
= 1;
267 else if (data
.initiator
!= CECDEVICE_BROADCAST
)
268 output
->maxTries
= iMaxTries
;
270 output
->lineTimeout
= iLineTimeout
;
271 output
->retryTimeout
= iRetryLineTimeout
;
275 while (bRetry
&& ++output
->tries
< output
->maxTries
)
277 bRetry
= (!Write(output
) || output
->NeedsRetry()) && output
->transmit_timeout
> 0;
279 Sleep(CEC_DEFAULT_TRANSMIT_RETRY_WAIT
);
281 retVal
= output
->state
;
287 bool CUSBCECAdapterCommunication::Write(CCECAdapterMessage
*data
)
289 data
->state
= ADAPTER_MESSAGE_STATE_WAITING_TO_BE_SENT
;
290 m_outBuffer
.Push(data
);
291 data
->event
.Wait(5000);
293 if ((data
->expectControllerAck
&& data
->state
!= ADAPTER_MESSAGE_STATE_SENT_ACKED
) ||
294 (!data
->expectControllerAck
&& data
->state
!= ADAPTER_MESSAGE_STATE_SENT
))
296 CLibCEC::AddLog(CEC_LOG_DEBUG
, "command was not %s", data
->state
== ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED
? "acked" : "sent");
303 bool CUSBCECAdapterCommunication::Read(cec_command
&command
, uint32_t iTimeout
)
308 CCECAdapterMessage msg
;
309 if (Read(msg
, iTimeout
))
311 if (ParseMessage(msg
))
313 command
= m_currentframe
;
314 m_currentframe
.Clear();
321 bool CUSBCECAdapterCommunication::Read(CCECAdapterMessage
&msg
, uint32_t iTimeout
)
323 CLockObject
lock(m_mutex
);
326 CCECAdapterMessage
*buf(NULL
);
328 if (!m_inBuffer
.Pop(buf
))
330 if (iTimeout
== 0 || !m_rcvCondition
.Wait(m_mutex
, m_bHasData
, iTimeout
))
333 m_bHasData
= !m_inBuffer
.IsEmpty();
338 msg
.packet
= buf
->packet
;
339 msg
.state
= ADAPTER_MESSAGE_STATE_INCOMING
;
346 CStdString
CUSBCECAdapterCommunication::GetError(void) const
349 strError
= m_port
->GetError();
353 bool CUSBCECAdapterCommunication::StartBootloader(void)
359 CLibCEC::AddLog(CEC_LOG_DEBUG
, "starting the bootloader");
360 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
362 output
->PushBack(MSGSTART
);
363 output
->PushEscaped(MSGCODE_START_BOOTLOADER
);
364 output
->PushBack(MSGEND
);
365 output
->isTransmission
= false;
366 output
->expectControllerAck
= false;
368 if ((bReturn
= Write(output
)) == false)
369 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not start the bootloader");
375 bool CUSBCECAdapterCommunication::PingAdapter(void)
381 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 if ((bReturn
= Write(output
)) == false)
390 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not ping the adapter");
396 bool CUSBCECAdapterCommunication::ParseMessage(const CCECAdapterMessage
&msg
)
399 bool bIsError(msg
.IsError());
404 CLockObject
adapterLock(m_mutex
);
405 switch(msg
.Message())
407 case MSGCODE_FRAME_START
:
409 m_currentframe
.Clear();
412 m_currentframe
.initiator
= msg
.Initiator();
413 m_currentframe
.destination
= msg
.Destination();
414 m_currentframe
.ack
= msg
.IsACK();
415 m_currentframe
.eom
= msg
.IsEOM();
417 if (m_currentframe
.ack
== 0x1)
419 m_lastInitiator
= m_currentframe
.initiator
;
420 m_processor
->HandlePoll(m_currentframe
.initiator
, m_currentframe
.destination
);
424 case MSGCODE_RECEIVE_FAILED
:
426 m_currentframe
.Clear();
427 if (m_lastInitiator
!= CECDEVICE_UNKNOWN
)
428 bIsError
= m_processor
->HandleReceiveFailed(m_lastInitiator
);
431 case MSGCODE_FRAME_DATA
:
435 m_currentframe
.PushBack(msg
[1]);
436 m_currentframe
.eom
= msg
.IsEOM();
444 CLibCEC::AddLog(bIsError
? CEC_LOG_WARNING
: CEC_LOG_DEBUG
, msg
.ToString());
448 uint16_t CUSBCECAdapterCommunication::GetFirmwareVersion(void)
450 uint16_t iReturn(m_iFirmwareVersion
);
454 if (iReturn
== CEC_FW_VERSION_UNKNOWN
)
456 CLockObject
lock(m_mutex
);
457 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting the firmware version");
458 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
460 output
->PushBack(MSGSTART
);
461 output
->PushEscaped(MSGCODE_FIRMWARE_VERSION
);
462 output
->PushBack(MSGEND
);
463 output
->isTransmission
= false;
464 output
->expectControllerAck
= false;
466 SendMessageToAdapter(output
);
467 bool bWriteOk
= output
->state
== ADAPTER_MESSAGE_STATE_SENT
;
471 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not request the firmware version");
475 Sleep(250); // TODO ReadFromDevice() isn't waiting for the timeout to pass on win32
476 ReadFromDevice(CEC_DEFAULT_TRANSMIT_WAIT
, 5 /* start + msgcode + 2 bytes for fw version + end */);
477 CCECAdapterMessage input
;
480 if (input
.Message() != MSGCODE_FIRMWARE_VERSION
|| input
.Size() != 3)
481 CLibCEC::AddLog(CEC_LOG_ERROR
, "invalid firmware version (size = %d, message = %d)", input
.Size(), input
.Message());
484 m_iFirmwareVersion
= (input
[1] << 8 | input
[2]);
485 iReturn
= m_iFirmwareVersion
;
490 CLibCEC::AddLog(CEC_LOG_ERROR
, "no firmware version received");
497 bool CUSBCECAdapterCommunication::SetLineTimeout(uint8_t iTimeout
)
499 m_iLineTimeout
= iTimeout
;
502 // bool bReturn(m_iLineTimeout != iTimeout);
506 // CCECAdapterMessage *output = new CCECAdapterMessage;
508 // output->PushBack(MSGSTART);
509 // output->PushEscaped(MSGCODE_TRANSMIT_IDLETIME);
510 // output->PushEscaped(iTimeout);
511 // output->PushBack(MSGEND);
512 // output->isTransmission = false;
514 // if ((bReturn = Write(output)) == false)
515 // CLibCEC::AddLog(CEC_LOG_ERROR, "could not set the idletime");
522 bool CUSBCECAdapterCommunication::SetAckMask(uint16_t iMask
)
524 return SetAckMaskInternal(iMask
, false);
527 bool CUSBCECAdapterCommunication::SetAckMaskInternal(uint16_t iMask
, bool bWriteDirectly
/* = false */)
530 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting ackmask to %2x", iMask
);
532 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
534 output
->PushBack(MSGSTART
);
535 output
->PushEscaped(MSGCODE_SET_ACK_MASK
);
536 output
->PushEscaped(iMask
>> 8);
537 output
->PushEscaped((uint8_t)iMask
);
538 output
->PushBack(MSGEND
);
539 output
->isTransmission
= false;
542 SendMessageToAdapter(output
);
543 else if ((bReturn
= Write(output
)) == false)
544 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not set the ackmask");
551 bool CUSBCECAdapterCommunication::SetControlledMode(bool controlled
)
554 CLibCEC::AddLog(CEC_LOG_DEBUG
, "turning controlled mode %s", controlled
? "on" : "off");
556 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
558 output
->PushBack(MSGSTART
);
559 output
->PushEscaped(MSGCODE_SET_CONTROLLED
);
560 output
->PushEscaped(controlled
);
561 output
->PushBack(MSGEND
);
562 output
->isTransmission
= false;
564 if ((bReturn
= Write(output
)) == false)
565 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not set controlled mode");
571 bool CUSBCECAdapterCommunication::IsOpen(void)
573 return !IsStopped() && m_port
->IsOpen() && IsRunning();
576 bool CUSBCECAdapterCommunication::WaitForAck(CCECAdapterMessage
&message
)
579 bool bTransmitSucceeded(false);
580 uint8_t iPacketsLeft(message
.Size() / 4);
582 int64_t iNow
= GetTimeMs();
583 int64_t iTargetTime
= iNow
+ (message
.transmit_timeout
<= 5 ? CEC_DEFAULT_TRANSMIT_WAIT
: message
.transmit_timeout
);
585 while (!bTransmitSucceeded
&& !bError
&& iNow
< iTargetTime
)
588 CCECAdapterMessage msg
;
595 if (msg
.Message() == MSGCODE_FRAME_START
&& msg
.IsACK())
597 m_processor
->HandlePoll(msg
.Initiator(), msg
.Destination());
598 m_lastInitiator
= msg
.Initiator();
603 if (msg
.Message() == MSGCODE_RECEIVE_FAILED
&&
604 m_lastInitiator
!= CECDEVICE_UNKNOWN
&&
605 m_processor
->HandleReceiveFailed(m_lastInitiator
))
611 bError
= msg
.IsError();
614 message
.reply
= msg
.Message();
615 CLibCEC::AddLog(CEC_LOG_DEBUG
, msg
.ToString());
619 switch(msg
.Message())
621 case MSGCODE_COMMAND_ACCEPTED
:
622 CLibCEC::AddLog(CEC_LOG_DEBUG
, msg
.ToString());
623 if (iPacketsLeft
> 0)
625 if (!message
.isTransmission
&& iPacketsLeft
== 0)
626 bTransmitSucceeded
= true;
628 case MSGCODE_TRANSMIT_SUCCEEDED
:
629 CLibCEC::AddLog(CEC_LOG_DEBUG
, msg
.ToString());
630 bTransmitSucceeded
= (iPacketsLeft
== 0);
631 bError
= !bTransmitSucceeded
;
632 message
.reply
= MSGCODE_TRANSMIT_SUCCEEDED
;
635 // ignore other data while waiting
643 message
.state
= bTransmitSucceeded
&& !bError
?
644 ADAPTER_MESSAGE_STATE_SENT_ACKED
:
645 ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED
;
647 return bTransmitSucceeded
&& !bError
;
650 void CUSBCECAdapterCommunication::AddData(uint8_t *data
, size_t iLen
)
652 CLockObject
lock(m_mutex
);
653 for (size_t iPtr
= 0; iPtr
< iLen
; iPtr
++)
657 if (data
[iPtr
] == MSGSTART
)
660 else if (data
[iPtr
] == MSGSTART
) //we found a msgstart before msgend, this is not right, remove
662 if (m_currentAdapterMessage
.Size() > 0)
663 CLibCEC::AddLog(CEC_LOG_WARNING
, "received MSGSTART before MSGEND, removing previous buffer contents");
664 m_currentAdapterMessage
.Clear();
667 else if (data
[iPtr
] == MSGEND
)
669 CCECAdapterMessage
*newMessage
= new CCECAdapterMessage
;
670 newMessage
->packet
= m_currentAdapterMessage
.packet
;
671 m_inBuffer
.Push(newMessage
);
672 m_currentAdapterMessage
.Clear();
674 m_bNextIsEscaped
= false;
676 m_rcvCondition
.Broadcast();
678 else if (m_bNextIsEscaped
)
680 m_currentAdapterMessage
.PushBack(data
[iPtr
] + (uint8_t)ESCOFFSET
);
681 m_bNextIsEscaped
= false;
683 else if (data
[iPtr
] == MSGESC
)
685 m_bNextIsEscaped
= true;
689 m_currentAdapterMessage
.PushBack(data
[iPtr
]);
694 bool CUSBCECAdapterCommunication::ReadFromDevice(uint32_t iTimeout
, size_t iSize
/* = 256 */)
703 CLockObject
lock(m_mutex
);
704 iBytesRead
= m_port
->Read(buff
, sizeof(uint8_t) * iSize
, iTimeout
);
705 if (iBytesRead
< 0 || iBytesRead
> 256)
707 CLibCEC::AddLog(CEC_LOG_ERROR
, "error reading from serial port: %s", m_port
->GetError().c_str());
711 else if (iBytesRead
> 0)
713 AddData(buff
, iBytesRead
);
716 return iBytesRead
> 0;
719 void CUSBCECAdapterCommunication::SendMessageToAdapter(CCECAdapterMessage
*msg
)
721 CLockObject
adapterLock(m_mutex
);
722 if (!m_port
->IsOpen())
724 CLibCEC::AddLog(CEC_LOG_ERROR
, "error writing to serial port: the connection is closed");
725 msg
->state
= ADAPTER_MESSAGE_STATE_ERROR
;
730 SetLineTimeout(msg
->lineTimeout
);
732 SetLineTimeout(msg
->retryTimeout
);
734 if (m_port
->Write(msg
->packet
.data
, msg
->Size()) != (ssize_t
) msg
->Size())
736 CLibCEC::AddLog(CEC_LOG_ERROR
, "error writing to serial port: %s", m_port
->GetError().c_str());
737 msg
->state
= ADAPTER_MESSAGE_STATE_ERROR
;
741 CLibCEC::AddLog(CEC_LOG_DEBUG
, "command sent");
742 msg
->state
= ADAPTER_MESSAGE_STATE_SENT
;
744 if (msg
->expectControllerAck
)
746 if (!WaitForAck(*msg
))
747 CLibCEC::AddLog(CEC_LOG_DEBUG
, "did not receive ack");
753 void CUSBCECAdapterCommunication::WriteNextCommand(void)
755 CCECAdapterMessage
*msg(NULL
);
756 if (m_outBuffer
.Pop(msg
))
757 SendMessageToAdapter(msg
);
760 CStdString
CUSBCECAdapterCommunication::GetPortName(void)
763 strName
= m_port
->GetName();