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 */)
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");
209 CLibCEC::AddLog(CEC_LOG_DEBUG
, "communication thread started");
214 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not create a communication thread");
221 void CUSBCECAdapterCommunication::Close(void)
226 void *CUSBCECAdapterCommunication::Process(void)
228 m_messageProcessor
= new CUSBCECAdapterProcessor(m_callback
);
229 m_messageProcessor
->CreateThread();
233 bool bCommandReceived(false);
234 CTimeout
pingTimeout(CEC_ADAPTER_PING_TIMEOUT
);
238 CLockObject
lock(m_mutex
);
240 bCommandReceived
= m_callback
&& Read(command
, 0) && m_bInitialised
;
243 /* push the next command to the callback method if there is one */
244 if (!IsStopped() && bCommandReceived
)
245 m_messageProcessor
->AddCommand(command
);
247 /* ping the adapter every 15 seconds */
248 if (pingTimeout
.TimeLeft() == 0)
250 pingTimeout
.Init(CEC_ADAPTER_PING_TIMEOUT
);
261 /* stop the message processor */
262 m_messageProcessor
->StopThread();
263 delete m_messageProcessor
;
265 /* notify all threads that are waiting on messages to be sent */
266 CCECAdapterMessage
*msg(NULL
);
267 while (m_outBuffer
.Pop(msg
))
268 msg
->event
.Broadcast();
270 /* set the ackmask to 0 before closing the connection */
271 SetAckMaskInternal(0, true);
273 if (m_iFirmwareVersion
>= 2)
274 SetControlledMode(false);
285 cec_adapter_message_state
CUSBCECAdapterCommunication::Write(const cec_command
&data
, uint8_t iMaxTries
, uint8_t iLineTimeout
/* = 3 */, uint8_t iRetryLineTimeout
/* = 3 */)
287 cec_adapter_message_state
retVal(ADAPTER_MESSAGE_STATE_UNKNOWN
);
291 CCECAdapterMessage
*output
= new CCECAdapterMessage(data
);
293 /* set the number of retries */
294 if (data
.opcode
== CEC_OPCODE_NONE
) //TODO
295 output
->maxTries
= 1;
296 else if (data
.initiator
!= CECDEVICE_BROADCAST
)
297 output
->maxTries
= iMaxTries
;
299 output
->lineTimeout
= iLineTimeout
;
300 output
->retryTimeout
= iRetryLineTimeout
;
304 CLockObject
lock(m_mutex
);
305 m_bWaitingForAck
[data
.destination
] = true;
309 while (bRetry
&& ++output
->tries
< output
->maxTries
)
311 bRetry
= (!Write(output
) || output
->NeedsRetry()) && output
->transmit_timeout
> 0;
313 Sleep(CEC_DEFAULT_TRANSMIT_RETRY_WAIT
);
315 retVal
= output
->state
;
321 bool CUSBCECAdapterCommunication::Write(CCECAdapterMessage
*data
)
323 data
->state
= ADAPTER_MESSAGE_STATE_WAITING_TO_BE_SENT
;
324 m_outBuffer
.Push(data
);
325 data
->event
.Wait(5000);
327 if ((data
->expectControllerAck
&& data
->state
!= ADAPTER_MESSAGE_STATE_SENT_ACKED
) ||
328 (!data
->expectControllerAck
&& data
->state
!= ADAPTER_MESSAGE_STATE_SENT
))
330 CLibCEC::AddLog(CEC_LOG_DEBUG
, "command was not %s", data
->state
== ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED
? "acked" : "sent");
337 bool CUSBCECAdapterCommunication::Read(cec_command
&command
, uint32_t iTimeout
)
342 CCECAdapterMessage msg
;
343 if (Read(msg
, iTimeout
))
345 if (ParseMessage(msg
))
347 command
= m_currentframe
;
348 m_currentframe
.Clear();
355 bool CUSBCECAdapterCommunication::Read(CCECAdapterMessage
&msg
, uint32_t iTimeout
)
357 CLockObject
lock(m_mutex
);
360 CCECAdapterMessage
*buf(NULL
);
362 if (!m_inBuffer
.Pop(buf
))
364 if (iTimeout
== 0 || !m_rcvCondition
.Wait(m_mutex
, m_bHasData
, iTimeout
))
367 m_bHasData
= !m_inBuffer
.IsEmpty();
372 msg
.packet
= buf
->packet
;
373 msg
.state
= ADAPTER_MESSAGE_STATE_INCOMING
;
380 CStdString
CUSBCECAdapterCommunication::GetError(void) const
383 strError
= m_port
->GetError();
387 bool CUSBCECAdapterCommunication::StartBootloader(void)
393 CLibCEC::AddLog(CEC_LOG_DEBUG
, "starting the bootloader");
395 CCECAdapterMessage params
;
396 return SendCommand(MSGCODE_START_BOOTLOADER
, params
, false);
399 bool CUSBCECAdapterCommunication::PingAdapter(void)
401 CLockObject
lock(m_mutex
);
402 CLibCEC::AddLog(CEC_LOG_DEBUG
, "sending ping");
404 CCECAdapterMessage params
;
405 return SendCommand(MSGCODE_PING
, params
);
408 bool CUSBCECAdapterCommunication::ParseMessage(const CCECAdapterMessage
&msg
)
411 bool bIsError(msg
.IsError());
416 CLockObject
adapterLock(m_mutex
);
417 switch(msg
.Message())
419 case MSGCODE_FRAME_START
:
421 m_currentframe
.Clear();
424 m_currentframe
.initiator
= msg
.Initiator();
425 m_currentframe
.destination
= msg
.Destination();
426 m_currentframe
.ack
= msg
.IsACK();
427 m_currentframe
.eom
= msg
.IsEOM();
429 if (m_currentframe
.ack
== 0x1)
431 m_lastDestination
= m_currentframe
.destination
;
432 if (!m_bWaitingForAck
[m_currentframe
.destination
])
433 m_processor
->HandlePoll(m_currentframe
.initiator
, m_currentframe
.destination
);
435 m_bWaitingForAck
[m_currentframe
.destination
] = false;
439 case MSGCODE_RECEIVE_FAILED
:
441 m_currentframe
.Clear();
442 if (m_lastDestination
!= CECDEVICE_UNKNOWN
)
443 bIsError
= m_processor
->HandleReceiveFailed(m_lastDestination
);
446 case MSGCODE_FRAME_DATA
:
450 m_currentframe
.PushBack(msg
[1]);
451 m_currentframe
.eom
= msg
.IsEOM();
459 CLibCEC::AddLog(bIsError
? CEC_LOG_WARNING
: CEC_LOG_DEBUG
, msg
.ToString());
463 uint16_t CUSBCECAdapterCommunication::GetFirmwareVersion(void)
465 uint16_t iReturn(m_iFirmwareVersion
);
467 if (iReturn
== CEC_FW_VERSION_UNKNOWN
)
469 CLockObject
lock(m_mutex
);
470 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting the firmware version");
471 cec_datapacket response
= GetSetting(MSGCODE_FIRMWARE_VERSION
, 2);
472 if (response
.size
== 2)
474 m_iFirmwareVersion
= (response
[0] << 8 | response
[1]);
475 iReturn
= m_iFirmwareVersion
;
476 CLibCEC::AddLog(CEC_LOG_DEBUG
, "firmware version %d", m_iFirmwareVersion
);
483 bool CUSBCECAdapterCommunication::SetLineTimeout(uint8_t iTimeout
)
487 if (m_iLineTimeout
!= iTimeout
)
489 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the line timeout to %d", iTimeout
);
490 CCECAdapterMessage params
;
491 params
.PushEscaped(iTimeout
);
492 bReturn
= SendCommand(MSGCODE_TRANSMIT_IDLETIME
, params
);
494 m_iLineTimeout
= iTimeout
;
500 bool CUSBCECAdapterCommunication::SetAckMask(uint16_t iMask
)
502 return SetAckMaskInternal(iMask
, IsRunning());
505 bool CUSBCECAdapterCommunication::SetAckMaskInternal(uint16_t iMask
, bool bWriteDirectly
/* = false */)
507 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting ackmask to %2x", iMask
);
509 CCECAdapterMessage params
;
510 params
.PushEscaped(iMask
>> 8);
511 params
.PushEscaped((uint8_t)iMask
);
512 return SendCommand(MSGCODE_SET_ACK_MASK
, params
, true, false, bWriteDirectly
);
515 bool CUSBCECAdapterCommunication::PersistConfiguration(libcec_configuration
*configuration
)
517 if (m_iFirmwareVersion
< 2)
521 bReturn
&= SetSettingAutoEnabled(true);
522 bReturn
&= SetSettingDeviceType(CLibCEC::GetType(configuration
->logicalAddresses
.primary
));
523 bReturn
&= SetSettingDefaultLogicalAddress(configuration
->logicalAddresses
.primary
);
524 bReturn
&= SetSettingLogicalAddressMask(CLibCEC::GetMaskForType(configuration
->logicalAddresses
.primary
));
525 bReturn
&= SetSettingPhysicalAddress(configuration
->iPhysicalAddress
);
526 bReturn
&= SetSettingCECVersion(CEC_VERSION_1_3A
);
527 bReturn
&= SetSettingOSDName(configuration
->strDeviceName
);
529 bReturn
= WriteEEPROM();
533 bool CUSBCECAdapterCommunication::GetConfiguration(libcec_configuration
*configuration
)
535 if (m_iFirmwareVersion
< 2)
539 cec_device_type type
;
540 if (GetSettingDeviceType(type
))
542 CLibCEC::AddLog(CEC_LOG_DEBUG
, "using persisted device type setting %s", m_processor
->ToString(type
));
543 configuration
->deviceTypes
.Clear();
544 configuration
->deviceTypes
.Add(type
);
548 CLibCEC::AddLog(CEC_LOG_DEBUG
, "no persisted device type setting");
552 if (GetSettingPhysicalAddress(configuration
->iPhysicalAddress
))
554 CLibCEC::AddLog(CEC_LOG_DEBUG
, "using persisted physical address setting %4x", configuration
->iPhysicalAddress
);
558 CLibCEC::AddLog(CEC_LOG_DEBUG
, "no persisted physical address setting");
562 CStdString strDeviceName
;
563 if (GetSettingOSDName(strDeviceName
))
565 snprintf(configuration
->strDeviceName
, 13, "%s", strDeviceName
.c_str());
566 CLibCEC::AddLog(CEC_LOG_DEBUG
, "using persisted device name setting %s", configuration
->strDeviceName
);
570 CLibCEC::AddLog(CEC_LOG_DEBUG
, "no persisted device name setting");
574 // don't read the following settings:
575 // - auto enabled (always enabled)
576 // - default logical address (autodetected)
577 // - logical address mask (autodetected)
578 // - CEC version (1.3a)
580 // TODO to be added to the firmware:
581 // - base device (4 bits)
582 // - HDMI port number (4 bits)
583 // - TV vendor id (12 bits)
584 // - wake devices (8 bits)
585 // - standby devices (8 bits)
586 // - use TV menu language (1 bit)
587 // - activate source (1 bit)
588 // - power off screensaver (1 bit)
589 // - power off on standby (1 bit)
590 // - send inactive source (1 bit)
594 bool CUSBCECAdapterCommunication::SetControlledMode(bool controlled
)
596 CLockObject
lock(m_mutex
);
597 CLibCEC::AddLog(CEC_LOG_DEBUG
, "turning controlled mode %s", controlled
? "on" : "off");
599 CCECAdapterMessage params
;
600 params
.PushEscaped(controlled
? 1 : 0);
601 return SendCommand(MSGCODE_SET_CONTROLLED
, params
);
604 bool CUSBCECAdapterCommunication::SetSettingAutoEnabled(bool enabled
)
606 CLockObject
lock(m_mutex
);
607 CLibCEC::AddLog(CEC_LOG_DEBUG
, "turning autonomous mode %s", enabled
? "on" : "off");
609 CCECAdapterMessage params
;
610 params
.PushEscaped(enabled
? 1 : 0);
611 return SendCommand(MSGCODE_SET_AUTO_ENABLED
, params
);
614 bool CUSBCECAdapterCommunication::GetSettingAutoEnabled(bool &enabled
)
616 CLockObject
lock(m_mutex
);
617 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting autonomous mode setting");
619 cec_datapacket response
= GetSetting(MSGCODE_GET_AUTO_ENABLED
, 1);
620 if (response
.size
== 1)
622 enabled
= response
[0] == 1;
628 bool CUSBCECAdapterCommunication::SetSettingDeviceType(cec_device_type type
)
630 CLockObject
lock(m_mutex
);
631 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the device type to %1X", (uint8_t)type
);
633 CCECAdapterMessage params
;
634 params
.PushEscaped((uint8_t)type
);
635 return SendCommand(MSGCODE_SET_DEVICE_TYPE
, params
);
638 bool CUSBCECAdapterCommunication::GetSettingDeviceType(cec_device_type
&value
)
640 CLockObject
lock(m_mutex
);
641 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting device type setting");
643 cec_datapacket response
= GetSetting(MSGCODE_GET_DEVICE_TYPE
, 1);
644 if (response
.size
== 1)
646 value
= (cec_device_type
)response
[0];
652 bool CUSBCECAdapterCommunication::SetSettingDefaultLogicalAddress(cec_logical_address address
)
654 CLockObject
lock(m_mutex
);
655 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the default logical address to %1X", address
);
657 CCECAdapterMessage params
;
658 params
.PushEscaped((uint8_t)address
);
659 return SendCommand(MSGCODE_SET_DEFAULT_LOGICAL_ADDRESS
, params
);
662 bool CUSBCECAdapterCommunication::GetSettingDefaultLogicalAddress(cec_logical_address
&address
)
664 CLockObject
lock(m_mutex
);
665 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting default logical address setting");
667 cec_datapacket response
= GetSetting(MSGCODE_GET_DEFAULT_LOGICAL_ADDRESS
, 1);
668 if (response
.size
== 1)
670 address
= (cec_logical_address
)response
[0];
676 bool CUSBCECAdapterCommunication::SetSettingLogicalAddressMask(uint16_t iMask
)
678 CLockObject
lock(m_mutex
);
679 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the logical address mask to %2X", iMask
);
681 CCECAdapterMessage params
;
682 params
.PushEscaped(iMask
>> 8);
683 params
.PushEscaped((uint8_t)iMask
);
684 return SendCommand(MSGCODE_SET_LOGICAL_ADDRESS_MASK
, params
);
687 bool CUSBCECAdapterCommunication::GetSettingLogicalAddressMask(uint16_t &iMask
)
689 CLockObject
lock(m_mutex
);
690 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting logical address mask setting");
692 cec_datapacket response
= GetSetting(MSGCODE_GET_LOGICAL_ADDRESS_MASK
, 2);
693 if (response
.size
== 2)
695 iMask
= ((uint16_t)response
[0] << 8) | ((uint16_t)response
[1]);
701 bool CUSBCECAdapterCommunication::SetSettingPhysicalAddress(uint16_t iPhysicalAddress
)
703 CLockObject
lock(m_mutex
);
704 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the physical address to %04X", iPhysicalAddress
);
706 CCECAdapterMessage params
;
707 params
.PushEscaped(iPhysicalAddress
>> 8);
708 params
.PushEscaped((uint8_t)iPhysicalAddress
);
709 return SendCommand(MSGCODE_SET_PHYSICAL_ADDRESS
, params
);
712 bool CUSBCECAdapterCommunication::GetSettingPhysicalAddress(uint16_t &iPhysicalAddress
)
714 CLockObject
lock(m_mutex
);
715 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting physical address setting");
717 cec_datapacket response
= GetSetting(MSGCODE_GET_PHYSICAL_ADDRESS
, 2);
718 if (response
.size
== 2)
720 iPhysicalAddress
= ((uint16_t)response
[0] << 8) | ((uint16_t)response
[1]);
726 bool CUSBCECAdapterCommunication::SetSettingCECVersion(cec_version version
)
728 CLockObject
lock(m_mutex
);
729 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the CEC version to %s", CLibCEC::GetInstance()->ToString(version
));
731 CCECAdapterMessage params
;
732 params
.PushEscaped((uint8_t)version
);
733 return SendCommand(MSGCODE_SET_HDMI_VERSION
, params
);
736 bool CUSBCECAdapterCommunication::GetSettingCECVersion(cec_version
&version
)
738 CLockObject
lock(m_mutex
);
739 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting CEC version setting");
741 cec_datapacket response
= GetSetting(MSGCODE_GET_HDMI_VERSION
, 1);
742 if (response
.size
== 1)
744 version
= (cec_version
)response
[0];
750 bool CUSBCECAdapterCommunication::SetSettingOSDName(const char *strOSDName
)
752 CLockObject
lock(m_mutex
);
753 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the OSD name to %s", strOSDName
);
755 CCECAdapterMessage params
;
756 for (size_t iPtr
= 0; iPtr
< strlen(strOSDName
); iPtr
++)
757 params
.PushEscaped(strOSDName
[iPtr
]);
758 return SendCommand(MSGCODE_SET_OSD_NAME
, params
);
761 bool CUSBCECAdapterCommunication::GetSettingOSDName(CStdString
&strOSDName
)
763 CLockObject
lock(m_mutex
);
764 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting OSD name setting");
766 cec_datapacket response
= GetSetting(MSGCODE_GET_OSD_NAME
, 13);
767 if (response
.size
== 0)
771 for (uint8_t iPtr
= 0; iPtr
< response
.size
&& iPtr
< 13; iPtr
++)
772 buf
[iPtr
] = (char)response
[iPtr
];
773 buf
[response
.size
] = 0;
775 strOSDName
.Format("%s", buf
);
779 bool CUSBCECAdapterCommunication::WriteEEPROM(void)
781 CLockObject
lock(m_mutex
);
782 CLibCEC::AddLog(CEC_LOG_DEBUG
, "writing settings in the EEPROM");
784 CCECAdapterMessage params
;
785 return SendCommand(MSGCODE_WRITE_EEPROM
, params
);
788 bool CUSBCECAdapterCommunication::IsOpen(void)
790 return !IsStopped() && m_port
->IsOpen() && IsRunning();
793 bool CUSBCECAdapterCommunication::WaitForAck(CCECAdapterMessage
&message
)
796 bool bTransmitSucceeded(false);
797 uint8_t iPacketsLeft(message
.isTransmission
? message
.Size() / 4 : 1);
799 int64_t iNow
= GetTimeMs();
800 int64_t iTargetTime
= iNow
+ (message
.transmit_timeout
<= 5 ? CEC_DEFAULT_TRANSMIT_WAIT
: message
.transmit_timeout
);
802 while (!bTransmitSucceeded
&& !bError
&& iNow
< iTargetTime
)
805 CCECAdapterMessage msg
;
812 if (msg
.Message() == MSGCODE_FRAME_START
&& msg
.IsACK())
814 if (m_bWaitingForAck
[msg
.Initiator()])
815 m_bWaitingForAck
[msg
.Initiator()] = false;
818 m_processor
->HandlePoll(msg
.Initiator(), msg
.Destination());
819 m_lastDestination
= msg
.Initiator();
825 if (msg
.Message() == MSGCODE_RECEIVE_FAILED
&&
826 m_lastDestination
!= CECDEVICE_UNKNOWN
&&
827 m_processor
->HandleReceiveFailed(m_lastDestination
))
833 bError
= msg
.IsError();
836 message
.reply
= msg
.Message();
837 CLibCEC::AddLog(CEC_LOG_DEBUG
, msg
.ToString());
841 switch(msg
.Message())
843 case MSGCODE_COMMAND_ACCEPTED
:
844 if (iPacketsLeft
> 0)
846 if (!message
.isTransmission
&& iPacketsLeft
== 0)
847 bTransmitSucceeded
= true;
848 CLibCEC::AddLog(CEC_LOG_DEBUG
, "%s - waiting for %d more", msg
.ToString().c_str(), iPacketsLeft
);
850 case MSGCODE_TRANSMIT_SUCCEEDED
:
851 CLibCEC::AddLog(CEC_LOG_DEBUG
, msg
.ToString());
852 bTransmitSucceeded
= (iPacketsLeft
== 0);
853 bError
= !bTransmitSucceeded
;
854 message
.reply
= MSGCODE_TRANSMIT_SUCCEEDED
;
857 // ignore other data while waiting
865 message
.state
= bTransmitSucceeded
&& !bError
?
866 ADAPTER_MESSAGE_STATE_SENT_ACKED
:
867 ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED
;
869 return bTransmitSucceeded
&& !bError
;
872 void CUSBCECAdapterCommunication::AddData(uint8_t *data
, size_t iLen
)
874 CLockObject
lock(m_mutex
);
875 for (size_t iPtr
= 0; iPtr
< iLen
; iPtr
++)
879 if (data
[iPtr
] == MSGSTART
)
882 else if (data
[iPtr
] == MSGSTART
) //we found a msgstart before msgend, this is not right, remove
884 if (m_currentAdapterMessage
.Size() > 0)
885 CLibCEC::AddLog(CEC_LOG_WARNING
, "received MSGSTART before MSGEND, removing previous buffer contents");
886 m_currentAdapterMessage
.Clear();
889 else if (data
[iPtr
] == MSGEND
)
891 CCECAdapterMessage
*newMessage
= new CCECAdapterMessage
;
892 newMessage
->packet
= m_currentAdapterMessage
.packet
;
893 m_inBuffer
.Push(newMessage
);
894 m_currentAdapterMessage
.Clear();
896 m_bNextIsEscaped
= false;
898 m_rcvCondition
.Broadcast();
900 else if (m_bNextIsEscaped
)
902 m_currentAdapterMessage
.PushBack(data
[iPtr
] + (uint8_t)ESCOFFSET
);
903 m_bNextIsEscaped
= false;
905 else if (data
[iPtr
] == MSGESC
)
907 m_bNextIsEscaped
= true;
911 m_currentAdapterMessage
.PushBack(data
[iPtr
]);
916 bool CUSBCECAdapterCommunication::ReadFromDevice(uint32_t iTimeout
, size_t iSize
/* = 256 */)
925 CLockObject
lock(m_mutex
);
926 iBytesRead
= m_port
->Read(buff
, sizeof(uint8_t) * iSize
, iTimeout
);
927 if (iBytesRead
< 0 || iBytesRead
> 256)
929 CLibCEC::AddLog(CEC_LOG_ERROR
, "error reading from serial port: %s", m_port
->GetError().c_str());
933 else if (iBytesRead
> 0)
935 AddData(buff
, iBytesRead
);
938 return iBytesRead
> 0;
941 void CUSBCECAdapterCommunication::SendMessageToAdapter(CCECAdapterMessage
*msg
)
943 CLockObject
adapterLock(m_mutex
);
944 if (!m_port
->IsOpen())
946 CLibCEC::AddLog(CEC_LOG_ERROR
, "error writing to serial port: the connection is closed");
947 msg
->state
= ADAPTER_MESSAGE_STATE_ERROR
;
951 if (msg
->isTransmission
&& (msg
->Size() < 2 || msg
->At(1) != MSGCODE_TRANSMIT_IDLETIME
))
954 SetLineTimeout(msg
->lineTimeout
);
956 SetLineTimeout(msg
->retryTimeout
);
959 if (m_port
->Write(msg
->packet
.data
, msg
->Size()) != (ssize_t
) msg
->Size())
961 CLibCEC::AddLog(CEC_LOG_ERROR
, "error writing to serial port: %s", m_port
->GetError().c_str());
962 msg
->state
= ADAPTER_MESSAGE_STATE_ERROR
;
966 CLibCEC::AddLog(CEC_LOG_DEBUG
, "command sent");
967 msg
->state
= ADAPTER_MESSAGE_STATE_SENT
;
969 if (msg
->expectControllerAck
)
971 if (!WaitForAck(*msg
))
972 CLibCEC::AddLog(CEC_LOG_DEBUG
, "did not receive ack");
978 void CUSBCECAdapterCommunication::WriteNextCommand(void)
980 CCECAdapterMessage
*msg(NULL
);
981 if (m_outBuffer
.Pop(msg
))
982 SendMessageToAdapter(msg
);
985 CStdString
CUSBCECAdapterCommunication::GetPortName(void)
988 strName
= m_port
->GetName();
992 bool CUSBCECAdapterCommunication::SendCommand(cec_adapter_messagecode msgCode
, CCECAdapterMessage
¶ms
, bool bExpectAck
/* = true */, bool bIsTransmission
/* = false */, bool bSendDirectly
/* = true */, bool bIsRetry
/* = false */)
994 CLockObject
lock(m_mutex
);
996 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
998 output
->PushBack(MSGSTART
);
999 output
->PushEscaped((uint8_t)msgCode
);
1000 output
->Append(params
);
1001 output
->PushBack(MSGEND
);
1002 output
->isTransmission
= bIsTransmission
;
1003 output
->expectControllerAck
= bExpectAck
;
1006 SendMessageToAdapter(output
);
1010 bool bWriteOk
= output
->state
== (output
->expectControllerAck
? ADAPTER_MESSAGE_STATE_SENT_ACKED
: ADAPTER_MESSAGE_STATE_SENT
);
1013 CLibCEC::AddLog(CEC_LOG_ERROR
, "'%s' failed", CCECAdapterMessage::ToString(msgCode
));
1016 if (!bIsRetry
&& output
->reply
== MSGCODE_COMMAND_REJECTED
&& msgCode
!= MSGCODE_SET_CONTROLLED
)
1018 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting controlled mode and retrying");
1019 if (SetControlledMode(true))
1020 return SendCommand(msgCode
, params
, bExpectAck
, bIsTransmission
, bSendDirectly
, true);
1029 cec_datapacket
CUSBCECAdapterCommunication::GetSetting(cec_adapter_messagecode msgCode
, uint8_t iResponseLength
)
1031 cec_datapacket retVal
;
1034 CCECAdapterMessage params
;
1035 if (!SendCommand(msgCode
, params
, false))
1037 CLibCEC::AddLog(CEC_LOG_ERROR
, "%s failed", CCECAdapterMessage::ToString(msgCode
));
1041 Sleep(250); // TODO ReadFromDevice() isn't waiting for the timeout to pass on win32
1042 ReadFromDevice(CEC_DEFAULT_TRANSMIT_WAIT
, iResponseLength
+ 3 /* start + msgcode + iResponseLength + end */);
1043 CCECAdapterMessage input
;
1046 if (input
.Message() != msgCode
)
1047 CLibCEC::AddLog(CEC_LOG_ERROR
, "invalid response to %s received (%s)", CCECAdapterMessage::ToString(msgCode
), CCECAdapterMessage::ToString(input
.Message()));
1050 for (uint8_t iPtr
= 1; iPtr
< input
.Size(); iPtr
++)
1051 retVal
.PushBack(input
[iPtr
]);
1056 CLibCEC::AddLog(CEC_LOG_ERROR
, "no response to %s received", CCECAdapterMessage::ToString(msgCode
));