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 "USBCECAdapterCommands.h"
35 #include "USBCECAdapterMessageQueue.h"
36 #include "../platform/sockets/serialport.h"
37 #include "../platform/util/timeutils.h"
38 #include "../platform/util/util.h"
39 #include "../platform/util/edid.h"
40 #include "../platform/adl/adl-edid.h"
41 #include "../LibCEC.h"
42 #include "../CECProcessor.h"
46 using namespace PLATFORM
;
48 #define CEC_ADAPTER_PING_TIMEOUT 15000
51 #define CEC_LATEST_ADAPTER_FW_VERSION 2
52 // firmware date Thu Apr 26 20:14:49 2012 +0000
53 #define CEC_LATEST_ADAPTER_FW_DATE 0x4F99ACB9
55 #define LIB_CEC m_callback->GetLib()
57 CUSBCECAdapterCommunication::CUSBCECAdapterCommunication(IAdapterCommunicationCallback
*callback
, const char *strPort
, uint16_t iBaudRate
/* = CEC_SERIAL_DEFAULT_BAUDRATE */) :
58 IAdapterCommunication(callback
),
61 m_lastPollDestination(CECDEVICE_UNKNOWN
),
62 m_bInitialised(false),
65 m_adapterMessageQueue(NULL
),
68 for (unsigned int iPtr
= CECDEVICE_TV
; iPtr
< CECDEVICE_BROADCAST
; iPtr
++)
69 m_bWaitingForAck
[iPtr
] = false;
70 m_port
= new CSerialPort(strPort
, iBaudRate
);
71 m_commands
= new CUSBCECAdapterCommands(this);
74 CUSBCECAdapterCommunication::~CUSBCECAdapterCommunication(void)
77 DELETE_AND_NULL(m_commands
);
78 DELETE_AND_NULL(m_adapterMessageQueue
);
79 DELETE_AND_NULL(m_port
);
82 void CUSBCECAdapterCommunication::ResetMessageQueue(void)
84 DELETE_AND_NULL(m_adapterMessageQueue
);
85 m_adapterMessageQueue
= new CCECAdapterMessageQueue(this);
86 m_adapterMessageQueue
->CreateThread();
89 bool CUSBCECAdapterCommunication::Open(uint32_t iTimeoutMs
/* = CEC_DEFAULT_CONNECT_TIMEOUT */, bool bSkipChecks
/* = false */, bool bStartListening
/* = true */)
91 bool bConnectionOpened(false);
93 CLockObject
lock(m_mutex
);
95 /* we need the port settings here */
98 LIB_CEC
->AddLog(CEC_LOG_ERROR
, "port is NULL");
99 return bConnectionOpened
;
102 /* return true when the port is already open */
105 LIB_CEC
->AddLog(CEC_LOG_WARNING
, "port is already open");
111 /* try to open the connection */
113 CTimeout
timeout(iTimeoutMs
);
114 while (!bConnectionOpened
&& timeout
.TimeLeft() > 0)
116 if ((bConnectionOpened
= m_port
->Open(timeout
.TimeLeft())) == false)
118 strError
.Format("error opening serial port '%s': %s", m_port
->GetName().c_str(), m_port
->GetError().c_str());
121 /* and retry every 250ms until the timeout passed */
124 /* return false when we couldn't connect */
125 if (!bConnectionOpened
)
127 LIB_CEC
->AddLog(CEC_LOG_ERROR
, strError
);
129 if (m_port
->GetErrorNumber() == EACCES
)
131 libcec_parameter param
;
132 param
.paramType
= CEC_PARAMETER_TYPE_STRING
;
133 param
.paramData
= (void*)"No permission to open the device";
134 LIB_CEC
->Alert(CEC_ALERT_PERMISSION_ERROR
, param
);
136 else if (m_port
->GetErrorNumber() == EBUSY
)
138 libcec_parameter param
;
139 param
.paramType
= CEC_PARAMETER_TYPE_STRING
;
140 param
.paramData
= (void*)"The serial port is busy. Only one program can access the device directly.";
141 LIB_CEC
->Alert(CEC_ALERT_PORT_BUSY
, param
);
146 LIB_CEC
->AddLog(CEC_LOG_DEBUG
, "connection opened, clearing any previous input and waiting for active transmissions to end before starting");
150 // always start by setting the ackmask to 0, to clear previous values
155 bConnectionOpened
= false;
156 LIB_CEC
->AddLog(CEC_LOG_ERROR
, "could not create a communication thread");
158 else if (!bSkipChecks
&& !CheckAdapter())
160 bConnectionOpened
= false;
161 LIB_CEC
->AddLog(CEC_LOG_ERROR
, "the adapter failed to pass basic checks");
163 else if (bStartListening
)
165 /* start a ping thread, that will ping the adapter every 15 seconds
166 if it doesn't receive any ping for 30 seconds, it'll switch to auto mode */
167 m_pingThread
= new CAdapterPingThread(this, CEC_ADAPTER_PING_TIMEOUT
);
168 if (m_pingThread
->CreateThread())
170 bConnectionOpened
= true;
174 bConnectionOpened
= false;
175 LIB_CEC
->AddLog(CEC_LOG_ERROR
, "could not create a ping thread");
179 if (!bConnectionOpened
|| !bStartListening
)
182 return bConnectionOpened
;
185 void CUSBCECAdapterCommunication::Close(void)
187 /* stop the reader thread */
190 CLockObject
lock(m_mutex
);
192 /* set the ackmask to 0 before closing the connection */
193 if (IsOpen() && m_port
->GetErrorNumber() == 0)
195 LIB_CEC
->AddLog(CEC_LOG_DEBUG
, "%s - closing the connection", __FUNCTION__
);
197 if (m_commands
->GetFirmwareVersion() >= 2)
198 SetControlledMode(false);
201 m_adapterMessageQueue
->Clear();
203 /* stop and delete the ping thread */
204 DELETE_AND_NULL(m_pingThread
);
206 /* close and delete the com port connection */
211 cec_adapter_message_state
CUSBCECAdapterCommunication::Write(const cec_command
&data
, bool &bRetry
, uint8_t iLineTimeout
)
213 cec_adapter_message_state
retVal(ADAPTER_MESSAGE_STATE_UNKNOWN
);
217 CCECAdapterMessage
*output
= new CCECAdapterMessage(data
, iLineTimeout
);
219 /* mark as waiting for an ack from the destination */
220 MarkAsWaiting(data
.destination
);
222 /* send the message */
223 bRetry
= (!m_adapterMessageQueue
->Write(output
) || output
->NeedsRetry()) && output
->transmit_timeout
> 0;
225 Sleep(CEC_DEFAULT_TRANSMIT_RETRY_WAIT
);
226 retVal
= output
->state
;
232 void *CUSBCECAdapterCommunication::Process(void)
234 CCECAdapterMessage msg
;
235 LIB_CEC
->AddLog(CEC_LOG_DEBUG
, "communication thread started");
239 /* read from the serial port */
240 if (!ReadFromDevice(50, 5))
242 libcec_parameter param
;
243 param
.paramData
= NULL
; param
.paramType
= CEC_PARAMETER_TYPE_UNKOWN
;
244 LIB_CEC
->Alert(CEC_ALERT_CONNECTION_LOST
, param
);
249 /* TODO sleep 5 ms so other threads can get a lock */
253 m_adapterMessageQueue
->Clear();
254 LIB_CEC
->AddLog(CEC_LOG_DEBUG
, "communication thread ended");
258 bool CUSBCECAdapterCommunication::HandlePoll(const CCECAdapterMessage
&msg
)
260 bool bIsError(msg
.IsError());
261 cec_adapter_messagecode
messageCode(msg
.Message());
262 CLockObject
lock(m_mutex
);
264 if (messageCode
== MSGCODE_FRAME_START
&& msg
.IsACK())
266 m_lastPollDestination
= msg
.Destination();
267 if (msg
.Destination() < CECDEVICE_BROADCAST
)
269 if (!m_bWaitingForAck
[msg
.Destination()] && !msg
.IsEOM())
272 m_callback
->HandlePoll(msg
.Initiator(), msg
.Destination());
275 m_bWaitingForAck
[msg
.Destination()] = false;
278 else if (messageCode
== MSGCODE_RECEIVE_FAILED
)
280 /* hack to suppress warnings when an LG is polling */
281 if (m_lastPollDestination
!= CECDEVICE_UNKNOWN
)
282 bIsError
= m_callback
->HandleReceiveFailed(m_lastPollDestination
);
288 void CUSBCECAdapterCommunication::MarkAsWaiting(const cec_logical_address dest
)
290 /* mark as waiting for an ack from the destination */
291 if (dest
< CECDEVICE_BROADCAST
)
293 CLockObject
lock(m_mutex
);
294 m_bWaitingForAck
[dest
] = true;
298 void CUSBCECAdapterCommunication::ClearInputBytes(uint32_t iTimeout
/* = CEC_CLEAR_INPUT_DEFAULT_WAIT */)
300 CTimeout
timeout(iTimeout
);
302 ssize_t
iBytesRead(0);
303 bool bGotMsgEnd(true);
305 while (timeout
.TimeLeft() > 0 && ((iBytesRead
= m_port
->Read(buff
, 1024, 5)) > 0 || !bGotMsgEnd
))
308 /* if something was received, wait for MSGEND */
309 for (ssize_t iPtr
= 0; iPtr
< iBytesRead
; iPtr
++)
310 bGotMsgEnd
= buff
[iPtr
] == MSGEND
;
314 bool CUSBCECAdapterCommunication::SetLineTimeout(uint8_t iTimeout
)
317 bool bChanged(false);
319 /* only send the command if the timeout changed */
321 CLockObject
lock(m_mutex
);
322 bChanged
= (m_iLineTimeout
!= iTimeout
);
323 m_iLineTimeout
= iTimeout
;
327 bReturn
= m_commands
->SetLineTimeout(iTimeout
);
332 bool CUSBCECAdapterCommunication::WriteToDevice(CCECAdapterMessage
*message
)
334 CLockObject
adapterLock(m_mutex
);
337 LIB_CEC
->AddLog(CEC_LOG_DEBUG
, "error writing command '%s' to serial port '%s': the connection is closed", CCECAdapterMessage::ToString(message
->Message()), m_port
->GetName().c_str());
338 message
->state
= ADAPTER_MESSAGE_STATE_ERROR
;
342 /* write the message */
343 if (m_port
->Write(message
->packet
.data
, message
->Size()) != (ssize_t
) message
->Size())
345 LIB_CEC
->AddLog(CEC_LOG_DEBUG
, "error writing command '%s' to serial port '%s': %s", CCECAdapterMessage::ToString(message
->Message()), m_port
->GetName().c_str(), m_port
->GetError().c_str());
346 message
->state
= ADAPTER_MESSAGE_STATE_ERROR
;
347 // this will trigger an alert in the reader thread
352 LIB_CEC
->AddLog(CEC_LOG_DEBUG
, "command '%s' sent", message
->IsTranmission() ? "CEC transmission" : CCECAdapterMessage::ToString(message
->Message()));
353 message
->state
= ADAPTER_MESSAGE_STATE_SENT
;
357 bool CUSBCECAdapterCommunication::ReadFromDevice(uint32_t iTimeout
, size_t iSize
/* = 256 */)
359 ssize_t
iBytesRead(0);
364 /* read from the serial port */
366 CLockObject
lock(m_mutex
);
370 iBytesRead
= m_port
->Read(buff
, sizeof(uint8_t) * iSize
, iTimeout
);
372 if (m_port
->GetErrorNumber())
374 LIB_CEC
->AddLog(CEC_LOG_ERROR
, "error reading from serial port: %s", m_port
->GetError().c_str());
380 if (iBytesRead
< 0 || iBytesRead
> 256)
382 else if (iBytesRead
> 0)
384 /* add the data to the current frame */
385 m_adapterMessageQueue
->AddData(buff
, iBytesRead
);
391 CCECAdapterMessage
*CUSBCECAdapterCommunication::SendCommand(cec_adapter_messagecode msgCode
, CCECAdapterMessage
¶ms
, bool bIsRetry
/* = false */)
393 if (!IsOpen() || !m_adapterMessageQueue
)
396 /* create the adapter message for this command */
397 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
398 output
->PushBack(MSGSTART
);
399 output
->PushEscaped((uint8_t)msgCode
);
400 output
->Append(params
);
401 output
->PushBack(MSGEND
);
403 /* write the command */
404 if (!m_adapterMessageQueue
->Write(output
))
406 // this will trigger an alert in the reader thread
407 if (output
->state
== ADAPTER_MESSAGE_STATE_ERROR
)
413 if (!bIsRetry
&& output
->Reply() == MSGCODE_COMMAND_REJECTED
&& msgCode
!= MSGCODE_SET_CONTROLLED
&&
414 msgCode
!= MSGCODE_GET_BUILDDATE
/* same messagecode value had a different meaning in older fw builds */)
416 /* if the controller reported that the command was rejected, and we didn't send the command
417 to set controlled mode, then the controller probably switched to auto mode. set controlled
419 LIB_CEC
->AddLog(CEC_LOG_DEBUG
, "setting controlled mode and retrying");
421 if (SetControlledMode(true))
422 return SendCommand(msgCode
, params
, true);
429 bool CUSBCECAdapterCommunication::CheckAdapter(uint32_t iTimeoutMs
/* = CEC_DEFAULT_CONNECT_TIMEOUT */)
432 CTimeout
timeout(iTimeoutMs
> 0 ? iTimeoutMs
: CEC_DEFAULT_TRANSMIT_WAIT
);
434 /* try to ping the adapter */
436 unsigned iPingTry(0);
437 while (timeout
.TimeLeft() > 0 && (bPinged
= PingAdapter()) == false)
439 LIB_CEC
->AddLog(CEC_LOG_ERROR
, "the adapter did not respond correctly to a ping (try %d)", ++iPingTry
);
443 /* try to read the firmware version */
444 if (bPinged
&& timeout
.TimeLeft() > 0 && m_commands
->RequestFirmwareVersion() >= 2)
446 /* try to set controlled mode for v2+ firmwares */
447 unsigned iControlledTry(0);
448 bool bControlled(false);
449 while (timeout
.TimeLeft() > 0 && (bControlled
= SetControlledMode(true)) == false)
451 LIB_CEC
->AddLog(CEC_LOG_ERROR
, "the adapter did not respond correctly to setting controlled mode (try %d)", ++iControlledTry
);
454 bReturn
= bControlled
;
459 /* try to read the build date */
460 m_commands
->RequestBuildDate();
462 SetInitialised(bReturn
);
466 bool CUSBCECAdapterCommunication::IsOpen(void)
468 /* thread is not being stopped, the port is open and the thread is running */
469 return !IsStopped() && m_port
->IsOpen() && IsRunning();
472 CStdString
CUSBCECAdapterCommunication::GetError(void) const
474 return m_port
->GetError();
477 void CUSBCECAdapterCommunication::SetInitialised(bool bSetTo
/* = true */)
479 CLockObject
lock(m_mutex
);
480 m_bInitialised
= bSetTo
;
483 bool CUSBCECAdapterCommunication::IsInitialised(void)
485 CLockObject
lock(m_mutex
);
486 return m_bInitialised
;
489 bool CUSBCECAdapterCommunication::StartBootloader(void)
491 if (m_port
->IsOpen() && m_commands
->StartBootloader())
499 bool CUSBCECAdapterCommunication::SetAckMask(uint16_t iMask
)
502 CLockObject
lock(m_mutex
);
503 if (m_iAckMask
== iMask
)
507 if (IsOpen() && m_commands
->SetAckMask(iMask
))
509 CLockObject
lock(m_mutex
);
514 LIB_CEC
->AddLog(CEC_LOG_ERROR
, "couldn't change the ackmask: the connection is closed");
518 uint16_t CUSBCECAdapterCommunication::GetAckMask(void)
520 CLockObject
lock(m_mutex
);
524 bool CUSBCECAdapterCommunication::PingAdapter(void)
526 return IsOpen() ? m_commands
->PingAdapter() : false;
529 uint16_t CUSBCECAdapterCommunication::GetFirmwareVersion(void)
531 return IsOpen() ? m_commands
->GetFirmwareVersion() : CEC_FW_VERSION_UNKNOWN
;
534 uint32_t CUSBCECAdapterCommunication::GetFirmwareBuildDate(void)
536 return IsOpen() ? m_commands
->RequestBuildDate() : 0;
539 bool CUSBCECAdapterCommunication::IsRunningLatestFirmware(void)
541 return GetFirmwareVersion() >= CEC_LATEST_ADAPTER_FW_VERSION
&&
542 GetFirmwareBuildDate() >= CEC_LATEST_ADAPTER_FW_DATE
;
545 bool CUSBCECAdapterCommunication::PersistConfiguration(const libcec_configuration
&configuration
)
547 return IsOpen() ? m_commands
->PersistConfiguration(configuration
) : false;
550 bool CUSBCECAdapterCommunication::GetConfiguration(libcec_configuration
&configuration
)
552 return IsOpen() ? m_commands
->GetConfiguration(configuration
) : false;
555 CStdString
CUSBCECAdapterCommunication::GetPortName(void)
557 return m_port
->GetName();
560 bool CUSBCECAdapterCommunication::SetControlledMode(bool controlled
)
562 return IsOpen() ? m_commands
->SetControlledMode(controlled
) : false;
565 uint16_t CUSBCECAdapterCommunication::GetPhysicalAddress(void)
569 // try to get the PA from ADL
570 #if defined(HAS_ADL_EDID_PARSER)
572 LIB_CEC
->AddLog(CEC_LOG_DEBUG
, "%s - trying to get the physical address via ADL", __FUNCTION__
);
574 iPA
= adl
.GetPhysicalAddress();
575 LIB_CEC
->AddLog(CEC_LOG_DEBUG
, "%s - ADL returned physical address %04x", __FUNCTION__
, iPA
);
579 // try to get the PA from the OS
582 LIB_CEC
->AddLog(CEC_LOG_DEBUG
, "%s - trying to get the physical address from the OS", __FUNCTION__
);
583 iPA
= CEDIDParser::GetPhysicalAddress();
584 LIB_CEC
->AddLog(CEC_LOG_DEBUG
, "%s - OS returned physical address %04x", __FUNCTION__
, iPA
);
590 void *CAdapterPingThread::Process(void)
594 if (m_timeout
.TimeLeft() == 0)
596 /* reinit the timeout */
597 m_timeout
.Init(CEC_ADAPTER_PING_TIMEOUT
);
599 /* send a ping to the adapter */
601 int iFailedCounter(0);
602 while (!bPinged
&& iFailedCounter
< 3)
604 if (!m_com
->PingAdapter())
606 /* sleep and retry */
607 Sleep(CEC_DEFAULT_TRANSMIT_RETRY_WAIT
);
616 if (iFailedCounter
== 3)
618 /* failed to ping the adapter 3 times in a row. something must be wrong with the connection */
619 m_com
->LIB_CEC
->AddLog(CEC_LOG_ERROR
, "failed to ping the adapter 3 times in a row. closing the connection.");
620 m_com
->StopThread(false);