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");
207 else if (bStartListening
)
211 CLibCEC::AddLog(CEC_LOG_DEBUG
, "communication thread started");
218 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not create a communication thread");
230 void CUSBCECAdapterCommunication::Close(void)
235 void *CUSBCECAdapterCommunication::Process(void)
237 m_messageProcessor
= new CUSBCECAdapterProcessor(m_callback
);
238 m_messageProcessor
->CreateThread();
242 bool bCommandReceived(false);
243 CTimeout
pingTimeout(CEC_ADAPTER_PING_TIMEOUT
);
247 CLockObject
lock(m_mutex
);
249 bCommandReceived
= m_callback
&& Read(command
, 0) && m_bInitialised
;
252 /* push the next command to the callback method if there is one */
253 if (!IsStopped() && bCommandReceived
)
254 m_messageProcessor
->AddCommand(command
);
256 /* ping the adapter every 15 seconds */
257 if (pingTimeout
.TimeLeft() == 0)
259 pingTimeout
.Init(CEC_ADAPTER_PING_TIMEOUT
);
270 /* stop the message processor */
271 m_messageProcessor
->StopThread();
272 delete m_messageProcessor
;
273 m_messageProcessor
= NULL
;
275 /* notify all threads that are waiting on messages to be sent */
276 CCECAdapterMessage
*msg(NULL
);
277 while (m_outBuffer
.Pop(msg
))
278 msg
->event
.Broadcast();
280 /* set the ackmask to 0 before closing the connection */
281 SetAckMaskInternal(0, true);
283 if (m_iFirmwareVersion
>= 2)
284 SetControlledMode(false);
292 m_rcvCondition
.Broadcast();
296 cec_adapter_message_state
CUSBCECAdapterCommunication::Write(const cec_command
&data
, uint8_t iMaxTries
, uint8_t iLineTimeout
/* = 3 */, uint8_t iRetryLineTimeout
/* = 3 */)
298 cec_adapter_message_state
retVal(ADAPTER_MESSAGE_STATE_UNKNOWN
);
302 CCECAdapterMessage
*output
= new CCECAdapterMessage(data
);
304 /* set the number of retries */
305 if (data
.opcode
== CEC_OPCODE_NONE
) //TODO
306 output
->maxTries
= 1;
307 else if (data
.initiator
!= CECDEVICE_BROADCAST
)
308 output
->maxTries
= iMaxTries
;
310 output
->lineTimeout
= iLineTimeout
;
311 output
->retryTimeout
= iRetryLineTimeout
;
314 if (data
.destination
< 15)
316 CLockObject
lock(m_mutex
);
317 m_bWaitingForAck
[data
.destination
] = true;
321 while (bRetry
&& ++output
->tries
< output
->maxTries
)
323 bRetry
= (!Write(output
) || output
->NeedsRetry()) && output
->transmit_timeout
> 0;
325 Sleep(CEC_DEFAULT_TRANSMIT_RETRY_WAIT
);
327 retVal
= output
->state
;
333 bool CUSBCECAdapterCommunication::Write(CCECAdapterMessage
*data
)
335 data
->state
= ADAPTER_MESSAGE_STATE_WAITING_TO_BE_SENT
;
336 m_outBuffer
.Push(data
);
337 data
->event
.Wait(5000);
339 if ((data
->expectControllerAck
&& data
->state
!= ADAPTER_MESSAGE_STATE_SENT_ACKED
) ||
340 (!data
->expectControllerAck
&& data
->state
!= ADAPTER_MESSAGE_STATE_SENT
))
342 CLibCEC::AddLog(CEC_LOG_DEBUG
, "command was not %s", data
->state
== ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED
? "acked" : "sent");
349 bool CUSBCECAdapterCommunication::Read(cec_command
&command
, uint32_t iTimeout
)
354 CCECAdapterMessage msg
;
355 if (Read(msg
, iTimeout
))
357 if (ParseMessage(msg
))
359 command
= m_currentframe
;
360 m_currentframe
.Clear();
367 bool CUSBCECAdapterCommunication::Read(CCECAdapterMessage
&msg
, uint32_t iTimeout
)
369 CLockObject
lock(m_mutex
);
372 CCECAdapterMessage
*buf(NULL
);
374 if (!m_inBuffer
.Pop(buf
))
376 if (iTimeout
== 0 || !m_rcvCondition
.Wait(m_mutex
, m_bHasData
, iTimeout
))
379 m_bHasData
= !m_inBuffer
.IsEmpty();
384 msg
.packet
= buf
->packet
;
385 msg
.state
= ADAPTER_MESSAGE_STATE_INCOMING
;
392 CStdString
CUSBCECAdapterCommunication::GetError(void) const
395 strError
= m_port
->GetError();
399 bool CUSBCECAdapterCommunication::StartBootloader(void)
405 CLibCEC::AddLog(CEC_LOG_DEBUG
, "starting the bootloader");
407 CCECAdapterMessage params
;
408 return SendCommand(MSGCODE_START_BOOTLOADER
, params
, false);
411 bool CUSBCECAdapterCommunication::PingAdapter(void)
413 CLockObject
lock(m_mutex
);
414 CLibCEC::AddLog(CEC_LOG_DEBUG
, "sending ping");
416 CCECAdapterMessage params
;
417 return SendCommand(MSGCODE_PING
, params
);
420 bool CUSBCECAdapterCommunication::ParseMessage(const CCECAdapterMessage
&msg
)
423 bool bIsError(msg
.IsError());
428 CLockObject
adapterLock(m_mutex
);
429 switch(msg
.Message())
431 case MSGCODE_FRAME_START
:
433 m_currentframe
.Clear();
436 m_currentframe
.initiator
= msg
.Initiator();
437 m_currentframe
.destination
= msg
.Destination();
438 m_currentframe
.ack
= msg
.IsACK();
439 m_currentframe
.eom
= msg
.IsEOM();
441 if (m_currentframe
.ack
== 0x1)
443 m_lastDestination
= m_currentframe
.destination
;
444 if (m_currentframe
.destination
< 15)
446 if (!m_bWaitingForAck
[m_currentframe
.destination
])
447 m_processor
->HandlePoll(m_currentframe
.initiator
, m_currentframe
.destination
);
449 m_bWaitingForAck
[m_currentframe
.destination
] = false;
454 case MSGCODE_RECEIVE_FAILED
:
456 m_currentframe
.Clear();
457 if (m_lastDestination
!= CECDEVICE_UNKNOWN
)
458 bIsError
= m_processor
->HandleReceiveFailed(m_lastDestination
);
461 case MSGCODE_FRAME_DATA
:
465 m_currentframe
.PushBack(msg
[1]);
466 m_currentframe
.eom
= msg
.IsEOM();
474 CLibCEC::AddLog(bIsError
? CEC_LOG_WARNING
: CEC_LOG_DEBUG
, msg
.ToString());
478 uint16_t CUSBCECAdapterCommunication::GetFirmwareVersion(void)
480 uint16_t iReturn(m_iFirmwareVersion
);
482 if (iReturn
== CEC_FW_VERSION_UNKNOWN
)
484 CLockObject
lock(m_mutex
);
485 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting the firmware version");
486 cec_datapacket response
= GetSetting(MSGCODE_FIRMWARE_VERSION
, 2);
487 if (response
.size
== 2)
489 m_iFirmwareVersion
= (response
[0] << 8 | response
[1]);
490 iReturn
= m_iFirmwareVersion
;
491 CLibCEC::AddLog(CEC_LOG_DEBUG
, "firmware version %d", m_iFirmwareVersion
);
498 bool CUSBCECAdapterCommunication::SetLineTimeout(uint8_t iTimeout
)
502 if (m_iLineTimeout
!= iTimeout
)
504 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the line timeout to %d", iTimeout
);
505 CCECAdapterMessage params
;
506 params
.PushEscaped(iTimeout
);
507 bReturn
= SendCommand(MSGCODE_TRANSMIT_IDLETIME
, params
);
509 m_iLineTimeout
= iTimeout
;
515 bool CUSBCECAdapterCommunication::SetAckMask(uint16_t iMask
)
517 return SetAckMaskInternal(iMask
, IsRunning());
520 bool CUSBCECAdapterCommunication::SetAckMaskInternal(uint16_t iMask
, bool bWriteDirectly
/* = false */)
522 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting ackmask to %2x", iMask
);
524 CCECAdapterMessage params
;
525 params
.PushEscaped(iMask
>> 8);
526 params
.PushEscaped((uint8_t)iMask
);
527 return SendCommand(MSGCODE_SET_ACK_MASK
, params
, true, false, bWriteDirectly
);
530 bool CUSBCECAdapterCommunication::PersistConfiguration(libcec_configuration
*configuration
)
532 if (m_iFirmwareVersion
< 2)
536 bReturn
&= SetSettingAutoEnabled(true);
537 bReturn
&= SetSettingDeviceType(CLibCEC::GetType(configuration
->logicalAddresses
.primary
));
538 bReturn
&= SetSettingDefaultLogicalAddress(configuration
->logicalAddresses
.primary
);
539 bReturn
&= SetSettingLogicalAddressMask(CLibCEC::GetMaskForType(configuration
->logicalAddresses
.primary
));
540 bReturn
&= SetSettingPhysicalAddress(configuration
->iPhysicalAddress
);
541 bReturn
&= SetSettingCECVersion(CEC_VERSION_1_3A
);
542 bReturn
&= SetSettingOSDName(configuration
->strDeviceName
);
544 bReturn
= WriteEEPROM();
548 bool CUSBCECAdapterCommunication::GetConfiguration(libcec_configuration
*configuration
)
550 configuration
->iFirmwareVersion
= m_iFirmwareVersion
;
551 if (m_iFirmwareVersion
< 2)
555 cec_device_type type
;
556 if (GetSettingDeviceType(type
))
558 CLibCEC::AddLog(CEC_LOG_DEBUG
, "using persisted device type setting %s", m_processor
->ToString(type
));
559 configuration
->deviceTypes
.Clear();
560 configuration
->deviceTypes
.Add(type
);
564 CLibCEC::AddLog(CEC_LOG_DEBUG
, "no persisted device type setting");
568 if (GetSettingPhysicalAddress(configuration
->iPhysicalAddress
))
570 CLibCEC::AddLog(CEC_LOG_DEBUG
, "using persisted physical address setting %4x", configuration
->iPhysicalAddress
);
574 CLibCEC::AddLog(CEC_LOG_DEBUG
, "no persisted physical address setting");
578 CStdString strDeviceName
;
579 if (GetSettingOSDName(strDeviceName
))
581 snprintf(configuration
->strDeviceName
, 13, "%s", strDeviceName
.c_str());
582 CLibCEC::AddLog(CEC_LOG_DEBUG
, "using persisted device name setting %s", configuration
->strDeviceName
);
586 CLibCEC::AddLog(CEC_LOG_DEBUG
, "no persisted device name setting");
590 // don't read the following settings:
591 // - auto enabled (always enabled)
592 // - default logical address (autodetected)
593 // - logical address mask (autodetected)
594 // - CEC version (1.3a)
596 // TODO to be added to the firmware:
597 // - base device (4 bits)
598 // - HDMI port number (4 bits)
599 // - TV vendor id (12 bits)
600 // - wake devices (8 bits)
601 // - standby devices (8 bits)
602 // - use TV menu language (1 bit)
603 // - activate source (1 bit)
604 // - power off screensaver (1 bit)
605 // - power off on standby (1 bit)
606 // - send inactive source (1 bit)
610 bool CUSBCECAdapterCommunication::SetControlledMode(bool controlled
)
612 CLockObject
lock(m_mutex
);
613 CLibCEC::AddLog(CEC_LOG_DEBUG
, "turning controlled mode %s", controlled
? "on" : "off");
615 CCECAdapterMessage params
;
616 params
.PushEscaped(controlled
? 1 : 0);
617 return SendCommand(MSGCODE_SET_CONTROLLED
, params
);
620 bool CUSBCECAdapterCommunication::SetSettingAutoEnabled(bool enabled
)
622 CLockObject
lock(m_mutex
);
623 CLibCEC::AddLog(CEC_LOG_DEBUG
, "turning autonomous mode %s", enabled
? "on" : "off");
625 CCECAdapterMessage params
;
626 params
.PushEscaped(enabled
? 1 : 0);
627 return SendCommand(MSGCODE_SET_AUTO_ENABLED
, params
);
630 bool CUSBCECAdapterCommunication::GetSettingAutoEnabled(bool &enabled
)
632 CLockObject
lock(m_mutex
);
633 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting autonomous mode setting");
635 cec_datapacket response
= GetSetting(MSGCODE_GET_AUTO_ENABLED
, 1);
636 if (response
.size
== 1)
638 enabled
= response
[0] == 1;
644 bool CUSBCECAdapterCommunication::SetSettingDeviceType(cec_device_type type
)
646 CLockObject
lock(m_mutex
);
647 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the device type to %1X", (uint8_t)type
);
649 CCECAdapterMessage params
;
650 params
.PushEscaped((uint8_t)type
);
651 return SendCommand(MSGCODE_SET_DEVICE_TYPE
, params
);
654 bool CUSBCECAdapterCommunication::GetSettingDeviceType(cec_device_type
&value
)
656 CLockObject
lock(m_mutex
);
657 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting device type setting");
659 cec_datapacket response
= GetSetting(MSGCODE_GET_DEVICE_TYPE
, 1);
660 if (response
.size
== 1)
662 value
= (cec_device_type
)response
[0];
668 bool CUSBCECAdapterCommunication::SetSettingDefaultLogicalAddress(cec_logical_address address
)
670 CLockObject
lock(m_mutex
);
671 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the default logical address to %1X", address
);
673 CCECAdapterMessage params
;
674 params
.PushEscaped((uint8_t)address
);
675 return SendCommand(MSGCODE_SET_DEFAULT_LOGICAL_ADDRESS
, params
);
678 bool CUSBCECAdapterCommunication::GetSettingDefaultLogicalAddress(cec_logical_address
&address
)
680 CLockObject
lock(m_mutex
);
681 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting default logical address setting");
683 cec_datapacket response
= GetSetting(MSGCODE_GET_DEFAULT_LOGICAL_ADDRESS
, 1);
684 if (response
.size
== 1)
686 address
= (cec_logical_address
)response
[0];
692 bool CUSBCECAdapterCommunication::SetSettingLogicalAddressMask(uint16_t iMask
)
694 CLockObject
lock(m_mutex
);
695 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the logical address mask to %2X", iMask
);
697 CCECAdapterMessage params
;
698 params
.PushEscaped(iMask
>> 8);
699 params
.PushEscaped((uint8_t)iMask
);
700 return SendCommand(MSGCODE_SET_LOGICAL_ADDRESS_MASK
, params
);
703 bool CUSBCECAdapterCommunication::GetSettingLogicalAddressMask(uint16_t &iMask
)
705 CLockObject
lock(m_mutex
);
706 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting logical address mask setting");
708 cec_datapacket response
= GetSetting(MSGCODE_GET_LOGICAL_ADDRESS_MASK
, 2);
709 if (response
.size
== 2)
711 iMask
= ((uint16_t)response
[0] << 8) | ((uint16_t)response
[1]);
717 bool CUSBCECAdapterCommunication::SetSettingPhysicalAddress(uint16_t iPhysicalAddress
)
719 CLockObject
lock(m_mutex
);
720 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the physical address to %04X", iPhysicalAddress
);
722 CCECAdapterMessage params
;
723 params
.PushEscaped(iPhysicalAddress
>> 8);
724 params
.PushEscaped((uint8_t)iPhysicalAddress
);
725 return SendCommand(MSGCODE_SET_PHYSICAL_ADDRESS
, params
);
728 bool CUSBCECAdapterCommunication::GetSettingPhysicalAddress(uint16_t &iPhysicalAddress
)
730 CLockObject
lock(m_mutex
);
731 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting physical address setting");
733 cec_datapacket response
= GetSetting(MSGCODE_GET_PHYSICAL_ADDRESS
, 2);
734 if (response
.size
== 2)
736 iPhysicalAddress
= ((uint16_t)response
[0] << 8) | ((uint16_t)response
[1]);
742 bool CUSBCECAdapterCommunication::SetSettingCECVersion(cec_version version
)
744 CLockObject
lock(m_mutex
);
745 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the CEC version to %s", CLibCEC::GetInstance()->ToString(version
));
747 CCECAdapterMessage params
;
748 params
.PushEscaped((uint8_t)version
);
749 return SendCommand(MSGCODE_SET_HDMI_VERSION
, params
);
752 bool CUSBCECAdapterCommunication::GetSettingCECVersion(cec_version
&version
)
754 CLockObject
lock(m_mutex
);
755 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting CEC version setting");
757 cec_datapacket response
= GetSetting(MSGCODE_GET_HDMI_VERSION
, 1);
758 if (response
.size
== 1)
760 version
= (cec_version
)response
[0];
766 bool CUSBCECAdapterCommunication::SetSettingOSDName(const char *strOSDName
)
768 CLockObject
lock(m_mutex
);
769 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the OSD name to %s", strOSDName
);
771 CCECAdapterMessage params
;
772 for (size_t iPtr
= 0; iPtr
< strlen(strOSDName
); iPtr
++)
773 params
.PushEscaped(strOSDName
[iPtr
]);
774 return SendCommand(MSGCODE_SET_OSD_NAME
, params
);
777 bool CUSBCECAdapterCommunication::GetSettingOSDName(CStdString
&strOSDName
)
779 CLockObject
lock(m_mutex
);
780 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting OSD name setting");
782 cec_datapacket response
= GetSetting(MSGCODE_GET_OSD_NAME
, 13);
783 if (response
.size
== 0)
787 for (uint8_t iPtr
= 0; iPtr
< response
.size
&& iPtr
< 13; iPtr
++)
788 buf
[iPtr
] = (char)response
[iPtr
];
789 buf
[response
.size
] = 0;
791 strOSDName
.Format("%s", buf
);
795 bool CUSBCECAdapterCommunication::WriteEEPROM(void)
797 CLockObject
lock(m_mutex
);
798 CLibCEC::AddLog(CEC_LOG_DEBUG
, "writing settings in the EEPROM");
800 CCECAdapterMessage params
;
801 return SendCommand(MSGCODE_WRITE_EEPROM
, params
);
804 bool CUSBCECAdapterCommunication::IsOpen(void)
806 return !IsStopped() && m_port
->IsOpen() && IsRunning();
809 bool CUSBCECAdapterCommunication::WaitForAck(CCECAdapterMessage
&message
)
812 bool bTransmitSucceeded(false);
813 uint8_t iPacketsLeft(message
.isTransmission
? message
.Size() / 4 : 1);
815 int64_t iNow
= GetTimeMs();
816 int64_t iTargetTime
= iNow
+ (message
.transmit_timeout
<= 5 ? CEC_DEFAULT_TRANSMIT_WAIT
: message
.transmit_timeout
);
818 while (!bTransmitSucceeded
&& !bError
&& iNow
< iTargetTime
)
821 CCECAdapterMessage msg
;
828 if (msg
.Message() == MSGCODE_FRAME_START
&& msg
.IsACK())
830 if (msg
.Initiator() < 15 && m_bWaitingForAck
[msg
.Initiator()])
831 m_bWaitingForAck
[msg
.Initiator()] = false;
832 else if (msg
.Initiator() < 15)
834 m_processor
->HandlePoll(msg
.Initiator(), msg
.Destination());
835 m_lastDestination
= msg
.Initiator();
841 if (msg
.Message() == MSGCODE_RECEIVE_FAILED
&&
842 m_lastDestination
!= CECDEVICE_UNKNOWN
&&
843 m_processor
->HandleReceiveFailed(m_lastDestination
))
849 bError
= msg
.IsError();
852 message
.reply
= msg
.Message();
853 CLibCEC::AddLog(CEC_LOG_DEBUG
, msg
.ToString());
857 switch(msg
.Message())
859 case MSGCODE_COMMAND_ACCEPTED
:
860 if (iPacketsLeft
> 0)
862 if (!message
.isTransmission
&& iPacketsLeft
== 0)
863 bTransmitSucceeded
= true;
864 CLibCEC::AddLog(CEC_LOG_DEBUG
, "%s - waiting for %d more", msg
.ToString().c_str(), iPacketsLeft
);
866 case MSGCODE_TRANSMIT_SUCCEEDED
:
867 CLibCEC::AddLog(CEC_LOG_DEBUG
, msg
.ToString());
868 bTransmitSucceeded
= (iPacketsLeft
== 0);
869 bError
= !bTransmitSucceeded
;
870 message
.reply
= MSGCODE_TRANSMIT_SUCCEEDED
;
873 // ignore other data while waiting
881 message
.state
= bTransmitSucceeded
&& !bError
?
882 ADAPTER_MESSAGE_STATE_SENT_ACKED
:
883 ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED
;
885 return bTransmitSucceeded
&& !bError
;
888 void CUSBCECAdapterCommunication::AddData(uint8_t *data
, size_t iLen
)
890 CLockObject
lock(m_mutex
);
891 for (size_t iPtr
= 0; iPtr
< iLen
; iPtr
++)
895 if (data
[iPtr
] == MSGSTART
)
898 else if (data
[iPtr
] == MSGSTART
) //we found a msgstart before msgend, this is not right, remove
900 if (m_currentAdapterMessage
.Size() > 0)
901 CLibCEC::AddLog(CEC_LOG_WARNING
, "received MSGSTART before MSGEND, removing previous buffer contents");
902 m_currentAdapterMessage
.Clear();
905 else if (data
[iPtr
] == MSGEND
)
907 CCECAdapterMessage
*newMessage
= new CCECAdapterMessage
;
908 newMessage
->packet
= m_currentAdapterMessage
.packet
;
909 m_inBuffer
.Push(newMessage
);
910 m_currentAdapterMessage
.Clear();
912 m_bNextIsEscaped
= false;
914 m_rcvCondition
.Broadcast();
916 else if (m_bNextIsEscaped
)
918 m_currentAdapterMessage
.PushBack(data
[iPtr
] + (uint8_t)ESCOFFSET
);
919 m_bNextIsEscaped
= false;
921 else if (data
[iPtr
] == MSGESC
)
923 m_bNextIsEscaped
= true;
927 m_currentAdapterMessage
.PushBack(data
[iPtr
]);
932 bool CUSBCECAdapterCommunication::ReadFromDevice(uint32_t iTimeout
, size_t iSize
/* = 256 */)
941 CLockObject
lock(m_mutex
);
942 iBytesRead
= m_port
->Read(buff
, sizeof(uint8_t) * iSize
, iTimeout
);
943 if (iBytesRead
< 0 || iBytesRead
> 256)
945 CLibCEC::AddLog(CEC_LOG_ERROR
, "error reading from serial port: %s", m_port
->GetError().c_str());
949 else if (iBytesRead
> 0)
951 AddData(buff
, iBytesRead
);
954 return iBytesRead
> 0;
957 void CUSBCECAdapterCommunication::SendMessageToAdapter(CCECAdapterMessage
*msg
)
959 CLockObject
adapterLock(m_mutex
);
960 if (!m_port
->IsOpen())
962 CLibCEC::AddLog(CEC_LOG_ERROR
, "error writing to serial port: the connection is closed");
963 msg
->state
= ADAPTER_MESSAGE_STATE_ERROR
;
967 if (msg
->isTransmission
&& (msg
->Size() < 2 || msg
->At(1) != MSGCODE_TRANSMIT_IDLETIME
))
970 SetLineTimeout(msg
->lineTimeout
);
972 SetLineTimeout(msg
->retryTimeout
);
975 if (m_port
->Write(msg
->packet
.data
, msg
->Size()) != (ssize_t
) msg
->Size())
977 CLibCEC::AddLog(CEC_LOG_ERROR
, "error writing to serial port: %s", m_port
->GetError().c_str());
978 msg
->state
= ADAPTER_MESSAGE_STATE_ERROR
;
982 CLibCEC::AddLog(CEC_LOG_DEBUG
, "command sent");
983 msg
->state
= ADAPTER_MESSAGE_STATE_SENT
;
985 if (msg
->expectControllerAck
)
987 if (!WaitForAck(*msg
))
988 CLibCEC::AddLog(CEC_LOG_DEBUG
, "did not receive ack");
994 void CUSBCECAdapterCommunication::WriteNextCommand(void)
996 CCECAdapterMessage
*msg(NULL
);
997 if (m_outBuffer
.Pop(msg
))
998 SendMessageToAdapter(msg
);
1001 CStdString
CUSBCECAdapterCommunication::GetPortName(void)
1004 strName
= m_port
->GetName();
1008 bool CUSBCECAdapterCommunication::SendCommand(cec_adapter_messagecode msgCode
, CCECAdapterMessage
¶ms
, bool bExpectAck
/* = true */, bool bIsTransmission
/* = false */, bool bSendDirectly
/* = true */, bool bIsRetry
/* = false */)
1010 CLockObject
lock(m_mutex
);
1012 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
1014 output
->PushBack(MSGSTART
);
1015 output
->PushEscaped((uint8_t)msgCode
);
1016 output
->Append(params
);
1017 output
->PushBack(MSGEND
);
1018 output
->isTransmission
= bIsTransmission
;
1019 output
->expectControllerAck
= bExpectAck
;
1022 SendMessageToAdapter(output
);
1026 bool bWriteOk
= output
->state
== (output
->expectControllerAck
? ADAPTER_MESSAGE_STATE_SENT_ACKED
: ADAPTER_MESSAGE_STATE_SENT
);
1027 cec_adapter_messagecode reply
= output
->reply
;
1032 CLibCEC::AddLog(CEC_LOG_ERROR
, "'%s' failed", CCECAdapterMessage::ToString(msgCode
));
1034 if (!bIsRetry
&& reply
== MSGCODE_COMMAND_REJECTED
&& msgCode
!= MSGCODE_SET_CONTROLLED
)
1036 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting controlled mode and retrying");
1037 if (SetControlledMode(true))
1038 return SendCommand(msgCode
, params
, bExpectAck
, bIsTransmission
, bSendDirectly
, true);
1046 cec_datapacket
CUSBCECAdapterCommunication::GetSetting(cec_adapter_messagecode msgCode
, uint8_t iResponseLength
)
1048 cec_datapacket retVal
;
1051 CCECAdapterMessage params
;
1052 if (!SendCommand(msgCode
, params
, false))
1054 CLibCEC::AddLog(CEC_LOG_ERROR
, "%s failed", CCECAdapterMessage::ToString(msgCode
));
1058 Sleep(250); // TODO ReadFromDevice() isn't waiting for the timeout to pass on win32
1059 ReadFromDevice(CEC_DEFAULT_TRANSMIT_WAIT
, iResponseLength
+ 3 /* start + msgcode + iResponseLength + end */);
1060 CCECAdapterMessage input
;
1063 if (input
.Message() != msgCode
)
1064 CLibCEC::AddLog(CEC_LOG_ERROR
, "invalid response to %s received (%s)", CCECAdapterMessage::ToString(msgCode
), CCECAdapterMessage::ToString(input
.Message()));
1067 for (uint8_t iPtr
= 1; iPtr
< input
.Size(); iPtr
++)
1068 retVal
.PushBack(input
[iPtr
]);
1073 CLibCEC::AddLog(CEC_LOG_ERROR
, "no response to %s received", CCECAdapterMessage::ToString(msgCode
));