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::Open(IAdapterCommunicationCallback
*cb
, uint32_t iTimeoutMs
/* = 10000 */)
62 uint64_t iNow
= GetTimeMs();
63 uint64_t iTimeout
= iNow
+ iTimeoutMs
;
65 CLockObject
lock(m_mutex
);
69 CLibCEC::AddLog(CEC_LOG_ERROR
, "port is NULL");
75 CLibCEC::AddLog(CEC_LOG_ERROR
, "port is already open");
81 bool bConnected(false);
82 while (!bConnected
&& iNow
< iTimeout
)
84 if ((bConnected
= m_port
->Open(iTimeout
)) == false)
86 strError
.Format("error opening serial port '%s': %s", m_port
->GetName().c_str(), m_port
->GetError().c_str());
94 CLibCEC::AddLog(CEC_LOG_ERROR
, strError
);
98 CLibCEC::AddLog(CEC_LOG_DEBUG
, "connection opened, clearing any previous input and waiting for active transmissions to end before starting");
100 //clear any input bytes
102 while (m_port
->Read(buff
, 1024, 100) > 0)
104 CLibCEC::AddLog(CEC_LOG_DEBUG
, "data received, clearing it");
110 CLibCEC::AddLog(CEC_LOG_DEBUG
, "communication thread started");
115 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not create a communication thread");
121 void CUSBCECAdapterCommunication::Close(void)
123 CLockObject
lock(m_mutex
);
124 m_rcvCondition
.Broadcast();
128 void *CUSBCECAdapterCommunication::Process(void)
135 /* push the next command to the callback method if there is one */
136 if (m_callback
&& Read(command
, 0))
137 m_callback
->OnCommandReceived(command
);
143 CCECAdapterMessage
*msg(NULL
);
144 if (m_outBuffer
.Pop(msg
))
145 msg
->condition
.Broadcast();
156 cec_adapter_message_state
CUSBCECAdapterCommunication::Write(const cec_command
&data
, uint8_t iMaxTries
, uint8_t iLineTimeout
/* = 3 */, uint8_t iRetryLineTimeout
/* = 3 */)
158 cec_adapter_message_state
retVal(ADAPTER_MESSAGE_STATE_UNKNOWN
);
160 CCECAdapterMessage
*output
= new CCECAdapterMessage(data
);
162 /* set the number of retries */
163 if (data
.opcode
== CEC_OPCODE_NONE
) //TODO
164 output
->maxTries
= 1;
165 else if (data
.initiator
!= CECDEVICE_BROADCAST
)
166 output
->maxTries
= iMaxTries
;
168 output
->lineTimeout
= iLineTimeout
;
169 output
->retryTimeout
= iRetryLineTimeout
;
173 while (bRetry
&& ++output
->tries
< output
->maxTries
)
175 bRetry
= (!Write(output
) || output
->NeedsRetry()) && output
->transmit_timeout
> 0;
177 Sleep(CEC_DEFAULT_TRANSMIT_RETRY_WAIT
);
179 retVal
= output
->state
;
185 bool CUSBCECAdapterCommunication::Write(CCECAdapterMessage
*data
)
187 CLockObject
lock(data
->mutex
);
188 data
->state
= ADAPTER_MESSAGE_STATE_WAITING_TO_BE_SENT
;
189 m_outBuffer
.Push(data
);
190 data
->condition
.Wait(data
->mutex
);
192 if ((data
->expectControllerAck
&& data
->state
!= ADAPTER_MESSAGE_STATE_SENT_ACKED
) ||
193 (!data
->expectControllerAck
&& data
->state
!= ADAPTER_MESSAGE_STATE_SENT
))
195 CLibCEC::AddLog(CEC_LOG_DEBUG
, "command was not %s", data
->state
== ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED
? "acked" : "sent");
202 bool CUSBCECAdapterCommunication::Read(cec_command
&command
, uint32_t iTimeout
)
204 CCECAdapterMessage msg
;
205 if (Read(msg
, iTimeout
))
207 if (ParseMessage(msg
))
209 command
= m_currentframe
;
210 m_currentframe
.Clear();
217 bool CUSBCECAdapterCommunication::Read(CCECAdapterMessage
&msg
, uint32_t iTimeout
)
219 CLockObject
lock(m_mutex
);
222 CCECAdapterMessage
*buf(NULL
);
224 if (!m_inBuffer
.Pop(buf
))
226 if (iTimeout
== 0 || !m_rcvCondition
.Wait(m_mutex
, iTimeout
))
233 msg
.packet
= buf
->packet
;
234 msg
.state
= msg
.state
= ADAPTER_MESSAGE_STATE_INCOMING
;
241 CStdString
CUSBCECAdapterCommunication::GetError(void) const
244 strError
= m_port
->GetError();
248 bool CUSBCECAdapterCommunication::StartBootloader(void)
254 CLibCEC::AddLog(CEC_LOG_DEBUG
, "starting the bootloader");
255 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
257 output
->PushBack(MSGSTART
);
258 output
->PushEscaped(MSGCODE_START_BOOTLOADER
);
259 output
->PushBack(MSGEND
);
260 output
->isTransmission
= false;
261 output
->expectControllerAck
= false;
263 if ((bReturn
= Write(output
)) == false)
264 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not start the bootloader");
270 bool CUSBCECAdapterCommunication::PingAdapter(void)
276 CLibCEC::AddLog(CEC_LOG_DEBUG
, "sending ping");
277 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
279 output
->PushBack(MSGSTART
);
280 output
->PushEscaped(MSGCODE_PING
);
281 output
->PushBack(MSGEND
);
282 output
->isTransmission
= false;
284 if ((bReturn
= Write(output
)) == false)
285 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not ping the adapter");
291 bool CUSBCECAdapterCommunication::ParseMessage(const CCECAdapterMessage
&msg
)
294 bool bIsError(msg
.IsError());
299 switch(msg
.Message())
301 case MSGCODE_FRAME_START
:
303 m_currentframe
.Clear();
306 m_currentframe
.initiator
= msg
.Initiator();
307 m_currentframe
.destination
= msg
.Destination();
308 m_currentframe
.ack
= msg
.IsACK();
309 m_currentframe
.eom
= msg
.IsEOM();
311 if (m_currentframe
.ack
== 0x1)
313 m_lastInitiator
= m_currentframe
.initiator
;
314 m_processor
->HandlePoll(m_currentframe
.initiator
, m_currentframe
.destination
);
318 case MSGCODE_RECEIVE_FAILED
:
320 m_currentframe
.Clear();
321 if (m_lastInitiator
!= CECDEVICE_UNKNOWN
)
322 bIsError
= m_processor
->HandleReceiveFailed(m_lastInitiator
);
325 case MSGCODE_FRAME_DATA
:
329 m_currentframe
.PushBack(msg
[1]);
330 m_currentframe
.eom
= msg
.IsEOM();
339 CLibCEC::AddLog(bIsError
? CEC_LOG_WARNING
: CEC_LOG_DEBUG
, msg
.ToString());
343 uint16_t CUSBCECAdapterCommunication::GetFirmwareVersion(void)
345 uint16_t iReturn(m_iFirmwareVersion
);
349 if (iReturn
== CEC_FW_VERSION_UNKNOWN
)
351 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting the firmware version");
352 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
354 output
->PushBack(MSGSTART
);
355 output
->PushEscaped(MSGCODE_FIRMWARE_VERSION
);
356 output
->PushBack(MSGEND
);
357 output
->isTransmission
= false;
358 output
->expectControllerAck
= false;
360 bool bWriteOk
= Write(output
);
364 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not request the firmware version");
368 ReadFromDevice(CEC_DEFAULT_TRANSMIT_WAIT
, 5 /* start + msgcode + 2 bytes for fw version + end */);
369 CCECAdapterMessage input
;
370 if (!Read(input
, 0) || input
.Message() != MSGCODE_FIRMWARE_VERSION
|| input
.Size() != 3)
371 CLibCEC::AddLog(CEC_LOG_ERROR
, "no or invalid firmware version (size = %d, message = %d)", input
.Size(), input
.Message());
374 m_iFirmwareVersion
= (input
[1] << 8 | input
[2]);
375 iReturn
= m_iFirmwareVersion
;
383 bool CUSBCECAdapterCommunication::SetLineTimeout(uint8_t iTimeout
)
385 m_iLineTimeout
= iTimeout
;
388 // bool bReturn(m_iLineTimeout != iTimeout);
392 // CCECAdapterMessage *output = new CCECAdapterMessage;
394 // output->PushBack(MSGSTART);
395 // output->PushEscaped(MSGCODE_TRANSMIT_IDLETIME);
396 // output->PushEscaped(iTimeout);
397 // output->PushBack(MSGEND);
398 // output->isTransmission = false;
400 // if ((bReturn = Write(output)) == false)
401 // CLibCEC::AddLog(CEC_LOG_ERROR, "could not set the idletime");
408 bool CUSBCECAdapterCommunication::SetAckMask(uint16_t iMask
)
411 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting ackmask to %2x", iMask
);
413 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
415 output
->PushBack(MSGSTART
);
416 output
->PushEscaped(MSGCODE_SET_ACK_MASK
);
417 output
->PushEscaped(iMask
>> 8);
418 output
->PushEscaped((uint8_t)iMask
);
419 output
->PushBack(MSGEND
);
420 output
->isTransmission
= false;
422 if ((bReturn
= Write(output
)) == false)
423 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not set the ackmask");
430 bool CUSBCECAdapterCommunication::SetControlledMode(bool controlled
)
433 CLibCEC::AddLog(CEC_LOG_DEBUG
, "turning controlled mode %s", controlled
? "on" : "off");
435 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
437 output
->PushBack(MSGSTART
);
438 output
->PushEscaped(MSGCODE_SET_CONTROLLED
);
439 output
->PushEscaped(controlled
);
440 output
->PushBack(MSGEND
);
441 output
->isTransmission
= false;
443 if ((bReturn
= Write(output
)) == false)
444 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not set controlled mode");
450 bool CUSBCECAdapterCommunication::IsOpen(void)
452 return !IsStopped() && m_port
->IsOpen() && IsRunning();
455 bool CUSBCECAdapterCommunication::WaitForAck(CCECAdapterMessage
&message
)
458 bool bTransmitSucceeded(false);
459 uint8_t iPacketsLeft(message
.Size() / 4);
461 int64_t iNow
= GetTimeMs();
462 int64_t iTargetTime
= iNow
+ (message
.transmit_timeout
<= 5 ? CEC_DEFAULT_TRANSMIT_WAIT
: message
.transmit_timeout
);
464 while (!bTransmitSucceeded
&& !bError
&& iNow
< iTargetTime
)
467 CCECAdapterMessage msg
;
474 if (msg
.Message() == MSGCODE_FRAME_START
&& msg
.IsACK())
476 m_processor
->HandlePoll(msg
.Initiator(), msg
.Destination());
477 m_lastInitiator
= msg
.Initiator();
482 if (msg
.Message() == MSGCODE_RECEIVE_FAILED
&&
483 m_lastInitiator
!= CECDEVICE_UNKNOWN
&&
484 m_processor
->HandleReceiveFailed(m_lastInitiator
))
490 bError
= msg
.IsError();
493 message
.reply
= msg
.Message();
494 CLibCEC::AddLog(CEC_LOG_DEBUG
, msg
.ToString());
498 switch(msg
.Message())
500 case MSGCODE_COMMAND_ACCEPTED
:
501 CLibCEC::AddLog(CEC_LOG_DEBUG
, msg
.ToString());
502 if (iPacketsLeft
> 0)
504 if (!message
.isTransmission
&& iPacketsLeft
== 0)
505 bTransmitSucceeded
= true;
507 case MSGCODE_TRANSMIT_SUCCEEDED
:
508 CLibCEC::AddLog(CEC_LOG_DEBUG
, msg
.ToString());
509 bTransmitSucceeded
= (iPacketsLeft
== 0);
510 bError
= !bTransmitSucceeded
;
511 message
.reply
= MSGCODE_TRANSMIT_SUCCEEDED
;
514 // ignore other data while waiting
522 message
.state
= bTransmitSucceeded
&& !bError
?
523 ADAPTER_MESSAGE_STATE_SENT_ACKED
:
524 ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED
;
526 return bTransmitSucceeded
&& !bError
;
529 void CUSBCECAdapterCommunication::AddData(uint8_t *data
, size_t iLen
)
531 CLockObject
lock(m_mutex
);
532 for (size_t iPtr
= 0; iPtr
< iLen
; iPtr
++)
536 if (data
[iPtr
] == MSGSTART
)
539 else if (data
[iPtr
] == MSGSTART
) //we found a msgstart before msgend, this is not right, remove
541 if (m_currentAdapterMessage
.Size() > 0)
542 CLibCEC::AddLog(CEC_LOG_WARNING
, "received MSGSTART before MSGEND, removing previous buffer contents");
543 m_currentAdapterMessage
.Clear();
546 else if (data
[iPtr
] == MSGEND
)
548 CCECAdapterMessage
*newMessage
= new CCECAdapterMessage
;
549 newMessage
->packet
= m_currentAdapterMessage
.packet
;
550 m_inBuffer
.Push(newMessage
);
551 m_currentAdapterMessage
.Clear();
553 m_bNextIsEscaped
= false;
554 m_rcvCondition
.Signal();
556 else if (m_bNextIsEscaped
)
558 m_currentAdapterMessage
.PushBack(data
[iPtr
] + (uint8_t)ESCOFFSET
);
559 m_bNextIsEscaped
= false;
561 else if (data
[iPtr
] == MSGESC
)
563 m_bNextIsEscaped
= true;
567 m_currentAdapterMessage
.PushBack(data
[iPtr
]);
572 bool CUSBCECAdapterCommunication::ReadFromDevice(uint32_t iTimeout
, size_t iSize
/* = 256 */)
581 CLockObject
lock(m_mutex
);
582 iBytesRead
= m_port
->Read(buff
, sizeof(uint8_t) * iSize
, iTimeout
);
583 if (iBytesRead
< 0 || iBytesRead
> 256)
585 CLibCEC::AddLog(CEC_LOG_ERROR
, "error reading from serial port: %s", m_port
->GetError().c_str());
588 else if (iBytesRead
> 0)
590 AddData(buff
, iBytesRead
);
593 return iBytesRead
> 0;
596 void CUSBCECAdapterCommunication::SendMessageToAdapter(CCECAdapterMessage
*msg
)
598 CLockObject
adapterLock(m_mutex
);
599 CLockObject
lock(msg
->mutex
);
601 SetLineTimeout(msg
->lineTimeout
);
603 SetLineTimeout(msg
->retryTimeout
);
605 if (m_port
->Write(msg
->packet
.data
, msg
->Size()) != (ssize_t
) msg
->Size())
607 CLibCEC::AddLog(CEC_LOG_ERROR
, "error writing to serial port: %s", m_port
->GetError().c_str());
608 msg
->state
= ADAPTER_MESSAGE_STATE_ERROR
;
612 CLibCEC::AddLog(CEC_LOG_DEBUG
, "command sent");
613 msg
->state
= ADAPTER_MESSAGE_STATE_SENT
;
615 if (msg
->expectControllerAck
)
617 if (!WaitForAck(*msg
))
618 CLibCEC::AddLog(CEC_LOG_DEBUG
, "did not receive ack");
621 msg
->condition
.Signal();
624 void CUSBCECAdapterCommunication::WriteNextCommand(void)
626 CCECAdapterMessage
*msg(NULL
);
627 if (m_outBuffer
.Pop(msg
))
628 SendMessageToAdapter(msg
);