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