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 CUSBCECAdapterCommunication::CUSBCECAdapterCommunication(CCECProcessor
*processor
, const char *strPort
, uint16_t iBaudRate
/* = 38400 */) :
47 m_processor(processor
),
50 m_iFirmwareVersion(CEC_FW_VERSION_UNKNOWN
),
51 m_lastDestination(CECDEVICE_UNKNOWN
),
52 m_bNextIsEscaped(false),
56 for (unsigned int iPtr
= 0; iPtr
< 15; iPtr
++)
57 m_bWaitingForAck
[iPtr
] = false;
58 m_port
= new CSerialPort(strPort
, iBaudRate
);
61 bool CUSBCECAdapterCommunication::CheckAdapter(uint32_t iTimeoutMs
/* = 10000 */)
64 uint64_t iNow
= GetTimeMs();
65 uint64_t iTarget
= iTimeoutMs
> 0 ? iNow
+ iTimeoutMs
: iNow
+ CEC_DEFAULT_TRANSMIT_WAIT
;
67 /* try to ping the adapter */
70 while (iNow
< iTarget
&& (bPinged
= PingAdapter()) == false)
72 CLibCEC::AddLog(CEC_LOG_ERROR
, "the adapter did not respond correctly to a ping (try %d)", ++iPingTry
);
77 /* try to read the firmware version */
78 m_iFirmwareVersion
= CEC_FW_VERSION_UNKNOWN
;
79 unsigned iFwVersionTry(0);
80 while (bPinged
&& iNow
< iTarget
&& (m_iFirmwareVersion
= GetFirmwareVersion()) == CEC_FW_VERSION_UNKNOWN
&& iFwVersionTry
< 3)
82 CLibCEC::AddLog(CEC_LOG_WARNING
, "the adapter did not respond with a correct firmware version (try %d)", ++iFwVersionTry
);
87 if (m_iFirmwareVersion
== CEC_FW_VERSION_UNKNOWN
)
89 CLibCEC::AddLog(CEC_LOG_DEBUG
, "defaulting to firmware version 1");
90 m_iFirmwareVersion
= 1;
93 if (m_iFirmwareVersion
>= 2)
95 /* try to set controlled mode */
96 unsigned iControlledTry(0);
97 bool bControlled(false);
98 while (iNow
< iTarget
&& (bControlled
= SetControlledMode(true)) == false)
100 CLibCEC::AddLog(CEC_LOG_ERROR
, "the adapter did not respond correctly to setting controlled mode (try %d)", ++iControlledTry
);
104 bReturn
= bControlled
;
110 CLockObject
lock(m_mutex
);
111 m_bInitialised
= bReturn
;
117 bool CUSBCECAdapterCommunication::Open(IAdapterCommunicationCallback
*cb
, uint32_t iTimeoutMs
/* = 10000 */, bool bSkipChecks
/* = false */, bool bStartListening
/* = true */)
119 uint64_t iNow
= GetTimeMs();
120 uint64_t iTimeout
= iNow
+ iTimeoutMs
;
123 CLockObject
lock(m_mutex
);
127 CLibCEC::AddLog(CEC_LOG_ERROR
, "port is NULL");
133 CLibCEC::AddLog(CEC_LOG_ERROR
, "port is already open");
139 bool bConnected(false);
140 while (!bConnected
&& iNow
< iTimeout
)
142 if ((bConnected
= m_port
->Open(iTimeout
)) == false)
144 strError
.Format("error opening serial port '%s': %s", m_port
->GetName().c_str(), m_port
->GetError().c_str());
152 CLibCEC::AddLog(CEC_LOG_ERROR
, strError
);
156 CLibCEC::AddLog(CEC_LOG_DEBUG
, "connection opened, clearing any previous input and waiting for active transmissions to end before starting");
160 //clear any input bytes
162 ssize_t
iBytesRead(0);
163 bool bGotMsgStart(false), bGotMsgEnd(false);
164 while ((iBytesRead
= m_port
->Read(buff
, 1024, 100)) > 0 || (bGotMsgStart
&& !bGotMsgEnd
))
167 CLibCEC::AddLog(CEC_LOG_DEBUG
, "data received, clearing it");
168 // if something was received, wait for MSGEND
169 for (ssize_t iPtr
= 0; iPtr
< iBytesRead
; iPtr
++)
171 if (buff
[iPtr
] == MSGSTART
)
173 else if (buff
[iPtr
] == MSGEND
)
181 if (!bSkipChecks
&& !CheckAdapter())
183 CLibCEC::AddLog(CEC_LOG_ERROR
, "the adapter failed to pass basic checks");
188 else if (bStartListening
)
192 CLibCEC::AddLog(CEC_LOG_DEBUG
, "communication thread started");
199 CLibCEC::AddLog(CEC_LOG_ERROR
, "could not create a communication thread");
212 void CUSBCECAdapterCommunication::Close(void)
217 void *CUSBCECAdapterCommunication::Process(void)
221 bool bCommandReceived(false);
222 CTimeout
pingTimeout(CEC_ADAPTER_PING_TIMEOUT
);
226 CLockObject
lock(m_mutex
);
228 bCommandReceived
= m_callback
&& Read(command
, 0) && m_bInitialised
;
231 /* push the next command to the callback method if there is one */
232 if (!IsStopped() && bCommandReceived
)
233 m_callback
->OnCommandReceived(command
);
235 /* ping the adapter every 15 seconds */
236 if (pingTimeout
.TimeLeft() == 0)
238 pingTimeout
.Init(CEC_ADAPTER_PING_TIMEOUT
);
249 /* notify all threads that are waiting on messages to be sent */
250 CCECAdapterMessage
*msg(NULL
);
251 while (m_outBuffer
.Pop(msg
))
252 msg
->event
.Broadcast();
254 /* set the ackmask to 0 before closing the connection */
255 SetAckMaskInternal(0, true);
257 if (m_iFirmwareVersion
>= 2)
258 SetControlledMode(false);
266 m_rcvCondition
.Broadcast();
270 cec_adapter_message_state
CUSBCECAdapterCommunication::Write(const cec_command
&data
, uint8_t iMaxTries
, uint8_t iLineTimeout
/* = 3 */, uint8_t iRetryLineTimeout
/* = 3 */)
272 cec_adapter_message_state
retVal(ADAPTER_MESSAGE_STATE_UNKNOWN
);
276 CCECAdapterMessage
*output
= new CCECAdapterMessage(data
);
278 /* set the number of retries */
279 if (data
.opcode
== CEC_OPCODE_NONE
) //TODO
280 output
->maxTries
= 1;
281 else if (data
.initiator
!= CECDEVICE_BROADCAST
)
282 output
->maxTries
= iMaxTries
;
284 output
->lineTimeout
= iLineTimeout
;
285 output
->retryTimeout
= iRetryLineTimeout
;
288 if (data
.destination
< 15)
290 CLockObject
lock(m_mutex
);
291 m_bWaitingForAck
[data
.destination
] = true;
295 while (bRetry
&& ++output
->tries
< output
->maxTries
)
297 bRetry
= (!Write(output
) || output
->NeedsRetry()) && output
->transmit_timeout
> 0;
299 Sleep(CEC_DEFAULT_TRANSMIT_RETRY_WAIT
);
301 retVal
= output
->state
;
307 bool CUSBCECAdapterCommunication::Write(CCECAdapterMessage
*data
)
309 data
->state
= ADAPTER_MESSAGE_STATE_WAITING_TO_BE_SENT
;
310 m_outBuffer
.Push(data
);
311 data
->event
.Wait(5000);
313 if ((data
->expectControllerAck
&& data
->state
!= ADAPTER_MESSAGE_STATE_SENT_ACKED
) ||
314 (!data
->expectControllerAck
&& data
->state
!= ADAPTER_MESSAGE_STATE_SENT
))
316 CLibCEC::AddLog(CEC_LOG_DEBUG
, "command was not %s", data
->state
== ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED
? "acked" : "sent");
323 bool CUSBCECAdapterCommunication::Read(cec_command
&command
, uint32_t iTimeout
)
328 CCECAdapterMessage msg
;
329 if (Read(msg
, iTimeout
))
331 if (ParseMessage(msg
))
333 command
= m_currentframe
;
334 m_currentframe
.Clear();
341 bool CUSBCECAdapterCommunication::Read(CCECAdapterMessage
&msg
, uint32_t iTimeout
)
343 CLockObject
lock(m_mutex
);
346 CCECAdapterMessage
*buf(NULL
);
348 if (!m_inBuffer
.Pop(buf
))
350 if (iTimeout
== 0 || !m_rcvCondition
.Wait(m_mutex
, m_bHasData
, iTimeout
))
353 m_bHasData
= !m_inBuffer
.IsEmpty();
358 msg
.packet
= buf
->packet
;
359 msg
.state
= ADAPTER_MESSAGE_STATE_INCOMING
;
366 CStdString
CUSBCECAdapterCommunication::GetError(void) const
369 strError
= m_port
->GetError();
373 bool CUSBCECAdapterCommunication::StartBootloader(void)
379 CLibCEC::AddLog(CEC_LOG_DEBUG
, "starting the bootloader");
381 CCECAdapterMessage params
;
382 return SendCommand(MSGCODE_START_BOOTLOADER
, params
, false);
385 bool CUSBCECAdapterCommunication::PingAdapter(void)
387 CLockObject
lock(m_mutex
);
388 CLibCEC::AddLog(CEC_LOG_DEBUG
, "sending ping");
390 CCECAdapterMessage params
;
391 return SendCommand(MSGCODE_PING
, params
);
394 bool CUSBCECAdapterCommunication::ParseMessage(const CCECAdapterMessage
&msg
)
397 bool bIsError(msg
.IsError());
402 CLockObject
adapterLock(m_mutex
);
403 switch(msg
.Message())
405 case MSGCODE_FRAME_START
:
407 m_currentframe
.Clear();
410 m_currentframe
.initiator
= msg
.Initiator();
411 m_currentframe
.destination
= msg
.Destination();
412 m_currentframe
.ack
= msg
.IsACK();
413 m_currentframe
.eom
= msg
.IsEOM();
415 if (m_currentframe
.ack
== 0x1)
417 m_lastDestination
= m_currentframe
.destination
;
418 if (m_currentframe
.destination
< 15)
420 if (!m_bWaitingForAck
[m_currentframe
.destination
])
421 m_processor
->HandlePoll(m_currentframe
.initiator
, m_currentframe
.destination
);
423 m_bWaitingForAck
[m_currentframe
.destination
] = false;
428 case MSGCODE_RECEIVE_FAILED
:
430 m_currentframe
.Clear();
431 if (m_lastDestination
!= CECDEVICE_UNKNOWN
)
432 bIsError
= m_processor
->HandleReceiveFailed(m_lastDestination
);
435 case MSGCODE_FRAME_DATA
:
439 m_currentframe
.PushBack(msg
[1]);
440 m_currentframe
.eom
= msg
.IsEOM();
448 CLibCEC::AddLog(bIsError
? CEC_LOG_WARNING
: CEC_LOG_DEBUG
, msg
.ToString());
452 uint16_t CUSBCECAdapterCommunication::GetFirmwareVersion(void)
454 uint16_t iReturn(m_iFirmwareVersion
);
456 if (iReturn
== CEC_FW_VERSION_UNKNOWN
)
458 CLockObject
lock(m_mutex
);
459 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting the firmware version");
460 cec_datapacket response
= GetSetting(MSGCODE_FIRMWARE_VERSION
, 2);
461 if (response
.size
== 2)
463 m_iFirmwareVersion
= (response
[0] << 8 | response
[1]);
464 iReturn
= m_iFirmwareVersion
;
465 CLibCEC::AddLog(CEC_LOG_DEBUG
, "firmware version %d", m_iFirmwareVersion
);
472 bool CUSBCECAdapterCommunication::SetLineTimeout(uint8_t iTimeout
)
476 if (m_iLineTimeout
!= iTimeout
)
478 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the line timeout to %d", iTimeout
);
479 CCECAdapterMessage params
;
480 params
.PushEscaped(iTimeout
);
481 bReturn
= SendCommand(MSGCODE_TRANSMIT_IDLETIME
, params
);
483 m_iLineTimeout
= iTimeout
;
489 bool CUSBCECAdapterCommunication::SetAckMask(uint16_t iMask
)
491 return SetAckMaskInternal(iMask
, IsRunning());
494 bool CUSBCECAdapterCommunication::SetAckMaskInternal(uint16_t iMask
, bool bWriteDirectly
/* = false */)
496 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting ackmask to %2x", iMask
);
498 CCECAdapterMessage params
;
499 params
.PushEscaped(iMask
>> 8);
500 params
.PushEscaped((uint8_t)iMask
);
501 return SendCommand(MSGCODE_SET_ACK_MASK
, params
, true, false, bWriteDirectly
);
504 bool CUSBCECAdapterCommunication::PersistConfiguration(libcec_configuration
*configuration
)
506 if (m_iFirmwareVersion
< 2)
510 bReturn
&= SetSettingAutoEnabled(true);
511 bReturn
&= SetSettingDeviceType(CLibCEC::GetType(configuration
->logicalAddresses
.primary
));
512 bReturn
&= SetSettingDefaultLogicalAddress(configuration
->logicalAddresses
.primary
);
513 bReturn
&= SetSettingLogicalAddressMask(CLibCEC::GetMaskForType(configuration
->logicalAddresses
.primary
));
514 bReturn
&= SetSettingPhysicalAddress(configuration
->iPhysicalAddress
);
515 bReturn
&= SetSettingCECVersion(CEC_VERSION_1_3A
);
516 bReturn
&= SetSettingOSDName(configuration
->strDeviceName
);
518 bReturn
= WriteEEPROM();
522 bool CUSBCECAdapterCommunication::GetConfiguration(libcec_configuration
*configuration
)
524 configuration
->iFirmwareVersion
= m_iFirmwareVersion
;
525 if (m_iFirmwareVersion
< 2)
529 cec_device_type type
;
530 if (GetSettingDeviceType(type
))
532 CLibCEC::AddLog(CEC_LOG_DEBUG
, "using persisted device type setting %s", m_processor
->ToString(type
));
533 configuration
->deviceTypes
.Clear();
534 configuration
->deviceTypes
.Add(type
);
538 CLibCEC::AddLog(CEC_LOG_DEBUG
, "no persisted device type setting");
542 if (GetSettingPhysicalAddress(configuration
->iPhysicalAddress
))
544 CLibCEC::AddLog(CEC_LOG_DEBUG
, "using persisted physical address setting %4x", configuration
->iPhysicalAddress
);
548 CLibCEC::AddLog(CEC_LOG_DEBUG
, "no persisted physical address setting");
552 CStdString strDeviceName
;
553 if (GetSettingOSDName(strDeviceName
))
555 snprintf(configuration
->strDeviceName
, 13, "%s", strDeviceName
.c_str());
556 CLibCEC::AddLog(CEC_LOG_DEBUG
, "using persisted device name setting %s", configuration
->strDeviceName
);
560 CLibCEC::AddLog(CEC_LOG_DEBUG
, "no persisted device name setting");
564 // don't read the following settings:
565 // - auto enabled (always enabled)
566 // - default logical address (autodetected)
567 // - logical address mask (autodetected)
568 // - CEC version (1.3a)
570 // TODO to be added to the firmware:
571 // - base device (4 bits)
572 // - HDMI port number (4 bits)
573 // - TV vendor id (12 bits)
574 // - wake devices (8 bits)
575 // - standby devices (8 bits)
576 // - use TV menu language (1 bit)
577 // - activate source (1 bit)
578 // - power off screensaver (1 bit)
579 // - power off on standby (1 bit)
580 // - send inactive source (1 bit)
584 bool CUSBCECAdapterCommunication::SetControlledMode(bool controlled
)
586 CLockObject
lock(m_mutex
);
587 CLibCEC::AddLog(CEC_LOG_DEBUG
, "turning controlled mode %s", controlled
? "on" : "off");
589 CCECAdapterMessage params
;
590 params
.PushEscaped(controlled
? 1 : 0);
591 return SendCommand(MSGCODE_SET_CONTROLLED
, params
);
594 bool CUSBCECAdapterCommunication::SetSettingAutoEnabled(bool enabled
)
596 CLockObject
lock(m_mutex
);
597 CLibCEC::AddLog(CEC_LOG_DEBUG
, "turning autonomous mode %s", enabled
? "on" : "off");
599 CCECAdapterMessage params
;
600 params
.PushEscaped(enabled
? 1 : 0);
601 return SendCommand(MSGCODE_SET_AUTO_ENABLED
, params
);
604 bool CUSBCECAdapterCommunication::GetSettingAutoEnabled(bool &enabled
)
606 CLockObject
lock(m_mutex
);
607 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting autonomous mode setting");
609 cec_datapacket response
= GetSetting(MSGCODE_GET_AUTO_ENABLED
, 1);
610 if (response
.size
== 1)
612 enabled
= response
[0] == 1;
618 bool CUSBCECAdapterCommunication::SetSettingDeviceType(cec_device_type type
)
620 CLockObject
lock(m_mutex
);
621 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the device type to %1X", (uint8_t)type
);
623 CCECAdapterMessage params
;
624 params
.PushEscaped((uint8_t)type
);
625 return SendCommand(MSGCODE_SET_DEVICE_TYPE
, params
);
628 bool CUSBCECAdapterCommunication::GetSettingDeviceType(cec_device_type
&value
)
630 CLockObject
lock(m_mutex
);
631 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting device type setting");
633 cec_datapacket response
= GetSetting(MSGCODE_GET_DEVICE_TYPE
, 1);
634 if (response
.size
== 1)
636 value
= (cec_device_type
)response
[0];
642 bool CUSBCECAdapterCommunication::SetSettingDefaultLogicalAddress(cec_logical_address address
)
644 CLockObject
lock(m_mutex
);
645 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the default logical address to %1X", address
);
647 CCECAdapterMessage params
;
648 params
.PushEscaped((uint8_t)address
);
649 return SendCommand(MSGCODE_SET_DEFAULT_LOGICAL_ADDRESS
, params
);
652 bool CUSBCECAdapterCommunication::GetSettingDefaultLogicalAddress(cec_logical_address
&address
)
654 CLockObject
lock(m_mutex
);
655 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting default logical address setting");
657 cec_datapacket response
= GetSetting(MSGCODE_GET_DEFAULT_LOGICAL_ADDRESS
, 1);
658 if (response
.size
== 1)
660 address
= (cec_logical_address
)response
[0];
666 bool CUSBCECAdapterCommunication::SetSettingLogicalAddressMask(uint16_t iMask
)
668 CLockObject
lock(m_mutex
);
669 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the logical address mask to %2X", iMask
);
671 CCECAdapterMessage params
;
672 params
.PushEscaped(iMask
>> 8);
673 params
.PushEscaped((uint8_t)iMask
);
674 return SendCommand(MSGCODE_SET_LOGICAL_ADDRESS_MASK
, params
);
677 bool CUSBCECAdapterCommunication::GetSettingLogicalAddressMask(uint16_t &iMask
)
679 CLockObject
lock(m_mutex
);
680 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting logical address mask setting");
682 cec_datapacket response
= GetSetting(MSGCODE_GET_LOGICAL_ADDRESS_MASK
, 2);
683 if (response
.size
== 2)
685 iMask
= ((uint16_t)response
[0] << 8) | ((uint16_t)response
[1]);
691 bool CUSBCECAdapterCommunication::SetSettingPhysicalAddress(uint16_t iPhysicalAddress
)
693 CLockObject
lock(m_mutex
);
694 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the physical address to %04X", iPhysicalAddress
);
696 CCECAdapterMessage params
;
697 params
.PushEscaped(iPhysicalAddress
>> 8);
698 params
.PushEscaped((uint8_t)iPhysicalAddress
);
699 return SendCommand(MSGCODE_SET_PHYSICAL_ADDRESS
, params
);
702 bool CUSBCECAdapterCommunication::GetSettingPhysicalAddress(uint16_t &iPhysicalAddress
)
704 CLockObject
lock(m_mutex
);
705 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting physical address setting");
707 cec_datapacket response
= GetSetting(MSGCODE_GET_PHYSICAL_ADDRESS
, 2);
708 if (response
.size
== 2)
710 iPhysicalAddress
= ((uint16_t)response
[0] << 8) | ((uint16_t)response
[1]);
716 bool CUSBCECAdapterCommunication::SetSettingCECVersion(cec_version version
)
718 CLockObject
lock(m_mutex
);
719 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the CEC version to %s", CLibCEC::GetInstance()->ToString(version
));
721 CCECAdapterMessage params
;
722 params
.PushEscaped((uint8_t)version
);
723 return SendCommand(MSGCODE_SET_HDMI_VERSION
, params
);
726 bool CUSBCECAdapterCommunication::GetSettingCECVersion(cec_version
&version
)
728 CLockObject
lock(m_mutex
);
729 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting CEC version setting");
731 cec_datapacket response
= GetSetting(MSGCODE_GET_HDMI_VERSION
, 1);
732 if (response
.size
== 1)
734 version
= (cec_version
)response
[0];
740 bool CUSBCECAdapterCommunication::SetSettingOSDName(const char *strOSDName
)
742 CLockObject
lock(m_mutex
);
743 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting the OSD name to %s", strOSDName
);
745 CCECAdapterMessage params
;
746 for (size_t iPtr
= 0; iPtr
< strlen(strOSDName
); iPtr
++)
747 params
.PushEscaped(strOSDName
[iPtr
]);
748 return SendCommand(MSGCODE_SET_OSD_NAME
, params
);
751 bool CUSBCECAdapterCommunication::GetSettingOSDName(CStdString
&strOSDName
)
753 CLockObject
lock(m_mutex
);
754 CLibCEC::AddLog(CEC_LOG_DEBUG
, "requesting OSD name setting");
756 cec_datapacket response
= GetSetting(MSGCODE_GET_OSD_NAME
, 13);
757 if (response
.size
== 0)
761 for (uint8_t iPtr
= 0; iPtr
< response
.size
&& iPtr
< 13; iPtr
++)
762 buf
[iPtr
] = (char)response
[iPtr
];
763 buf
[response
.size
] = 0;
765 strOSDName
.Format("%s", buf
);
769 bool CUSBCECAdapterCommunication::WriteEEPROM(void)
771 CLockObject
lock(m_mutex
);
772 CLibCEC::AddLog(CEC_LOG_DEBUG
, "writing settings in the EEPROM");
774 CCECAdapterMessage params
;
775 return SendCommand(MSGCODE_WRITE_EEPROM
, params
);
778 bool CUSBCECAdapterCommunication::IsOpen(void)
780 return !IsStopped() && m_port
->IsOpen() && IsRunning();
783 bool CUSBCECAdapterCommunication::WaitForAck(CCECAdapterMessage
&message
)
786 bool bTransmitSucceeded(false);
787 uint8_t iPacketsLeft(message
.isTransmission
? message
.Size() / 4 : 1);
789 int64_t iNow
= GetTimeMs();
790 int64_t iTargetTime
= iNow
+ (message
.transmit_timeout
<= 5 ? CEC_DEFAULT_TRANSMIT_WAIT
: message
.transmit_timeout
);
792 while (!bTransmitSucceeded
&& !bError
&& iNow
< iTargetTime
)
795 CCECAdapterMessage msg
;
802 if (msg
.Message() == MSGCODE_FRAME_START
&& msg
.IsACK())
804 if (msg
.Initiator() < 15 && m_bWaitingForAck
[msg
.Initiator()])
805 m_bWaitingForAck
[msg
.Initiator()] = false;
806 else if (msg
.Initiator() < 15)
808 m_processor
->HandlePoll(msg
.Initiator(), msg
.Destination());
809 m_lastDestination
= msg
.Initiator();
815 if (msg
.Message() == MSGCODE_RECEIVE_FAILED
&&
816 m_lastDestination
!= CECDEVICE_UNKNOWN
&&
817 m_processor
->HandleReceiveFailed(m_lastDestination
))
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
);
1001 cec_adapter_messagecode reply
= output
->reply
;
1006 CLibCEC::AddLog(CEC_LOG_ERROR
, "'%s' failed", CCECAdapterMessage::ToString(msgCode
));
1008 if (!bIsRetry
&& reply
== MSGCODE_COMMAND_REJECTED
&& msgCode
!= MSGCODE_SET_CONTROLLED
)
1010 CLibCEC::AddLog(CEC_LOG_DEBUG
, "setting controlled mode and retrying");
1011 if (SetControlledMode(true))
1012 return SendCommand(msgCode
, params
, bExpectAck
, bIsTransmission
, bSendDirectly
, true);
1020 cec_datapacket
CUSBCECAdapterCommunication::GetSetting(cec_adapter_messagecode msgCode
, uint8_t iResponseLength
)
1022 cec_datapacket retVal
;
1025 CCECAdapterMessage params
;
1026 if (!SendCommand(msgCode
, params
, false))
1028 CLibCEC::AddLog(CEC_LOG_ERROR
, "%s failed", CCECAdapterMessage::ToString(msgCode
));
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
));