cec: fix ACK handling after d297cbd4fc30bc93836532a9a31027b7e64150b3. bugzid: 591
[deb_libcec.git] / src / lib / adapter / USBCECAdapterCommunication.cpp
1 /*
2 * This file is part of the libCEC(R) library.
3 *
4 * libCEC(R) is Copyright (C) 2011-2012 Pulse-Eight Limited. All rights reserved.
5 * libCEC(R) is an original work, containing original code.
6 *
7 * libCEC(R) is a trademark of Pulse-Eight Limited.
8 *
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.
13 *
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.
18 *
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.
22 *
23 *
24 * Alternatively, you can license this library under a commercial license,
25 * please contact Pulse-Eight Licensing for more information.
26 *
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/
31 */
32
33 #include "USBCECAdapterCommunication.h"
34 #include "../platform/sockets/serialport.h"
35 #include "../platform/util/timeutils.h"
36 #include "../LibCEC.h"
37 #include "../CECProcessor.h"
38
39 using namespace std;
40 using namespace CEC;
41 using namespace PLATFORM;
42
43 #define CEC_ADAPTER_PING_TIMEOUT 15000
44
45 void *CUSBCECAdapterProcessor::Process(void)
46 {
47 cec_command command;
48 while (!IsStopped())
49 {
50 if (m_inBuffer.Pop(command))
51 m_callback->OnCommandReceived(command);
52 Sleep(5);
53 }
54
55 return NULL;
56 }
57
58 void CUSBCECAdapterProcessor::AddCommand(cec_command command)
59 {
60 m_inBuffer.Push(command);
61 }
62
63 CUSBCECAdapterCommunication::CUSBCECAdapterCommunication(CCECProcessor *processor, const char *strPort, uint16_t iBaudRate /* = 38400 */) :
64 m_port(NULL),
65 m_processor(processor),
66 m_bHasData(false),
67 m_iLineTimeout(0),
68 m_iFirmwareVersion(CEC_FW_VERSION_UNKNOWN),
69 m_lastInitiator(CECDEVICE_UNKNOWN),
70 m_bNextIsEscaped(false),
71 m_bGotStart(false),
72 m_messageProcessor(NULL),
73 m_bInitialised(false)
74 {
75 for (unsigned int iPtr = 0; iPtr < 15; iPtr++)
76 m_bWaitingForAck[iPtr] = false;
77 m_port = new CSerialPort(strPort, iBaudRate);
78 }
79
80 CUSBCECAdapterCommunication::~CUSBCECAdapterCommunication(void)
81 {
82 Close();
83 }
84
85 bool CUSBCECAdapterCommunication::CheckAdapter(uint32_t iTimeoutMs /* = 10000 */)
86 {
87 bool bReturn(false);
88 uint64_t iNow = GetTimeMs();
89 uint64_t iTarget = iTimeoutMs > 0 ? iNow + iTimeoutMs : iNow + CEC_DEFAULT_TRANSMIT_WAIT;
90
91 /* try to ping the adapter */
92 bool bPinged(false);
93 unsigned iPingTry(0);
94 while (iNow < iTarget && (bPinged = PingAdapter()) == false)
95 {
96 CLibCEC::AddLog(CEC_LOG_ERROR, "the adapter did not respond correctly to a ping (try %d)", ++iPingTry);
97 CEvent::Sleep(500);
98 iNow = GetTimeMs();
99 }
100
101 /* try to read the firmware version */
102 m_iFirmwareVersion = CEC_FW_VERSION_UNKNOWN;
103 unsigned iFwVersionTry(0);
104 while (bPinged && iNow < iTarget && (m_iFirmwareVersion = GetFirmwareVersion()) == CEC_FW_VERSION_UNKNOWN && iFwVersionTry < 3)
105 {
106 CLibCEC::AddLog(CEC_LOG_WARNING, "the adapter did not respond with a correct firmware version (try %d)", ++iFwVersionTry);
107 CEvent::Sleep(500);
108 iNow = GetTimeMs();
109 }
110
111 if (m_iFirmwareVersion == CEC_FW_VERSION_UNKNOWN)
112 {
113 CLibCEC::AddLog(CEC_LOG_DEBUG, "defaulting to firmware version 1");
114 m_iFirmwareVersion = 1;
115 }
116
117 if (m_iFirmwareVersion >= 2)
118 {
119 /* try to set controlled mode */
120 unsigned iControlledTry(0);
121 bool bControlled(false);
122 while (iNow < iTarget && (bControlled = SetControlledMode(true)) == false)
123 {
124 CLibCEC::AddLog(CEC_LOG_ERROR, "the adapter did not respond correctly to setting controlled mode (try %d)", ++iControlledTry);
125 CEvent::Sleep(500);
126 iNow = GetTimeMs();
127 }
128 bReturn = bControlled;
129 }
130 else
131 bReturn = true;
132
133 {
134 CLockObject lock(m_mutex);
135 m_bInitialised = bReturn;
136 }
137
138 return bReturn;
139 }
140
141 bool CUSBCECAdapterCommunication::Open(IAdapterCommunicationCallback *cb, uint32_t iTimeoutMs /* = 10000 */, bool bSkipChecks /* = false */)
142 {
143 uint64_t iNow = GetTimeMs();
144 uint64_t iTimeout = iNow + iTimeoutMs;
145
146 {
147 CLockObject lock(m_mutex);
148
149 if (!m_port)
150 {
151 CLibCEC::AddLog(CEC_LOG_ERROR, "port is NULL");
152 return false;
153 }
154
155 if (IsOpen())
156 {
157 CLibCEC::AddLog(CEC_LOG_ERROR, "port is already open");
158 return true;
159 }
160
161 m_callback = cb;
162 CStdString strError;
163 bool bConnected(false);
164 while (!bConnected && iNow < iTimeout)
165 {
166 if ((bConnected = m_port->Open(iTimeout)) == false)
167 {
168 strError.Format("error opening serial port '%s': %s", m_port->GetName().c_str(), m_port->GetError().c_str());
169 Sleep(250);
170 iNow = GetTimeMs();
171 }
172 }
173
174 if (!bConnected)
175 {
176 CLibCEC::AddLog(CEC_LOG_ERROR, strError);
177 return false;
178 }
179
180 CLibCEC::AddLog(CEC_LOG_DEBUG, "connection opened, clearing any previous input and waiting for active transmissions to end before starting");
181
182 if (!bSkipChecks)
183 {
184 //clear any input bytes
185 uint8_t buff[1024];
186 ssize_t iBytesRead(0);
187 bool bGotMsgStart(false), bGotMsgEnd(false);
188 while ((iBytesRead = m_port->Read(buff, 1024, 100)) > 0 || (bGotMsgStart && !bGotMsgEnd))
189 {
190 if (!bGotMsgStart)
191 CLibCEC::AddLog(CEC_LOG_DEBUG, "data received, clearing it");
192 // if something was received, wait for MSGEND
193 for (ssize_t iPtr = 0; iPtr < iBytesRead; iPtr++)
194 {
195 if (buff[iPtr] == MSGSTART)
196 bGotMsgStart = true;
197 else if (buff[iPtr] == MSGEND)
198 bGotMsgEnd = true;
199 }
200 Sleep(250);
201 }
202 }
203 }
204
205 if (!bSkipChecks && !CheckAdapter())
206 {
207 CLibCEC::AddLog(CEC_LOG_ERROR, "the adapter failed to pass basic checks");
208 return false;
209 }
210 else
211 {
212 if (CreateThread())
213 {
214 CLibCEC::AddLog(CEC_LOG_DEBUG, "communication thread started");
215 return true;
216 }
217 else
218 {
219 CLibCEC::AddLog(CEC_LOG_ERROR, "could not create a communication thread");
220 }
221 }
222
223 return false;
224 }
225
226 void CUSBCECAdapterCommunication::Close(void)
227 {
228 StopThread();
229 }
230
231 void *CUSBCECAdapterCommunication::Process(void)
232 {
233 m_messageProcessor = new CUSBCECAdapterProcessor(m_callback);
234 m_messageProcessor->CreateThread();
235
236 cec_command command;
237 command.Clear();
238 bool bCommandReceived(false);
239 CTimeout pingTimeout(CEC_ADAPTER_PING_TIMEOUT);
240 while (!IsStopped())
241 {
242 {
243 CLockObject lock(m_mutex);
244 ReadFromDevice(50);
245 bCommandReceived = m_callback && Read(command, 0) && m_bInitialised;
246 }
247
248 /* push the next command to the callback method if there is one */
249 if (!IsStopped() && bCommandReceived)
250 m_messageProcessor->AddCommand(command);
251
252 /* ping the adapter every 15 seconds */
253 if (pingTimeout.TimeLeft() == 0)
254 {
255 pingTimeout.Init(CEC_ADAPTER_PING_TIMEOUT);
256 PingAdapter();
257 }
258
259 if (!IsStopped())
260 {
261 Sleep(5);
262 WriteNextCommand();
263 }
264 }
265
266 /* stop the message processor */
267 m_messageProcessor->StopThread();
268 delete m_messageProcessor;
269
270 /* notify all threads that are waiting on messages to be sent */
271 CCECAdapterMessage *msg(NULL);
272 while (m_outBuffer.Pop(msg))
273 msg->event.Broadcast();
274
275 /* set the ackmask to 0 before closing the connection */
276 SetAckMaskInternal(0, true);
277
278 if (m_iFirmwareVersion >= 2)
279 SetControlledMode(false);
280
281 if (m_port)
282 {
283 delete m_port;
284 m_port = NULL;
285 }
286
287 return NULL;
288 }
289
290 cec_adapter_message_state CUSBCECAdapterCommunication::Write(const cec_command &data, uint8_t iMaxTries, uint8_t iLineTimeout /* = 3 */, uint8_t iRetryLineTimeout /* = 3 */)
291 {
292 cec_adapter_message_state retVal(ADAPTER_MESSAGE_STATE_UNKNOWN);
293 if (!IsRunning())
294 return retVal;
295
296 CCECAdapterMessage *output = new CCECAdapterMessage(data);
297
298 /* set the number of retries */
299 if (data.opcode == CEC_OPCODE_NONE) //TODO
300 output->maxTries = 1;
301 else if (data.initiator != CECDEVICE_BROADCAST)
302 output->maxTries = iMaxTries;
303
304 output->lineTimeout = iLineTimeout;
305 output->retryTimeout = iRetryLineTimeout;
306 output->tries = 0;
307
308 {
309 CLockObject lock(m_mutex);
310 m_bWaitingForAck[data.destination] = true;
311 }
312
313 bool bRetry(true);
314 while (bRetry && ++output->tries < output->maxTries)
315 {
316 bRetry = (!Write(output) || output->NeedsRetry()) && output->transmit_timeout > 0;
317 if (bRetry)
318 Sleep(CEC_DEFAULT_TRANSMIT_RETRY_WAIT);
319 }
320 retVal = output->state;
321
322 delete output;
323 return retVal;
324 }
325
326 bool CUSBCECAdapterCommunication::Write(CCECAdapterMessage *data)
327 {
328 data->state = ADAPTER_MESSAGE_STATE_WAITING_TO_BE_SENT;
329 m_outBuffer.Push(data);
330 data->event.Wait(5000);
331
332 if ((data->expectControllerAck && data->state != ADAPTER_MESSAGE_STATE_SENT_ACKED) ||
333 (!data->expectControllerAck && data->state != ADAPTER_MESSAGE_STATE_SENT))
334 {
335 CLibCEC::AddLog(CEC_LOG_DEBUG, "command was not %s", data->state == ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED ? "acked" : "sent");
336 return false;
337 }
338
339 return true;
340 }
341
342 bool CUSBCECAdapterCommunication::Read(cec_command &command, uint32_t iTimeout)
343 {
344 if (!IsRunning())
345 return false;
346
347 CCECAdapterMessage msg;
348 if (Read(msg, iTimeout))
349 {
350 if (ParseMessage(msg))
351 {
352 command = m_currentframe;
353 m_currentframe.Clear();
354 return true;
355 }
356 }
357 return false;
358 }
359
360 bool CUSBCECAdapterCommunication::Read(CCECAdapterMessage &msg, uint32_t iTimeout)
361 {
362 CLockObject lock(m_mutex);
363
364 msg.Clear();
365 CCECAdapterMessage *buf(NULL);
366
367 if (!m_inBuffer.Pop(buf))
368 {
369 if (iTimeout == 0 || !m_rcvCondition.Wait(m_mutex, m_bHasData, iTimeout))
370 return false;
371 m_inBuffer.Pop(buf);
372 m_bHasData = !m_inBuffer.IsEmpty();
373 }
374
375 if (buf)
376 {
377 msg.packet = buf->packet;
378 msg.state = ADAPTER_MESSAGE_STATE_INCOMING;
379 delete buf;
380 return true;
381 }
382 return false;
383 }
384
385 CStdString CUSBCECAdapterCommunication::GetError(void) const
386 {
387 CStdString strError;
388 strError = m_port->GetError();
389 return strError;
390 }
391
392 bool CUSBCECAdapterCommunication::StartBootloader(void)
393 {
394 bool bReturn(false);
395 if (!IsRunning())
396 return bReturn;
397
398 CLibCEC::AddLog(CEC_LOG_DEBUG, "starting the bootloader");
399
400 CCECAdapterMessage params;
401 return SendCommand(MSGCODE_START_BOOTLOADER, params, false);
402 }
403
404 bool CUSBCECAdapterCommunication::PingAdapter(void)
405 {
406 CLockObject lock(m_mutex);
407 CLibCEC::AddLog(CEC_LOG_DEBUG, "sending ping");
408
409 CCECAdapterMessage params;
410 return SendCommand(MSGCODE_PING, params);
411 }
412
413 bool CUSBCECAdapterCommunication::ParseMessage(const CCECAdapterMessage &msg)
414 {
415 bool bEom(false);
416 bool bIsError(msg.IsError());
417
418 if (msg.IsEmpty())
419 return bEom;
420
421 CLockObject adapterLock(m_mutex);
422 switch(msg.Message())
423 {
424 case MSGCODE_FRAME_START:
425 {
426 m_currentframe.Clear();
427 if (msg.Size() >= 2)
428 {
429 m_currentframe.initiator = msg.Initiator();
430 m_currentframe.destination = msg.Destination();
431 m_currentframe.ack = msg.IsACK();
432 m_currentframe.eom = msg.IsEOM();
433 }
434 if (m_currentframe.ack == 0x1)
435 {
436 m_lastInitiator = m_currentframe.initiator;
437 if (!m_bWaitingForAck[m_currentframe.destination])
438 {
439 m_currentframe.eom = 1;
440 bEom = true;
441 }
442 else
443 {
444 m_bWaitingForAck[m_currentframe.destination] = false;
445 }
446 }
447 }
448 break;
449 case MSGCODE_RECEIVE_FAILED:
450 {
451 m_currentframe.Clear();
452 if (m_lastInitiator != CECDEVICE_UNKNOWN)
453 bIsError = m_processor->HandleReceiveFailed(m_lastInitiator);
454 }
455 break;
456 case MSGCODE_FRAME_DATA:
457 {
458 if (msg.Size() >= 2)
459 {
460 m_currentframe.PushBack(msg[1]);
461 m_currentframe.eom = msg.IsEOM();
462 }
463 }
464 break;
465 default:
466 break;
467 }
468
469 CLibCEC::AddLog(bIsError ? CEC_LOG_WARNING : CEC_LOG_DEBUG, msg.ToString());
470 return msg.IsEOM() || bEom;
471 }
472
473 uint16_t CUSBCECAdapterCommunication::GetFirmwareVersion(void)
474 {
475 uint16_t iReturn(m_iFirmwareVersion);
476
477 if (iReturn == CEC_FW_VERSION_UNKNOWN)
478 {
479 CLockObject lock(m_mutex);
480 CLibCEC::AddLog(CEC_LOG_DEBUG, "requesting the firmware version");
481 cec_datapacket response = GetSetting(MSGCODE_FIRMWARE_VERSION, 2);
482 if (response.size == 2)
483 {
484 m_iFirmwareVersion = (response[0] << 8 | response[1]);
485 iReturn = m_iFirmwareVersion;
486 CLibCEC::AddLog(CEC_LOG_DEBUG, "firmware version %d", m_iFirmwareVersion);
487 }
488 }
489
490 return iReturn;
491 }
492
493 bool CUSBCECAdapterCommunication::SetLineTimeout(uint8_t iTimeout)
494 {
495 m_iLineTimeout = iTimeout;
496 bool bReturn(m_iLineTimeout != iTimeout);
497
498 if (!bReturn)
499 {
500 CLibCEC::AddLog(CEC_LOG_DEBUG, "setting the line timeout to %d", iTimeout);
501 CCECAdapterMessage params;
502 params.PushEscaped(iTimeout);
503 bReturn = SendCommand(MSGCODE_TRANSMIT_IDLETIME, params);
504 }
505
506 return bReturn;
507 }
508
509 bool CUSBCECAdapterCommunication::SetAckMask(uint16_t iMask)
510 {
511 return SetAckMaskInternal(iMask, IsRunning());
512 }
513
514 bool CUSBCECAdapterCommunication::SetAckMaskInternal(uint16_t iMask, bool bWriteDirectly /* = false */)
515 {
516 CLibCEC::AddLog(CEC_LOG_DEBUG, "setting ackmask to %2x", iMask);
517
518 CCECAdapterMessage params;
519 params.PushEscaped(iMask >> 8);
520 params.PushEscaped((uint8_t)iMask);
521 return SendCommand(MSGCODE_SET_ACK_MASK, params, true, false, bWriteDirectly);
522 }
523
524 bool CUSBCECAdapterCommunication::PersistConfiguration(libcec_configuration *configuration)
525 {
526 if (m_iFirmwareVersion < 2)
527 return false;
528
529 bool bReturn(true);
530 bReturn &= SetSettingAutoEnabled(true);
531 bReturn &= SetSettingDeviceType(CLibCEC::GetType(configuration->logicalAddresses.primary));
532 bReturn &= SetSettingDefaultLogicalAddress(configuration->logicalAddresses.primary);
533 bReturn &= SetSettingLogicalAddressMask(CLibCEC::GetMaskForType(configuration->logicalAddresses.primary));
534 bReturn &= SetSettingPhysicalAddress(configuration->iPhysicalAddress);
535 bReturn &= SetSettingCECVersion(CEC_VERSION_1_3A);
536 bReturn &= SetSettingOSDName(configuration->strDeviceName);
537 if (bReturn)
538 bReturn = WriteEEPROM();
539 return bReturn;
540 }
541
542 bool CUSBCECAdapterCommunication::GetConfiguration(libcec_configuration *configuration)
543 {
544 if (m_iFirmwareVersion < 2)
545 return false;
546
547 bool bReturn(true);
548 cec_device_type type;
549 if (GetSettingDeviceType(type))
550 {
551 CLibCEC::AddLog(CEC_LOG_DEBUG, "using persisted device type setting %s", m_processor->ToString(type));
552 configuration->deviceTypes.Clear();
553 configuration->deviceTypes.Add(type);
554 }
555 else
556 {
557 CLibCEC::AddLog(CEC_LOG_DEBUG, "no persisted device type setting");
558 bReturn = false;
559 }
560
561 if (GetSettingPhysicalAddress(configuration->iPhysicalAddress))
562 {
563 CLibCEC::AddLog(CEC_LOG_DEBUG, "using persisted physical address setting %4x", configuration->iPhysicalAddress);
564 }
565 else
566 {
567 CLibCEC::AddLog(CEC_LOG_DEBUG, "no persisted physical address setting");
568 bReturn = false;
569 }
570
571 CStdString strDeviceName;
572 if (GetSettingOSDName(strDeviceName))
573 {
574 snprintf(configuration->strDeviceName, 13, "%s", strDeviceName.c_str());
575 CLibCEC::AddLog(CEC_LOG_DEBUG, "using persisted device name setting %s", configuration->strDeviceName);
576 }
577 else
578 {
579 CLibCEC::AddLog(CEC_LOG_DEBUG, "no persisted device name setting");
580 bReturn = false;
581 }
582
583 // don't read the following settings:
584 // - auto enabled (always enabled)
585 // - default logical address (autodetected)
586 // - logical address mask (autodetected)
587 // - CEC version (1.3a)
588
589 // TODO to be added to the firmware:
590 // - base device (4 bits)
591 // - HDMI port number (4 bits)
592 // - TV vendor id (12 bits)
593 // - wake devices (8 bits)
594 // - standby devices (8 bits)
595 // - use TV menu language (1 bit)
596 // - activate source (1 bit)
597 // - power off screensaver (1 bit)
598 // - power off on standby (1 bit)
599 // - send inactive source (1 bit)
600 return bReturn;
601 }
602
603 bool CUSBCECAdapterCommunication::SetControlledMode(bool controlled)
604 {
605 CLockObject lock(m_mutex);
606 CLibCEC::AddLog(CEC_LOG_DEBUG, "turning controlled mode %s", controlled ? "on" : "off");
607
608 CCECAdapterMessage params;
609 params.PushEscaped(controlled ? 1 : 0);
610 return SendCommand(MSGCODE_SET_CONTROLLED, params);
611 }
612
613 bool CUSBCECAdapterCommunication::SetSettingAutoEnabled(bool enabled)
614 {
615 CLockObject lock(m_mutex);
616 CLibCEC::AddLog(CEC_LOG_DEBUG, "turning autonomous mode %s", enabled ? "on" : "off");
617
618 CCECAdapterMessage params;
619 params.PushEscaped(enabled ? 1 : 0);
620 return SendCommand(MSGCODE_SET_AUTO_ENABLED, params);
621 }
622
623 bool CUSBCECAdapterCommunication::GetSettingAutoEnabled(bool &enabled)
624 {
625 CLockObject lock(m_mutex);
626 CLibCEC::AddLog(CEC_LOG_DEBUG, "requesting autonomous mode setting");
627
628 cec_datapacket response = GetSetting(MSGCODE_GET_AUTO_ENABLED, 1);
629 if (response.size == 1)
630 {
631 enabled = response[0] == 1;
632 return true;
633 }
634 return false;
635 }
636
637 bool CUSBCECAdapterCommunication::SetSettingDeviceType(cec_device_type type)
638 {
639 CLockObject lock(m_mutex);
640 CLibCEC::AddLog(CEC_LOG_DEBUG, "setting the device type to %1X", (uint8_t)type);
641
642 CCECAdapterMessage params;
643 params.PushEscaped((uint8_t)type);
644 return SendCommand(MSGCODE_SET_DEVICE_TYPE, params);
645 }
646
647 bool CUSBCECAdapterCommunication::GetSettingDeviceType(cec_device_type &value)
648 {
649 CLockObject lock(m_mutex);
650 CLibCEC::AddLog(CEC_LOG_DEBUG, "requesting device type setting");
651
652 cec_datapacket response = GetSetting(MSGCODE_GET_DEVICE_TYPE, 1);
653 if (response.size == 1)
654 {
655 value = (cec_device_type)response[0];
656 return true;
657 }
658 return false;
659 }
660
661 bool CUSBCECAdapterCommunication::SetSettingDefaultLogicalAddress(cec_logical_address address)
662 {
663 CLockObject lock(m_mutex);
664 CLibCEC::AddLog(CEC_LOG_DEBUG, "setting the default logical address to %1X", address);
665
666 CCECAdapterMessage params;
667 params.PushEscaped((uint8_t)address);
668 return SendCommand(MSGCODE_SET_DEFAULT_LOGICAL_ADDRESS, params);
669 }
670
671 bool CUSBCECAdapterCommunication::GetSettingDefaultLogicalAddress(cec_logical_address &address)
672 {
673 CLockObject lock(m_mutex);
674 CLibCEC::AddLog(CEC_LOG_DEBUG, "requesting default logical address setting");
675
676 cec_datapacket response = GetSetting(MSGCODE_GET_DEFAULT_LOGICAL_ADDRESS, 1);
677 if (response.size == 1)
678 {
679 address = (cec_logical_address)response[0];
680 return true;
681 }
682 return false;
683 }
684
685 bool CUSBCECAdapterCommunication::SetSettingLogicalAddressMask(uint16_t iMask)
686 {
687 CLockObject lock(m_mutex);
688 CLibCEC::AddLog(CEC_LOG_DEBUG, "setting the logical address mask to %2X", iMask);
689
690 CCECAdapterMessage params;
691 params.PushEscaped(iMask >> 8);
692 params.PushEscaped((uint8_t)iMask);
693 return SendCommand(MSGCODE_SET_LOGICAL_ADDRESS_MASK, params);
694 }
695
696 bool CUSBCECAdapterCommunication::GetSettingLogicalAddressMask(uint16_t &iMask)
697 {
698 CLockObject lock(m_mutex);
699 CLibCEC::AddLog(CEC_LOG_DEBUG, "requesting logical address mask setting");
700
701 cec_datapacket response = GetSetting(MSGCODE_GET_LOGICAL_ADDRESS_MASK, 2);
702 if (response.size == 2)
703 {
704 iMask = ((uint16_t)response[0] << 8) | ((uint16_t)response[1]);
705 return true;
706 }
707 return false;
708 }
709
710 bool CUSBCECAdapterCommunication::SetSettingPhysicalAddress(uint16_t iPhysicalAddress)
711 {
712 CLockObject lock(m_mutex);
713 CLibCEC::AddLog(CEC_LOG_DEBUG, "setting the physical address to %04X", iPhysicalAddress);
714
715 CCECAdapterMessage params;
716 params.PushEscaped(iPhysicalAddress >> 8);
717 params.PushEscaped((uint8_t)iPhysicalAddress);
718 return SendCommand(MSGCODE_SET_PHYSICAL_ADDRESS, params);
719 }
720
721 bool CUSBCECAdapterCommunication::GetSettingPhysicalAddress(uint16_t &iPhysicalAddress)
722 {
723 CLockObject lock(m_mutex);
724 CLibCEC::AddLog(CEC_LOG_DEBUG, "requesting physical address setting");
725
726 cec_datapacket response = GetSetting(MSGCODE_GET_PHYSICAL_ADDRESS, 2);
727 if (response.size == 2)
728 {
729 iPhysicalAddress = ((uint16_t)response[0] << 8) | ((uint16_t)response[1]);
730 return true;
731 }
732 return false;
733 }
734
735 bool CUSBCECAdapterCommunication::SetSettingCECVersion(cec_version version)
736 {
737 CLockObject lock(m_mutex);
738 CLibCEC::AddLog(CEC_LOG_DEBUG, "setting the CEC version to %s", CLibCEC::GetInstance()->ToString(version));
739
740 CCECAdapterMessage params;
741 params.PushEscaped((uint8_t)version);
742 return SendCommand(MSGCODE_SET_HDMI_VERSION, params);
743 }
744
745 bool CUSBCECAdapterCommunication::GetSettingCECVersion(cec_version &version)
746 {
747 CLockObject lock(m_mutex);
748 CLibCEC::AddLog(CEC_LOG_DEBUG, "requesting CEC version setting");
749
750 cec_datapacket response = GetSetting(MSGCODE_GET_HDMI_VERSION, 1);
751 if (response.size == 1)
752 {
753 version = (cec_version)response[0];
754 return true;
755 }
756 return false;
757 }
758
759 bool CUSBCECAdapterCommunication::SetSettingOSDName(const char *strOSDName)
760 {
761 CLockObject lock(m_mutex);
762 CLibCEC::AddLog(CEC_LOG_DEBUG, "setting the OSD name to %s", strOSDName);
763
764 CCECAdapterMessage params;
765 for (size_t iPtr = 0; iPtr < strlen(strOSDName); iPtr++)
766 params.PushEscaped(strOSDName[iPtr]);
767 return SendCommand(MSGCODE_SET_OSD_NAME, params);
768 }
769
770 bool CUSBCECAdapterCommunication::GetSettingOSDName(CStdString &strOSDName)
771 {
772 CLockObject lock(m_mutex);
773 CLibCEC::AddLog(CEC_LOG_DEBUG, "requesting OSD name setting");
774
775 cec_datapacket response = GetSetting(MSGCODE_GET_OSD_NAME, 13);
776 if (response.size == 0)
777 return false;
778
779 char buf[14];
780 for (uint8_t iPtr = 0; iPtr < response.size && iPtr < 13; iPtr++)
781 buf[iPtr] = (char)response[iPtr];
782 buf[response.size] = 0;
783
784 strOSDName.Format("%s", buf);
785 return true;
786 }
787
788 bool CUSBCECAdapterCommunication::WriteEEPROM(void)
789 {
790 CLockObject lock(m_mutex);
791 CLibCEC::AddLog(CEC_LOG_DEBUG, "writing settings in the EEPROM");
792
793 CCECAdapterMessage params;
794 return SendCommand(MSGCODE_WRITE_EEPROM, params);
795 }
796
797 bool CUSBCECAdapterCommunication::IsOpen(void)
798 {
799 return !IsStopped() && m_port->IsOpen() && IsRunning();
800 }
801
802 bool CUSBCECAdapterCommunication::WaitForAck(CCECAdapterMessage &message)
803 {
804 bool bError(false);
805 bool bTransmitSucceeded(false);
806 uint8_t iPacketsLeft(message.isTransmission ? message.Size() / 4 : 1);
807
808 int64_t iNow = GetTimeMs();
809 int64_t iTargetTime = iNow + (message.transmit_timeout <= 5 ? CEC_DEFAULT_TRANSMIT_WAIT : message.transmit_timeout);
810
811 while (!bTransmitSucceeded && !bError && iNow < iTargetTime)
812 {
813 ReadFromDevice(50);
814 CCECAdapterMessage msg;
815 if (!Read(msg, 0))
816 {
817 iNow = GetTimeMs();
818 continue;
819 }
820
821 if (msg.Message() == MSGCODE_FRAME_START && msg.IsACK())
822 {
823 if (m_bWaitingForAck[msg.Initiator()])
824 m_bWaitingForAck[msg.Initiator()] = false;
825 else
826 {
827 m_processor->HandlePoll(msg.Initiator(), msg.Destination());
828 m_lastInitiator = msg.Initiator();
829 }
830 iNow = GetTimeMs();
831 continue;
832 }
833
834 if (msg.Message() == MSGCODE_RECEIVE_FAILED &&
835 m_lastInitiator != CECDEVICE_UNKNOWN &&
836 m_processor->HandleReceiveFailed(m_lastInitiator))
837 {
838 iNow = GetTimeMs();
839 continue;
840 }
841
842 bError = msg.IsError();
843 if (bError)
844 {
845 message.reply = msg.Message();
846 CLibCEC::AddLog(CEC_LOG_DEBUG, msg.ToString());
847 }
848 else
849 {
850 switch(msg.Message())
851 {
852 case MSGCODE_COMMAND_ACCEPTED:
853 if (iPacketsLeft > 0)
854 iPacketsLeft--;
855 if (!message.isTransmission && iPacketsLeft == 0)
856 bTransmitSucceeded = true;
857 CLibCEC::AddLog(CEC_LOG_DEBUG, "%s - waiting for %d more", msg.ToString().c_str(), iPacketsLeft);
858 break;
859 case MSGCODE_TRANSMIT_SUCCEEDED:
860 CLibCEC::AddLog(CEC_LOG_DEBUG, msg.ToString());
861 bTransmitSucceeded = (iPacketsLeft == 0);
862 bError = !bTransmitSucceeded;
863 message.reply = MSGCODE_TRANSMIT_SUCCEEDED;
864 break;
865 default:
866 // ignore other data while waiting
867 break;
868 }
869
870 iNow = GetTimeMs();
871 }
872 }
873
874 message.state = bTransmitSucceeded && !bError ?
875 ADAPTER_MESSAGE_STATE_SENT_ACKED :
876 ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED;
877
878 return bTransmitSucceeded && !bError;
879 }
880
881 void CUSBCECAdapterCommunication::AddData(uint8_t *data, size_t iLen)
882 {
883 CLockObject lock(m_mutex);
884 for (size_t iPtr = 0; iPtr < iLen; iPtr++)
885 {
886 if (!m_bGotStart)
887 {
888 if (data[iPtr] == MSGSTART)
889 m_bGotStart = true;
890 }
891 else if (data[iPtr] == MSGSTART) //we found a msgstart before msgend, this is not right, remove
892 {
893 if (m_currentAdapterMessage.Size() > 0)
894 CLibCEC::AddLog(CEC_LOG_WARNING, "received MSGSTART before MSGEND, removing previous buffer contents");
895 m_currentAdapterMessage.Clear();
896 m_bGotStart = true;
897 }
898 else if (data[iPtr] == MSGEND)
899 {
900 CCECAdapterMessage *newMessage = new CCECAdapterMessage;
901 newMessage->packet = m_currentAdapterMessage.packet;
902 m_inBuffer.Push(newMessage);
903 m_currentAdapterMessage.Clear();
904 m_bGotStart = false;
905 m_bNextIsEscaped = false;
906 m_bHasData = true;
907 m_rcvCondition.Broadcast();
908 }
909 else if (m_bNextIsEscaped)
910 {
911 m_currentAdapterMessage.PushBack(data[iPtr] + (uint8_t)ESCOFFSET);
912 m_bNextIsEscaped = false;
913 }
914 else if (data[iPtr] == MSGESC)
915 {
916 m_bNextIsEscaped = true;
917 }
918 else
919 {
920 m_currentAdapterMessage.PushBack(data[iPtr]);
921 }
922 }
923 }
924
925 bool CUSBCECAdapterCommunication::ReadFromDevice(uint32_t iTimeout, size_t iSize /* = 256 */)
926 {
927 ssize_t iBytesRead;
928 uint8_t buff[256];
929 if (!m_port)
930 return false;
931 if (iSize > 256)
932 iSize = 256;
933
934 CLockObject lock(m_mutex);
935 iBytesRead = m_port->Read(buff, sizeof(uint8_t) * iSize, iTimeout);
936 if (iBytesRead < 0 || iBytesRead > 256)
937 {
938 CLibCEC::AddLog(CEC_LOG_ERROR, "error reading from serial port: %s", m_port->GetError().c_str());
939 StopThread(false);
940 return false;
941 }
942 else if (iBytesRead > 0)
943 {
944 AddData(buff, iBytesRead);
945 }
946
947 return iBytesRead > 0;
948 }
949
950 void CUSBCECAdapterCommunication::SendMessageToAdapter(CCECAdapterMessage *msg)
951 {
952 CLockObject adapterLock(m_mutex);
953 if (!m_port->IsOpen())
954 {
955 CLibCEC::AddLog(CEC_LOG_ERROR, "error writing to serial port: the connection is closed");
956 msg->state = ADAPTER_MESSAGE_STATE_ERROR;
957 return;
958 }
959
960 if (msg->isTransmission && (msg->Size() < 2 || msg->At(1) != MSGCODE_TRANSMIT_IDLETIME))
961 {
962 if (msg->tries == 1)
963 SetLineTimeout(msg->lineTimeout);
964 else
965 SetLineTimeout(msg->retryTimeout);
966 }
967
968 if (m_port->Write(msg->packet.data, msg->Size()) != (ssize_t) msg->Size())
969 {
970 CLibCEC::AddLog(CEC_LOG_ERROR, "error writing to serial port: %s", m_port->GetError().c_str());
971 msg->state = ADAPTER_MESSAGE_STATE_ERROR;
972 }
973 else
974 {
975 CLibCEC::AddLog(CEC_LOG_DEBUG, "command sent");
976 msg->state = ADAPTER_MESSAGE_STATE_SENT;
977
978 if (msg->expectControllerAck)
979 {
980 if (!WaitForAck(*msg))
981 CLibCEC::AddLog(CEC_LOG_DEBUG, "did not receive ack");
982 }
983 }
984 msg->event.Signal();
985 }
986
987 void CUSBCECAdapterCommunication::WriteNextCommand(void)
988 {
989 CCECAdapterMessage *msg(NULL);
990 if (m_outBuffer.Pop(msg))
991 SendMessageToAdapter(msg);
992 }
993
994 CStdString CUSBCECAdapterCommunication::GetPortName(void)
995 {
996 CStdString strName;
997 strName = m_port->GetName();
998 return strName;
999 }
1000
1001 bool CUSBCECAdapterCommunication::SendCommand(cec_adapter_messagecode msgCode, CCECAdapterMessage &params, bool bExpectAck /* = true */, bool bIsTransmission /* = false */, bool bSendDirectly /* = true */, bool bIsRetry /* = false */)
1002 {
1003 CLockObject lock(m_mutex);
1004
1005 CCECAdapterMessage *output = new CCECAdapterMessage;
1006
1007 output->PushBack(MSGSTART);
1008 output->PushEscaped((uint8_t)msgCode);
1009 output->Append(params);
1010 output->PushBack(MSGEND);
1011 output->isTransmission = bIsTransmission;
1012 output->expectControllerAck = bExpectAck;
1013
1014 if (bSendDirectly)
1015 SendMessageToAdapter(output);
1016 else
1017 Write(output);
1018
1019 bool bWriteOk = output->state == (output->expectControllerAck ? ADAPTER_MESSAGE_STATE_SENT_ACKED : ADAPTER_MESSAGE_STATE_SENT);
1020 if (!bWriteOk)
1021 {
1022 CLibCEC::AddLog(CEC_LOG_ERROR, "'%s' failed", CCECAdapterMessage::ToString(msgCode));
1023 delete output;
1024
1025 if (!bIsRetry && output->reply == MSGCODE_COMMAND_REJECTED && msgCode != MSGCODE_SET_CONTROLLED)
1026 {
1027 CLibCEC::AddLog(CEC_LOG_DEBUG, "setting controlled mode and retrying");
1028 if (SetControlledMode(true))
1029 return SendCommand(msgCode, params, bExpectAck, bIsTransmission, bSendDirectly, true);
1030 }
1031 return false;
1032 }
1033
1034 delete output;
1035 return true;
1036 }
1037
1038 cec_datapacket CUSBCECAdapterCommunication::GetSetting(cec_adapter_messagecode msgCode, uint8_t iResponseLength)
1039 {
1040 cec_datapacket retVal;
1041 retVal.Clear();
1042
1043 CCECAdapterMessage params;
1044 if (!SendCommand(msgCode, params, false))
1045 {
1046 CLibCEC::AddLog(CEC_LOG_ERROR, "%s failed", CCECAdapterMessage::ToString(msgCode));
1047 return retVal;
1048 }
1049
1050 Sleep(250); // TODO ReadFromDevice() isn't waiting for the timeout to pass on win32
1051 ReadFromDevice(CEC_DEFAULT_TRANSMIT_WAIT, iResponseLength + 3 /* start + msgcode + iResponseLength + end */);
1052 CCECAdapterMessage input;
1053 if (Read(input, 0))
1054 {
1055 if (input.Message() != msgCode)
1056 CLibCEC::AddLog(CEC_LOG_ERROR, "invalid response to %s received (%s)", CCECAdapterMessage::ToString(msgCode), CCECAdapterMessage::ToString(input.Message()));
1057 else
1058 {
1059 for (uint8_t iPtr = 1; iPtr < input.Size(); iPtr++)
1060 retVal.PushBack(input[iPtr]);
1061 }
1062 }
1063 else
1064 {
1065 CLibCEC::AddLog(CEC_LOG_ERROR, "no response to %s received", CCECAdapterMessage::ToString(msgCode));
1066 }
1067
1068 return retVal;
1069 }