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 CUSBCECAdapterCommunication::~CUSBCECAdapterCommunication(void)
85 bool CUSBCECAdapterCommunication::CheckAdapter(uint32_t iTimeoutMs
/* = 10000 */)
88 uint64_t iNow
= GetTimeMs();
89 uint64_t iTarget
= iTimeoutMs
> 0 ? iNow
+ iTimeoutMs
: iNow
+ CEC_DEFAULT_TRANSMIT_WAIT
;
91 /* try to ping the adapter */
94 while (iNow
< iTarget
&& (bPinged
= PingAdapter()) == false)
96 CLibCEC::AddLog(CEC_LOG_ERROR
, "the adapter did not respond correctly to a ping (try %d)", ++iPingTry
);
101 /* try to read the firmware version */
102 m_iFirmwareVersion
= CEC_FW_VERSION_UNKNOWN
;
103 unsigned iFwVersionTry(0);
104 while (bPinged
&& iNow
< iTarget
&& (m_iFirmwareVersion
= GetFirmwareVersion()) == CEC_FW_VERSION_UNKNOWN
&& iFwVersionTry
< 3)
106 CLibCEC::AddLog(CEC_LOG_WARNING
, "the adapter did not respond with a correct firmware version (try %d)", ++iFwVersionTry
);
111 if (m_iFirmwareVersion
== CEC_FW_VERSION_UNKNOWN
)
113 CLibCEC::AddLog(CEC_LOG_DEBUG
, "defaulting to firmware version 1");
114 m_iFirmwareVersion
= 1;
117 if (m_iFirmwareVersion
>= 2)
119 /* try to set controlled mode */
120 unsigned iControlledTry(0);
121 bool bControlled(false);
122 while (iNow
< iTarget
&& (bControlled
= SetControlledMode(true)) == false)
124 CLibCEC::AddLog(CEC_LOG_ERROR
, "the adapter did not respond correctly to setting controlled mode (try %d)", ++iControlledTry
);
128 bReturn
= bControlled
;
134 CLockObject
lock(m_mutex
);
135 m_bInitialised
= bReturn
;
141 bool CUSBCECAdapterCommunication::Open(IAdapterCommunicationCallback
*cb
, uint32_t iTimeoutMs
/* = 10000 */, bool bSkipChecks
/* = false */)
143 uint64_t iNow
= GetTimeMs();
144 uint64_t iTimeout
= iNow
+ iTimeoutMs
;
147 CLockObject
lock(m_mutex
);
151 CLibCEC::AddLog(CEC_LOG_ERROR
, "port is NULL");
157 CLibCEC::AddLog(CEC_LOG_ERROR
, "port is already open");
163 bool bConnected(false);
164 while (!bConnected
&& iNow
< iTimeout
)
166 if ((bConnected
= m_port
->Open(iTimeout
)) == false)
168 strError
.Format("error opening serial port '%s': %s", m_port
->GetName().c_str(), m_port
->GetError().c_str());
176 CLibCEC::AddLog(CEC_LOG_ERROR
, strError
);
180 CLibCEC::AddLog(CEC_LOG_DEBUG
, "connection opened, clearing any previous input and waiting for active transmissions to end before starting");
184 //clear any input bytes
186 ssize_t
iBytesRead(0);
187 bool bGotMsgStart(false), bGotMsgEnd(false);
188 while ((iBytesRead
= m_port
->Read(buff
, 1024, 100)) > 0 || (bGotMsgStart
&& !bGotMsgEnd
))
191 CLibCEC::AddLog(CEC_LOG_DEBUG
, "data received, clearing it");
192 // if something was received, wait for MSGEND
193 for (ssize_t iPtr
= 0; iPtr
< iBytesRead
; iPtr
++)
195 if (buff
[iPtr
] == MSGSTART
)
197 else if (buff
[iPtr
] == MSGEND
)
205 if (!bSkipChecks
&& !CheckAdapter())
207 CLibCEC::AddLog(CEC_LOG_ERROR
, "the adapter failed to pass basic checks");
214 CLibCEC::AddLog(CEC_LOG_DEBUG
, "communication thread started");
219 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not create a communication thread");
226 void CUSBCECAdapterCommunication::Close(void)
231 void *CUSBCECAdapterCommunication::Process(void)
233 m_messageProcessor
= new CUSBCECAdapterProcessor(m_callback
);
234 m_messageProcessor
->CreateThread();
238 bool bCommandReceived(false);
239 CTimeout
pingTimeout(CEC_ADAPTER_PING_TIMEOUT
);
243 CLockObject
lock(m_mutex
);
245 bCommandReceived
= m_callback
&& Read(command
, 0) && m_bInitialised
;
248 /* push the next command to the callback method if there is one */
249 if (!IsStopped() && bCommandReceived
)
250 m_messageProcessor
->AddCommand(command
);
252 /* ping the adapter every 15 seconds */
253 if (pingTimeout
.TimeLeft() == 0)
255 pingTimeout
.Init(CEC_ADAPTER_PING_TIMEOUT
);
266 /* stop the message processor */
267 m_messageProcessor
->StopThread();
268 delete m_messageProcessor
;
270 /* notify all threads that are waiting on messages to be sent */
271 CCECAdapterMessage
*msg(NULL
);
272 while (m_outBuffer
.Pop(msg
))
273 msg
->event
.Broadcast();
275 /* set the ackmask to 0 before closing the connection */
276 SetAckMaskInternal(0, true);
278 if (m_iFirmwareVersion
>= 2)
279 SetControlledMode(false);
290 cec_adapter_message_state
CUSBCECAdapterCommunication::Write(const cec_command
&data
, uint8_t iMaxTries
, uint8_t iLineTimeout
/* = 3 */, uint8_t iRetryLineTimeout
/* = 3 */)
292 cec_adapter_message_state
retVal(ADAPTER_MESSAGE_STATE_UNKNOWN
);
296 CCECAdapterMessage
*output
= new CCECAdapterMessage(data
);
298 /* set the number of retries */
299 if (data
.opcode
== CEC_OPCODE_NONE
) //TODO
300 output
->maxTries
= 1;
301 else if (data
.initiator
!= CECDEVICE_BROADCAST
)
302 output
->maxTries
= iMaxTries
;
304 output
->lineTimeout
= iLineTimeout
;
305 output
->retryTimeout
= iRetryLineTimeout
;
309 CLockObject
lock(m_mutex
);
310 m_bWaitingForAck
[data
.destination
] = true;
314 while (bRetry
&& ++output
->tries
< output
->maxTries
)
316 bRetry
= (!Write(output
) || output
->NeedsRetry()) && output
->transmit_timeout
> 0;
318 Sleep(CEC_DEFAULT_TRANSMIT_RETRY_WAIT
);
320 retVal
= output
->state
;
326 bool CUSBCECAdapterCommunication::Write(CCECAdapterMessage
*data
)
328 data
->state
= ADAPTER_MESSAGE_STATE_WAITING_TO_BE_SENT
;
329 m_outBuffer
.Push(data
);
330 data
->event
.Wait(5000);
332 if ((data
->expectControllerAck
&& data
->state
!= ADAPTER_MESSAGE_STATE_SENT_ACKED
) ||
333 (!data
->expectControllerAck
&& data
->state
!= ADAPTER_MESSAGE_STATE_SENT
))
335 CLibCEC::AddLog(CEC_LOG_DEBUG
, "command was not %s", data
->state
== ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED
? "acked" : "sent");
342 bool CUSBCECAdapterCommunication::Read(cec_command
&command
, uint32_t iTimeout
)
347 CCECAdapterMessage msg
;
348 if (Read(msg
, iTimeout
))
350 if (ParseMessage(msg
))
352 command
= m_currentframe
;
353 m_currentframe
.Clear();
360 bool CUSBCECAdapterCommunication::Read(CCECAdapterMessage
&msg
, uint32_t iTimeout
)
362 CLockObject
lock(m_mutex
);
365 CCECAdapterMessage
*buf(NULL
);
367 if (!m_inBuffer
.Pop(buf
))
369 if (iTimeout
== 0 || !m_rcvCondition
.Wait(m_mutex
, m_bHasData
, iTimeout
))
372 m_bHasData
= !m_inBuffer
.IsEmpty();
377 msg
.packet
= buf
->packet
;
378 msg
.state
= ADAPTER_MESSAGE_STATE_INCOMING
;
385 CStdString
CUSBCECAdapterCommunication::GetError(void) const
388 strError
= m_port
->GetError();
392 bool CUSBCECAdapterCommunication::StartBootloader(void)
398 CLibCEC::AddLog(CEC_LOG_DEBUG
, "starting the bootloader");
400 CCECAdapterMessage params
;
401 return SendCommand(MSGCODE_START_BOOTLOADER
, params
, false);
404 bool CUSBCECAdapterCommunication::PingAdapter(void)
406 CLockObject
lock(m_mutex
);
407 CLibCEC::AddLog(CEC_LOG_DEBUG
, "sending ping");
409 CCECAdapterMessage params
;
410 return SendCommand(MSGCODE_PING
, params
);
413 bool CUSBCECAdapterCommunication::ParseMessage(const CCECAdapterMessage
&msg
)
416 bool bIsError(msg
.IsError());
421 CLockObject
adapterLock(m_mutex
);
422 switch(msg
.Message())
424 case MSGCODE_FRAME_START
:
426 m_currentframe
.Clear();
429 m_currentframe
.initiator
= msg
.Initiator();
430 m_currentframe
.destination
= msg
.Destination();
431 m_currentframe
.ack
= msg
.IsACK();
432 m_currentframe
.eom
= msg
.IsEOM();
434 if (m_currentframe
.ack
== 0x1)
436 m_lastDestination
= m_currentframe
.destination
;
437 if (!m_bWaitingForAck
[m_currentframe
.destination
])
438 m_processor
->HandlePoll(m_currentframe
.initiator
, m_currentframe
.destination
);
440 m_bWaitingForAck
[m_currentframe
.destination
] = false;
444 case MSGCODE_RECEIVE_FAILED
:
446 m_currentframe
.Clear();
447 if (m_lastDestination
!= CECDEVICE_UNKNOWN
)
448 bIsError
= m_processor
->HandleReceiveFailed(m_lastDestination
);
451 case MSGCODE_FRAME_DATA
:
455 m_currentframe
.PushBack(msg
[1]);
456 m_currentframe
.eom
= msg
.IsEOM();
464 CLibCEC::AddLog(bIsError
? CEC_LOG_WARNING
: CEC_LOG_DEBUG
, msg
.ToString());
468 uint16_t CUSBCECAdapterCommunication::GetFirmwareVersion(void)
470 uint16_t iReturn(m_iFirmwareVersion
);
472 if (iReturn
== CEC_FW_VERSION_UNKNOWN
)
474 CLockObject
lock(m_mutex
);
475 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting the firmware version");
476 cec_datapacket response
= GetSetting(MSGCODE_FIRMWARE_VERSION
, 2);
477 if (response
.size
== 2)
479 m_iFirmwareVersion
= (response
[0] << 8 | response
[1]);
480 iReturn
= m_iFirmwareVersion
;
481 CLibCEC::AddLog(CEC_LOG_DEBUG
, "firmware version %d", m_iFirmwareVersion
);
488 bool CUSBCECAdapterCommunication::SetLineTimeout(uint8_t iTimeout
)
492 if (m_iLineTimeout
!= iTimeout
)
494 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the line timeout to %d", iTimeout
);
495 CCECAdapterMessage params
;
496 params
.PushEscaped(iTimeout
);
497 bReturn
= SendCommand(MSGCODE_TRANSMIT_IDLETIME
, params
);
499 m_iLineTimeout
= iTimeout
;
505 bool CUSBCECAdapterCommunication::SetAckMask(uint16_t iMask
)
507 return SetAckMaskInternal(iMask
, IsRunning());
510 bool CUSBCECAdapterCommunication::SetAckMaskInternal(uint16_t iMask
, bool bWriteDirectly
/* = false */)
512 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting ackmask to %2x", iMask
);
514 CCECAdapterMessage params
;
515 params
.PushEscaped(iMask
>> 8);
516 params
.PushEscaped((uint8_t)iMask
);
517 return SendCommand(MSGCODE_SET_ACK_MASK
, params
, true, false, bWriteDirectly
);
520 bool CUSBCECAdapterCommunication::PersistConfiguration(libcec_configuration
*configuration
)
522 if (m_iFirmwareVersion
< 2)
526 bReturn
&= SetSettingAutoEnabled(true);
527 bReturn
&= SetSettingDeviceType(CLibCEC::GetType(configuration
->logicalAddresses
.primary
));
528 bReturn
&= SetSettingDefaultLogicalAddress(configuration
->logicalAddresses
.primary
);
529 bReturn
&= SetSettingLogicalAddressMask(CLibCEC::GetMaskForType(configuration
->logicalAddresses
.primary
));
530 bReturn
&= SetSettingPhysicalAddress(configuration
->iPhysicalAddress
);
531 bReturn
&= SetSettingCECVersion(CEC_VERSION_1_3A
);
532 bReturn
&= SetSettingOSDName(configuration
->strDeviceName
);
534 bReturn
= WriteEEPROM();
538 bool CUSBCECAdapterCommunication::GetConfiguration(libcec_configuration
*configuration
)
540 if (m_iFirmwareVersion
< 2)
544 cec_device_type type
;
545 if (GetSettingDeviceType(type
))
547 CLibCEC::AddLog(CEC_LOG_DEBUG
, "using persisted device type setting %s", m_processor
->ToString(type
));
548 configuration
->deviceTypes
.Clear();
549 configuration
->deviceTypes
.Add(type
);
553 CLibCEC::AddLog(CEC_LOG_DEBUG
, "no persisted device type setting");
557 if (GetSettingPhysicalAddress(configuration
->iPhysicalAddress
))
559 CLibCEC::AddLog(CEC_LOG_DEBUG
, "using persisted physical address setting %4x", configuration
->iPhysicalAddress
);
563 CLibCEC::AddLog(CEC_LOG_DEBUG
, "no persisted physical address setting");
567 CStdString strDeviceName
;
568 if (GetSettingOSDName(strDeviceName
))
570 snprintf(configuration
->strDeviceName
, 13, "%s", strDeviceName
.c_str());
571 CLibCEC::AddLog(CEC_LOG_DEBUG
, "using persisted device name setting %s", configuration
->strDeviceName
);
575 CLibCEC::AddLog(CEC_LOG_DEBUG
, "no persisted device name setting");
579 // don't read the following settings:
580 // - auto enabled (always enabled)
581 // - default logical address (autodetected)
582 // - logical address mask (autodetected)
583 // - CEC version (1.3a)
585 // TODO to be added to the firmware:
586 // - base device (4 bits)
587 // - HDMI port number (4 bits)
588 // - TV vendor id (12 bits)
589 // - wake devices (8 bits)
590 // - standby devices (8 bits)
591 // - use TV menu language (1 bit)
592 // - activate source (1 bit)
593 // - power off screensaver (1 bit)
594 // - power off on standby (1 bit)
595 // - send inactive source (1 bit)
599 bool CUSBCECAdapterCommunication::SetControlledMode(bool controlled
)
601 CLockObject
lock(m_mutex
);
602 CLibCEC::AddLog(CEC_LOG_DEBUG
, "turning controlled mode %s", controlled
? "on" : "off");
604 CCECAdapterMessage params
;
605 params
.PushEscaped(controlled
? 1 : 0);
606 return SendCommand(MSGCODE_SET_CONTROLLED
, params
);
609 bool CUSBCECAdapterCommunication::SetSettingAutoEnabled(bool enabled
)
611 CLockObject
lock(m_mutex
);
612 CLibCEC::AddLog(CEC_LOG_DEBUG
, "turning autonomous mode %s", enabled
? "on" : "off");
614 CCECAdapterMessage params
;
615 params
.PushEscaped(enabled
? 1 : 0);
616 return SendCommand(MSGCODE_SET_AUTO_ENABLED
, params
);
619 bool CUSBCECAdapterCommunication::GetSettingAutoEnabled(bool &enabled
)
621 CLockObject
lock(m_mutex
);
622 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting autonomous mode setting");
624 cec_datapacket response
= GetSetting(MSGCODE_GET_AUTO_ENABLED
, 1);
625 if (response
.size
== 1)
627 enabled
= response
[0] == 1;
633 bool CUSBCECAdapterCommunication::SetSettingDeviceType(cec_device_type type
)
635 CLockObject
lock(m_mutex
);
636 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the device type to %1X", (uint8_t)type
);
638 CCECAdapterMessage params
;
639 params
.PushEscaped((uint8_t)type
);
640 return SendCommand(MSGCODE_SET_DEVICE_TYPE
, params
);
643 bool CUSBCECAdapterCommunication::GetSettingDeviceType(cec_device_type
&value
)
645 CLockObject
lock(m_mutex
);
646 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting device type setting");
648 cec_datapacket response
= GetSetting(MSGCODE_GET_DEVICE_TYPE
, 1);
649 if (response
.size
== 1)
651 value
= (cec_device_type
)response
[0];
657 bool CUSBCECAdapterCommunication::SetSettingDefaultLogicalAddress(cec_logical_address address
)
659 CLockObject
lock(m_mutex
);
660 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the default logical address to %1X", address
);
662 CCECAdapterMessage params
;
663 params
.PushEscaped((uint8_t)address
);
664 return SendCommand(MSGCODE_SET_DEFAULT_LOGICAL_ADDRESS
, params
);
667 bool CUSBCECAdapterCommunication::GetSettingDefaultLogicalAddress(cec_logical_address
&address
)
669 CLockObject
lock(m_mutex
);
670 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting default logical address setting");
672 cec_datapacket response
= GetSetting(MSGCODE_GET_DEFAULT_LOGICAL_ADDRESS
, 1);
673 if (response
.size
== 1)
675 address
= (cec_logical_address
)response
[0];
681 bool CUSBCECAdapterCommunication::SetSettingLogicalAddressMask(uint16_t iMask
)
683 CLockObject
lock(m_mutex
);
684 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the logical address mask to %2X", iMask
);
686 CCECAdapterMessage params
;
687 params
.PushEscaped(iMask
>> 8);
688 params
.PushEscaped((uint8_t)iMask
);
689 return SendCommand(MSGCODE_SET_LOGICAL_ADDRESS_MASK
, params
);
692 bool CUSBCECAdapterCommunication::GetSettingLogicalAddressMask(uint16_t &iMask
)
694 CLockObject
lock(m_mutex
);
695 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting logical address mask setting");
697 cec_datapacket response
= GetSetting(MSGCODE_GET_LOGICAL_ADDRESS_MASK
, 2);
698 if (response
.size
== 2)
700 iMask
= ((uint16_t)response
[0] << 8) | ((uint16_t)response
[1]);
706 bool CUSBCECAdapterCommunication::SetSettingPhysicalAddress(uint16_t iPhysicalAddress
)
708 CLockObject
lock(m_mutex
);
709 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the physical address to %04X", iPhysicalAddress
);
711 CCECAdapterMessage params
;
712 params
.PushEscaped(iPhysicalAddress
>> 8);
713 params
.PushEscaped((uint8_t)iPhysicalAddress
);
714 return SendCommand(MSGCODE_SET_PHYSICAL_ADDRESS
, params
);
717 bool CUSBCECAdapterCommunication::GetSettingPhysicalAddress(uint16_t &iPhysicalAddress
)
719 CLockObject
lock(m_mutex
);
720 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting physical address setting");
722 cec_datapacket response
= GetSetting(MSGCODE_GET_PHYSICAL_ADDRESS
, 2);
723 if (response
.size
== 2)
725 iPhysicalAddress
= ((uint16_t)response
[0] << 8) | ((uint16_t)response
[1]);
731 bool CUSBCECAdapterCommunication::SetSettingCECVersion(cec_version version
)
733 CLockObject
lock(m_mutex
);
734 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the CEC version to %s", CLibCEC::GetInstance()->ToString(version
));
736 CCECAdapterMessage params
;
737 params
.PushEscaped((uint8_t)version
);
738 return SendCommand(MSGCODE_SET_HDMI_VERSION
, params
);
741 bool CUSBCECAdapterCommunication::GetSettingCECVersion(cec_version
&version
)
743 CLockObject
lock(m_mutex
);
744 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting CEC version setting");
746 cec_datapacket response
= GetSetting(MSGCODE_GET_HDMI_VERSION
, 1);
747 if (response
.size
== 1)
749 version
= (cec_version
)response
[0];
755 bool CUSBCECAdapterCommunication::SetSettingOSDName(const char *strOSDName
)
757 CLockObject
lock(m_mutex
);
758 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the OSD name to %s", strOSDName
);
760 CCECAdapterMessage params
;
761 for (size_t iPtr
= 0; iPtr
< strlen(strOSDName
); iPtr
++)
762 params
.PushEscaped(strOSDName
[iPtr
]);
763 return SendCommand(MSGCODE_SET_OSD_NAME
, params
);
766 bool CUSBCECAdapterCommunication::GetSettingOSDName(CStdString
&strOSDName
)
768 CLockObject
lock(m_mutex
);
769 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting OSD name setting");
771 cec_datapacket response
= GetSetting(MSGCODE_GET_OSD_NAME
, 13);
772 if (response
.size
== 0)
776 for (uint8_t iPtr
= 0; iPtr
< response
.size
&& iPtr
< 13; iPtr
++)
777 buf
[iPtr
] = (char)response
[iPtr
];
778 buf
[response
.size
] = 0;
780 strOSDName
.Format("%s", buf
);
784 bool CUSBCECAdapterCommunication::WriteEEPROM(void)
786 CLockObject
lock(m_mutex
);
787 CLibCEC::AddLog(CEC_LOG_DEBUG
, "writing settings in the EEPROM");
789 CCECAdapterMessage params
;
790 return SendCommand(MSGCODE_WRITE_EEPROM
, params
);
793 bool CUSBCECAdapterCommunication::IsOpen(void)
795 return !IsStopped() && m_port
->IsOpen() && IsRunning();
798 bool CUSBCECAdapterCommunication::WaitForAck(CCECAdapterMessage
&message
)
801 bool bTransmitSucceeded(false);
802 uint8_t iPacketsLeft(message
.isTransmission
? message
.Size() / 4 : 1);
804 int64_t iNow
= GetTimeMs();
805 int64_t iTargetTime
= iNow
+ (message
.transmit_timeout
<= 5 ? CEC_DEFAULT_TRANSMIT_WAIT
: message
.transmit_timeout
);
807 while (!bTransmitSucceeded
&& !bError
&& iNow
< iTargetTime
)
810 CCECAdapterMessage msg
;
817 if (msg
.Message() == MSGCODE_FRAME_START
&& msg
.IsACK())
819 if (m_bWaitingForAck
[msg
.Initiator()])
820 m_bWaitingForAck
[msg
.Initiator()] = false;
823 m_processor
->HandlePoll(msg
.Initiator(), msg
.Destination());
824 m_lastDestination
= msg
.Initiator();
830 if (msg
.Message() == MSGCODE_RECEIVE_FAILED
&&
831 m_lastDestination
!= CECDEVICE_UNKNOWN
&&
832 m_processor
->HandleReceiveFailed(m_lastDestination
))
838 bError
= msg
.IsError();
841 message
.reply
= msg
.Message();
842 CLibCEC::AddLog(CEC_LOG_DEBUG
, msg
.ToString());
846 switch(msg
.Message())
848 case MSGCODE_COMMAND_ACCEPTED
:
849 if (iPacketsLeft
> 0)
851 if (!message
.isTransmission
&& iPacketsLeft
== 0)
852 bTransmitSucceeded
= true;
853 CLibCEC::AddLog(CEC_LOG_DEBUG
, "%s - waiting for %d more", msg
.ToString().c_str(), iPacketsLeft
);
855 case MSGCODE_TRANSMIT_SUCCEEDED
:
856 CLibCEC::AddLog(CEC_LOG_DEBUG
, msg
.ToString());
857 bTransmitSucceeded
= (iPacketsLeft
== 0);
858 bError
= !bTransmitSucceeded
;
859 message
.reply
= MSGCODE_TRANSMIT_SUCCEEDED
;
862 // ignore other data while waiting
870 message
.state
= bTransmitSucceeded
&& !bError
?
871 ADAPTER_MESSAGE_STATE_SENT_ACKED
:
872 ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED
;
874 return bTransmitSucceeded
&& !bError
;
877 void CUSBCECAdapterCommunication::AddData(uint8_t *data
, size_t iLen
)
879 CLockObject
lock(m_mutex
);
880 for (size_t iPtr
= 0; iPtr
< iLen
; iPtr
++)
884 if (data
[iPtr
] == MSGSTART
)
887 else if (data
[iPtr
] == MSGSTART
) //we found a msgstart before msgend, this is not right, remove
889 if (m_currentAdapterMessage
.Size() > 0)
890 CLibCEC::AddLog(CEC_LOG_WARNING
, "received MSGSTART before MSGEND, removing previous buffer contents");
891 m_currentAdapterMessage
.Clear();
894 else if (data
[iPtr
] == MSGEND
)
896 CCECAdapterMessage
*newMessage
= new CCECAdapterMessage
;
897 newMessage
->packet
= m_currentAdapterMessage
.packet
;
898 m_inBuffer
.Push(newMessage
);
899 m_currentAdapterMessage
.Clear();
901 m_bNextIsEscaped
= false;
903 m_rcvCondition
.Broadcast();
905 else if (m_bNextIsEscaped
)
907 m_currentAdapterMessage
.PushBack(data
[iPtr
] + (uint8_t)ESCOFFSET
);
908 m_bNextIsEscaped
= false;
910 else if (data
[iPtr
] == MSGESC
)
912 m_bNextIsEscaped
= true;
916 m_currentAdapterMessage
.PushBack(data
[iPtr
]);
921 bool CUSBCECAdapterCommunication::ReadFromDevice(uint32_t iTimeout
, size_t iSize
/* = 256 */)
930 CLockObject
lock(m_mutex
);
931 iBytesRead
= m_port
->Read(buff
, sizeof(uint8_t) * iSize
, iTimeout
);
932 if (iBytesRead
< 0 || iBytesRead
> 256)
934 CLibCEC::AddLog(CEC_LOG_ERROR
, "error reading from serial port: %s", m_port
->GetError().c_str());
938 else if (iBytesRead
> 0)
940 AddData(buff
, iBytesRead
);
943 return iBytesRead
> 0;
946 void CUSBCECAdapterCommunication::SendMessageToAdapter(CCECAdapterMessage
*msg
)
948 CLockObject
adapterLock(m_mutex
);
949 if (!m_port
->IsOpen())
951 CLibCEC::AddLog(CEC_LOG_ERROR
, "error writing to serial port: the connection is closed");
952 msg
->state
= ADAPTER_MESSAGE_STATE_ERROR
;
956 if (msg
->isTransmission
&& (msg
->Size() < 2 || msg
->At(1) != MSGCODE_TRANSMIT_IDLETIME
))
959 SetLineTimeout(msg
->lineTimeout
);
961 SetLineTimeout(msg
->retryTimeout
);
964 if (m_port
->Write(msg
->packet
.data
, msg
->Size()) != (ssize_t
) msg
->Size())
966 CLibCEC::AddLog(CEC_LOG_ERROR
, "error writing to serial port: %s", m_port
->GetError().c_str());
967 msg
->state
= ADAPTER_MESSAGE_STATE_ERROR
;
971 CLibCEC::AddLog(CEC_LOG_DEBUG
, "command sent");
972 msg
->state
= ADAPTER_MESSAGE_STATE_SENT
;
974 if (msg
->expectControllerAck
)
976 if (!WaitForAck(*msg
))
977 CLibCEC::AddLog(CEC_LOG_DEBUG
, "did not receive ack");
983 void CUSBCECAdapterCommunication::WriteNextCommand(void)
985 CCECAdapterMessage
*msg(NULL
);
986 if (m_outBuffer
.Pop(msg
))
987 SendMessageToAdapter(msg
);
990 CStdString
CUSBCECAdapterCommunication::GetPortName(void)
993 strName
= m_port
->GetName();
997 bool CUSBCECAdapterCommunication::SendCommand(cec_adapter_messagecode msgCode
, CCECAdapterMessage
¶ms
, bool bExpectAck
/* = true */, bool bIsTransmission
/* = false */, bool bSendDirectly
/* = true */, bool bIsRetry
/* = false */)
999 CLockObject
lock(m_mutex
);
1001 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
1003 output
->PushBack(MSGSTART
);
1004 output
->PushEscaped((uint8_t)msgCode
);
1005 output
->Append(params
);
1006 output
->PushBack(MSGEND
);
1007 output
->isTransmission
= bIsTransmission
;
1008 output
->expectControllerAck
= bExpectAck
;
1011 SendMessageToAdapter(output
);
1015 bool bWriteOk
= output
->state
== (output
->expectControllerAck
? ADAPTER_MESSAGE_STATE_SENT_ACKED
: ADAPTER_MESSAGE_STATE_SENT
);
1018 CLibCEC::AddLog(CEC_LOG_ERROR
, "'%s' failed", CCECAdapterMessage::ToString(msgCode
));
1021 if (!bIsRetry
&& output
->reply
== MSGCODE_COMMAND_REJECTED
&& msgCode
!= MSGCODE_SET_CONTROLLED
)
1023 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting controlled mode and retrying");
1024 if (SetControlledMode(true))
1025 return SendCommand(msgCode
, params
, bExpectAck
, bIsTransmission
, bSendDirectly
, true);
1034 cec_datapacket
CUSBCECAdapterCommunication::GetSetting(cec_adapter_messagecode msgCode
, uint8_t iResponseLength
)
1036 cec_datapacket retVal
;
1039 CCECAdapterMessage params
;
1040 if (!SendCommand(msgCode
, params
, false))
1042 CLibCEC::AddLog(CEC_LOG_ERROR
, "%s failed", CCECAdapterMessage::ToString(msgCode
));
1046 Sleep(250); // TODO ReadFromDevice() isn't waiting for the timeout to pass on win32
1047 ReadFromDevice(CEC_DEFAULT_TRANSMIT_WAIT
, iResponseLength
+ 3 /* start + msgcode + iResponseLength + end */);
1048 CCECAdapterMessage input
;
1051 if (input
.Message() != msgCode
)
1052 CLibCEC::AddLog(CEC_LOG_ERROR
, "invalid response to %s received (%s)", CCECAdapterMessage::ToString(msgCode
), CCECAdapterMessage::ToString(input
.Message()));
1055 for (uint8_t iPtr
= 1; iPtr
< input
.Size(); iPtr
++)
1056 retVal
.PushBack(input
[iPtr
]);
1061 CLibCEC::AddLog(CEC_LOG_ERROR
, "no response to %s received", CCECAdapterMessage::ToString(msgCode
));