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 CUSBCECAdapterCommunication::CUSBCECAdapterCommunication(CCECProcessor
*processor
, const char *strPort
, uint16_t iBaudRate
/* = 38400 */) :
45 m_processor(processor
),
48 m_iFirmwareVersion(CEC_FW_VERSION_UNKNOWN
),
49 m_lastInitiator(CECDEVICE_UNKNOWN
),
50 m_bNextIsEscaped(false),
53 m_port
= new PLATFORM::CSerialPort(strPort
, iBaudRate
);
56 CUSBCECAdapterCommunication::~CUSBCECAdapterCommunication(void)
61 bool CUSBCECAdapterCommunication::CheckAdapter(uint32_t iTimeoutMs
/* = 10000 */)
64 uint64_t iNow
= GetTimeMs();
65 uint64_t iTarget
= iTimeoutMs
> 0 ? iNow
+ iTimeoutMs
: iNow
+ CEC_DEFAULT_TRANSMIT_WAIT
;
67 /* try to ping the adapter */
70 while (iNow
< iTarget
&& (bPinged
= PingAdapter()) == false)
72 CLibCEC::AddLog(CEC_LOG_ERROR
, "the adapter did not respond correctly to a ping (try %d)", ++iPingTry
);
77 /* try to read the firmware version */
78 m_iFirmwareVersion
= CEC_FW_VERSION_UNKNOWN
;
79 unsigned iFwVersionTry(0);
80 while (bPinged
&& iNow
< iTarget
&& (m_iFirmwareVersion
= GetFirmwareVersion()) == CEC_FW_VERSION_UNKNOWN
)
82 CLibCEC::AddLog(CEC_LOG_ERROR
, "the adapter did not respond with a correct firmware version (try %d)", ++iFwVersionTry
);
87 if (m_iFirmwareVersion
>= 2)
89 /* try to set controlled mode */
90 unsigned iControlledTry(0);
91 bool bControlled(false);
92 while (iNow
< iTarget
&& (bControlled
= SetControlledMode(true)) == false)
94 CLibCEC::AddLog(CEC_LOG_ERROR
, "the adapter did not respond correctly to setting controlled mode (try %d)", ++iControlledTry
);
98 bReturn
= bControlled
;
106 bool CUSBCECAdapterCommunication::Open(IAdapterCommunicationCallback
*cb
, uint32_t iTimeoutMs
/* = 10000 */)
108 uint64_t iNow
= GetTimeMs();
109 uint64_t iTimeout
= iNow
+ iTimeoutMs
;
112 CLockObject
lock(m_mutex
);
116 CLibCEC::AddLog(CEC_LOG_ERROR
, "port is NULL");
122 CLibCEC::AddLog(CEC_LOG_ERROR
, "port is already open");
128 bool bConnected(false);
129 while (!bConnected
&& iNow
< iTimeout
)
131 if ((bConnected
= m_port
->Open(iTimeout
)) == false)
133 strError
.Format("error opening serial port '%s': %s", m_port
->GetName().c_str(), m_port
->GetError().c_str());
141 CLibCEC::AddLog(CEC_LOG_ERROR
, strError
);
145 CLibCEC::AddLog(CEC_LOG_DEBUG
, "connection opened, clearing any previous input and waiting for active transmissions to end before starting");
147 //clear any input bytes
149 while (m_port
->Read(buff
, 1024, 100) > 0)
151 CLibCEC::AddLog(CEC_LOG_DEBUG
, "data received, clearing it");
161 CLibCEC::AddLog(CEC_LOG_ERROR
, "the adapter failed to pass basic checks");
165 CLibCEC::AddLog(CEC_LOG_DEBUG
, "communication thread started");
169 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not create a communication thread");
174 void CUSBCECAdapterCommunication::Close(void)
178 CLockObject
lock(m_mutex
);
180 m_rcvCondition
.Broadcast();
185 void *CUSBCECAdapterCommunication::Process(void)
188 bool bCommandReceived(false);
192 CLockObject
lock(m_mutex
);
194 bCommandReceived
= m_callback
&& Read(command
, 0);
197 /* push the next command to the callback method if there is one */
198 if (!IsStopped() && bCommandReceived
)
199 m_callback
->OnCommandReceived(command
);
208 CCECAdapterMessage
*msg(NULL
);
209 if (m_outBuffer
.Pop(msg
))
210 msg
->event
.Broadcast();
221 cec_adapter_message_state
CUSBCECAdapterCommunication::Write(const cec_command
&data
, uint8_t iMaxTries
, uint8_t iLineTimeout
/* = 3 */, uint8_t iRetryLineTimeout
/* = 3 */)
223 cec_adapter_message_state
retVal(ADAPTER_MESSAGE_STATE_UNKNOWN
);
227 CCECAdapterMessage
*output
= new CCECAdapterMessage(data
);
229 /* set the number of retries */
230 if (data
.opcode
== CEC_OPCODE_NONE
) //TODO
231 output
->maxTries
= 1;
232 else if (data
.initiator
!= CECDEVICE_BROADCAST
)
233 output
->maxTries
= iMaxTries
;
235 output
->lineTimeout
= iLineTimeout
;
236 output
->retryTimeout
= iRetryLineTimeout
;
240 while (bRetry
&& ++output
->tries
< output
->maxTries
)
242 bRetry
= (!Write(output
) || output
->NeedsRetry()) && output
->transmit_timeout
> 0;
244 Sleep(CEC_DEFAULT_TRANSMIT_RETRY_WAIT
);
246 retVal
= output
->state
;
252 bool CUSBCECAdapterCommunication::Write(CCECAdapterMessage
*data
)
254 data
->state
= ADAPTER_MESSAGE_STATE_WAITING_TO_BE_SENT
;
255 m_outBuffer
.Push(data
);
258 if ((data
->expectControllerAck
&& data
->state
!= ADAPTER_MESSAGE_STATE_SENT_ACKED
) ||
259 (!data
->expectControllerAck
&& data
->state
!= ADAPTER_MESSAGE_STATE_SENT
))
261 CLibCEC::AddLog(CEC_LOG_DEBUG
, "command was not %s", data
->state
== ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED
? "acked" : "sent");
268 bool CUSBCECAdapterCommunication::Read(cec_command
&command
, uint32_t iTimeout
)
273 CCECAdapterMessage msg
;
274 if (Read(msg
, iTimeout
))
276 if (ParseMessage(msg
))
278 command
= m_currentframe
;
279 m_currentframe
.Clear();
286 bool CUSBCECAdapterCommunication::Read(CCECAdapterMessage
&msg
, uint32_t iTimeout
)
288 CLockObject
lock(m_mutex
);
291 CCECAdapterMessage
*buf(NULL
);
293 if (!m_inBuffer
.Pop(buf
))
295 if (iTimeout
== 0 || !m_rcvCondition
.Wait(m_mutex
, m_bHasData
, iTimeout
))
298 m_bHasData
= m_inBuffer
.Size() > 0;
303 msg
.packet
= buf
->packet
;
304 msg
.state
= ADAPTER_MESSAGE_STATE_INCOMING
;
311 CStdString
CUSBCECAdapterCommunication::GetError(void) const
314 strError
= m_port
->GetError();
318 bool CUSBCECAdapterCommunication::StartBootloader(void)
324 CLibCEC::AddLog(CEC_LOG_DEBUG
, "starting the bootloader");
325 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
327 output
->PushBack(MSGSTART
);
328 output
->PushEscaped(MSGCODE_START_BOOTLOADER
);
329 output
->PushBack(MSGEND
);
330 output
->isTransmission
= false;
331 output
->expectControllerAck
= false;
333 if ((bReturn
= Write(output
)) == false)
334 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not start the bootloader");
340 bool CUSBCECAdapterCommunication::PingAdapter(void)
346 CLibCEC::AddLog(CEC_LOG_DEBUG
, "sending ping");
347 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
349 output
->PushBack(MSGSTART
);
350 output
->PushEscaped(MSGCODE_PING
);
351 output
->PushBack(MSGEND
);
352 output
->isTransmission
= false;
354 if ((bReturn
= Write(output
)) == false)
355 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not ping the adapter");
361 bool CUSBCECAdapterCommunication::ParseMessage(const CCECAdapterMessage
&msg
)
364 bool bIsError(msg
.IsError());
369 switch(msg
.Message())
371 case MSGCODE_FRAME_START
:
373 m_currentframe
.Clear();
376 m_currentframe
.initiator
= msg
.Initiator();
377 m_currentframe
.destination
= msg
.Destination();
378 m_currentframe
.ack
= msg
.IsACK();
379 m_currentframe
.eom
= msg
.IsEOM();
381 if (m_currentframe
.ack
== 0x1)
383 m_lastInitiator
= m_currentframe
.initiator
;
384 m_processor
->HandlePoll(m_currentframe
.initiator
, m_currentframe
.destination
);
388 case MSGCODE_RECEIVE_FAILED
:
390 m_currentframe
.Clear();
391 if (m_lastInitiator
!= CECDEVICE_UNKNOWN
)
392 bIsError
= m_processor
->HandleReceiveFailed(m_lastInitiator
);
395 case MSGCODE_FRAME_DATA
:
399 m_currentframe
.PushBack(msg
[1]);
400 m_currentframe
.eom
= msg
.IsEOM();
409 CLibCEC::AddLog(bIsError
? CEC_LOG_WARNING
: CEC_LOG_DEBUG
, msg
.ToString());
413 uint16_t CUSBCECAdapterCommunication::GetFirmwareVersion(void)
415 uint16_t iReturn(m_iFirmwareVersion
);
419 if (iReturn
== CEC_FW_VERSION_UNKNOWN
)
421 CLockObject
lock(m_mutex
);
422 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting the firmware version");
423 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
425 output
->PushBack(MSGSTART
);
426 output
->PushEscaped(MSGCODE_FIRMWARE_VERSION
);
427 output
->PushBack(MSGEND
);
428 output
->isTransmission
= false;
429 output
->expectControllerAck
= false;
431 SendMessageToAdapter(output
);
432 bool bWriteOk
= output
->state
== ADAPTER_MESSAGE_STATE_SENT
;
436 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not request the firmware version");
440 Sleep(250); // TODO ReadFromDevice() isn't waiting for the timeout to pass on win32
441 ReadFromDevice(CEC_DEFAULT_TRANSMIT_WAIT
, 5 /* start + msgcode + 2 bytes for fw version + end */);
442 CCECAdapterMessage input
;
445 if (input
.Message() != MSGCODE_FIRMWARE_VERSION
|| input
.Size() != 3)
446 CLibCEC::AddLog(CEC_LOG_ERROR
, "invalid firmware version (size = %d, message = %d)", input
.Size(), input
.Message());
449 m_iFirmwareVersion
= (input
[1] << 8 | input
[2]);
450 iReturn
= m_iFirmwareVersion
;
455 CLibCEC::AddLog(CEC_LOG_ERROR
, "no firmware version received");
462 bool CUSBCECAdapterCommunication::SetLineTimeout(uint8_t iTimeout
)
464 m_iLineTimeout
= iTimeout
;
467 // bool bReturn(m_iLineTimeout != iTimeout);
471 // CCECAdapterMessage *output = new CCECAdapterMessage;
473 // output->PushBack(MSGSTART);
474 // output->PushEscaped(MSGCODE_TRANSMIT_IDLETIME);
475 // output->PushEscaped(iTimeout);
476 // output->PushBack(MSGEND);
477 // output->isTransmission = false;
479 // if ((bReturn = Write(output)) == false)
480 // CLibCEC::AddLog(CEC_LOG_ERROR, "could not set the idletime");
487 bool CUSBCECAdapterCommunication::SetAckMask(uint16_t iMask
)
490 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting ackmask to %2x", iMask
);
492 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
494 output
->PushBack(MSGSTART
);
495 output
->PushEscaped(MSGCODE_SET_ACK_MASK
);
496 output
->PushEscaped(iMask
>> 8);
497 output
->PushEscaped((uint8_t)iMask
);
498 output
->PushBack(MSGEND
);
499 output
->isTransmission
= false;
501 if ((bReturn
= Write(output
)) == false)
502 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not set the ackmask");
509 bool CUSBCECAdapterCommunication::SetControlledMode(bool controlled
)
512 CLibCEC::AddLog(CEC_LOG_DEBUG
, "turning controlled mode %s", controlled
? "on" : "off");
514 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
516 output
->PushBack(MSGSTART
);
517 output
->PushEscaped(MSGCODE_SET_CONTROLLED
);
518 output
->PushEscaped(controlled
);
519 output
->PushBack(MSGEND
);
520 output
->isTransmission
= false;
522 if ((bReturn
= Write(output
)) == false)
523 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not set controlled mode");
529 bool CUSBCECAdapterCommunication::IsOpen(void)
531 return !IsStopped() && m_port
->IsOpen() && IsRunning();
534 bool CUSBCECAdapterCommunication::WaitForAck(CCECAdapterMessage
&message
)
537 bool bTransmitSucceeded(false);
538 uint8_t iPacketsLeft(message
.Size() / 4);
540 int64_t iNow
= GetTimeMs();
541 int64_t iTargetTime
= iNow
+ (message
.transmit_timeout
<= 5 ? CEC_DEFAULT_TRANSMIT_WAIT
: message
.transmit_timeout
);
543 while (!bTransmitSucceeded
&& !bError
&& iNow
< iTargetTime
)
546 CCECAdapterMessage msg
;
553 if (msg
.Message() == MSGCODE_FRAME_START
&& msg
.IsACK())
555 m_processor
->HandlePoll(msg
.Initiator(), msg
.Destination());
556 m_lastInitiator
= msg
.Initiator();
561 if (msg
.Message() == MSGCODE_RECEIVE_FAILED
&&
562 m_lastInitiator
!= CECDEVICE_UNKNOWN
&&
563 m_processor
->HandleReceiveFailed(m_lastInitiator
))
569 bError
= msg
.IsError();
572 message
.reply
= msg
.Message();
573 CLibCEC::AddLog(CEC_LOG_DEBUG
, msg
.ToString());
577 switch(msg
.Message())
579 case MSGCODE_COMMAND_ACCEPTED
:
580 CLibCEC::AddLog(CEC_LOG_DEBUG
, msg
.ToString());
581 if (iPacketsLeft
> 0)
583 if (!message
.isTransmission
&& iPacketsLeft
== 0)
584 bTransmitSucceeded
= true;
586 case MSGCODE_TRANSMIT_SUCCEEDED
:
587 CLibCEC::AddLog(CEC_LOG_DEBUG
, msg
.ToString());
588 bTransmitSucceeded
= (iPacketsLeft
== 0);
589 bError
= !bTransmitSucceeded
;
590 message
.reply
= MSGCODE_TRANSMIT_SUCCEEDED
;
593 // ignore other data while waiting
601 message
.state
= bTransmitSucceeded
&& !bError
?
602 ADAPTER_MESSAGE_STATE_SENT_ACKED
:
603 ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED
;
605 return bTransmitSucceeded
&& !bError
;
608 void CUSBCECAdapterCommunication::AddData(uint8_t *data
, size_t iLen
)
610 CLockObject
lock(m_mutex
);
611 for (size_t iPtr
= 0; iPtr
< iLen
; iPtr
++)
615 if (data
[iPtr
] == MSGSTART
)
618 else if (data
[iPtr
] == MSGSTART
) //we found a msgstart before msgend, this is not right, remove
620 if (m_currentAdapterMessage
.Size() > 0)
621 CLibCEC::AddLog(CEC_LOG_WARNING
, "received MSGSTART before MSGEND, removing previous buffer contents");
622 m_currentAdapterMessage
.Clear();
625 else if (data
[iPtr
] == MSGEND
)
627 CCECAdapterMessage
*newMessage
= new CCECAdapterMessage
;
628 newMessage
->packet
= m_currentAdapterMessage
.packet
;
629 m_inBuffer
.Push(newMessage
);
630 m_currentAdapterMessage
.Clear();
632 m_bNextIsEscaped
= false;
634 m_rcvCondition
.Signal();
636 else if (m_bNextIsEscaped
)
638 m_currentAdapterMessage
.PushBack(data
[iPtr
] + (uint8_t)ESCOFFSET
);
639 m_bNextIsEscaped
= false;
641 else if (data
[iPtr
] == MSGESC
)
643 m_bNextIsEscaped
= true;
647 m_currentAdapterMessage
.PushBack(data
[iPtr
]);
652 bool CUSBCECAdapterCommunication::ReadFromDevice(uint32_t iTimeout
, size_t iSize
/* = 256 */)
661 CLockObject
lock(m_mutex
);
662 iBytesRead
= m_port
->Read(buff
, sizeof(uint8_t) * iSize
, iTimeout
);
663 if (iBytesRead
< 0 || iBytesRead
> 256)
665 CLibCEC::AddLog(CEC_LOG_ERROR
, "error reading from serial port: %s", m_port
->GetError().c_str());
669 else if (iBytesRead
> 0)
671 AddData(buff
, iBytesRead
);
674 return iBytesRead
> 0;
677 void CUSBCECAdapterCommunication::SendMessageToAdapter(CCECAdapterMessage
*msg
)
679 CLockObject
adapterLock(m_mutex
);
681 SetLineTimeout(msg
->lineTimeout
);
683 SetLineTimeout(msg
->retryTimeout
);
685 if (m_port
->Write(msg
->packet
.data
, msg
->Size()) != (ssize_t
) msg
->Size())
687 CLibCEC::AddLog(CEC_LOG_ERROR
, "error writing to serial port: %s", m_port
->GetError().c_str());
688 msg
->state
= ADAPTER_MESSAGE_STATE_ERROR
;
692 CLibCEC::AddLog(CEC_LOG_DEBUG
, "command sent");
693 msg
->state
= ADAPTER_MESSAGE_STATE_SENT
;
695 if (msg
->expectControllerAck
)
697 if (!WaitForAck(*msg
))
698 CLibCEC::AddLog(CEC_LOG_DEBUG
, "did not receive ack");
704 void CUSBCECAdapterCommunication::WriteNextCommand(void)
706 CCECAdapterMessage
*msg(NULL
);
707 if (m_outBuffer
.Pop(msg
))
708 SendMessageToAdapter(msg
);