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 "../LibCEC.h"
40 #include "../CECProcessor.h"
44 using namespace PLATFORM
;
46 #define CEC_ADAPTER_PING_TIMEOUT 15000
49 #define CEC_LATEST_ADAPTER_FW_VERSION 2
50 // firmware date Thu Apr 26 20:14:49 2012 +0000
51 #define CEC_LATEST_ADAPTER_FW_DATE 0x4F99ACB9
53 #define LIB_CEC m_callback->GetLib()
55 CUSBCECAdapterCommunication::CUSBCECAdapterCommunication(IAdapterCommunicationCallback
*callback
, const char *strPort
, uint16_t iBaudRate
/* = CEC_SERIAL_DEFAULT_BAUDRATE */) :
56 IAdapterCommunication(callback
),
59 m_lastPollDestination(CECDEVICE_UNKNOWN
),
60 m_bInitialised(false),
63 m_adapterMessageQueue(NULL
),
66 for (unsigned int iPtr
= CECDEVICE_TV
; iPtr
< CECDEVICE_BROADCAST
; iPtr
++)
67 m_bWaitingForAck
[iPtr
] = false;
68 m_port
= new CSerialPort(strPort
, iBaudRate
);
71 CUSBCECAdapterCommunication::~CUSBCECAdapterCommunication(void)
74 DELETE_AND_NULL(m_commands
);
75 DELETE_AND_NULL(m_adapterMessageQueue
);
76 DELETE_AND_NULL(m_port
);
79 bool CUSBCECAdapterCommunication::Open(uint32_t iTimeoutMs
/* = CEC_DEFAULT_CONNECT_TIMEOUT */, bool bSkipChecks
/* = false */, bool bStartListening
/* = true */)
81 bool bConnectionOpened(false);
83 CLockObject
lock(m_mutex
);
85 /* we need the port settings here */
88 LIB_CEC
->AddLog(CEC_LOG_ERROR
, "port is NULL");
89 return bConnectionOpened
;
92 /* return true when the port is already open */
95 LIB_CEC
->AddLog(CEC_LOG_WARNING
, "port is already open");
99 /* adapter commands */
101 m_commands
= new CUSBCECAdapterCommands(this);
103 if (!m_adapterMessageQueue
)
105 m_adapterMessageQueue
= new CCECAdapterMessageQueue(this);
106 m_adapterMessageQueue
->CreateThread();
109 /* try to open the connection */
111 CTimeout
timeout(iTimeoutMs
);
112 while (!bConnectionOpened
&& timeout
.TimeLeft() > 0)
114 if ((bConnectionOpened
= m_port
->Open(timeout
.TimeLeft())) == false)
116 strError
.Format("error opening serial port '%s': %s", m_port
->GetName().c_str(), m_port
->GetError().c_str());
119 /* and retry every 250ms until the timeout passed */
122 /* return false when we couldn't connect */
123 if (!bConnectionOpened
)
125 LIB_CEC
->AddLog(CEC_LOG_ERROR
, strError
);
127 if (m_port
->GetErrorNumber() == EACCES
)
129 libcec_parameter param
;
130 param
.paramType
= CEC_PARAMETER_TYPE_STRING
;
131 param
.paramData
= (void*)"No permission to open the device";
132 LIB_CEC
->Alert(CEC_ALERT_PERMISSION_ERROR
, param
);
134 else if (m_port
->GetErrorNumber() == EBUSY
)
136 libcec_parameter param
;
137 param
.paramType
= CEC_PARAMETER_TYPE_STRING
;
138 param
.paramData
= (void*)"The serial port is busy. Only one program can access the device directly.";
139 LIB_CEC
->Alert(CEC_ALERT_PORT_BUSY
, param
);
144 LIB_CEC
->AddLog(CEC_LOG_DEBUG
, "connection opened, clearing any previous input and waiting for active transmissions to end before starting");
150 bConnectionOpened
= false;
151 LIB_CEC
->AddLog(CEC_LOG_ERROR
, "could not create a communication thread");
153 else if (!bSkipChecks
&& !CheckAdapter())
155 bConnectionOpened
= false;
156 LIB_CEC
->AddLog(CEC_LOG_ERROR
, "the adapter failed to pass basic checks");
158 else if (bStartListening
)
160 /* start a ping thread, that will ping the adapter every 15 seconds
161 if it doesn't receive any ping for 30 seconds, it'll switch to auto mode */
162 m_pingThread
= new CAdapterPingThread(this, CEC_ADAPTER_PING_TIMEOUT
);
163 if (m_pingThread
->CreateThread())
165 bConnectionOpened
= true;
169 bConnectionOpened
= false;
170 LIB_CEC
->AddLog(CEC_LOG_ERROR
, "could not create a ping thread");
174 if (!bConnectionOpened
|| !bStartListening
)
177 return bConnectionOpened
;
180 void CUSBCECAdapterCommunication::Close(void)
182 /* stop the reader thread */
185 CLockObject
lock(m_mutex
);
187 /* set the ackmask to 0 before closing the connection */
188 if (IsOpen() && m_port
->GetErrorNumber() == 0)
190 LIB_CEC
->AddLog(CEC_LOG_DEBUG
, "%s - closing the connection", __FUNCTION__
);
192 if (m_commands
->GetFirmwareVersion() >= 2)
193 SetControlledMode(false);
196 m_adapterMessageQueue
->Clear();
198 /* stop and delete the ping thread */
199 DELETE_AND_NULL(m_pingThread
);
201 /* close and delete the com port connection */
206 cec_adapter_message_state
CUSBCECAdapterCommunication::Write(const cec_command
&data
, bool &bRetry
, uint8_t iLineTimeout
)
208 cec_adapter_message_state
retVal(ADAPTER_MESSAGE_STATE_UNKNOWN
);
212 CCECAdapterMessage
*output
= new CCECAdapterMessage(data
, iLineTimeout
);
214 /* mark as waiting for an ack from the destination */
215 MarkAsWaiting(data
.destination
);
217 /* send the message */
218 bRetry
= (!m_adapterMessageQueue
->Write(output
) || output
->NeedsRetry()) && output
->transmit_timeout
> 0;
220 Sleep(CEC_DEFAULT_TRANSMIT_RETRY_WAIT
);
221 retVal
= output
->state
;
227 void *CUSBCECAdapterCommunication::Process(void)
229 CCECAdapterMessage msg
;
230 LIB_CEC
->AddLog(CEC_LOG_DEBUG
, "communication thread started");
234 /* read from the serial port */
235 if (!ReadFromDevice(50, 5))
237 libcec_parameter param
;
238 param
.paramData
= NULL
; param
.paramType
= CEC_PARAMETER_TYPE_UNKOWN
;
239 LIB_CEC
->Alert(CEC_ALERT_CONNECTION_LOST
, param
);
244 /* TODO sleep 5 ms so other threads can get a lock */
248 m_adapterMessageQueue
->Clear();
249 LIB_CEC
->AddLog(CEC_LOG_DEBUG
, "communication thread ended");
253 bool CUSBCECAdapterCommunication::HandlePoll(const CCECAdapterMessage
&msg
)
255 bool bIsError(msg
.IsError());
256 cec_adapter_messagecode
messageCode(msg
.Message());
257 CLockObject
lock(m_mutex
);
259 if (messageCode
== MSGCODE_FRAME_START
&& msg
.IsACK())
261 m_lastPollDestination
= msg
.Destination();
262 if (msg
.Destination() < CECDEVICE_BROADCAST
)
264 if (!m_bWaitingForAck
[msg
.Destination()] && !msg
.IsEOM())
267 m_callback
->HandlePoll(msg
.Initiator(), msg
.Destination());
270 m_bWaitingForAck
[msg
.Destination()] = false;
273 else if (messageCode
== MSGCODE_RECEIVE_FAILED
)
275 /* hack to suppress warnings when an LG is polling */
276 if (m_lastPollDestination
!= CECDEVICE_UNKNOWN
)
277 bIsError
= m_callback
->HandleReceiveFailed(m_lastPollDestination
);
283 void CUSBCECAdapterCommunication::MarkAsWaiting(const cec_logical_address dest
)
285 /* mark as waiting for an ack from the destination */
286 if (dest
< CECDEVICE_BROADCAST
)
288 CLockObject
lock(m_mutex
);
289 m_bWaitingForAck
[dest
] = true;
293 void CUSBCECAdapterCommunication::ClearInputBytes(uint32_t iTimeout
/* = CEC_CLEAR_INPUT_DEFAULT_WAIT */)
295 CTimeout
timeout(iTimeout
);
297 ssize_t
iBytesRead(0);
298 bool bGotMsgEnd(true);
300 while (timeout
.TimeLeft() > 0 && ((iBytesRead
= m_port
->Read(buff
, 1024, 5)) > 0 || !bGotMsgEnd
))
303 /* if something was received, wait for MSGEND */
304 for (ssize_t iPtr
= 0; iPtr
< iBytesRead
; iPtr
++)
305 bGotMsgEnd
= buff
[iPtr
] == MSGEND
;
309 bool CUSBCECAdapterCommunication::SetLineTimeout(uint8_t iTimeout
)
312 bool bChanged(false);
314 /* only send the command if the timeout changed */
316 CLockObject
lock(m_mutex
);
317 bChanged
= (m_iLineTimeout
!= iTimeout
);
318 m_iLineTimeout
= iTimeout
;
322 bReturn
= m_commands
->SetLineTimeout(iTimeout
);
327 bool CUSBCECAdapterCommunication::WriteToDevice(CCECAdapterMessage
*message
)
329 CLockObject
adapterLock(m_mutex
);
332 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());
333 message
->state
= ADAPTER_MESSAGE_STATE_ERROR
;
337 /* write the message */
338 if (m_port
->Write(message
->packet
.data
, message
->Size()) != (ssize_t
) message
->Size())
340 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());
341 message
->state
= ADAPTER_MESSAGE_STATE_ERROR
;
342 // this will trigger an alert in the reader thread
347 LIB_CEC
->AddLog(CEC_LOG_DEBUG
, "command '%s' sent", message
->IsTranmission() ? "CEC transmission" : CCECAdapterMessage::ToString(message
->Message()));
348 message
->state
= ADAPTER_MESSAGE_STATE_SENT
;
352 bool CUSBCECAdapterCommunication::ReadFromDevice(uint32_t iTimeout
, size_t iSize
/* = 256 */)
354 ssize_t
iBytesRead(0);
359 /* read from the serial port */
361 CLockObject
lock(m_mutex
);
365 iBytesRead
= m_port
->Read(buff
, sizeof(uint8_t) * iSize
, iTimeout
);
367 if (m_port
->GetErrorNumber())
369 LIB_CEC
->AddLog(CEC_LOG_ERROR
, "error reading from serial port: %s", m_port
->GetError().c_str());
375 if (iBytesRead
< 0 || iBytesRead
> 256)
377 else if (iBytesRead
> 0)
379 /* add the data to the current frame */
380 m_adapterMessageQueue
->AddData(buff
, iBytesRead
);
386 CCECAdapterMessage
*CUSBCECAdapterCommunication::SendCommand(cec_adapter_messagecode msgCode
, CCECAdapterMessage
¶ms
, bool bIsRetry
/* = false */)
388 if (!IsOpen() || !m_adapterMessageQueue
)
391 /* create the adapter message for this command */
392 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
393 output
->PushBack(MSGSTART
);
394 output
->PushEscaped((uint8_t)msgCode
);
395 output
->Append(params
);
396 output
->PushBack(MSGEND
);
398 /* write the command */
399 if (!m_adapterMessageQueue
->Write(output
))
401 // this will trigger an alert in the reader thread
402 if (output
->state
== ADAPTER_MESSAGE_STATE_ERROR
)
408 if (!bIsRetry
&& output
->Reply() == MSGCODE_COMMAND_REJECTED
&& msgCode
!= MSGCODE_SET_CONTROLLED
&&
409 msgCode
!= MSGCODE_GET_BUILDDATE
/* same messagecode value had a different meaning in older fw builds */)
411 /* if the controller reported that the command was rejected, and we didn't send the command
412 to set controlled mode, then the controller probably switched to auto mode. set controlled
414 LIB_CEC
->AddLog(CEC_LOG_DEBUG
, "setting controlled mode and retrying");
416 if (SetControlledMode(true))
417 return SendCommand(msgCode
, params
, true);
424 bool CUSBCECAdapterCommunication::CheckAdapter(uint32_t iTimeoutMs
/* = CEC_DEFAULT_CONNECT_TIMEOUT */)
427 CTimeout
timeout(iTimeoutMs
> 0 ? iTimeoutMs
: CEC_DEFAULT_TRANSMIT_WAIT
);
429 /* try to ping the adapter */
431 unsigned iPingTry(0);
432 while (timeout
.TimeLeft() > 0 && (bPinged
= PingAdapter()) == false)
434 LIB_CEC
->AddLog(CEC_LOG_ERROR
, "the adapter did not respond correctly to a ping (try %d)", ++iPingTry
);
438 /* try to read the firmware version */
439 if (bPinged
&& timeout
.TimeLeft() > 0 && m_commands
->RequestFirmwareVersion() >= 2)
441 /* try to set controlled mode for v2+ firmwares */
442 unsigned iControlledTry(0);
443 bool bControlled(false);
444 while (timeout
.TimeLeft() > 0 && (bControlled
= SetControlledMode(true)) == false)
446 LIB_CEC
->AddLog(CEC_LOG_ERROR
, "the adapter did not respond correctly to setting controlled mode (try %d)", ++iControlledTry
);
449 bReturn
= bControlled
;
454 /* try to read the build date */
455 m_commands
->RequestBuildDate();
457 SetInitialised(bReturn
);
461 bool CUSBCECAdapterCommunication::IsOpen(void)
463 /* thread is not being stopped, the port is open and the thread is running */
464 return !IsStopped() && m_port
->IsOpen() && IsRunning();
467 CStdString
CUSBCECAdapterCommunication::GetError(void) const
469 return m_port
->GetError();
472 void CUSBCECAdapterCommunication::SetInitialised(bool bSetTo
/* = true */)
474 CLockObject
lock(m_mutex
);
475 m_bInitialised
= bSetTo
;
478 bool CUSBCECAdapterCommunication::IsInitialised(void)
480 CLockObject
lock(m_mutex
);
481 return m_bInitialised
;
484 bool CUSBCECAdapterCommunication::StartBootloader(void)
486 if (m_port
->IsOpen() && m_commands
->StartBootloader())
494 bool CUSBCECAdapterCommunication::SetAckMask(uint16_t iMask
)
496 if (m_iAckMask
== iMask
)
499 if (IsOpen() && m_commands
->SetAckMask(iMask
))
505 LIB_CEC
->AddLog(CEC_LOG_ERROR
, "couldn't change the ackmask: the connection is closed");
509 uint16_t CUSBCECAdapterCommunication::GetAckMask(void)
514 bool CUSBCECAdapterCommunication::PingAdapter(void)
516 return IsOpen() ? m_commands
->PingAdapter() : false;
519 uint16_t CUSBCECAdapterCommunication::GetFirmwareVersion(void)
521 return IsOpen() ? m_commands
->GetFirmwareVersion() : CEC_FW_VERSION_UNKNOWN
;
524 uint32_t CUSBCECAdapterCommunication::GetFirmwareBuildDate(void)
526 return IsOpen() ? m_commands
->RequestBuildDate() : 0;
529 bool CUSBCECAdapterCommunication::IsRunningLatestFirmware(void)
531 return GetFirmwareVersion() >= CEC_LATEST_ADAPTER_FW_VERSION
&&
532 GetFirmwareBuildDate() >= CEC_LATEST_ADAPTER_FW_DATE
;
535 bool CUSBCECAdapterCommunication::PersistConfiguration(const libcec_configuration
&configuration
)
537 return IsOpen() ? m_commands
->PersistConfiguration(configuration
) : false;
540 bool CUSBCECAdapterCommunication::GetConfiguration(libcec_configuration
&configuration
)
542 return IsOpen() ? m_commands
->GetConfiguration(configuration
) : false;
545 CStdString
CUSBCECAdapterCommunication::GetPortName(void)
547 return m_port
->GetName();
550 bool CUSBCECAdapterCommunication::SetControlledMode(bool controlled
)
552 return IsOpen() ? m_commands
->SetControlledMode(controlled
) : false;
555 void *CAdapterPingThread::Process(void)
559 if (m_timeout
.TimeLeft() == 0)
561 /* reinit the timeout */
562 m_timeout
.Init(CEC_ADAPTER_PING_TIMEOUT
);
564 /* send a ping to the adapter */
566 int iFailedCounter(0);
567 while (!bPinged
&& iFailedCounter
< 3)
569 if (!m_com
->PingAdapter())
571 /* sleep and retry */
572 Sleep(CEC_DEFAULT_TRANSMIT_RETRY_WAIT
);
581 if (iFailedCounter
== 3)
583 /* failed to ping the adapter 3 times in a row. something must be wrong with the connection */
584 m_com
->LIB_CEC
->AddLog(CEC_LOG_ERROR
, "failed to ping the adapter 3 times in a row. closing the connection.");
585 m_com
->StopThread(false);