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 void *CUSBCECAdapterProcessor::Process(void)
50 if (m_inBuffer
.Pop(command
))
51 m_callback
->OnCommandReceived(command
);
58 void CUSBCECAdapterProcessor::AddCommand(cec_command command
)
60 m_inBuffer
.Push(command
);
63 CUSBCECAdapterCommunication::CUSBCECAdapterCommunication(CCECProcessor
*processor
, const char *strPort
, uint16_t iBaudRate
/* = 38400 */) :
65 m_processor(processor
),
68 m_iFirmwareVersion(CEC_FW_VERSION_UNKNOWN
),
69 m_lastDestination(CECDEVICE_UNKNOWN
),
70 m_bNextIsEscaped(false),
72 m_messageProcessor(NULL
),
75 for (unsigned int iPtr
= 0; iPtr
< 15; iPtr
++)
76 m_bWaitingForAck
[iPtr
] = false;
77 m_port
= new CSerialPort(strPort
, iBaudRate
);
80 bool CUSBCECAdapterCommunication::CheckAdapter(uint32_t iTimeoutMs
/* = 10000 */)
83 uint64_t iNow
= GetTimeMs();
84 uint64_t iTarget
= iTimeoutMs
> 0 ? iNow
+ iTimeoutMs
: iNow
+ CEC_DEFAULT_TRANSMIT_WAIT
;
86 /* try to ping the adapter */
89 while (iNow
< iTarget
&& (bPinged
= PingAdapter()) == false)
91 CLibCEC::AddLog(CEC_LOG_ERROR
, "the adapter did not respond correctly to a ping (try %d)", ++iPingTry
);
96 /* try to read the firmware version */
97 m_iFirmwareVersion
= CEC_FW_VERSION_UNKNOWN
;
98 unsigned iFwVersionTry(0);
99 while (bPinged
&& iNow
< iTarget
&& (m_iFirmwareVersion
= GetFirmwareVersion()) == CEC_FW_VERSION_UNKNOWN
&& iFwVersionTry
< 3)
101 CLibCEC::AddLog(CEC_LOG_WARNING
, "the adapter did not respond with a correct firmware version (try %d)", ++iFwVersionTry
);
106 if (m_iFirmwareVersion
== CEC_FW_VERSION_UNKNOWN
)
108 CLibCEC::AddLog(CEC_LOG_DEBUG
, "defaulting to firmware version 1");
109 m_iFirmwareVersion
= 1;
112 if (m_iFirmwareVersion
>= 2)
114 /* try to set controlled mode */
115 unsigned iControlledTry(0);
116 bool bControlled(false);
117 while (iNow
< iTarget
&& (bControlled
= SetControlledMode(true)) == false)
119 CLibCEC::AddLog(CEC_LOG_ERROR
, "the adapter did not respond correctly to setting controlled mode (try %d)", ++iControlledTry
);
123 bReturn
= bControlled
;
129 CLockObject
lock(m_mutex
);
130 m_bInitialised
= bReturn
;
136 bool CUSBCECAdapterCommunication::Open(IAdapterCommunicationCallback
*cb
, uint32_t iTimeoutMs
/* = 10000 */, bool bSkipChecks
/* = false */, bool bStartListening
/* = true */)
138 uint64_t iNow
= GetTimeMs();
139 uint64_t iTimeout
= iNow
+ iTimeoutMs
;
142 CLockObject
lock(m_mutex
);
146 CLibCEC::AddLog(CEC_LOG_ERROR
, "port is NULL");
152 CLibCEC::AddLog(CEC_LOG_ERROR
, "port is already open");
158 bool bConnected(false);
159 while (!bConnected
&& iNow
< iTimeout
)
161 if ((bConnected
= m_port
->Open(iTimeout
)) == false)
163 strError
.Format("error opening serial port '%s': %s", m_port
->GetName().c_str(), m_port
->GetError().c_str());
171 CLibCEC::AddLog(CEC_LOG_ERROR
, strError
);
175 CLibCEC::AddLog(CEC_LOG_DEBUG
, "connection opened, clearing any previous input and waiting for active transmissions to end before starting");
179 //clear any input bytes
181 ssize_t
iBytesRead(0);
182 bool bGotMsgStart(false), bGotMsgEnd(false);
183 while ((iBytesRead
= m_port
->Read(buff
, 1024, 100)) > 0 || (bGotMsgStart
&& !bGotMsgEnd
))
186 CLibCEC::AddLog(CEC_LOG_DEBUG
, "data received, clearing it");
187 // if something was received, wait for MSGEND
188 for (ssize_t iPtr
= 0; iPtr
< iBytesRead
; iPtr
++)
190 if (buff
[iPtr
] == MSGSTART
)
192 else if (buff
[iPtr
] == MSGEND
)
200 if (!bSkipChecks
&& !CheckAdapter())
202 CLibCEC::AddLog(CEC_LOG_ERROR
, "the adapter failed to pass basic checks");
206 else if (bStartListening
)
210 CLibCEC::AddLog(CEC_LOG_DEBUG
, "communication thread started");
216 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not create a communication thread");
227 void CUSBCECAdapterCommunication::Close(void)
232 void *CUSBCECAdapterCommunication::Process(void)
234 m_messageProcessor
= new CUSBCECAdapterProcessor(m_callback
);
235 m_messageProcessor
->CreateThread();
239 bool bCommandReceived(false);
240 CTimeout
pingTimeout(CEC_ADAPTER_PING_TIMEOUT
);
244 CLockObject
lock(m_mutex
);
246 bCommandReceived
= m_callback
&& Read(command
, 0) && m_bInitialised
;
249 /* push the next command to the callback method if there is one */
250 if (!IsStopped() && bCommandReceived
)
251 m_messageProcessor
->AddCommand(command
);
253 /* ping the adapter every 15 seconds */
254 if (pingTimeout
.TimeLeft() == 0)
256 pingTimeout
.Init(CEC_ADAPTER_PING_TIMEOUT
);
267 /* stop the message processor */
268 m_messageProcessor
->StopThread();
269 delete m_messageProcessor
;
271 /* notify all threads that are waiting on messages to be sent */
272 CCECAdapterMessage
*msg(NULL
);
273 while (m_outBuffer
.Pop(msg
))
274 msg
->event
.Broadcast();
276 /* set the ackmask to 0 before closing the connection */
277 SetAckMaskInternal(0, true);
279 if (m_iFirmwareVersion
>= 2)
280 SetControlledMode(false);
291 cec_adapter_message_state
CUSBCECAdapterCommunication::Write(const cec_command
&data
, uint8_t iMaxTries
, uint8_t iLineTimeout
/* = 3 */, uint8_t iRetryLineTimeout
/* = 3 */)
293 cec_adapter_message_state
retVal(ADAPTER_MESSAGE_STATE_UNKNOWN
);
297 CCECAdapterMessage
*output
= new CCECAdapterMessage(data
);
299 /* set the number of retries */
300 if (data
.opcode
== CEC_OPCODE_NONE
) //TODO
301 output
->maxTries
= 1;
302 else if (data
.initiator
!= CECDEVICE_BROADCAST
)
303 output
->maxTries
= iMaxTries
;
305 output
->lineTimeout
= iLineTimeout
;
306 output
->retryTimeout
= iRetryLineTimeout
;
310 CLockObject
lock(m_mutex
);
311 m_bWaitingForAck
[data
.destination
] = true;
315 while (bRetry
&& ++output
->tries
< output
->maxTries
)
317 bRetry
= (!Write(output
) || output
->NeedsRetry()) && output
->transmit_timeout
> 0;
319 Sleep(CEC_DEFAULT_TRANSMIT_RETRY_WAIT
);
321 retVal
= output
->state
;
327 bool CUSBCECAdapterCommunication::Write(CCECAdapterMessage
*data
)
329 data
->state
= ADAPTER_MESSAGE_STATE_WAITING_TO_BE_SENT
;
330 m_outBuffer
.Push(data
);
331 data
->event
.Wait(5000);
333 if ((data
->expectControllerAck
&& data
->state
!= ADAPTER_MESSAGE_STATE_SENT_ACKED
) ||
334 (!data
->expectControllerAck
&& data
->state
!= ADAPTER_MESSAGE_STATE_SENT
))
336 CLibCEC::AddLog(CEC_LOG_DEBUG
, "command was not %s", data
->state
== ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED
? "acked" : "sent");
343 bool CUSBCECAdapterCommunication::Read(cec_command
&command
, uint32_t iTimeout
)
348 CCECAdapterMessage msg
;
349 if (Read(msg
, iTimeout
))
351 if (ParseMessage(msg
))
353 command
= m_currentframe
;
354 m_currentframe
.Clear();
361 bool CUSBCECAdapterCommunication::Read(CCECAdapterMessage
&msg
, uint32_t iTimeout
)
363 CLockObject
lock(m_mutex
);
366 CCECAdapterMessage
*buf(NULL
);
368 if (!m_inBuffer
.Pop(buf
))
370 if (iTimeout
== 0 || !m_rcvCondition
.Wait(m_mutex
, m_bHasData
, iTimeout
))
373 m_bHasData
= !m_inBuffer
.IsEmpty();
378 msg
.packet
= buf
->packet
;
379 msg
.state
= ADAPTER_MESSAGE_STATE_INCOMING
;
386 CStdString
CUSBCECAdapterCommunication::GetError(void) const
389 strError
= m_port
->GetError();
393 bool CUSBCECAdapterCommunication::StartBootloader(void)
399 CLibCEC::AddLog(CEC_LOG_DEBUG
, "starting the bootloader");
401 CCECAdapterMessage params
;
402 return SendCommand(MSGCODE_START_BOOTLOADER
, params
, false);
405 bool CUSBCECAdapterCommunication::PingAdapter(void)
407 CLockObject
lock(m_mutex
);
408 CLibCEC::AddLog(CEC_LOG_DEBUG
, "sending ping");
410 CCECAdapterMessage params
;
411 return SendCommand(MSGCODE_PING
, params
);
414 bool CUSBCECAdapterCommunication::ParseMessage(const CCECAdapterMessage
&msg
)
417 bool bIsError(msg
.IsError());
422 CLockObject
adapterLock(m_mutex
);
423 switch(msg
.Message())
425 case MSGCODE_FRAME_START
:
427 m_currentframe
.Clear();
430 m_currentframe
.initiator
= msg
.Initiator();
431 m_currentframe
.destination
= msg
.Destination();
432 m_currentframe
.ack
= msg
.IsACK();
433 m_currentframe
.eom
= msg
.IsEOM();
435 if (m_currentframe
.ack
== 0x1)
437 m_lastDestination
= m_currentframe
.destination
;
438 if (!m_bWaitingForAck
[m_currentframe
.destination
])
439 m_processor
->HandlePoll(m_currentframe
.initiator
, m_currentframe
.destination
);
441 m_bWaitingForAck
[m_currentframe
.destination
] = false;
445 case MSGCODE_RECEIVE_FAILED
:
447 m_currentframe
.Clear();
448 if (m_lastDestination
!= CECDEVICE_UNKNOWN
)
449 bIsError
= m_processor
->HandleReceiveFailed(m_lastDestination
);
452 case MSGCODE_FRAME_DATA
:
456 m_currentframe
.PushBack(msg
[1]);
457 m_currentframe
.eom
= msg
.IsEOM();
465 CLibCEC::AddLog(bIsError
? CEC_LOG_WARNING
: CEC_LOG_DEBUG
, msg
.ToString());
469 uint16_t CUSBCECAdapterCommunication::GetFirmwareVersion(void)
471 uint16_t iReturn(m_iFirmwareVersion
);
473 if (iReturn
== CEC_FW_VERSION_UNKNOWN
)
475 CLockObject
lock(m_mutex
);
476 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting the firmware version");
477 cec_datapacket response
= GetSetting(MSGCODE_FIRMWARE_VERSION
, 2);
478 if (response
.size
== 2)
480 m_iFirmwareVersion
= (response
[0] << 8 | response
[1]);
481 iReturn
= m_iFirmwareVersion
;
482 CLibCEC::AddLog(CEC_LOG_DEBUG
, "firmware version %d", m_iFirmwareVersion
);
489 bool CUSBCECAdapterCommunication::SetLineTimeout(uint8_t iTimeout
)
493 if (m_iLineTimeout
!= iTimeout
)
495 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the line timeout to %d", iTimeout
);
496 CCECAdapterMessage params
;
497 params
.PushEscaped(iTimeout
);
498 bReturn
= SendCommand(MSGCODE_TRANSMIT_IDLETIME
, params
);
500 m_iLineTimeout
= iTimeout
;
506 bool CUSBCECAdapterCommunication::SetAckMask(uint16_t iMask
)
508 return SetAckMaskInternal(iMask
, IsRunning());
511 bool CUSBCECAdapterCommunication::SetAckMaskInternal(uint16_t iMask
, bool bWriteDirectly
/* = false */)
513 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting ackmask to %2x", iMask
);
515 CCECAdapterMessage params
;
516 params
.PushEscaped(iMask
>> 8);
517 params
.PushEscaped((uint8_t)iMask
);
518 return SendCommand(MSGCODE_SET_ACK_MASK
, params
, true, false, bWriteDirectly
);
521 bool CUSBCECAdapterCommunication::PersistConfiguration(libcec_configuration
*configuration
)
523 if (m_iFirmwareVersion
< 2)
527 bReturn
&= SetSettingAutoEnabled(true);
528 bReturn
&= SetSettingDeviceType(CLibCEC::GetType(configuration
->logicalAddresses
.primary
));
529 bReturn
&= SetSettingDefaultLogicalAddress(configuration
->logicalAddresses
.primary
);
530 bReturn
&= SetSettingLogicalAddressMask(CLibCEC::GetMaskForType(configuration
->logicalAddresses
.primary
));
531 bReturn
&= SetSettingPhysicalAddress(configuration
->iPhysicalAddress
);
532 bReturn
&= SetSettingCECVersion(CEC_VERSION_1_3A
);
533 bReturn
&= SetSettingOSDName(configuration
->strDeviceName
);
535 bReturn
= WriteEEPROM();
539 bool CUSBCECAdapterCommunication::GetConfiguration(libcec_configuration
*configuration
)
541 configuration
->iFirmwareVersion
= m_iFirmwareVersion
;
542 if (m_iFirmwareVersion
< 2)
546 cec_device_type type
;
547 if (GetSettingDeviceType(type
))
549 CLibCEC::AddLog(CEC_LOG_DEBUG
, "using persisted device type setting %s", m_processor
->ToString(type
));
550 configuration
->deviceTypes
.Clear();
551 configuration
->deviceTypes
.Add(type
);
555 CLibCEC::AddLog(CEC_LOG_DEBUG
, "no persisted device type setting");
559 if (GetSettingPhysicalAddress(configuration
->iPhysicalAddress
))
561 CLibCEC::AddLog(CEC_LOG_DEBUG
, "using persisted physical address setting %4x", configuration
->iPhysicalAddress
);
565 CLibCEC::AddLog(CEC_LOG_DEBUG
, "no persisted physical address setting");
569 CStdString strDeviceName
;
570 if (GetSettingOSDName(strDeviceName
))
572 snprintf(configuration
->strDeviceName
, 13, "%s", strDeviceName
.c_str());
573 CLibCEC::AddLog(CEC_LOG_DEBUG
, "using persisted device name setting %s", configuration
->strDeviceName
);
577 CLibCEC::AddLog(CEC_LOG_DEBUG
, "no persisted device name setting");
581 // don't read the following settings:
582 // - auto enabled (always enabled)
583 // - default logical address (autodetected)
584 // - logical address mask (autodetected)
585 // - CEC version (1.3a)
587 // TODO to be added to the firmware:
588 // - base device (4 bits)
589 // - HDMI port number (4 bits)
590 // - TV vendor id (12 bits)
591 // - wake devices (8 bits)
592 // - standby devices (8 bits)
593 // - use TV menu language (1 bit)
594 // - activate source (1 bit)
595 // - power off screensaver (1 bit)
596 // - power off on standby (1 bit)
597 // - send inactive source (1 bit)
601 bool CUSBCECAdapterCommunication::SetControlledMode(bool controlled
)
603 CLockObject
lock(m_mutex
);
604 CLibCEC::AddLog(CEC_LOG_DEBUG
, "turning controlled mode %s", controlled
? "on" : "off");
606 CCECAdapterMessage params
;
607 params
.PushEscaped(controlled
? 1 : 0);
608 return SendCommand(MSGCODE_SET_CONTROLLED
, params
);
611 bool CUSBCECAdapterCommunication::SetSettingAutoEnabled(bool enabled
)
613 CLockObject
lock(m_mutex
);
614 CLibCEC::AddLog(CEC_LOG_DEBUG
, "turning autonomous mode %s", enabled
? "on" : "off");
616 CCECAdapterMessage params
;
617 params
.PushEscaped(enabled
? 1 : 0);
618 return SendCommand(MSGCODE_SET_AUTO_ENABLED
, params
);
621 bool CUSBCECAdapterCommunication::GetSettingAutoEnabled(bool &enabled
)
623 CLockObject
lock(m_mutex
);
624 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting autonomous mode setting");
626 cec_datapacket response
= GetSetting(MSGCODE_GET_AUTO_ENABLED
, 1);
627 if (response
.size
== 1)
629 enabled
= response
[0] == 1;
635 bool CUSBCECAdapterCommunication::SetSettingDeviceType(cec_device_type type
)
637 CLockObject
lock(m_mutex
);
638 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the device type to %1X", (uint8_t)type
);
640 CCECAdapterMessage params
;
641 params
.PushEscaped((uint8_t)type
);
642 return SendCommand(MSGCODE_SET_DEVICE_TYPE
, params
);
645 bool CUSBCECAdapterCommunication::GetSettingDeviceType(cec_device_type
&value
)
647 CLockObject
lock(m_mutex
);
648 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting device type setting");
650 cec_datapacket response
= GetSetting(MSGCODE_GET_DEVICE_TYPE
, 1);
651 if (response
.size
== 1)
653 value
= (cec_device_type
)response
[0];
659 bool CUSBCECAdapterCommunication::SetSettingDefaultLogicalAddress(cec_logical_address address
)
661 CLockObject
lock(m_mutex
);
662 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the default logical address to %1X", address
);
664 CCECAdapterMessage params
;
665 params
.PushEscaped((uint8_t)address
);
666 return SendCommand(MSGCODE_SET_DEFAULT_LOGICAL_ADDRESS
, params
);
669 bool CUSBCECAdapterCommunication::GetSettingDefaultLogicalAddress(cec_logical_address
&address
)
671 CLockObject
lock(m_mutex
);
672 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting default logical address setting");
674 cec_datapacket response
= GetSetting(MSGCODE_GET_DEFAULT_LOGICAL_ADDRESS
, 1);
675 if (response
.size
== 1)
677 address
= (cec_logical_address
)response
[0];
683 bool CUSBCECAdapterCommunication::SetSettingLogicalAddressMask(uint16_t iMask
)
685 CLockObject
lock(m_mutex
);
686 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the logical address mask to %2X", iMask
);
688 CCECAdapterMessage params
;
689 params
.PushEscaped(iMask
>> 8);
690 params
.PushEscaped((uint8_t)iMask
);
691 return SendCommand(MSGCODE_SET_LOGICAL_ADDRESS_MASK
, params
);
694 bool CUSBCECAdapterCommunication::GetSettingLogicalAddressMask(uint16_t &iMask
)
696 CLockObject
lock(m_mutex
);
697 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting logical address mask setting");
699 cec_datapacket response
= GetSetting(MSGCODE_GET_LOGICAL_ADDRESS_MASK
, 2);
700 if (response
.size
== 2)
702 iMask
= ((uint16_t)response
[0] << 8) | ((uint16_t)response
[1]);
708 bool CUSBCECAdapterCommunication::SetSettingPhysicalAddress(uint16_t iPhysicalAddress
)
710 CLockObject
lock(m_mutex
);
711 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the physical address to %04X", iPhysicalAddress
);
713 CCECAdapterMessage params
;
714 params
.PushEscaped(iPhysicalAddress
>> 8);
715 params
.PushEscaped((uint8_t)iPhysicalAddress
);
716 return SendCommand(MSGCODE_SET_PHYSICAL_ADDRESS
, params
);
719 bool CUSBCECAdapterCommunication::GetSettingPhysicalAddress(uint16_t &iPhysicalAddress
)
721 CLockObject
lock(m_mutex
);
722 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting physical address setting");
724 cec_datapacket response
= GetSetting(MSGCODE_GET_PHYSICAL_ADDRESS
, 2);
725 if (response
.size
== 2)
727 iPhysicalAddress
= ((uint16_t)response
[0] << 8) | ((uint16_t)response
[1]);
733 bool CUSBCECAdapterCommunication::SetSettingCECVersion(cec_version version
)
735 CLockObject
lock(m_mutex
);
736 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the CEC version to %s", CLibCEC::GetInstance()->ToString(version
));
738 CCECAdapterMessage params
;
739 params
.PushEscaped((uint8_t)version
);
740 return SendCommand(MSGCODE_SET_HDMI_VERSION
, params
);
743 bool CUSBCECAdapterCommunication::GetSettingCECVersion(cec_version
&version
)
745 CLockObject
lock(m_mutex
);
746 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting CEC version setting");
748 cec_datapacket response
= GetSetting(MSGCODE_GET_HDMI_VERSION
, 1);
749 if (response
.size
== 1)
751 version
= (cec_version
)response
[0];
757 bool CUSBCECAdapterCommunication::SetSettingOSDName(const char *strOSDName
)
759 CLockObject
lock(m_mutex
);
760 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the OSD name to %s", strOSDName
);
762 CCECAdapterMessage params
;
763 for (size_t iPtr
= 0; iPtr
< strlen(strOSDName
); iPtr
++)
764 params
.PushEscaped(strOSDName
[iPtr
]);
765 return SendCommand(MSGCODE_SET_OSD_NAME
, params
);
768 bool CUSBCECAdapterCommunication::GetSettingOSDName(CStdString
&strOSDName
)
770 CLockObject
lock(m_mutex
);
771 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting OSD name setting");
773 cec_datapacket response
= GetSetting(MSGCODE_GET_OSD_NAME
, 13);
774 if (response
.size
== 0)
778 for (uint8_t iPtr
= 0; iPtr
< response
.size
&& iPtr
< 13; iPtr
++)
779 buf
[iPtr
] = (char)response
[iPtr
];
780 buf
[response
.size
] = 0;
782 strOSDName
.Format("%s", buf
);
786 bool CUSBCECAdapterCommunication::WriteEEPROM(void)
788 CLockObject
lock(m_mutex
);
789 CLibCEC::AddLog(CEC_LOG_DEBUG
, "writing settings in the EEPROM");
791 CCECAdapterMessage params
;
792 return SendCommand(MSGCODE_WRITE_EEPROM
, params
);
795 bool CUSBCECAdapterCommunication::IsOpen(void)
797 return !IsStopped() && m_port
->IsOpen() && IsRunning();
800 bool CUSBCECAdapterCommunication::WaitForAck(CCECAdapterMessage
&message
)
803 bool bTransmitSucceeded(false);
804 uint8_t iPacketsLeft(message
.isTransmission
? message
.Size() / 4 : 1);
806 int64_t iNow
= GetTimeMs();
807 int64_t iTargetTime
= iNow
+ (message
.transmit_timeout
<= 5 ? CEC_DEFAULT_TRANSMIT_WAIT
: message
.transmit_timeout
);
809 while (!bTransmitSucceeded
&& !bError
&& iNow
< iTargetTime
)
812 CCECAdapterMessage msg
;
819 if (msg
.Message() == MSGCODE_FRAME_START
&& msg
.IsACK())
821 if (m_bWaitingForAck
[msg
.Initiator()])
822 m_bWaitingForAck
[msg
.Initiator()] = false;
825 m_processor
->HandlePoll(msg
.Initiator(), msg
.Destination());
826 m_lastDestination
= msg
.Initiator();
832 if (msg
.Message() == MSGCODE_RECEIVE_FAILED
&&
833 m_lastDestination
!= CECDEVICE_UNKNOWN
&&
834 m_processor
->HandleReceiveFailed(m_lastDestination
))
840 bError
= msg
.IsError();
843 message
.reply
= msg
.Message();
844 CLibCEC::AddLog(CEC_LOG_DEBUG
, msg
.ToString());
848 switch(msg
.Message())
850 case MSGCODE_COMMAND_ACCEPTED
:
851 if (iPacketsLeft
> 0)
853 if (!message
.isTransmission
&& iPacketsLeft
== 0)
854 bTransmitSucceeded
= true;
855 CLibCEC::AddLog(CEC_LOG_DEBUG
, "%s - waiting for %d more", msg
.ToString().c_str(), iPacketsLeft
);
857 case MSGCODE_TRANSMIT_SUCCEEDED
:
858 CLibCEC::AddLog(CEC_LOG_DEBUG
, msg
.ToString());
859 bTransmitSucceeded
= (iPacketsLeft
== 0);
860 bError
= !bTransmitSucceeded
;
861 message
.reply
= MSGCODE_TRANSMIT_SUCCEEDED
;
864 // ignore other data while waiting
872 message
.state
= bTransmitSucceeded
&& !bError
?
873 ADAPTER_MESSAGE_STATE_SENT_ACKED
:
874 ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED
;
876 return bTransmitSucceeded
&& !bError
;
879 void CUSBCECAdapterCommunication::AddData(uint8_t *data
, size_t iLen
)
881 CLockObject
lock(m_mutex
);
882 for (size_t iPtr
= 0; iPtr
< iLen
; iPtr
++)
886 if (data
[iPtr
] == MSGSTART
)
889 else if (data
[iPtr
] == MSGSTART
) //we found a msgstart before msgend, this is not right, remove
891 if (m_currentAdapterMessage
.Size() > 0)
892 CLibCEC::AddLog(CEC_LOG_WARNING
, "received MSGSTART before MSGEND, removing previous buffer contents");
893 m_currentAdapterMessage
.Clear();
896 else if (data
[iPtr
] == MSGEND
)
898 CCECAdapterMessage
*newMessage
= new CCECAdapterMessage
;
899 newMessage
->packet
= m_currentAdapterMessage
.packet
;
900 m_inBuffer
.Push(newMessage
);
901 m_currentAdapterMessage
.Clear();
903 m_bNextIsEscaped
= false;
905 m_rcvCondition
.Broadcast();
907 else if (m_bNextIsEscaped
)
909 m_currentAdapterMessage
.PushBack(data
[iPtr
] + (uint8_t)ESCOFFSET
);
910 m_bNextIsEscaped
= false;
912 else if (data
[iPtr
] == MSGESC
)
914 m_bNextIsEscaped
= true;
918 m_currentAdapterMessage
.PushBack(data
[iPtr
]);
923 bool CUSBCECAdapterCommunication::ReadFromDevice(uint32_t iTimeout
, size_t iSize
/* = 256 */)
932 CLockObject
lock(m_mutex
);
933 iBytesRead
= m_port
->Read(buff
, sizeof(uint8_t) * iSize
, iTimeout
);
934 if (iBytesRead
< 0 || iBytesRead
> 256)
936 CLibCEC::AddLog(CEC_LOG_ERROR
, "error reading from serial port: %s", m_port
->GetError().c_str());
940 else if (iBytesRead
> 0)
942 AddData(buff
, iBytesRead
);
945 return iBytesRead
> 0;
948 void CUSBCECAdapterCommunication::SendMessageToAdapter(CCECAdapterMessage
*msg
)
950 CLockObject
adapterLock(m_mutex
);
951 if (!m_port
->IsOpen())
953 CLibCEC::AddLog(CEC_LOG_ERROR
, "error writing to serial port: the connection is closed");
954 msg
->state
= ADAPTER_MESSAGE_STATE_ERROR
;
958 if (msg
->isTransmission
&& (msg
->Size() < 2 || msg
->At(1) != MSGCODE_TRANSMIT_IDLETIME
))
961 SetLineTimeout(msg
->lineTimeout
);
963 SetLineTimeout(msg
->retryTimeout
);
966 if (m_port
->Write(msg
->packet
.data
, msg
->Size()) != (ssize_t
) msg
->Size())
968 CLibCEC::AddLog(CEC_LOG_ERROR
, "error writing to serial port: %s", m_port
->GetError().c_str());
969 msg
->state
= ADAPTER_MESSAGE_STATE_ERROR
;
973 CLibCEC::AddLog(CEC_LOG_DEBUG
, "command sent");
974 msg
->state
= ADAPTER_MESSAGE_STATE_SENT
;
976 if (msg
->expectControllerAck
)
978 if (!WaitForAck(*msg
))
979 CLibCEC::AddLog(CEC_LOG_DEBUG
, "did not receive ack");
985 void CUSBCECAdapterCommunication::WriteNextCommand(void)
987 CCECAdapterMessage
*msg(NULL
);
988 if (m_outBuffer
.Pop(msg
))
989 SendMessageToAdapter(msg
);
992 CStdString
CUSBCECAdapterCommunication::GetPortName(void)
995 strName
= m_port
->GetName();
999 bool CUSBCECAdapterCommunication::SendCommand(cec_adapter_messagecode msgCode
, CCECAdapterMessage
¶ms
, bool bExpectAck
/* = true */, bool bIsTransmission
/* = false */, bool bSendDirectly
/* = true */, bool bIsRetry
/* = false */)
1001 CLockObject
lock(m_mutex
);
1003 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
1005 output
->PushBack(MSGSTART
);
1006 output
->PushEscaped((uint8_t)msgCode
);
1007 output
->Append(params
);
1008 output
->PushBack(MSGEND
);
1009 output
->isTransmission
= bIsTransmission
;
1010 output
->expectControllerAck
= bExpectAck
;
1013 SendMessageToAdapter(output
);
1017 bool bWriteOk
= output
->state
== (output
->expectControllerAck
? ADAPTER_MESSAGE_STATE_SENT_ACKED
: ADAPTER_MESSAGE_STATE_SENT
);
1020 CLibCEC::AddLog(CEC_LOG_ERROR
, "'%s' failed", CCECAdapterMessage::ToString(msgCode
));
1023 if (!bIsRetry
&& output
->reply
== MSGCODE_COMMAND_REJECTED
&& msgCode
!= MSGCODE_SET_CONTROLLED
)
1025 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting controlled mode and retrying");
1026 if (SetControlledMode(true))
1027 return SendCommand(msgCode
, params
, bExpectAck
, bIsTransmission
, bSendDirectly
, true);
1036 cec_datapacket
CUSBCECAdapterCommunication::GetSetting(cec_adapter_messagecode msgCode
, uint8_t iResponseLength
)
1038 cec_datapacket retVal
;
1041 CCECAdapterMessage params
;
1042 if (!SendCommand(msgCode
, params
, false))
1044 CLibCEC::AddLog(CEC_LOG_ERROR
, "%s failed", CCECAdapterMessage::ToString(msgCode
));
1048 Sleep(250); // TODO ReadFromDevice() isn't waiting for the timeout to pass on win32
1049 ReadFromDevice(CEC_DEFAULT_TRANSMIT_WAIT
, iResponseLength
+ 3 /* start + msgcode + iResponseLength + end */);
1050 CCECAdapterMessage input
;
1053 if (input
.Message() != msgCode
)
1054 CLibCEC::AddLog(CEC_LOG_ERROR
, "invalid response to %s received (%s)", CCECAdapterMessage::ToString(msgCode
), CCECAdapterMessage::ToString(input
.Message()));
1057 for (uint8_t iPtr
= 1; iPtr
< input
.Size(); iPtr
++)
1058 retVal
.PushBack(input
[iPtr
]);
1063 CLibCEC::AddLog(CEC_LOG_ERROR
, "no response to %s received", CCECAdapterMessage::ToString(msgCode
));