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_lastInitiator(CECDEVICE_UNKNOWN
),
70 m_bNextIsEscaped(false),
72 m_messageProcessor(NULL
),
75 m_port
= new CSerialPort(strPort
, iBaudRate
);
78 CUSBCECAdapterCommunication::~CUSBCECAdapterCommunication(void)
83 bool CUSBCECAdapterCommunication::CheckAdapter(uint32_t iTimeoutMs
/* = 10000 */)
86 uint64_t iNow
= GetTimeMs();
87 uint64_t iTarget
= iTimeoutMs
> 0 ? iNow
+ iTimeoutMs
: iNow
+ CEC_DEFAULT_TRANSMIT_WAIT
;
89 /* try to ping the adapter */
92 while (iNow
< iTarget
&& (bPinged
= PingAdapter()) == false)
94 CLibCEC::AddLog(CEC_LOG_ERROR
, "the adapter did not respond correctly to a ping (try %d)", ++iPingTry
);
99 /* try to read the firmware version */
100 m_iFirmwareVersion
= CEC_FW_VERSION_UNKNOWN
;
101 unsigned iFwVersionTry(0);
102 while (bPinged
&& iNow
< iTarget
&& (m_iFirmwareVersion
= GetFirmwareVersion()) == CEC_FW_VERSION_UNKNOWN
&& iFwVersionTry
< 3)
104 CLibCEC::AddLog(CEC_LOG_WARNING
, "the adapter did not respond with a correct firmware version (try %d)", ++iFwVersionTry
);
109 if (m_iFirmwareVersion
== CEC_FW_VERSION_UNKNOWN
)
111 CLibCEC::AddLog(CEC_LOG_DEBUG
, "defaulting to firmware version 1");
112 m_iFirmwareVersion
= 1;
115 if (m_iFirmwareVersion
>= 2)
117 /* try to set controlled mode */
118 unsigned iControlledTry(0);
119 bool bControlled(false);
120 while (iNow
< iTarget
&& (bControlled
= SetControlledMode(true)) == false)
122 CLibCEC::AddLog(CEC_LOG_ERROR
, "the adapter did not respond correctly to setting controlled mode (try %d)", ++iControlledTry
);
126 bReturn
= bControlled
;
132 CLockObject
lock(m_mutex
);
133 m_bInitialised
= bReturn
;
139 bool CUSBCECAdapterCommunication::Open(IAdapterCommunicationCallback
*cb
, uint32_t iTimeoutMs
/* = 10000 */, bool bSkipChecks
/* = false */)
141 uint64_t iNow
= GetTimeMs();
142 uint64_t iTimeout
= iNow
+ iTimeoutMs
;
145 CLockObject
lock(m_mutex
);
149 CLibCEC::AddLog(CEC_LOG_ERROR
, "port is NULL");
155 CLibCEC::AddLog(CEC_LOG_ERROR
, "port is already open");
161 bool bConnected(false);
162 while (!bConnected
&& iNow
< iTimeout
)
164 if ((bConnected
= m_port
->Open(iTimeout
)) == false)
166 strError
.Format("error opening serial port '%s': %s", m_port
->GetName().c_str(), m_port
->GetError().c_str());
174 CLibCEC::AddLog(CEC_LOG_ERROR
, strError
);
178 CLibCEC::AddLog(CEC_LOG_DEBUG
, "connection opened, clearing any previous input and waiting for active transmissions to end before starting");
182 //clear any input bytes
184 while (m_port
->Read(buff
, 1024, 100) > 0)
186 CLibCEC::AddLog(CEC_LOG_DEBUG
, "data received, clearing it");
192 if (!bSkipChecks
&& !CheckAdapter())
194 CLibCEC::AddLog(CEC_LOG_ERROR
, "the adapter failed to pass basic checks");
201 CLibCEC::AddLog(CEC_LOG_DEBUG
, "communication thread started");
206 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not create a communication thread");
213 void CUSBCECAdapterCommunication::Close(void)
218 void *CUSBCECAdapterCommunication::Process(void)
220 m_messageProcessor
= new CUSBCECAdapterProcessor(m_callback
);
221 m_messageProcessor
->CreateThread();
225 bool bCommandReceived(false);
226 CTimeout
pingTimeout(CEC_ADAPTER_PING_TIMEOUT
);
230 CLockObject
lock(m_mutex
);
232 bCommandReceived
= m_callback
&& Read(command
, 0) && m_bInitialised
;
235 /* push the next command to the callback method if there is one */
236 if (!IsStopped() && bCommandReceived
)
237 m_messageProcessor
->AddCommand(command
);
239 /* ping the adapter every 15 seconds */
240 if (pingTimeout
.TimeLeft() == 0)
242 pingTimeout
.Init(CEC_ADAPTER_PING_TIMEOUT
);
253 /* stop the message processor */
254 m_messageProcessor
->StopThread();
255 delete m_messageProcessor
;
257 /* notify all threads that are waiting on messages to be sent */
258 CCECAdapterMessage
*msg(NULL
);
259 while (m_outBuffer
.Pop(msg
))
260 msg
->event
.Broadcast();
262 /* set the ackmask to 0 before closing the connection */
263 SetAckMaskInternal(0, true);
265 if (m_iFirmwareVersion
>= 2)
266 SetControlledMode(false);
277 cec_adapter_message_state
CUSBCECAdapterCommunication::Write(const cec_command
&data
, uint8_t iMaxTries
, uint8_t iLineTimeout
/* = 3 */, uint8_t iRetryLineTimeout
/* = 3 */)
279 cec_adapter_message_state
retVal(ADAPTER_MESSAGE_STATE_UNKNOWN
);
283 CCECAdapterMessage
*output
= new CCECAdapterMessage(data
);
285 /* set the number of retries */
286 if (data
.opcode
== CEC_OPCODE_NONE
) //TODO
287 output
->maxTries
= 1;
288 else if (data
.initiator
!= CECDEVICE_BROADCAST
)
289 output
->maxTries
= iMaxTries
;
291 output
->lineTimeout
= iLineTimeout
;
292 output
->retryTimeout
= iRetryLineTimeout
;
296 while (bRetry
&& ++output
->tries
< output
->maxTries
)
298 bRetry
= (!Write(output
) || output
->NeedsRetry()) && output
->transmit_timeout
> 0;
300 Sleep(CEC_DEFAULT_TRANSMIT_RETRY_WAIT
);
302 retVal
= output
->state
;
308 bool CUSBCECAdapterCommunication::Write(CCECAdapterMessage
*data
)
310 data
->state
= ADAPTER_MESSAGE_STATE_WAITING_TO_BE_SENT
;
311 m_outBuffer
.Push(data
);
312 data
->event
.Wait(5000);
314 if ((data
->expectControllerAck
&& data
->state
!= ADAPTER_MESSAGE_STATE_SENT_ACKED
) ||
315 (!data
->expectControllerAck
&& data
->state
!= ADAPTER_MESSAGE_STATE_SENT
))
317 CLibCEC::AddLog(CEC_LOG_DEBUG
, "command was not %s", data
->state
== ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED
? "acked" : "sent");
324 bool CUSBCECAdapterCommunication::Read(cec_command
&command
, uint32_t iTimeout
)
329 CCECAdapterMessage msg
;
330 if (Read(msg
, iTimeout
))
332 if (ParseMessage(msg
))
334 command
= m_currentframe
;
335 m_currentframe
.Clear();
342 bool CUSBCECAdapterCommunication::Read(CCECAdapterMessage
&msg
, uint32_t iTimeout
)
344 CLockObject
lock(m_mutex
);
347 CCECAdapterMessage
*buf(NULL
);
349 if (!m_inBuffer
.Pop(buf
))
351 if (iTimeout
== 0 || !m_rcvCondition
.Wait(m_mutex
, m_bHasData
, iTimeout
))
354 m_bHasData
= !m_inBuffer
.IsEmpty();
359 msg
.packet
= buf
->packet
;
360 msg
.state
= ADAPTER_MESSAGE_STATE_INCOMING
;
367 CStdString
CUSBCECAdapterCommunication::GetError(void) const
370 strError
= m_port
->GetError();
374 bool CUSBCECAdapterCommunication::StartBootloader(void)
380 CLibCEC::AddLog(CEC_LOG_DEBUG
, "starting the bootloader");
382 CCECAdapterMessage params
;
383 return SendCommand(MSGCODE_START_BOOTLOADER
, params
, false);
386 bool CUSBCECAdapterCommunication::PingAdapter(void)
388 CLockObject
lock(m_mutex
);
389 CLibCEC::AddLog(CEC_LOG_DEBUG
, "sending ping");
391 CCECAdapterMessage params
;
392 return SendCommand(MSGCODE_PING
, params
);
395 bool CUSBCECAdapterCommunication::ParseMessage(const CCECAdapterMessage
&msg
)
398 bool bIsError(msg
.IsError());
403 CLockObject
adapterLock(m_mutex
);
404 switch(msg
.Message())
406 case MSGCODE_FRAME_START
:
408 m_currentframe
.Clear();
411 m_currentframe
.initiator
= msg
.Initiator();
412 m_currentframe
.destination
= msg
.Destination();
413 m_currentframe
.ack
= msg
.IsACK();
414 m_currentframe
.eom
= msg
.IsEOM();
416 if (m_currentframe
.ack
== 0x1)
418 m_lastInitiator
= m_currentframe
.initiator
;
419 m_currentframe
.eom
= 1;
424 case MSGCODE_RECEIVE_FAILED
:
426 m_currentframe
.Clear();
427 if (m_lastInitiator
!= CECDEVICE_UNKNOWN
)
428 bIsError
= m_processor
->HandleReceiveFailed(m_lastInitiator
);
431 case MSGCODE_FRAME_DATA
:
435 m_currentframe
.PushBack(msg
[1]);
436 m_currentframe
.eom
= msg
.IsEOM();
444 CLibCEC::AddLog(bIsError
? CEC_LOG_WARNING
: CEC_LOG_DEBUG
, msg
.ToString());
445 return msg
.IsEOM() || bEom
;
448 uint16_t CUSBCECAdapterCommunication::GetFirmwareVersion(void)
450 uint16_t iReturn(m_iFirmwareVersion
);
452 if (iReturn
== CEC_FW_VERSION_UNKNOWN
)
454 CLockObject
lock(m_mutex
);
455 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting the firmware version");
456 cec_datapacket response
= GetSetting(MSGCODE_FIRMWARE_VERSION
, 2);
457 if (response
.size
== 2)
459 m_iFirmwareVersion
= (response
[0] << 8 | response
[1]);
460 iReturn
= m_iFirmwareVersion
;
461 CLibCEC::AddLog(CEC_LOG_DEBUG
, "firmware version %d", m_iFirmwareVersion
);
468 bool CUSBCECAdapterCommunication::SetLineTimeout(uint8_t iTimeout
)
470 m_iLineTimeout
= iTimeout
;
471 bool bReturn(m_iLineTimeout
!= iTimeout
);
475 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the line timeout to %d", iTimeout
);
476 CCECAdapterMessage params
;
477 params
.PushEscaped(iTimeout
);
478 bReturn
= SendCommand(MSGCODE_TRANSMIT_IDLETIME
, params
);
484 bool CUSBCECAdapterCommunication::SetAckMask(uint16_t iMask
)
486 return SetAckMaskInternal(iMask
, IsRunning());
489 bool CUSBCECAdapterCommunication::SetAckMaskInternal(uint16_t iMask
, bool bWriteDirectly
/* = false */)
491 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting ackmask to %2x", iMask
);
493 CCECAdapterMessage params
;
494 params
.PushEscaped(iMask
>> 8);
495 params
.PushEscaped((uint8_t)iMask
);
496 return SendCommand(MSGCODE_SET_ACK_MASK
, params
, true, false, bWriteDirectly
);
499 bool CUSBCECAdapterCommunication::PersistConfiguration(libcec_configuration
*configuration
)
501 if (m_iFirmwareVersion
< 2)
505 bReturn
&= SetSettingAutoEnabled(true);
506 bReturn
&= SetSettingDeviceType(CLibCEC::GetType(configuration
->logicalAddresses
.primary
));
507 bReturn
&= SetSettingDefaultLogicalAddress(configuration
->logicalAddresses
.primary
);
508 bReturn
&= SetSettingLogicalAddressMask(CLibCEC::GetMaskForType(configuration
->logicalAddresses
.primary
));
509 bReturn
&= SetSettingPhysicalAddress(configuration
->iPhysicalAddress
);
510 bReturn
&= SetSettingCECVersion(CEC_VERSION_1_3A
);
511 bReturn
&= SetSettingOSDName(configuration
->strDeviceName
);
513 bReturn
= WriteEEPROM();
517 bool CUSBCECAdapterCommunication::GetConfiguration(libcec_configuration
*configuration
)
519 if (m_iFirmwareVersion
< 2)
523 cec_device_type type
;
524 if (GetSettingDeviceType(type
))
526 CLibCEC::AddLog(CEC_LOG_DEBUG
, "using persisted device type setting %s", m_processor
->ToString(type
));
527 configuration
->deviceTypes
.Clear();
528 configuration
->deviceTypes
.Add(type
);
532 CLibCEC::AddLog(CEC_LOG_DEBUG
, "no persisted device type setting");
536 if (GetSettingPhysicalAddress(configuration
->iPhysicalAddress
))
538 CLibCEC::AddLog(CEC_LOG_DEBUG
, "using persisted physical address setting %4x", configuration
->iPhysicalAddress
);
542 CLibCEC::AddLog(CEC_LOG_DEBUG
, "no persisted physical address setting");
546 CStdString strDeviceName
;
547 if (GetSettingOSDName(strDeviceName
))
549 snprintf(configuration
->strDeviceName
, 13, "%s", strDeviceName
.c_str());
550 CLibCEC::AddLog(CEC_LOG_DEBUG
, "using persisted device name setting %s", configuration
->strDeviceName
);
554 CLibCEC::AddLog(CEC_LOG_DEBUG
, "no persisted device name setting");
558 // don't read the following settings:
559 // - auto enabled (always enabled)
560 // - default logical address (autodetected)
561 // - logical address mask (autodetected)
562 // - CEC version (1.3a)
564 // TODO to be added to the firmware:
565 // - base device (4 bits)
566 // - HDMI port number (4 bits)
567 // - TV vendor id (12 bits)
568 // - wake devices (8 bits)
569 // - standby devices (8 bits)
570 // - use TV menu language (1 bit)
571 // - activate source (1 bit)
572 // - power off screensaver (1 bit)
573 // - power off on standby (1 bit)
574 // - send inactive source (1 bit)
578 bool CUSBCECAdapterCommunication::SetControlledMode(bool controlled
)
580 CLockObject
lock(m_mutex
);
581 CLibCEC::AddLog(CEC_LOG_DEBUG
, "turning controlled mode %s", controlled
? "on" : "off");
583 CCECAdapterMessage params
;
584 params
.PushEscaped(controlled
? 1 : 0);
585 return SendCommand(MSGCODE_SET_CONTROLLED
, params
);
588 bool CUSBCECAdapterCommunication::SetSettingAutoEnabled(bool enabled
)
590 CLockObject
lock(m_mutex
);
591 CLibCEC::AddLog(CEC_LOG_DEBUG
, "turning autonomous mode %s", enabled
? "on" : "off");
593 CCECAdapterMessage params
;
594 params
.PushEscaped(enabled
? 1 : 0);
595 return SendCommand(MSGCODE_SET_AUTO_ENABLED
, params
);
598 bool CUSBCECAdapterCommunication::GetSettingAutoEnabled(bool &enabled
)
600 CLockObject
lock(m_mutex
);
601 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting autonomous mode setting");
603 cec_datapacket response
= GetSetting(MSGCODE_GET_AUTO_ENABLED
, 1);
604 if (response
.size
== 1)
606 enabled
= response
[0] == 1;
612 bool CUSBCECAdapterCommunication::SetSettingDeviceType(cec_device_type type
)
614 CLockObject
lock(m_mutex
);
615 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the device type to %1X", (uint8_t)type
);
617 CCECAdapterMessage params
;
618 params
.PushEscaped((uint8_t)type
);
619 return SendCommand(MSGCODE_SET_DEVICE_TYPE
, params
);
622 bool CUSBCECAdapterCommunication::GetSettingDeviceType(cec_device_type
&value
)
624 CLockObject
lock(m_mutex
);
625 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting device type setting");
627 cec_datapacket response
= GetSetting(MSGCODE_GET_DEVICE_TYPE
, 1);
628 if (response
.size
== 1)
630 value
= (cec_device_type
)response
[0];
636 bool CUSBCECAdapterCommunication::SetSettingDefaultLogicalAddress(cec_logical_address address
)
638 CLockObject
lock(m_mutex
);
639 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the default logical address to %1X", address
);
641 CCECAdapterMessage params
;
642 params
.PushEscaped((uint8_t)address
);
643 return SendCommand(MSGCODE_SET_DEFAULT_LOGICAL_ADDRESS
, params
);
646 bool CUSBCECAdapterCommunication::GetSettingDefaultLogicalAddress(cec_logical_address
&address
)
648 CLockObject
lock(m_mutex
);
649 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting default logical address setting");
651 cec_datapacket response
= GetSetting(MSGCODE_GET_DEFAULT_LOGICAL_ADDRESS
, 1);
652 if (response
.size
== 1)
654 address
= (cec_logical_address
)response
[0];
660 bool CUSBCECAdapterCommunication::SetSettingLogicalAddressMask(uint16_t iMask
)
662 CLockObject
lock(m_mutex
);
663 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the logical address mask to %2X", iMask
);
665 CCECAdapterMessage params
;
666 params
.PushEscaped(iMask
>> 8);
667 params
.PushEscaped((uint8_t)iMask
);
668 return SendCommand(MSGCODE_SET_LOGICAL_ADDRESS_MASK
, params
);
671 bool CUSBCECAdapterCommunication::GetSettingLogicalAddressMask(uint16_t &iMask
)
673 CLockObject
lock(m_mutex
);
674 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting logical address mask setting");
676 cec_datapacket response
= GetSetting(MSGCODE_GET_LOGICAL_ADDRESS_MASK
, 2);
677 if (response
.size
== 2)
679 iMask
= ((uint16_t)response
[0] << 8) | ((uint16_t)response
[1]);
685 bool CUSBCECAdapterCommunication::SetSettingPhysicalAddress(uint16_t iPhysicalAddress
)
687 CLockObject
lock(m_mutex
);
688 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the physical address to %04X", iPhysicalAddress
);
690 CCECAdapterMessage params
;
691 params
.PushEscaped(iPhysicalAddress
>> 8);
692 params
.PushEscaped((uint8_t)iPhysicalAddress
);
693 return SendCommand(MSGCODE_SET_PHYSICAL_ADDRESS
, params
);
696 bool CUSBCECAdapterCommunication::GetSettingPhysicalAddress(uint16_t &iPhysicalAddress
)
698 CLockObject
lock(m_mutex
);
699 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting physical address setting");
701 cec_datapacket response
= GetSetting(MSGCODE_GET_PHYSICAL_ADDRESS
, 2);
702 if (response
.size
== 2)
704 iPhysicalAddress
= ((uint16_t)response
[0] << 8) | ((uint16_t)response
[1]);
710 bool CUSBCECAdapterCommunication::SetSettingCECVersion(cec_version version
)
712 CLockObject
lock(m_mutex
);
713 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the CEC version to %s", CLibCEC::GetInstance()->ToString(version
));
715 CCECAdapterMessage params
;
716 params
.PushEscaped((uint8_t)version
);
717 return SendCommand(MSGCODE_SET_HDMI_VERSION
, params
);
720 bool CUSBCECAdapterCommunication::GetSettingCECVersion(cec_version
&version
)
722 CLockObject
lock(m_mutex
);
723 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting CEC version setting");
725 cec_datapacket response
= GetSetting(MSGCODE_GET_HDMI_VERSION
, 1);
726 if (response
.size
== 1)
728 version
= (cec_version
)response
[0];
734 bool CUSBCECAdapterCommunication::SetSettingOSDName(const char *strOSDName
)
736 CLockObject
lock(m_mutex
);
737 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the OSD name to %s", strOSDName
);
739 CCECAdapterMessage params
;
740 for (size_t iPtr
= 0; iPtr
< strlen(strOSDName
); iPtr
++)
741 params
.PushEscaped(strOSDName
[iPtr
]);
742 return SendCommand(MSGCODE_SET_OSD_NAME
, params
);
745 bool CUSBCECAdapterCommunication::GetSettingOSDName(CStdString
&strOSDName
)
747 CLockObject
lock(m_mutex
);
748 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting OSD name setting");
750 cec_datapacket response
= GetSetting(MSGCODE_GET_OSD_NAME
, 13);
751 if (response
.size
== 0)
755 for (uint8_t iPtr
= 0; iPtr
< response
.size
&& iPtr
< 13; iPtr
++)
756 buf
[iPtr
] = (char)response
[iPtr
];
757 buf
[response
.size
] = 0;
759 strOSDName
.Format("%s", buf
);
763 bool CUSBCECAdapterCommunication::WriteEEPROM(void)
765 CLockObject
lock(m_mutex
);
766 CLibCEC::AddLog(CEC_LOG_DEBUG
, "writing settings in the EEPROM");
768 CCECAdapterMessage params
;
769 return SendCommand(MSGCODE_WRITE_EEPROM
, params
);
772 bool CUSBCECAdapterCommunication::IsOpen(void)
774 return !IsStopped() && m_port
->IsOpen() && IsRunning();
777 bool CUSBCECAdapterCommunication::WaitForAck(CCECAdapterMessage
&message
)
780 bool bTransmitSucceeded(false);
781 uint8_t iPacketsLeft(message
.isTransmission
? message
.Size() / 4 : 1);
783 int64_t iNow
= GetTimeMs();
784 int64_t iTargetTime
= iNow
+ (message
.transmit_timeout
<= 5 ? CEC_DEFAULT_TRANSMIT_WAIT
: message
.transmit_timeout
);
786 while (!bTransmitSucceeded
&& !bError
&& iNow
< iTargetTime
)
789 CCECAdapterMessage msg
;
796 if (msg
.Message() == MSGCODE_FRAME_START
&& msg
.IsACK())
798 m_processor
->HandlePoll(msg
.Initiator(), msg
.Destination());
799 m_lastInitiator
= msg
.Initiator();
804 if (msg
.Message() == MSGCODE_RECEIVE_FAILED
&&
805 m_lastInitiator
!= CECDEVICE_UNKNOWN
&&
806 m_processor
->HandleReceiveFailed(m_lastInitiator
))
812 bError
= msg
.IsError();
815 message
.reply
= msg
.Message();
816 CLibCEC::AddLog(CEC_LOG_DEBUG
, msg
.ToString());
820 switch(msg
.Message())
822 case MSGCODE_COMMAND_ACCEPTED
:
823 if (iPacketsLeft
> 0)
825 if (!message
.isTransmission
&& iPacketsLeft
== 0)
826 bTransmitSucceeded
= true;
827 CLibCEC::AddLog(CEC_LOG_DEBUG
, "%s - waiting for %d more", msg
.ToString().c_str(), iPacketsLeft
);
829 case MSGCODE_TRANSMIT_SUCCEEDED
:
830 CLibCEC::AddLog(CEC_LOG_DEBUG
, msg
.ToString());
831 bTransmitSucceeded
= (iPacketsLeft
== 0);
832 bError
= !bTransmitSucceeded
;
833 message
.reply
= MSGCODE_TRANSMIT_SUCCEEDED
;
836 // ignore other data while waiting
844 message
.state
= bTransmitSucceeded
&& !bError
?
845 ADAPTER_MESSAGE_STATE_SENT_ACKED
:
846 ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED
;
848 return bTransmitSucceeded
&& !bError
;
851 void CUSBCECAdapterCommunication::AddData(uint8_t *data
, size_t iLen
)
853 CLockObject
lock(m_mutex
);
854 for (size_t iPtr
= 0; iPtr
< iLen
; iPtr
++)
858 if (data
[iPtr
] == MSGSTART
)
861 else if (data
[iPtr
] == MSGSTART
) //we found a msgstart before msgend, this is not right, remove
863 if (m_currentAdapterMessage
.Size() > 0)
864 CLibCEC::AddLog(CEC_LOG_WARNING
, "received MSGSTART before MSGEND, removing previous buffer contents");
865 m_currentAdapterMessage
.Clear();
868 else if (data
[iPtr
] == MSGEND
)
870 CCECAdapterMessage
*newMessage
= new CCECAdapterMessage
;
871 newMessage
->packet
= m_currentAdapterMessage
.packet
;
872 m_inBuffer
.Push(newMessage
);
873 m_currentAdapterMessage
.Clear();
875 m_bNextIsEscaped
= false;
877 m_rcvCondition
.Broadcast();
879 else if (m_bNextIsEscaped
)
881 m_currentAdapterMessage
.PushBack(data
[iPtr
] + (uint8_t)ESCOFFSET
);
882 m_bNextIsEscaped
= false;
884 else if (data
[iPtr
] == MSGESC
)
886 m_bNextIsEscaped
= true;
890 m_currentAdapterMessage
.PushBack(data
[iPtr
]);
895 bool CUSBCECAdapterCommunication::ReadFromDevice(uint32_t iTimeout
, size_t iSize
/* = 256 */)
904 CLockObject
lock(m_mutex
);
905 iBytesRead
= m_port
->Read(buff
, sizeof(uint8_t) * iSize
, iTimeout
);
906 if (iBytesRead
< 0 || iBytesRead
> 256)
908 CLibCEC::AddLog(CEC_LOG_ERROR
, "error reading from serial port: %s", m_port
->GetError().c_str());
912 else if (iBytesRead
> 0)
914 AddData(buff
, iBytesRead
);
917 return iBytesRead
> 0;
920 void CUSBCECAdapterCommunication::SendMessageToAdapter(CCECAdapterMessage
*msg
)
922 CLockObject
adapterLock(m_mutex
);
923 if (!m_port
->IsOpen())
925 CLibCEC::AddLog(CEC_LOG_ERROR
, "error writing to serial port: the connection is closed");
926 msg
->state
= ADAPTER_MESSAGE_STATE_ERROR
;
930 if (msg
->isTransmission
&& (msg
->Size() < 2 || msg
->At(1) != MSGCODE_TRANSMIT_IDLETIME
))
933 SetLineTimeout(msg
->lineTimeout
);
935 SetLineTimeout(msg
->retryTimeout
);
938 if (m_port
->Write(msg
->packet
.data
, msg
->Size()) != (ssize_t
) msg
->Size())
940 CLibCEC::AddLog(CEC_LOG_ERROR
, "error writing to serial port: %s", m_port
->GetError().c_str());
941 msg
->state
= ADAPTER_MESSAGE_STATE_ERROR
;
945 CLibCEC::AddLog(CEC_LOG_DEBUG
, "command sent");
946 msg
->state
= ADAPTER_MESSAGE_STATE_SENT
;
948 if (msg
->expectControllerAck
)
950 if (!WaitForAck(*msg
))
951 CLibCEC::AddLog(CEC_LOG_DEBUG
, "did not receive ack");
957 void CUSBCECAdapterCommunication::WriteNextCommand(void)
959 CCECAdapterMessage
*msg(NULL
);
960 if (m_outBuffer
.Pop(msg
))
961 SendMessageToAdapter(msg
);
964 CStdString
CUSBCECAdapterCommunication::GetPortName(void)
967 strName
= m_port
->GetName();
971 bool CUSBCECAdapterCommunication::SendCommand(cec_adapter_messagecode msgCode
, CCECAdapterMessage
¶ms
, bool bExpectAck
/* = true */, bool bIsTransmission
/* = false */, bool bSendDirectly
/* = true */, bool bIsRetry
/* = false */)
973 CLockObject
lock(m_mutex
);
975 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
977 output
->PushBack(MSGSTART
);
978 output
->PushEscaped((uint8_t)msgCode
);
979 output
->Append(params
);
980 output
->PushBack(MSGEND
);
981 output
->isTransmission
= bIsTransmission
;
982 output
->expectControllerAck
= bExpectAck
;
985 SendMessageToAdapter(output
);
989 bool bWriteOk
= output
->state
== (output
->expectControllerAck
? ADAPTER_MESSAGE_STATE_SENT_ACKED
: ADAPTER_MESSAGE_STATE_SENT
);
992 CLibCEC::AddLog(CEC_LOG_ERROR
, "'%s' failed", CCECAdapterMessage::ToString(msgCode
));
995 if (!bIsRetry
&& output
->reply
== MSGCODE_COMMAND_REJECTED
&& msgCode
!= MSGCODE_SET_CONTROLLED
)
997 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting controlled mode and retrying");
998 if (SetControlledMode(true))
999 return SendCommand(msgCode
, params
, bExpectAck
, bIsTransmission
, bSendDirectly
, true);
1008 cec_datapacket
CUSBCECAdapterCommunication::GetSetting(cec_adapter_messagecode msgCode
, uint8_t iResponseLength
)
1010 cec_datapacket retVal
;
1013 CCECAdapterMessage params
;
1014 if (!SendCommand(msgCode
, params
, false))
1016 CLibCEC::AddLog(CEC_LOG_ERROR
, "%s failed", CCECAdapterMessage::ToString(msgCode
));
1020 Sleep(250); // TODO ReadFromDevice() isn't waiting for the timeout to pass on win32
1021 ReadFromDevice(CEC_DEFAULT_TRANSMIT_WAIT
, iResponseLength
+ 3 /* start + msgcode + iResponseLength + end */);
1022 CCECAdapterMessage input
;
1025 if (input
.Message() != msgCode
)
1026 CLibCEC::AddLog(CEC_LOG_ERROR
, "invalid response to %s received (%s)", CCECAdapterMessage::ToString(msgCode
), CCECAdapterMessage::ToString(input
.Message()));
1029 for (uint8_t iPtr
= 1; iPtr
< input
.Size(); iPtr
++)
1030 retVal
.PushBack(input
[iPtr
]);
1035 CLibCEC::AddLog(CEC_LOG_ERROR
, "no response to %s received", CCECAdapterMessage::ToString(msgCode
));