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 #define CEC_ADAPTER_PING_TIMEOUT 15000
45 CUSBCECAdapterCommunication::CUSBCECAdapterCommunication(CCECProcessor
*processor
, const char *strPort
, uint16_t iBaudRate
/* = 38400 */) :
47 m_processor(processor
),
50 m_iFirmwareVersion(CEC_FW_VERSION_UNKNOWN
),
51 m_lastDestination(CECDEVICE_UNKNOWN
),
52 m_bNextIsEscaped(false),
54 m_bInitialised(false),
57 for (unsigned int iPtr
= 0; iPtr
< 15; iPtr
++)
58 m_bWaitingForAck
[iPtr
] = false;
59 m_port
= new CSerialPort(strPort
, iBaudRate
);
62 bool CUSBCECAdapterCommunication::CheckAdapter(uint32_t iTimeoutMs
/* = 10000 */)
65 uint64_t iNow
= GetTimeMs();
66 uint64_t iTarget
= iTimeoutMs
> 0 ? iNow
+ iTimeoutMs
: iNow
+ CEC_DEFAULT_TRANSMIT_WAIT
;
68 /* try to ping the adapter */
71 while (iNow
< iTarget
&& (bPinged
= PingAdapter()) == false)
73 CLibCEC::AddLog(CEC_LOG_ERROR
, "the adapter did not respond correctly to a ping (try %d)", ++iPingTry
);
78 /* try to read the firmware version */
79 m_iFirmwareVersion
= CEC_FW_VERSION_UNKNOWN
;
80 unsigned iFwVersionTry(0);
81 while (bPinged
&& iNow
< iTarget
&& (m_iFirmwareVersion
= GetFirmwareVersion()) == CEC_FW_VERSION_UNKNOWN
&& iFwVersionTry
< 3)
83 CLibCEC::AddLog(CEC_LOG_WARNING
, "the adapter did not respond with a correct firmware version (try %d)", ++iFwVersionTry
);
88 if (m_iFirmwareVersion
== CEC_FW_VERSION_UNKNOWN
)
90 CLibCEC::AddLog(CEC_LOG_DEBUG
, "defaulting to firmware version 1");
91 m_iFirmwareVersion
= 1;
94 if (m_iFirmwareVersion
>= 2)
96 /* try to set controlled mode */
97 unsigned iControlledTry(0);
98 bool bControlled(false);
99 while (iNow
< iTarget
&& (bControlled
= SetControlledMode(true)) == false)
101 CLibCEC::AddLog(CEC_LOG_ERROR
, "the adapter did not respond correctly to setting controlled mode (try %d)", ++iControlledTry
);
105 bReturn
= bControlled
;
111 CLockObject
lock(m_mutex
);
112 m_bInitialised
= bReturn
;
118 bool CUSBCECAdapterCommunication::Open(IAdapterCommunicationCallback
*cb
, uint32_t iTimeoutMs
/* = 10000 */, bool bSkipChecks
/* = false */, bool bStartListening
/* = true */)
120 uint64_t iNow
= GetTimeMs();
121 uint64_t iTimeout
= iNow
+ iTimeoutMs
;
124 CLockObject
lock(m_mutex
);
128 CLibCEC::AddLog(CEC_LOG_ERROR
, "port is NULL");
134 CLibCEC::AddLog(CEC_LOG_ERROR
, "port is already open");
140 bool bConnected(false);
141 while (!bConnected
&& iNow
< iTimeout
)
143 if ((bConnected
= m_port
->Open(iTimeout
)) == false)
145 strError
.Format("error opening serial port '%s': %s", m_port
->GetName().c_str(), m_port
->GetError().c_str());
153 CLibCEC::AddLog(CEC_LOG_ERROR
, strError
);
157 CLibCEC::AddLog(CEC_LOG_DEBUG
, "connection opened, clearing any previous input and waiting for active transmissions to end before starting");
161 //clear any input bytes
163 ssize_t
iBytesRead(0);
164 bool bGotMsgStart(false), bGotMsgEnd(false);
165 while ((iBytesRead
= m_port
->Read(buff
, 1024, 100)) > 0 || (bGotMsgStart
&& !bGotMsgEnd
))
168 CLibCEC::AddLog(CEC_LOG_DEBUG
, "data received, clearing it");
169 // if something was received, wait for MSGEND
170 for (ssize_t iPtr
= 0; iPtr
< iBytesRead
; iPtr
++)
172 if (buff
[iPtr
] == MSGSTART
)
174 else if (buff
[iPtr
] == MSGEND
)
182 if (!bSkipChecks
&& !CheckAdapter())
184 CLibCEC::AddLog(CEC_LOG_ERROR
, "the adapter failed to pass basic checks");
189 else if (bStartListening
)
191 m_pingThread
= new CAdapterPingThread(this, CEC_ADAPTER_PING_TIMEOUT
);
192 if (CreateThread() && m_pingThread
->CreateThread())
194 CLibCEC::AddLog(CEC_LOG_DEBUG
, "communication thread started");
201 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not create a communication thread");
214 void CUSBCECAdapterCommunication::Close(void)
217 m_pingThread
->StopThread(0);
223 void *CUSBCECAdapterCommunication::Process(void)
227 bool bCommandReceived(false);
231 CLockObject
lock(m_mutex
);
233 bCommandReceived
= m_callback
&& Read(command
, 0) && m_bInitialised
;
236 /* push the next command to the callback method if there is one */
237 if (!IsStopped() && bCommandReceived
)
238 m_callback
->OnCommandReceived(command
);
243 /* set the ackmask to 0 before closing the connection */
244 SetAckMaskInternal(0, true);
246 if (m_iFirmwareVersion
>= 2)
247 SetControlledMode(false);
255 m_rcvCondition
.Broadcast();
259 cec_adapter_message_state
CUSBCECAdapterCommunication::Write(const cec_command
&data
, uint8_t iMaxTries
, uint8_t iLineTimeout
/* = 3 */, uint8_t iRetryLineTimeout
/* = 3 */)
261 cec_adapter_message_state
retVal(ADAPTER_MESSAGE_STATE_UNKNOWN
);
265 CCECAdapterMessage
*output
= new CCECAdapterMessage(data
);
267 /* set the number of retries */
268 if (data
.opcode
== CEC_OPCODE_NONE
) //TODO
269 output
->maxTries
= 1;
270 else if (data
.initiator
!= CECDEVICE_BROADCAST
)
271 output
->maxTries
= iMaxTries
;
273 output
->lineTimeout
= iLineTimeout
;
274 output
->retryTimeout
= iRetryLineTimeout
;
277 if (data
.destination
< 15)
279 CLockObject
lock(m_mutex
);
280 m_bWaitingForAck
[data
.destination
] = true;
284 while (bRetry
&& ++output
->tries
< output
->maxTries
)
286 bRetry
= (!Write(output
) || output
->NeedsRetry()) && output
->transmit_timeout
> 0;
288 Sleep(CEC_DEFAULT_TRANSMIT_RETRY_WAIT
);
290 retVal
= output
->state
;
296 bool CUSBCECAdapterCommunication::Write(CCECAdapterMessage
*data
)
298 data
->state
= ADAPTER_MESSAGE_STATE_WAITING_TO_BE_SENT
;
299 SendMessageToAdapter(data
);
301 if ((data
->expectControllerAck
&& data
->state
!= ADAPTER_MESSAGE_STATE_SENT_ACKED
) ||
302 (!data
->expectControllerAck
&& data
->state
!= ADAPTER_MESSAGE_STATE_SENT
))
304 CLibCEC::AddLog(CEC_LOG_DEBUG
, "command was not %s", data
->state
== ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED
? "acked" : "sent");
311 bool CUSBCECAdapterCommunication::Read(cec_command
&command
, uint32_t iTimeout
)
316 CCECAdapterMessage msg
;
317 if (Read(msg
, iTimeout
))
319 if (ParseMessage(msg
))
321 command
= m_currentframe
;
322 m_currentframe
.Clear();
329 bool CUSBCECAdapterCommunication::Read(CCECAdapterMessage
&msg
, uint32_t iTimeout
)
331 CLockObject
lock(m_mutex
);
334 CCECAdapterMessage
*buf(NULL
);
336 if (!m_inBuffer
.Pop(buf
))
338 if (iTimeout
== 0 || !m_rcvCondition
.Wait(m_mutex
, m_bHasData
, iTimeout
))
341 m_bHasData
= !m_inBuffer
.IsEmpty();
346 msg
.packet
= buf
->packet
;
347 msg
.state
= ADAPTER_MESSAGE_STATE_INCOMING
;
354 CStdString
CUSBCECAdapterCommunication::GetError(void) const
357 strError
= m_port
->GetError();
361 bool CUSBCECAdapterCommunication::StartBootloader(void)
367 CLibCEC::AddLog(CEC_LOG_DEBUG
, "starting the bootloader");
369 CCECAdapterMessage params
;
370 return SendCommand(MSGCODE_START_BOOTLOADER
, params
, false);
373 bool CUSBCECAdapterCommunication::PingAdapter(void)
375 CLibCEC::AddLog(CEC_LOG_DEBUG
, "sending ping");
377 CCECAdapterMessage params
;
378 return SendCommand(MSGCODE_PING
, params
);
381 bool CUSBCECAdapterCommunication::ParseMessage(const CCECAdapterMessage
&msg
)
384 bool bIsError(msg
.IsError());
389 CLockObject
adapterLock(m_mutex
);
390 switch(msg
.Message())
392 case MSGCODE_FRAME_START
:
394 m_currentframe
.Clear();
397 m_currentframe
.initiator
= msg
.Initiator();
398 m_currentframe
.destination
= msg
.Destination();
399 m_currentframe
.ack
= msg
.IsACK();
400 m_currentframe
.eom
= msg
.IsEOM();
402 if (m_currentframe
.ack
== 0x1)
404 m_lastDestination
= m_currentframe
.destination
;
405 if (m_currentframe
.destination
< 15)
407 if (!m_bWaitingForAck
[m_currentframe
.destination
])
408 m_processor
->HandlePoll(m_currentframe
.initiator
, m_currentframe
.destination
);
410 m_bWaitingForAck
[m_currentframe
.destination
] = false;
415 case MSGCODE_RECEIVE_FAILED
:
417 m_currentframe
.Clear();
418 if (m_lastDestination
!= CECDEVICE_UNKNOWN
)
419 bIsError
= m_processor
->HandleReceiveFailed(m_lastDestination
);
422 case MSGCODE_FRAME_DATA
:
426 m_currentframe
.PushBack(msg
[1]);
427 m_currentframe
.eom
= msg
.IsEOM();
435 CLibCEC::AddLog(bIsError
? CEC_LOG_WARNING
: CEC_LOG_DEBUG
, msg
.ToString());
439 uint16_t CUSBCECAdapterCommunication::GetFirmwareVersion(void)
441 uint16_t iReturn(m_iFirmwareVersion
);
443 if (iReturn
== CEC_FW_VERSION_UNKNOWN
)
445 CLockObject
lock(m_mutex
);
446 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting the firmware version");
447 cec_datapacket response
= GetSetting(MSGCODE_FIRMWARE_VERSION
, 2);
448 if (response
.size
== 2)
450 m_iFirmwareVersion
= (response
[0] << 8 | response
[1]);
451 iReturn
= m_iFirmwareVersion
;
452 CLibCEC::AddLog(CEC_LOG_DEBUG
, "firmware version %d", m_iFirmwareVersion
);
459 bool CUSBCECAdapterCommunication::SetLineTimeout(uint8_t iTimeout
)
463 if (m_iLineTimeout
!= iTimeout
)
465 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the line timeout to %d", iTimeout
);
466 CCECAdapterMessage params
;
467 params
.PushEscaped(iTimeout
);
468 bReturn
= SendCommand(MSGCODE_TRANSMIT_IDLETIME
, params
);
470 m_iLineTimeout
= iTimeout
;
476 bool CUSBCECAdapterCommunication::SetAckMask(uint16_t iMask
)
478 return SetAckMaskInternal(iMask
, IsRunning());
481 bool CUSBCECAdapterCommunication::SetAckMaskInternal(uint16_t iMask
, bool bWriteDirectly
/* = false */)
483 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting ackmask to %2x", iMask
);
485 CCECAdapterMessage params
;
486 params
.PushEscaped(iMask
>> 8);
487 params
.PushEscaped((uint8_t)iMask
);
488 return SendCommand(MSGCODE_SET_ACK_MASK
, params
, true, false, bWriteDirectly
);
491 bool CUSBCECAdapterCommunication::PersistConfiguration(libcec_configuration
*configuration
)
493 if (m_iFirmwareVersion
< 2)
497 bReturn
&= SetSettingAutoEnabled(true);
498 bReturn
&= SetSettingDeviceType(CLibCEC::GetType(configuration
->logicalAddresses
.primary
));
499 bReturn
&= SetSettingDefaultLogicalAddress(configuration
->logicalAddresses
.primary
);
500 bReturn
&= SetSettingLogicalAddressMask(CLibCEC::GetMaskForType(configuration
->logicalAddresses
.primary
));
501 bReturn
&= SetSettingPhysicalAddress(configuration
->iPhysicalAddress
);
502 bReturn
&= SetSettingCECVersion(CEC_VERSION_1_3A
);
503 bReturn
&= SetSettingOSDName(configuration
->strDeviceName
);
505 bReturn
= WriteEEPROM();
509 bool CUSBCECAdapterCommunication::GetConfiguration(libcec_configuration
*configuration
)
511 configuration
->iFirmwareVersion
= m_iFirmwareVersion
;
512 if (m_iFirmwareVersion
< 2)
516 cec_device_type type
;
517 if (GetSettingDeviceType(type
))
519 CLibCEC::AddLog(CEC_LOG_DEBUG
, "using persisted device type setting %s", m_processor
->ToString(type
));
520 configuration
->deviceTypes
.Clear();
521 configuration
->deviceTypes
.Add(type
);
525 CLibCEC::AddLog(CEC_LOG_DEBUG
, "no persisted device type setting");
529 if (GetSettingPhysicalAddress(configuration
->iPhysicalAddress
))
531 CLibCEC::AddLog(CEC_LOG_DEBUG
, "using persisted physical address setting %4x", configuration
->iPhysicalAddress
);
535 CLibCEC::AddLog(CEC_LOG_DEBUG
, "no persisted physical address setting");
539 CStdString strDeviceName
;
540 if (GetSettingOSDName(strDeviceName
))
542 snprintf(configuration
->strDeviceName
, 13, "%s", strDeviceName
.c_str());
543 CLibCEC::AddLog(CEC_LOG_DEBUG
, "using persisted device name setting %s", configuration
->strDeviceName
);
547 CLibCEC::AddLog(CEC_LOG_DEBUG
, "no persisted device name setting");
551 // don't read the following settings:
552 // - auto enabled (always enabled)
553 // - default logical address (autodetected)
554 // - logical address mask (autodetected)
555 // - CEC version (1.3a)
557 // TODO to be added to the firmware:
558 // - base device (4 bits)
559 // - HDMI port number (4 bits)
560 // - TV vendor id (12 bits)
561 // - wake devices (8 bits)
562 // - standby devices (8 bits)
563 // - use TV menu language (1 bit)
564 // - activate source (1 bit)
565 // - power off screensaver (1 bit)
566 // - power off on standby (1 bit)
567 // - send inactive source (1 bit)
571 bool CUSBCECAdapterCommunication::SetControlledMode(bool controlled
)
573 CLockObject
lock(m_mutex
);
574 CLibCEC::AddLog(CEC_LOG_DEBUG
, "turning controlled mode %s", controlled
? "on" : "off");
576 CCECAdapterMessage params
;
577 params
.PushEscaped(controlled
? 1 : 0);
578 return SendCommand(MSGCODE_SET_CONTROLLED
, params
);
581 bool CUSBCECAdapterCommunication::SetSettingAutoEnabled(bool enabled
)
583 CLockObject
lock(m_mutex
);
584 CLibCEC::AddLog(CEC_LOG_DEBUG
, "turning autonomous mode %s", enabled
? "on" : "off");
586 CCECAdapterMessage params
;
587 params
.PushEscaped(enabled
? 1 : 0);
588 return SendCommand(MSGCODE_SET_AUTO_ENABLED
, params
);
591 bool CUSBCECAdapterCommunication::GetSettingAutoEnabled(bool &enabled
)
593 CLockObject
lock(m_mutex
);
594 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting autonomous mode setting");
596 cec_datapacket response
= GetSetting(MSGCODE_GET_AUTO_ENABLED
, 1);
597 if (response
.size
== 1)
599 enabled
= response
[0] == 1;
605 bool CUSBCECAdapterCommunication::SetSettingDeviceType(cec_device_type type
)
607 CLockObject
lock(m_mutex
);
608 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the device type to %1X", (uint8_t)type
);
610 CCECAdapterMessage params
;
611 params
.PushEscaped((uint8_t)type
);
612 return SendCommand(MSGCODE_SET_DEVICE_TYPE
, params
);
615 bool CUSBCECAdapterCommunication::GetSettingDeviceType(cec_device_type
&value
)
617 CLockObject
lock(m_mutex
);
618 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting device type setting");
620 cec_datapacket response
= GetSetting(MSGCODE_GET_DEVICE_TYPE
, 1);
621 if (response
.size
== 1)
623 value
= (cec_device_type
)response
[0];
629 bool CUSBCECAdapterCommunication::SetSettingDefaultLogicalAddress(cec_logical_address address
)
631 CLockObject
lock(m_mutex
);
632 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the default logical address to %1X", address
);
634 CCECAdapterMessage params
;
635 params
.PushEscaped((uint8_t)address
);
636 return SendCommand(MSGCODE_SET_DEFAULT_LOGICAL_ADDRESS
, params
);
639 bool CUSBCECAdapterCommunication::GetSettingDefaultLogicalAddress(cec_logical_address
&address
)
641 CLockObject
lock(m_mutex
);
642 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting default logical address setting");
644 cec_datapacket response
= GetSetting(MSGCODE_GET_DEFAULT_LOGICAL_ADDRESS
, 1);
645 if (response
.size
== 1)
647 address
= (cec_logical_address
)response
[0];
653 bool CUSBCECAdapterCommunication::SetSettingLogicalAddressMask(uint16_t iMask
)
655 CLockObject
lock(m_mutex
);
656 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the logical address mask to %2X", iMask
);
658 CCECAdapterMessage params
;
659 params
.PushEscaped(iMask
>> 8);
660 params
.PushEscaped((uint8_t)iMask
);
661 return SendCommand(MSGCODE_SET_LOGICAL_ADDRESS_MASK
, params
);
664 bool CUSBCECAdapterCommunication::GetSettingLogicalAddressMask(uint16_t &iMask
)
666 CLockObject
lock(m_mutex
);
667 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting logical address mask setting");
669 cec_datapacket response
= GetSetting(MSGCODE_GET_LOGICAL_ADDRESS_MASK
, 2);
670 if (response
.size
== 2)
672 iMask
= ((uint16_t)response
[0] << 8) | ((uint16_t)response
[1]);
678 bool CUSBCECAdapterCommunication::SetSettingPhysicalAddress(uint16_t iPhysicalAddress
)
680 CLockObject
lock(m_mutex
);
681 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the physical address to %04X", iPhysicalAddress
);
683 CCECAdapterMessage params
;
684 params
.PushEscaped(iPhysicalAddress
>> 8);
685 params
.PushEscaped((uint8_t)iPhysicalAddress
);
686 return SendCommand(MSGCODE_SET_PHYSICAL_ADDRESS
, params
);
689 bool CUSBCECAdapterCommunication::GetSettingPhysicalAddress(uint16_t &iPhysicalAddress
)
691 CLockObject
lock(m_mutex
);
692 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting physical address setting");
694 cec_datapacket response
= GetSetting(MSGCODE_GET_PHYSICAL_ADDRESS
, 2);
695 if (response
.size
== 2)
697 iPhysicalAddress
= ((uint16_t)response
[0] << 8) | ((uint16_t)response
[1]);
703 bool CUSBCECAdapterCommunication::SetSettingCECVersion(cec_version version
)
705 CLockObject
lock(m_mutex
);
706 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the CEC version to %s", CLibCEC::GetInstance()->ToString(version
));
708 CCECAdapterMessage params
;
709 params
.PushEscaped((uint8_t)version
);
710 return SendCommand(MSGCODE_SET_HDMI_VERSION
, params
);
713 bool CUSBCECAdapterCommunication::GetSettingCECVersion(cec_version
&version
)
715 CLockObject
lock(m_mutex
);
716 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting CEC version setting");
718 cec_datapacket response
= GetSetting(MSGCODE_GET_HDMI_VERSION
, 1);
719 if (response
.size
== 1)
721 version
= (cec_version
)response
[0];
727 bool CUSBCECAdapterCommunication::SetSettingOSDName(const char *strOSDName
)
729 CLockObject
lock(m_mutex
);
730 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the OSD name to %s", strOSDName
);
732 CCECAdapterMessage params
;
733 for (size_t iPtr
= 0; iPtr
< strlen(strOSDName
); iPtr
++)
734 params
.PushEscaped(strOSDName
[iPtr
]);
735 return SendCommand(MSGCODE_SET_OSD_NAME
, params
);
738 bool CUSBCECAdapterCommunication::GetSettingOSDName(CStdString
&strOSDName
)
740 CLockObject
lock(m_mutex
);
741 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting OSD name setting");
743 cec_datapacket response
= GetSetting(MSGCODE_GET_OSD_NAME
, 13);
744 if (response
.size
== 0)
748 for (uint8_t iPtr
= 0; iPtr
< response
.size
&& iPtr
< 13; iPtr
++)
749 buf
[iPtr
] = (char)response
[iPtr
];
750 buf
[response
.size
] = 0;
752 strOSDName
.Format("%s", buf
);
756 bool CUSBCECAdapterCommunication::WriteEEPROM(void)
758 CLockObject
lock(m_mutex
);
759 CLibCEC::AddLog(CEC_LOG_DEBUG
, "writing settings in the EEPROM");
761 CCECAdapterMessage params
;
762 return SendCommand(MSGCODE_WRITE_EEPROM
, params
);
765 bool CUSBCECAdapterCommunication::IsOpen(void)
767 return !IsStopped() && m_port
->IsOpen() && IsRunning();
770 bool CUSBCECAdapterCommunication::WaitForAck(CCECAdapterMessage
&message
)
773 bool bTransmitSucceeded(false);
774 uint8_t iPacketsLeft(message
.isTransmission
? message
.Size() / 4 : 1);
776 int64_t iNow
= GetTimeMs();
777 int64_t iTargetTime
= iNow
+ (message
.transmit_timeout
<= 5 ? CEC_DEFAULT_TRANSMIT_WAIT
: message
.transmit_timeout
);
779 while (!bTransmitSucceeded
&& !bError
&& iNow
< iTargetTime
)
782 CCECAdapterMessage msg
;
789 if (msg
.Message() == MSGCODE_FRAME_START
&& msg
.IsACK())
791 if (msg
.Initiator() < 15 && m_bWaitingForAck
[msg
.Initiator()])
792 m_bWaitingForAck
[msg
.Initiator()] = false;
793 else if (msg
.Initiator() < 15)
795 m_processor
->HandlePoll(msg
.Initiator(), msg
.Destination());
796 m_lastDestination
= msg
.Initiator();
802 if (msg
.Message() == MSGCODE_RECEIVE_FAILED
&&
803 m_lastDestination
!= CECDEVICE_UNKNOWN
&&
804 m_processor
->HandleReceiveFailed(m_lastDestination
))
810 bError
= msg
.IsError();
813 message
.reply
= msg
.Message();
814 CLibCEC::AddLog(CEC_LOG_DEBUG
, msg
.ToString());
818 switch(msg
.Message())
820 case MSGCODE_COMMAND_ACCEPTED
:
821 if (iPacketsLeft
> 0)
823 if (!message
.isTransmission
&& iPacketsLeft
== 0)
824 bTransmitSucceeded
= true;
825 CLibCEC::AddLog(CEC_LOG_DEBUG
, "%s - waiting for %d more", msg
.ToString().c_str(), iPacketsLeft
);
827 case MSGCODE_TRANSMIT_SUCCEEDED
:
828 CLibCEC::AddLog(CEC_LOG_DEBUG
, msg
.ToString());
829 bTransmitSucceeded
= (iPacketsLeft
== 0);
830 bError
= !bTransmitSucceeded
;
831 message
.reply
= MSGCODE_TRANSMIT_SUCCEEDED
;
834 // ignore other data while waiting
842 message
.state
= bTransmitSucceeded
&& !bError
?
843 ADAPTER_MESSAGE_STATE_SENT_ACKED
:
844 ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED
;
846 return bTransmitSucceeded
&& !bError
;
849 void CUSBCECAdapterCommunication::AddData(uint8_t *data
, size_t iLen
)
851 CLockObject
lock(m_mutex
);
852 for (size_t iPtr
= 0; iPtr
< iLen
; iPtr
++)
856 if (data
[iPtr
] == MSGSTART
)
859 else if (data
[iPtr
] == MSGSTART
) //we found a msgstart before msgend, this is not right, remove
861 if (m_currentAdapterMessage
.Size() > 0)
862 CLibCEC::AddLog(CEC_LOG_WARNING
, "received MSGSTART before MSGEND, removing previous buffer contents");
863 m_currentAdapterMessage
.Clear();
866 else if (data
[iPtr
] == MSGEND
)
868 CCECAdapterMessage
*newMessage
= new CCECAdapterMessage
;
869 newMessage
->packet
= m_currentAdapterMessage
.packet
;
870 m_inBuffer
.Push(newMessage
);
871 m_currentAdapterMessage
.Clear();
873 m_bNextIsEscaped
= false;
875 m_rcvCondition
.Broadcast();
877 else if (m_bNextIsEscaped
)
879 m_currentAdapterMessage
.PushBack(data
[iPtr
] + (uint8_t)ESCOFFSET
);
880 m_bNextIsEscaped
= false;
882 else if (data
[iPtr
] == MSGESC
)
884 m_bNextIsEscaped
= true;
888 m_currentAdapterMessage
.PushBack(data
[iPtr
]);
893 bool CUSBCECAdapterCommunication::ReadFromDevice(uint32_t iTimeout
, size_t iSize
/* = 256 */)
902 CLockObject
lock(m_mutex
);
903 iBytesRead
= m_port
->Read(buff
, sizeof(uint8_t) * iSize
, iTimeout
);
904 if (iBytesRead
< 0 || iBytesRead
> 256)
906 CLibCEC::AddLog(CEC_LOG_ERROR
, "error reading from serial port: %s", m_port
->GetError().c_str());
910 else if (iBytesRead
> 0)
912 AddData(buff
, iBytesRead
);
915 return iBytesRead
> 0;
918 void CUSBCECAdapterCommunication::SendMessageToAdapter(CCECAdapterMessage
*msg
)
920 CLockObject
adapterLock(m_mutex
);
921 if (!m_port
->IsOpen())
923 CLibCEC::AddLog(CEC_LOG_ERROR
, "error writing to serial port: the connection is closed");
924 msg
->state
= ADAPTER_MESSAGE_STATE_ERROR
;
928 if (msg
->isTransmission
&& (msg
->Size() < 2 || msg
->At(1) != MSGCODE_TRANSMIT_IDLETIME
))
931 SetLineTimeout(msg
->lineTimeout
);
933 SetLineTimeout(msg
->retryTimeout
);
936 if (m_port
->Write(msg
->packet
.data
, msg
->Size()) != (ssize_t
) msg
->Size())
938 CLibCEC::AddLog(CEC_LOG_ERROR
, "error writing to serial port: %s", m_port
->GetError().c_str());
939 msg
->state
= ADAPTER_MESSAGE_STATE_ERROR
;
943 CLibCEC::AddLog(CEC_LOG_DEBUG
, "command sent");
944 msg
->state
= ADAPTER_MESSAGE_STATE_SENT
;
946 if (msg
->expectControllerAck
)
948 if (!WaitForAck(*msg
))
949 CLibCEC::AddLog(CEC_LOG_DEBUG
, "did not receive ack");
954 CStdString
CUSBCECAdapterCommunication::GetPortName(void)
957 strName
= m_port
->GetName();
961 bool CUSBCECAdapterCommunication::SendCommand(cec_adapter_messagecode msgCode
, CCECAdapterMessage
¶ms
, bool bExpectAck
/* = true */, bool bIsTransmission
/* = false */, bool bSendDirectly
/* = true */, bool bIsRetry
/* = false */)
963 CLockObject
lock(m_mutex
);
965 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
967 output
->PushBack(MSGSTART
);
968 output
->PushEscaped((uint8_t)msgCode
);
969 output
->Append(params
);
970 output
->PushBack(MSGEND
);
971 output
->isTransmission
= bIsTransmission
;
972 output
->expectControllerAck
= bExpectAck
;
975 SendMessageToAdapter(output
);
979 bool bWriteOk
= output
->state
== (output
->expectControllerAck
? ADAPTER_MESSAGE_STATE_SENT_ACKED
: ADAPTER_MESSAGE_STATE_SENT
);
980 cec_adapter_messagecode reply
= output
->reply
;
985 CLibCEC::AddLog(CEC_LOG_ERROR
, "'%s' failed", CCECAdapterMessage::ToString(msgCode
));
987 if (!bIsRetry
&& reply
== MSGCODE_COMMAND_REJECTED
&& msgCode
!= MSGCODE_SET_CONTROLLED
)
989 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting controlled mode and retrying");
990 if (SetControlledMode(true))
991 return SendCommand(msgCode
, params
, bExpectAck
, bIsTransmission
, bSendDirectly
, true);
999 cec_datapacket
CUSBCECAdapterCommunication::GetSetting(cec_adapter_messagecode msgCode
, uint8_t iResponseLength
)
1001 cec_datapacket retVal
;
1004 CCECAdapterMessage params
;
1005 if (!SendCommand(msgCode
, params
, false))
1007 CLibCEC::AddLog(CEC_LOG_ERROR
, "%s failed", CCECAdapterMessage::ToString(msgCode
));
1011 ReadFromDevice(CEC_DEFAULT_TRANSMIT_WAIT
, iResponseLength
+ 3 /* start + msgcode + iResponseLength + end */);
1012 CCECAdapterMessage input
;
1015 if (input
.Message() != msgCode
)
1016 CLibCEC::AddLog(CEC_LOG_ERROR
, "invalid response to %s received (%s)", CCECAdapterMessage::ToString(msgCode
), CCECAdapterMessage::ToString(input
.Message()));
1019 for (uint8_t iPtr
= 1; iPtr
< input
.Size(); iPtr
++)
1020 retVal
.PushBack(input
[iPtr
]);
1025 CLibCEC::AddLog(CEC_LOG_ERROR
, "no response to %s received", CCECAdapterMessage::ToString(msgCode
));
1031 void *CAdapterPingThread::Process(void)
1033 while (!IsStopped())
1035 if (m_timeout
.TimeLeft() == 0)
1037 m_timeout
.Init(CEC_ADAPTER_PING_TIMEOUT
);
1038 m_com
->PingAdapter();