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
),
47 m_iFirmwareVersion(CEC_FW_VERSION_UNKNOWN
),
48 m_lastInitiator(CECDEVICE_UNKNOWN
),
49 m_bNextIsEscaped(false),
52 m_port
= new PLATFORM::CSerialPort(strPort
, iBaudRate
);
55 CUSBCECAdapterCommunication::~CUSBCECAdapterCommunication(void)
60 bool CUSBCECAdapterCommunication::CheckAdapter(uint32_t iTimeoutMs
/* = 10000 */)
63 uint64_t iNow
= GetTimeMs();
64 uint64_t iTarget
= iTimeoutMs
> 0 ? iNow
+ iTimeoutMs
: iNow
+ CEC_DEFAULT_TRANSMIT_WAIT
;
66 /* try to ping the adapter */
69 while (iNow
< iTarget
&& (bPinged
= PingAdapter()) == false)
71 CLibCEC::AddLog(CEC_LOG_ERROR
, "the adapter did not respond correctly to a ping (try %d)", ++iPingTry
);
76 /* try to read the firmware version */
77 m_iFirmwareVersion
= CEC_FW_VERSION_UNKNOWN
;
78 unsigned iFwVersionTry(0);
79 while (bPinged
&& iNow
< iTarget
&& (m_iFirmwareVersion
= GetFirmwareVersion()) == CEC_FW_VERSION_UNKNOWN
)
81 CLibCEC::AddLog(CEC_LOG_ERROR
, "the adapter did not respond with a correct firmware version (try %d)", ++iFwVersionTry
);
86 if (m_iFirmwareVersion
>= 2)
88 /* try to set controlled mode */
89 unsigned iControlledTry(0);
90 bool bControlled(false);
91 while (iNow
< iTarget
&& (bControlled
= SetControlledMode(true)) == false)
93 CLibCEC::AddLog(CEC_LOG_ERROR
, "the adapter did not respond correctly to setting controlled mode (try %d)", ++iControlledTry
);
97 bReturn
= bControlled
;
105 bool CUSBCECAdapterCommunication::Open(IAdapterCommunicationCallback
*cb
, uint32_t iTimeoutMs
/* = 10000 */)
107 uint64_t iNow
= GetTimeMs();
108 uint64_t iTimeout
= iNow
+ iTimeoutMs
;
111 CLockObject
lock(m_mutex
);
115 CLibCEC::AddLog(CEC_LOG_ERROR
, "port is NULL");
121 CLibCEC::AddLog(CEC_LOG_ERROR
, "port is already open");
127 bool bConnected(false);
128 while (!bConnected
&& iNow
< iTimeout
)
130 if ((bConnected
= m_port
->Open(iTimeout
)) == false)
132 strError
.Format("error opening serial port '%s': %s", m_port
->GetName().c_str(), m_port
->GetError().c_str());
140 CLibCEC::AddLog(CEC_LOG_ERROR
, strError
);
144 CLibCEC::AddLog(CEC_LOG_DEBUG
, "connection opened, clearing any previous input and waiting for active transmissions to end before starting");
146 //clear any input bytes
148 while (m_port
->Read(buff
, 1024, 100) > 0)
150 CLibCEC::AddLog(CEC_LOG_DEBUG
, "data received, clearing it");
160 CLibCEC::AddLog(CEC_LOG_ERROR
, "the adapter failed to pass basic checks");
164 CLibCEC::AddLog(CEC_LOG_DEBUG
, "communication thread started");
168 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not create a communication thread");
173 void CUSBCECAdapterCommunication::Close(void)
176 CLockObject
lock(m_mutex
);
177 m_rcvCondition
.Broadcast();
181 void *CUSBCECAdapterCommunication::Process(void)
184 bool bCommandReceived(false);
188 CLockObject
lock(m_mutex
);
190 bCommandReceived
= m_callback
&& Read(command
, 0);
193 /* push the next command to the callback method if there is one */
194 if (!IsStopped() && bCommandReceived
)
195 m_callback
->OnCommandReceived(command
);
204 CCECAdapterMessage
*msg(NULL
);
205 if (m_outBuffer
.Pop(msg
))
206 msg
->condition
.Broadcast();
217 cec_adapter_message_state
CUSBCECAdapterCommunication::Write(const cec_command
&data
, uint8_t iMaxTries
, uint8_t iLineTimeout
/* = 3 */, uint8_t iRetryLineTimeout
/* = 3 */)
219 cec_adapter_message_state
retVal(ADAPTER_MESSAGE_STATE_UNKNOWN
);
223 CCECAdapterMessage
*output
= new CCECAdapterMessage(data
);
225 /* set the number of retries */
226 if (data
.opcode
== CEC_OPCODE_NONE
) //TODO
227 output
->maxTries
= 1;
228 else if (data
.initiator
!= CECDEVICE_BROADCAST
)
229 output
->maxTries
= iMaxTries
;
231 output
->lineTimeout
= iLineTimeout
;
232 output
->retryTimeout
= iRetryLineTimeout
;
236 while (bRetry
&& ++output
->tries
< output
->maxTries
)
238 bRetry
= (!Write(output
) || output
->NeedsRetry()) && output
->transmit_timeout
> 0;
240 Sleep(CEC_DEFAULT_TRANSMIT_RETRY_WAIT
);
242 retVal
= output
->state
;
248 bool CUSBCECAdapterCommunication::Write(CCECAdapterMessage
*data
)
250 CLockObject
lock(data
->mutex
);
251 data
->state
= ADAPTER_MESSAGE_STATE_WAITING_TO_BE_SENT
;
252 m_outBuffer
.Push(data
);
253 data
->condition
.Wait(data
->mutex
);
255 if ((data
->expectControllerAck
&& data
->state
!= ADAPTER_MESSAGE_STATE_SENT_ACKED
) ||
256 (!data
->expectControllerAck
&& data
->state
!= ADAPTER_MESSAGE_STATE_SENT
))
258 CLibCEC::AddLog(CEC_LOG_DEBUG
, "command was not %s", data
->state
== ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED
? "acked" : "sent");
265 bool CUSBCECAdapterCommunication::Read(cec_command
&command
, uint32_t iTimeout
)
270 CCECAdapterMessage msg
;
271 if (Read(msg
, iTimeout
))
273 if (ParseMessage(msg
))
275 command
= m_currentframe
;
276 m_currentframe
.Clear();
283 bool CUSBCECAdapterCommunication::Read(CCECAdapterMessage
&msg
, uint32_t iTimeout
)
285 CLockObject
lock(m_mutex
);
288 CCECAdapterMessage
*buf(NULL
);
290 if (!m_inBuffer
.Pop(buf
))
292 if (iTimeout
== 0 || !m_rcvCondition
.Wait(m_mutex
, iTimeout
))
299 msg
.packet
= buf
->packet
;
300 msg
.state
= ADAPTER_MESSAGE_STATE_INCOMING
;
307 CStdString
CUSBCECAdapterCommunication::GetError(void) const
310 strError
= m_port
->GetError();
314 bool CUSBCECAdapterCommunication::StartBootloader(void)
320 CLibCEC::AddLog(CEC_LOG_DEBUG
, "starting the bootloader");
321 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
323 output
->PushBack(MSGSTART
);
324 output
->PushEscaped(MSGCODE_START_BOOTLOADER
);
325 output
->PushBack(MSGEND
);
326 output
->isTransmission
= false;
327 output
->expectControllerAck
= false;
329 if ((bReturn
= Write(output
)) == false)
330 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not start the bootloader");
336 bool CUSBCECAdapterCommunication::PingAdapter(void)
342 CLibCEC::AddLog(CEC_LOG_DEBUG
, "sending ping");
343 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
345 output
->PushBack(MSGSTART
);
346 output
->PushEscaped(MSGCODE_PING
);
347 output
->PushBack(MSGEND
);
348 output
->isTransmission
= false;
350 if ((bReturn
= Write(output
)) == false)
351 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not ping the adapter");
357 bool CUSBCECAdapterCommunication::ParseMessage(const CCECAdapterMessage
&msg
)
360 bool bIsError(msg
.IsError());
365 switch(msg
.Message())
367 case MSGCODE_FRAME_START
:
369 m_currentframe
.Clear();
372 m_currentframe
.initiator
= msg
.Initiator();
373 m_currentframe
.destination
= msg
.Destination();
374 m_currentframe
.ack
= msg
.IsACK();
375 m_currentframe
.eom
= msg
.IsEOM();
377 if (m_currentframe
.ack
== 0x1)
379 m_lastInitiator
= m_currentframe
.initiator
;
380 m_processor
->HandlePoll(m_currentframe
.initiator
, m_currentframe
.destination
);
384 case MSGCODE_RECEIVE_FAILED
:
386 m_currentframe
.Clear();
387 if (m_lastInitiator
!= CECDEVICE_UNKNOWN
)
388 bIsError
= m_processor
->HandleReceiveFailed(m_lastInitiator
);
391 case MSGCODE_FRAME_DATA
:
395 m_currentframe
.PushBack(msg
[1]);
396 m_currentframe
.eom
= msg
.IsEOM();
405 CLibCEC::AddLog(bIsError
? CEC_LOG_WARNING
: CEC_LOG_DEBUG
, msg
.ToString());
409 uint16_t CUSBCECAdapterCommunication::GetFirmwareVersion(void)
411 CLockObject
lock(m_mutex
);
412 uint16_t iReturn(m_iFirmwareVersion
);
416 if (iReturn
== CEC_FW_VERSION_UNKNOWN
)
418 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting the firmware version");
419 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
421 output
->PushBack(MSGSTART
);
422 output
->PushEscaped(MSGCODE_FIRMWARE_VERSION
);
423 output
->PushBack(MSGEND
);
424 output
->isTransmission
= false;
425 output
->expectControllerAck
= false;
427 SendMessageToAdapter(output
);
428 bool bWriteOk
= output
->state
== ADAPTER_MESSAGE_STATE_SENT
;
432 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not request the firmware version");
436 Sleep(250); // TODO ReadFromDevice() isn't waiting for the timeout to pass on win32
437 ReadFromDevice(CEC_DEFAULT_TRANSMIT_WAIT
, 5 /* start + msgcode + 2 bytes for fw version + end */);
438 CCECAdapterMessage input
;
441 if (input
.Message() != MSGCODE_FIRMWARE_VERSION
|| input
.Size() != 3)
442 CLibCEC::AddLog(CEC_LOG_ERROR
, "invalid firmware version (size = %d, message = %d)", input
.Size(), input
.Message());
445 m_iFirmwareVersion
= (input
[1] << 8 | input
[2]);
446 iReturn
= m_iFirmwareVersion
;
451 CLibCEC::AddLog(CEC_LOG_ERROR
, "no firmware version received");
458 bool CUSBCECAdapterCommunication::SetLineTimeout(uint8_t iTimeout
)
460 m_iLineTimeout
= iTimeout
;
463 // bool bReturn(m_iLineTimeout != iTimeout);
467 // CCECAdapterMessage *output = new CCECAdapterMessage;
469 // output->PushBack(MSGSTART);
470 // output->PushEscaped(MSGCODE_TRANSMIT_IDLETIME);
471 // output->PushEscaped(iTimeout);
472 // output->PushBack(MSGEND);
473 // output->isTransmission = false;
475 // if ((bReturn = Write(output)) == false)
476 // CLibCEC::AddLog(CEC_LOG_ERROR, "could not set the idletime");
483 bool CUSBCECAdapterCommunication::SetAckMask(uint16_t iMask
)
486 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting ackmask to %2x", iMask
);
488 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
490 output
->PushBack(MSGSTART
);
491 output
->PushEscaped(MSGCODE_SET_ACK_MASK
);
492 output
->PushEscaped(iMask
>> 8);
493 output
->PushEscaped((uint8_t)iMask
);
494 output
->PushBack(MSGEND
);
495 output
->isTransmission
= false;
497 if ((bReturn
= Write(output
)) == false)
498 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not set the ackmask");
505 bool CUSBCECAdapterCommunication::SetControlledMode(bool controlled
)
508 CLibCEC::AddLog(CEC_LOG_DEBUG
, "turning controlled mode %s", controlled
? "on" : "off");
510 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
512 output
->PushBack(MSGSTART
);
513 output
->PushEscaped(MSGCODE_SET_CONTROLLED
);
514 output
->PushEscaped(controlled
);
515 output
->PushBack(MSGEND
);
516 output
->isTransmission
= false;
518 if ((bReturn
= Write(output
)) == false)
519 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not set controlled mode");
525 bool CUSBCECAdapterCommunication::IsOpen(void)
527 return !IsStopped() && m_port
->IsOpen() && IsRunning();
530 bool CUSBCECAdapterCommunication::WaitForAck(CCECAdapterMessage
&message
)
533 bool bTransmitSucceeded(false);
534 uint8_t iPacketsLeft(message
.Size() / 4);
536 int64_t iNow
= GetTimeMs();
537 int64_t iTargetTime
= iNow
+ (message
.transmit_timeout
<= 5 ? CEC_DEFAULT_TRANSMIT_WAIT
: message
.transmit_timeout
);
539 while (!bTransmitSucceeded
&& !bError
&& iNow
< iTargetTime
)
542 CCECAdapterMessage msg
;
549 if (msg
.Message() == MSGCODE_FRAME_START
&& msg
.IsACK())
551 m_processor
->HandlePoll(msg
.Initiator(), msg
.Destination());
552 m_lastInitiator
= msg
.Initiator();
557 if (msg
.Message() == MSGCODE_RECEIVE_FAILED
&&
558 m_lastInitiator
!= CECDEVICE_UNKNOWN
&&
559 m_processor
->HandleReceiveFailed(m_lastInitiator
))
565 bError
= msg
.IsError();
568 message
.reply
= msg
.Message();
569 CLibCEC::AddLog(CEC_LOG_DEBUG
, msg
.ToString());
573 switch(msg
.Message())
575 case MSGCODE_COMMAND_ACCEPTED
:
576 CLibCEC::AddLog(CEC_LOG_DEBUG
, msg
.ToString());
577 if (iPacketsLeft
> 0)
579 if (!message
.isTransmission
&& iPacketsLeft
== 0)
580 bTransmitSucceeded
= true;
582 case MSGCODE_TRANSMIT_SUCCEEDED
:
583 CLibCEC::AddLog(CEC_LOG_DEBUG
, msg
.ToString());
584 bTransmitSucceeded
= (iPacketsLeft
== 0);
585 bError
= !bTransmitSucceeded
;
586 message
.reply
= MSGCODE_TRANSMIT_SUCCEEDED
;
589 // ignore other data while waiting
597 message
.state
= bTransmitSucceeded
&& !bError
?
598 ADAPTER_MESSAGE_STATE_SENT_ACKED
:
599 ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED
;
601 return bTransmitSucceeded
&& !bError
;
604 void CUSBCECAdapterCommunication::AddData(uint8_t *data
, size_t iLen
)
606 CLockObject
lock(m_mutex
);
607 for (size_t iPtr
= 0; iPtr
< iLen
; iPtr
++)
611 if (data
[iPtr
] == MSGSTART
)
614 else if (data
[iPtr
] == MSGSTART
) //we found a msgstart before msgend, this is not right, remove
616 if (m_currentAdapterMessage
.Size() > 0)
617 CLibCEC::AddLog(CEC_LOG_WARNING
, "received MSGSTART before MSGEND, removing previous buffer contents");
618 m_currentAdapterMessage
.Clear();
621 else if (data
[iPtr
] == MSGEND
)
623 CCECAdapterMessage
*newMessage
= new CCECAdapterMessage
;
624 newMessage
->packet
= m_currentAdapterMessage
.packet
;
625 m_inBuffer
.Push(newMessage
);
626 m_currentAdapterMessage
.Clear();
628 m_bNextIsEscaped
= false;
629 m_rcvCondition
.Signal();
631 else if (m_bNextIsEscaped
)
633 m_currentAdapterMessage
.PushBack(data
[iPtr
] + (uint8_t)ESCOFFSET
);
634 m_bNextIsEscaped
= false;
636 else if (data
[iPtr
] == MSGESC
)
638 m_bNextIsEscaped
= true;
642 m_currentAdapterMessage
.PushBack(data
[iPtr
]);
647 bool CUSBCECAdapterCommunication::ReadFromDevice(uint32_t iTimeout
, size_t iSize
/* = 256 */)
656 CLockObject
lock(m_mutex
);
657 iBytesRead
= m_port
->Read(buff
, sizeof(uint8_t) * iSize
, iTimeout
);
658 if (iBytesRead
< 0 || iBytesRead
> 256)
660 CLibCEC::AddLog(CEC_LOG_ERROR
, "error reading from serial port: %s", m_port
->GetError().c_str());
663 else if (iBytesRead
> 0)
665 AddData(buff
, iBytesRead
);
668 return iBytesRead
> 0;
671 void CUSBCECAdapterCommunication::SendMessageToAdapter(CCECAdapterMessage
*msg
)
673 CLockObject
adapterLock(m_mutex
);
674 CLockObject
lock(msg
->mutex
);
676 SetLineTimeout(msg
->lineTimeout
);
678 SetLineTimeout(msg
->retryTimeout
);
680 if (m_port
->Write(msg
->packet
.data
, msg
->Size()) != (ssize_t
) msg
->Size())
682 CLibCEC::AddLog(CEC_LOG_ERROR
, "error writing to serial port: %s", m_port
->GetError().c_str());
683 msg
->state
= ADAPTER_MESSAGE_STATE_ERROR
;
687 CLibCEC::AddLog(CEC_LOG_DEBUG
, "command sent");
688 msg
->state
= ADAPTER_MESSAGE_STATE_SENT
;
690 if (msg
->expectControllerAck
)
692 if (!WaitForAck(*msg
))
693 CLibCEC::AddLog(CEC_LOG_DEBUG
, "did not receive ack");
696 msg
->condition
.Signal();
699 void CUSBCECAdapterCommunication::WriteNextCommand(void)
701 CCECAdapterMessage
*msg(NULL
);
702 if (m_outBuffer
.Pop(msg
))
703 SendMessageToAdapter(msg
);