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 ssize_t
iBytesRead(0);
185 bool bGotMsgStart(false), bGotMsgEnd(false);
186 while ((iBytesRead
= m_port
->Read(buff
, 1024, 100)) > 0 || (bGotMsgStart
&& !bGotMsgEnd
))
189 CLibCEC::AddLog(CEC_LOG_DEBUG
, "data received, clearing it");
190 // if something was received, wait for MSGEND
191 for (ssize_t iPtr
= 0; iPtr
< iBytesRead
; iPtr
++)
193 if (buff
[iPtr
] == MSGSTART
)
195 else if (buff
[iPtr
] == MSGEND
)
203 if (!bSkipChecks
&& !CheckAdapter())
205 CLibCEC::AddLog(CEC_LOG_ERROR
, "the adapter failed to pass basic checks");
212 CLibCEC::AddLog(CEC_LOG_DEBUG
, "communication thread started");
217 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not create a communication thread");
224 void CUSBCECAdapterCommunication::Close(void)
229 void *CUSBCECAdapterCommunication::Process(void)
231 m_messageProcessor
= new CUSBCECAdapterProcessor(m_callback
);
232 m_messageProcessor
->CreateThread();
236 bool bCommandReceived(false);
237 CTimeout
pingTimeout(CEC_ADAPTER_PING_TIMEOUT
);
241 CLockObject
lock(m_mutex
);
243 bCommandReceived
= m_callback
&& Read(command
, 0) && m_bInitialised
;
246 /* push the next command to the callback method if there is one */
247 if (!IsStopped() && bCommandReceived
)
248 m_messageProcessor
->AddCommand(command
);
250 /* ping the adapter every 15 seconds */
251 if (pingTimeout
.TimeLeft() == 0)
253 pingTimeout
.Init(CEC_ADAPTER_PING_TIMEOUT
);
264 /* stop the message processor */
265 m_messageProcessor
->StopThread();
266 delete m_messageProcessor
;
268 /* notify all threads that are waiting on messages to be sent */
269 CCECAdapterMessage
*msg(NULL
);
270 while (m_outBuffer
.Pop(msg
))
271 msg
->event
.Broadcast();
273 /* set the ackmask to 0 before closing the connection */
274 SetAckMaskInternal(0, true);
276 if (m_iFirmwareVersion
>= 2)
277 SetControlledMode(false);
288 cec_adapter_message_state
CUSBCECAdapterCommunication::Write(const cec_command
&data
, uint8_t iMaxTries
, uint8_t iLineTimeout
/* = 3 */, uint8_t iRetryLineTimeout
/* = 3 */)
290 cec_adapter_message_state
retVal(ADAPTER_MESSAGE_STATE_UNKNOWN
);
294 CCECAdapterMessage
*output
= new CCECAdapterMessage(data
);
296 /* set the number of retries */
297 if (data
.opcode
== CEC_OPCODE_NONE
) //TODO
298 output
->maxTries
= 1;
299 else if (data
.initiator
!= CECDEVICE_BROADCAST
)
300 output
->maxTries
= iMaxTries
;
302 output
->lineTimeout
= iLineTimeout
;
303 output
->retryTimeout
= iRetryLineTimeout
;
307 while (bRetry
&& ++output
->tries
< output
->maxTries
)
309 bRetry
= (!Write(output
) || output
->NeedsRetry()) && output
->transmit_timeout
> 0;
311 Sleep(CEC_DEFAULT_TRANSMIT_RETRY_WAIT
);
313 retVal
= output
->state
;
319 bool CUSBCECAdapterCommunication::Write(CCECAdapterMessage
*data
)
321 data
->state
= ADAPTER_MESSAGE_STATE_WAITING_TO_BE_SENT
;
322 m_outBuffer
.Push(data
);
323 data
->event
.Wait(5000);
325 if ((data
->expectControllerAck
&& data
->state
!= ADAPTER_MESSAGE_STATE_SENT_ACKED
) ||
326 (!data
->expectControllerAck
&& data
->state
!= ADAPTER_MESSAGE_STATE_SENT
))
328 CLibCEC::AddLog(CEC_LOG_DEBUG
, "command was not %s", data
->state
== ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED
? "acked" : "sent");
335 bool CUSBCECAdapterCommunication::Read(cec_command
&command
, uint32_t iTimeout
)
340 CCECAdapterMessage msg
;
341 if (Read(msg
, iTimeout
))
343 if (ParseMessage(msg
))
345 command
= m_currentframe
;
346 m_currentframe
.Clear();
353 bool CUSBCECAdapterCommunication::Read(CCECAdapterMessage
&msg
, uint32_t iTimeout
)
355 CLockObject
lock(m_mutex
);
358 CCECAdapterMessage
*buf(NULL
);
360 if (!m_inBuffer
.Pop(buf
))
362 if (iTimeout
== 0 || !m_rcvCondition
.Wait(m_mutex
, m_bHasData
, iTimeout
))
365 m_bHasData
= !m_inBuffer
.IsEmpty();
370 msg
.packet
= buf
->packet
;
371 msg
.state
= ADAPTER_MESSAGE_STATE_INCOMING
;
378 CStdString
CUSBCECAdapterCommunication::GetError(void) const
381 strError
= m_port
->GetError();
385 bool CUSBCECAdapterCommunication::StartBootloader(void)
391 CLibCEC::AddLog(CEC_LOG_DEBUG
, "starting the bootloader");
393 CCECAdapterMessage params
;
394 return SendCommand(MSGCODE_START_BOOTLOADER
, params
, false);
397 bool CUSBCECAdapterCommunication::PingAdapter(void)
399 CLockObject
lock(m_mutex
);
400 CLibCEC::AddLog(CEC_LOG_DEBUG
, "sending ping");
402 CCECAdapterMessage params
;
403 return SendCommand(MSGCODE_PING
, params
);
406 bool CUSBCECAdapterCommunication::ParseMessage(const CCECAdapterMessage
&msg
)
409 bool bIsError(msg
.IsError());
414 CLockObject
adapterLock(m_mutex
);
415 switch(msg
.Message())
417 case MSGCODE_FRAME_START
:
419 m_currentframe
.Clear();
422 m_currentframe
.initiator
= msg
.Initiator();
423 m_currentframe
.destination
= msg
.Destination();
424 m_currentframe
.ack
= msg
.IsACK();
425 m_currentframe
.eom
= msg
.IsEOM();
427 if (m_currentframe
.ack
== 0x1)
429 m_lastInitiator
= m_currentframe
.initiator
;
430 m_currentframe
.eom
= 1;
435 case MSGCODE_RECEIVE_FAILED
:
437 m_currentframe
.Clear();
438 if (m_lastInitiator
!= CECDEVICE_UNKNOWN
)
439 bIsError
= m_processor
->HandleReceiveFailed(m_lastInitiator
);
442 case MSGCODE_FRAME_DATA
:
446 m_currentframe
.PushBack(msg
[1]);
447 m_currentframe
.eom
= msg
.IsEOM();
455 CLibCEC::AddLog(bIsError
? CEC_LOG_WARNING
: CEC_LOG_DEBUG
, msg
.ToString());
456 return msg
.IsEOM() || bEom
;
459 uint16_t CUSBCECAdapterCommunication::GetFirmwareVersion(void)
461 uint16_t iReturn(m_iFirmwareVersion
);
463 if (iReturn
== CEC_FW_VERSION_UNKNOWN
)
465 CLockObject
lock(m_mutex
);
466 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting the firmware version");
467 cec_datapacket response
= GetSetting(MSGCODE_FIRMWARE_VERSION
, 2);
468 if (response
.size
== 2)
470 m_iFirmwareVersion
= (response
[0] << 8 | response
[1]);
471 iReturn
= m_iFirmwareVersion
;
472 CLibCEC::AddLog(CEC_LOG_DEBUG
, "firmware version %d", m_iFirmwareVersion
);
479 bool CUSBCECAdapterCommunication::SetLineTimeout(uint8_t iTimeout
)
481 m_iLineTimeout
= iTimeout
;
482 bool bReturn(m_iLineTimeout
!= iTimeout
);
486 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the line timeout to %d", iTimeout
);
487 CCECAdapterMessage params
;
488 params
.PushEscaped(iTimeout
);
489 bReturn
= SendCommand(MSGCODE_TRANSMIT_IDLETIME
, params
);
495 bool CUSBCECAdapterCommunication::SetAckMask(uint16_t iMask
)
497 return SetAckMaskInternal(iMask
, IsRunning());
500 bool CUSBCECAdapterCommunication::SetAckMaskInternal(uint16_t iMask
, bool bWriteDirectly
/* = false */)
502 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting ackmask to %2x", iMask
);
504 CCECAdapterMessage params
;
505 params
.PushEscaped(iMask
>> 8);
506 params
.PushEscaped((uint8_t)iMask
);
507 return SendCommand(MSGCODE_SET_ACK_MASK
, params
, true, false, bWriteDirectly
);
510 bool CUSBCECAdapterCommunication::PersistConfiguration(libcec_configuration
*configuration
)
512 if (m_iFirmwareVersion
< 2)
516 bReturn
&= SetSettingAutoEnabled(true);
517 bReturn
&= SetSettingDeviceType(CLibCEC::GetType(configuration
->logicalAddresses
.primary
));
518 bReturn
&= SetSettingDefaultLogicalAddress(configuration
->logicalAddresses
.primary
);
519 bReturn
&= SetSettingLogicalAddressMask(CLibCEC::GetMaskForType(configuration
->logicalAddresses
.primary
));
520 bReturn
&= SetSettingPhysicalAddress(configuration
->iPhysicalAddress
);
521 bReturn
&= SetSettingCECVersion(CEC_VERSION_1_3A
);
522 bReturn
&= SetSettingOSDName(configuration
->strDeviceName
);
524 bReturn
= WriteEEPROM();
528 bool CUSBCECAdapterCommunication::GetConfiguration(libcec_configuration
*configuration
)
530 if (m_iFirmwareVersion
< 2)
534 cec_device_type type
;
535 if (GetSettingDeviceType(type
))
537 CLibCEC::AddLog(CEC_LOG_DEBUG
, "using persisted device type setting %s", m_processor
->ToString(type
));
538 configuration
->deviceTypes
.Clear();
539 configuration
->deviceTypes
.Add(type
);
543 CLibCEC::AddLog(CEC_LOG_DEBUG
, "no persisted device type setting");
547 if (GetSettingPhysicalAddress(configuration
->iPhysicalAddress
))
549 CLibCEC::AddLog(CEC_LOG_DEBUG
, "using persisted physical address setting %4x", configuration
->iPhysicalAddress
);
553 CLibCEC::AddLog(CEC_LOG_DEBUG
, "no persisted physical address setting");
557 CStdString strDeviceName
;
558 if (GetSettingOSDName(strDeviceName
))
560 snprintf(configuration
->strDeviceName
, 13, "%s", strDeviceName
.c_str());
561 CLibCEC::AddLog(CEC_LOG_DEBUG
, "using persisted device name setting %s", configuration
->strDeviceName
);
565 CLibCEC::AddLog(CEC_LOG_DEBUG
, "no persisted device name setting");
569 // don't read the following settings:
570 // - auto enabled (always enabled)
571 // - default logical address (autodetected)
572 // - logical address mask (autodetected)
573 // - CEC version (1.3a)
575 // TODO to be added to the firmware:
576 // - base device (4 bits)
577 // - HDMI port number (4 bits)
578 // - TV vendor id (12 bits)
579 // - wake devices (8 bits)
580 // - standby devices (8 bits)
581 // - use TV menu language (1 bit)
582 // - activate source (1 bit)
583 // - power off screensaver (1 bit)
584 // - power off on standby (1 bit)
585 // - send inactive source (1 bit)
589 bool CUSBCECAdapterCommunication::SetControlledMode(bool controlled
)
591 CLockObject
lock(m_mutex
);
592 CLibCEC::AddLog(CEC_LOG_DEBUG
, "turning controlled mode %s", controlled
? "on" : "off");
594 CCECAdapterMessage params
;
595 params
.PushEscaped(controlled
? 1 : 0);
596 return SendCommand(MSGCODE_SET_CONTROLLED
, params
);
599 bool CUSBCECAdapterCommunication::SetSettingAutoEnabled(bool enabled
)
601 CLockObject
lock(m_mutex
);
602 CLibCEC::AddLog(CEC_LOG_DEBUG
, "turning autonomous mode %s", enabled
? "on" : "off");
604 CCECAdapterMessage params
;
605 params
.PushEscaped(enabled
? 1 : 0);
606 return SendCommand(MSGCODE_SET_AUTO_ENABLED
, params
);
609 bool CUSBCECAdapterCommunication::GetSettingAutoEnabled(bool &enabled
)
611 CLockObject
lock(m_mutex
);
612 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting autonomous mode setting");
614 cec_datapacket response
= GetSetting(MSGCODE_GET_AUTO_ENABLED
, 1);
615 if (response
.size
== 1)
617 enabled
= response
[0] == 1;
623 bool CUSBCECAdapterCommunication::SetSettingDeviceType(cec_device_type type
)
625 CLockObject
lock(m_mutex
);
626 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the device type to %1X", (uint8_t)type
);
628 CCECAdapterMessage params
;
629 params
.PushEscaped((uint8_t)type
);
630 return SendCommand(MSGCODE_SET_DEVICE_TYPE
, params
);
633 bool CUSBCECAdapterCommunication::GetSettingDeviceType(cec_device_type
&value
)
635 CLockObject
lock(m_mutex
);
636 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting device type setting");
638 cec_datapacket response
= GetSetting(MSGCODE_GET_DEVICE_TYPE
, 1);
639 if (response
.size
== 1)
641 value
= (cec_device_type
)response
[0];
647 bool CUSBCECAdapterCommunication::SetSettingDefaultLogicalAddress(cec_logical_address address
)
649 CLockObject
lock(m_mutex
);
650 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the default logical address to %1X", address
);
652 CCECAdapterMessage params
;
653 params
.PushEscaped((uint8_t)address
);
654 return SendCommand(MSGCODE_SET_DEFAULT_LOGICAL_ADDRESS
, params
);
657 bool CUSBCECAdapterCommunication::GetSettingDefaultLogicalAddress(cec_logical_address
&address
)
659 CLockObject
lock(m_mutex
);
660 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting default logical address setting");
662 cec_datapacket response
= GetSetting(MSGCODE_GET_DEFAULT_LOGICAL_ADDRESS
, 1);
663 if (response
.size
== 1)
665 address
= (cec_logical_address
)response
[0];
671 bool CUSBCECAdapterCommunication::SetSettingLogicalAddressMask(uint16_t iMask
)
673 CLockObject
lock(m_mutex
);
674 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the logical address mask to %2X", iMask
);
676 CCECAdapterMessage params
;
677 params
.PushEscaped(iMask
>> 8);
678 params
.PushEscaped((uint8_t)iMask
);
679 return SendCommand(MSGCODE_SET_LOGICAL_ADDRESS_MASK
, params
);
682 bool CUSBCECAdapterCommunication::GetSettingLogicalAddressMask(uint16_t &iMask
)
684 CLockObject
lock(m_mutex
);
685 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting logical address mask setting");
687 cec_datapacket response
= GetSetting(MSGCODE_GET_LOGICAL_ADDRESS_MASK
, 2);
688 if (response
.size
== 2)
690 iMask
= ((uint16_t)response
[0] << 8) | ((uint16_t)response
[1]);
696 bool CUSBCECAdapterCommunication::SetSettingPhysicalAddress(uint16_t iPhysicalAddress
)
698 CLockObject
lock(m_mutex
);
699 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the physical address to %04X", iPhysicalAddress
);
701 CCECAdapterMessage params
;
702 params
.PushEscaped(iPhysicalAddress
>> 8);
703 params
.PushEscaped((uint8_t)iPhysicalAddress
);
704 return SendCommand(MSGCODE_SET_PHYSICAL_ADDRESS
, params
);
707 bool CUSBCECAdapterCommunication::GetSettingPhysicalAddress(uint16_t &iPhysicalAddress
)
709 CLockObject
lock(m_mutex
);
710 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting physical address setting");
712 cec_datapacket response
= GetSetting(MSGCODE_GET_PHYSICAL_ADDRESS
, 2);
713 if (response
.size
== 2)
715 iPhysicalAddress
= ((uint16_t)response
[0] << 8) | ((uint16_t)response
[1]);
721 bool CUSBCECAdapterCommunication::SetSettingCECVersion(cec_version version
)
723 CLockObject
lock(m_mutex
);
724 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the CEC version to %s", CLibCEC::GetInstance()->ToString(version
));
726 CCECAdapterMessage params
;
727 params
.PushEscaped((uint8_t)version
);
728 return SendCommand(MSGCODE_SET_HDMI_VERSION
, params
);
731 bool CUSBCECAdapterCommunication::GetSettingCECVersion(cec_version
&version
)
733 CLockObject
lock(m_mutex
);
734 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting CEC version setting");
736 cec_datapacket response
= GetSetting(MSGCODE_GET_HDMI_VERSION
, 1);
737 if (response
.size
== 1)
739 version
= (cec_version
)response
[0];
745 bool CUSBCECAdapterCommunication::SetSettingOSDName(const char *strOSDName
)
747 CLockObject
lock(m_mutex
);
748 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the OSD name to %s", strOSDName
);
750 CCECAdapterMessage params
;
751 for (size_t iPtr
= 0; iPtr
< strlen(strOSDName
); iPtr
++)
752 params
.PushEscaped(strOSDName
[iPtr
]);
753 return SendCommand(MSGCODE_SET_OSD_NAME
, params
);
756 bool CUSBCECAdapterCommunication::GetSettingOSDName(CStdString
&strOSDName
)
758 CLockObject
lock(m_mutex
);
759 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting OSD name setting");
761 cec_datapacket response
= GetSetting(MSGCODE_GET_OSD_NAME
, 13);
762 if (response
.size
== 0)
766 for (uint8_t iPtr
= 0; iPtr
< response
.size
&& iPtr
< 13; iPtr
++)
767 buf
[iPtr
] = (char)response
[iPtr
];
768 buf
[response
.size
] = 0;
770 strOSDName
.Format("%s", buf
);
774 bool CUSBCECAdapterCommunication::WriteEEPROM(void)
776 CLockObject
lock(m_mutex
);
777 CLibCEC::AddLog(CEC_LOG_DEBUG
, "writing settings in the EEPROM");
779 CCECAdapterMessage params
;
780 return SendCommand(MSGCODE_WRITE_EEPROM
, params
);
783 bool CUSBCECAdapterCommunication::IsOpen(void)
785 return !IsStopped() && m_port
->IsOpen() && IsRunning();
788 bool CUSBCECAdapterCommunication::WaitForAck(CCECAdapterMessage
&message
)
791 bool bTransmitSucceeded(false);
792 uint8_t iPacketsLeft(message
.isTransmission
? message
.Size() / 4 : 1);
794 int64_t iNow
= GetTimeMs();
795 int64_t iTargetTime
= iNow
+ (message
.transmit_timeout
<= 5 ? CEC_DEFAULT_TRANSMIT_WAIT
: message
.transmit_timeout
);
797 while (!bTransmitSucceeded
&& !bError
&& iNow
< iTargetTime
)
800 CCECAdapterMessage msg
;
807 if (msg
.Message() == MSGCODE_FRAME_START
&& msg
.IsACK())
809 m_processor
->HandlePoll(msg
.Initiator(), msg
.Destination());
810 m_lastInitiator
= msg
.Initiator();
815 if (msg
.Message() == MSGCODE_RECEIVE_FAILED
&&
816 m_lastInitiator
!= CECDEVICE_UNKNOWN
&&
817 m_processor
->HandleReceiveFailed(m_lastInitiator
))
823 bError
= msg
.IsError();
826 message
.reply
= msg
.Message();
827 CLibCEC::AddLog(CEC_LOG_DEBUG
, msg
.ToString());
831 switch(msg
.Message())
833 case MSGCODE_COMMAND_ACCEPTED
:
834 if (iPacketsLeft
> 0)
836 if (!message
.isTransmission
&& iPacketsLeft
== 0)
837 bTransmitSucceeded
= true;
838 CLibCEC::AddLog(CEC_LOG_DEBUG
, "%s - waiting for %d more", msg
.ToString().c_str(), iPacketsLeft
);
840 case MSGCODE_TRANSMIT_SUCCEEDED
:
841 CLibCEC::AddLog(CEC_LOG_DEBUG
, msg
.ToString());
842 bTransmitSucceeded
= (iPacketsLeft
== 0);
843 bError
= !bTransmitSucceeded
;
844 message
.reply
= MSGCODE_TRANSMIT_SUCCEEDED
;
847 // ignore other data while waiting
855 message
.state
= bTransmitSucceeded
&& !bError
?
856 ADAPTER_MESSAGE_STATE_SENT_ACKED
:
857 ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED
;
859 return bTransmitSucceeded
&& !bError
;
862 void CUSBCECAdapterCommunication::AddData(uint8_t *data
, size_t iLen
)
864 CLockObject
lock(m_mutex
);
865 for (size_t iPtr
= 0; iPtr
< iLen
; iPtr
++)
869 if (data
[iPtr
] == MSGSTART
)
872 else if (data
[iPtr
] == MSGSTART
) //we found a msgstart before msgend, this is not right, remove
874 if (m_currentAdapterMessage
.Size() > 0)
875 CLibCEC::AddLog(CEC_LOG_WARNING
, "received MSGSTART before MSGEND, removing previous buffer contents");
876 m_currentAdapterMessage
.Clear();
879 else if (data
[iPtr
] == MSGEND
)
881 CCECAdapterMessage
*newMessage
= new CCECAdapterMessage
;
882 newMessage
->packet
= m_currentAdapterMessage
.packet
;
883 m_inBuffer
.Push(newMessage
);
884 m_currentAdapterMessage
.Clear();
886 m_bNextIsEscaped
= false;
888 m_rcvCondition
.Broadcast();
890 else if (m_bNextIsEscaped
)
892 m_currentAdapterMessage
.PushBack(data
[iPtr
] + (uint8_t)ESCOFFSET
);
893 m_bNextIsEscaped
= false;
895 else if (data
[iPtr
] == MSGESC
)
897 m_bNextIsEscaped
= true;
901 m_currentAdapterMessage
.PushBack(data
[iPtr
]);
906 bool CUSBCECAdapterCommunication::ReadFromDevice(uint32_t iTimeout
, size_t iSize
/* = 256 */)
915 CLockObject
lock(m_mutex
);
916 iBytesRead
= m_port
->Read(buff
, sizeof(uint8_t) * iSize
, iTimeout
);
917 if (iBytesRead
< 0 || iBytesRead
> 256)
919 CLibCEC::AddLog(CEC_LOG_ERROR
, "error reading from serial port: %s", m_port
->GetError().c_str());
923 else if (iBytesRead
> 0)
925 AddData(buff
, iBytesRead
);
928 return iBytesRead
> 0;
931 void CUSBCECAdapterCommunication::SendMessageToAdapter(CCECAdapterMessage
*msg
)
933 CLockObject
adapterLock(m_mutex
);
934 if (!m_port
->IsOpen())
936 CLibCEC::AddLog(CEC_LOG_ERROR
, "error writing to serial port: the connection is closed");
937 msg
->state
= ADAPTER_MESSAGE_STATE_ERROR
;
941 if (msg
->isTransmission
&& (msg
->Size() < 2 || msg
->At(1) != MSGCODE_TRANSMIT_IDLETIME
))
944 SetLineTimeout(msg
->lineTimeout
);
946 SetLineTimeout(msg
->retryTimeout
);
949 if (m_port
->Write(msg
->packet
.data
, msg
->Size()) != (ssize_t
) msg
->Size())
951 CLibCEC::AddLog(CEC_LOG_ERROR
, "error writing to serial port: %s", m_port
->GetError().c_str());
952 msg
->state
= ADAPTER_MESSAGE_STATE_ERROR
;
956 CLibCEC::AddLog(CEC_LOG_DEBUG
, "command sent");
957 msg
->state
= ADAPTER_MESSAGE_STATE_SENT
;
959 if (msg
->expectControllerAck
)
961 if (!WaitForAck(*msg
))
962 CLibCEC::AddLog(CEC_LOG_DEBUG
, "did not receive ack");
968 void CUSBCECAdapterCommunication::WriteNextCommand(void)
970 CCECAdapterMessage
*msg(NULL
);
971 if (m_outBuffer
.Pop(msg
))
972 SendMessageToAdapter(msg
);
975 CStdString
CUSBCECAdapterCommunication::GetPortName(void)
978 strName
= m_port
->GetName();
982 bool CUSBCECAdapterCommunication::SendCommand(cec_adapter_messagecode msgCode
, CCECAdapterMessage
¶ms
, bool bExpectAck
/* = true */, bool bIsTransmission
/* = false */, bool bSendDirectly
/* = true */, bool bIsRetry
/* = false */)
984 CLockObject
lock(m_mutex
);
986 CCECAdapterMessage
*output
= new CCECAdapterMessage
;
988 output
->PushBack(MSGSTART
);
989 output
->PushEscaped((uint8_t)msgCode
);
990 output
->Append(params
);
991 output
->PushBack(MSGEND
);
992 output
->isTransmission
= bIsTransmission
;
993 output
->expectControllerAck
= bExpectAck
;
996 SendMessageToAdapter(output
);
1000 bool bWriteOk
= output
->state
== (output
->expectControllerAck
? ADAPTER_MESSAGE_STATE_SENT_ACKED
: ADAPTER_MESSAGE_STATE_SENT
);
1003 CLibCEC::AddLog(CEC_LOG_ERROR
, "'%s' failed", CCECAdapterMessage::ToString(msgCode
));
1006 if (!bIsRetry
&& output
->reply
== MSGCODE_COMMAND_REJECTED
&& msgCode
!= MSGCODE_SET_CONTROLLED
)
1008 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting controlled mode and retrying");
1009 if (SetControlledMode(true))
1010 return SendCommand(msgCode
, params
, bExpectAck
, bIsTransmission
, bSendDirectly
, true);
1019 cec_datapacket
CUSBCECAdapterCommunication::GetSetting(cec_adapter_messagecode msgCode
, uint8_t iResponseLength
)
1021 cec_datapacket retVal
;
1024 CCECAdapterMessage params
;
1025 if (!SendCommand(msgCode
, params
, false))
1027 CLibCEC::AddLog(CEC_LOG_ERROR
, "%s failed", CCECAdapterMessage::ToString(msgCode
));
1031 Sleep(250); // TODO ReadFromDevice() isn't waiting for the timeout to pass on win32
1032 ReadFromDevice(CEC_DEFAULT_TRANSMIT_WAIT
, iResponseLength
+ 3 /* start + msgcode + iResponseLength + end */);
1033 CCECAdapterMessage input
;
1036 if (input
.Message() != msgCode
)
1037 CLibCEC::AddLog(CEC_LOG_ERROR
, "invalid response to %s received (%s)", CCECAdapterMessage::ToString(msgCode
), CCECAdapterMessage::ToString(input
.Message()));
1040 for (uint8_t iPtr
= 1; iPtr
< input
.Size(); iPtr
++)
1041 retVal
.PushBack(input
[iPtr
]);
1046 CLibCEC::AddLog(CEC_LOG_ERROR
, "no response to %s received", CCECAdapterMessage::ToString(msgCode
));