e9d4d9333e399430a008b72ccf779bc3d3117f86
[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 bCommandReceived = m_callback && Read(command, 50) && m_bInitialised;
233 }
234
235 /* push the next command to the callback method if there is one */
236 if (!IsStopped() && bCommandReceived)
237 m_callback->OnCommandReceived(command);
238
239 Sleep(5);
240 }
241
242 /* set the ackmask to 0 before closing the connection */
243 SetAckMaskInternal(0, true);
244
245 if (m_iFirmwareVersion >= 2)
246 SetControlledMode(false);
247
248 if (m_port)
249 {
250 delete m_port;
251 m_port = NULL;
252 }
253
254 m_rcvCondition.Broadcast();
255 return NULL;
256 }
257
258 cec_adapter_message_state CUSBCECAdapterCommunication::Write(const cec_command &data, uint8_t iMaxTries, uint8_t iLineTimeout /* = 3 */, uint8_t iRetryLineTimeout /* = 3 */)
259 {
260 cec_adapter_message_state retVal(ADAPTER_MESSAGE_STATE_UNKNOWN);
261 if (!IsRunning())
262 return retVal;
263
264 CCECAdapterMessage *output = new CCECAdapterMessage(data);
265
266 /* set the number of retries */
267 if (data.opcode == CEC_OPCODE_NONE) //TODO
268 output->maxTries = 1;
269 else if (data.initiator != CECDEVICE_BROADCAST)
270 output->maxTries = iMaxTries;
271
272 output->lineTimeout = iLineTimeout;
273 output->retryTimeout = iRetryLineTimeout;
274 output->tries = 0;
275
276 if (data.destination < 15)
277 {
278 CLockObject lock(m_mutex);
279 m_bWaitingForAck[data.destination] = true;
280 }
281
282 bool bRetry(true);
283 while (bRetry && ++output->tries < output->maxTries)
284 {
285 bRetry = (!Write(output) || output->NeedsRetry()) && output->transmit_timeout > 0;
286 if (bRetry)
287 Sleep(CEC_DEFAULT_TRANSMIT_RETRY_WAIT);
288 }
289 retVal = output->state;
290
291 delete output;
292 return retVal;
293 }
294
295 bool CUSBCECAdapterCommunication::Write(CCECAdapterMessage *data)
296 {
297 data->state = ADAPTER_MESSAGE_STATE_WAITING_TO_BE_SENT;
298 SendMessageToAdapter(data);
299
300 if ((data->expectControllerAck && data->state != ADAPTER_MESSAGE_STATE_SENT_ACKED) ||
301 (!data->expectControllerAck && data->state != ADAPTER_MESSAGE_STATE_SENT))
302 {
303 CLibCEC::AddLog(CEC_LOG_DEBUG, "command was not %s", data->state == ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED ? "acked" : "sent");
304 return false;
305 }
306
307 return true;
308 }
309
310 bool CUSBCECAdapterCommunication::Read(cec_command &command, uint32_t iTimeout)
311 {
312 if (!IsRunning())
313 return false;
314
315 CCECAdapterMessage msg;
316 if (Read(msg, iTimeout))
317 {
318 if (ParseMessage(msg))
319 {
320 command = m_currentframe;
321 m_currentframe.Clear();
322 return true;
323 }
324 }
325 return false;
326 }
327
328 bool CUSBCECAdapterCommunication::Read(CCECAdapterMessage &msg, uint32_t iTimeout, size_t iLen)
329 {
330 CLockObject lock(m_mutex);
331 ReadFromDevice(iTimeout, iLen);
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 CCECAdapterMessage msg;
782 if (!Read(msg, 50))
783 {
784 iNow = GetTimeMs();
785 continue;
786 }
787
788 if (msg.Message() == MSGCODE_FRAME_START && msg.IsACK())
789 {
790 if (msg.Initiator() < 15 && m_bWaitingForAck[msg.Initiator()])
791 m_bWaitingForAck[msg.Initiator()] = false;
792 else if (msg.Initiator() < 15)
793 {
794 m_processor->HandlePoll(msg.Initiator(), msg.Destination());
795 m_lastDestination = msg.Initiator();
796 }
797 iNow = GetTimeMs();
798 continue;
799 }
800
801 if (msg.Message() == MSGCODE_RECEIVE_FAILED &&
802 m_lastDestination != CECDEVICE_UNKNOWN &&
803 m_processor->HandleReceiveFailed(m_lastDestination))
804 {
805 iNow = GetTimeMs();
806 continue;
807 }
808
809 bError = msg.IsError();
810 if (bError)
811 {
812 message.reply = msg.Message();
813 CLibCEC::AddLog(CEC_LOG_DEBUG, msg.ToString());
814 }
815 else
816 {
817 switch(msg.Message())
818 {
819 case MSGCODE_COMMAND_ACCEPTED:
820 if (iPacketsLeft > 0)
821 iPacketsLeft--;
822 if (!message.isTransmission && iPacketsLeft == 0)
823 bTransmitSucceeded = true;
824 CLibCEC::AddLog(CEC_LOG_DEBUG, "%s - waiting for %d more", msg.ToString().c_str(), iPacketsLeft);
825 break;
826 case MSGCODE_TRANSMIT_SUCCEEDED:
827 CLibCEC::AddLog(CEC_LOG_DEBUG, msg.ToString());
828 bTransmitSucceeded = (iPacketsLeft == 0);
829 bError = !bTransmitSucceeded;
830 message.reply = MSGCODE_TRANSMIT_SUCCEEDED;
831 break;
832 default:
833 // ignore other data while waiting
834 break;
835 }
836
837 iNow = GetTimeMs();
838 }
839 }
840
841 message.state = bTransmitSucceeded && !bError ?
842 ADAPTER_MESSAGE_STATE_SENT_ACKED :
843 ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED;
844
845 return bTransmitSucceeded && !bError;
846 }
847
848 void CUSBCECAdapterCommunication::AddData(uint8_t *data, size_t iLen)
849 {
850 CLockObject lock(m_mutex);
851 for (size_t iPtr = 0; iPtr < iLen; iPtr++)
852 {
853 if (!m_bGotStart)
854 {
855 if (data[iPtr] == MSGSTART)
856 m_bGotStart = true;
857 }
858 else if (data[iPtr] == MSGSTART) //we found a msgstart before msgend, this is not right, remove
859 {
860 if (m_currentAdapterMessage.Size() > 0)
861 CLibCEC::AddLog(CEC_LOG_WARNING, "received MSGSTART before MSGEND, removing previous buffer contents");
862 m_currentAdapterMessage.Clear();
863 m_bGotStart = true;
864 }
865 else if (data[iPtr] == MSGEND)
866 {
867 CCECAdapterMessage *newMessage = new CCECAdapterMessage;
868 newMessage->packet = m_currentAdapterMessage.packet;
869 m_inBuffer.Push(newMessage);
870 m_currentAdapterMessage.Clear();
871 m_bGotStart = false;
872 m_bNextIsEscaped = false;
873 m_bHasData = true;
874 m_rcvCondition.Broadcast();
875 }
876 else if (m_bNextIsEscaped)
877 {
878 m_currentAdapterMessage.PushBack(data[iPtr] + (uint8_t)ESCOFFSET);
879 m_bNextIsEscaped = false;
880 }
881 else if (data[iPtr] == MSGESC)
882 {
883 m_bNextIsEscaped = true;
884 }
885 else
886 {
887 m_currentAdapterMessage.PushBack(data[iPtr]);
888 }
889 }
890 }
891
892 bool CUSBCECAdapterCommunication::ReadFromDevice(uint32_t iTimeout, size_t iSize /* = 256 */)
893 {
894 ssize_t iBytesRead;
895 uint8_t buff[256];
896 if (!m_port)
897 return false;
898 if (iSize > 256)
899 iSize = 256;
900
901 CLockObject lock(m_mutex);
902 iBytesRead = m_port->Read(buff, sizeof(uint8_t) * iSize, iTimeout);
903 if (iBytesRead < 0 || iBytesRead > 256)
904 {
905 CLibCEC::AddLog(CEC_LOG_ERROR, "error reading from serial port: %s", m_port->GetError().c_str());
906 StopThread(false);
907 return false;
908 }
909 else if (iBytesRead > 0)
910 {
911 AddData(buff, iBytesRead);
912 }
913
914 return iBytesRead > 0;
915 }
916
917 void CUSBCECAdapterCommunication::SendMessageToAdapter(CCECAdapterMessage *msg)
918 {
919 CLockObject adapterLock(m_mutex);
920 if (!m_port->IsOpen())
921 {
922 CLibCEC::AddLog(CEC_LOG_ERROR, "error writing to serial port: the connection is closed");
923 msg->state = ADAPTER_MESSAGE_STATE_ERROR;
924 return;
925 }
926
927 if (msg->isTransmission && (msg->Size() < 2 || msg->At(1) != MSGCODE_TRANSMIT_IDLETIME))
928 {
929 if (msg->tries == 1)
930 SetLineTimeout(msg->lineTimeout);
931 else
932 SetLineTimeout(msg->retryTimeout);
933 }
934
935 if (m_port->Write(msg->packet.data, msg->Size()) != (ssize_t) msg->Size())
936 {
937 CLibCEC::AddLog(CEC_LOG_ERROR, "error writing to serial port: %s", m_port->GetError().c_str());
938 msg->state = ADAPTER_MESSAGE_STATE_ERROR;
939 }
940 else
941 {
942 CLibCEC::AddLog(CEC_LOG_DEBUG, "command sent");
943 msg->state = ADAPTER_MESSAGE_STATE_SENT;
944
945 if (msg->expectControllerAck)
946 {
947 if (!WaitForAck(*msg))
948 CLibCEC::AddLog(CEC_LOG_DEBUG, "did not receive ack");
949 }
950 }
951 }
952
953 CStdString CUSBCECAdapterCommunication::GetPortName(void)
954 {
955 CStdString strName;
956 strName = m_port->GetName();
957 return strName;
958 }
959
960 bool CUSBCECAdapterCommunication::SendCommand(cec_adapter_messagecode msgCode, CCECAdapterMessage &params, bool bExpectAck /* = true */, bool bIsTransmission /* = false */, bool bSendDirectly /* = true */, bool bIsRetry /* = false */)
961 {
962 CLockObject lock(m_mutex);
963
964 CCECAdapterMessage *output = new CCECAdapterMessage;
965
966 output->PushBack(MSGSTART);
967 output->PushEscaped((uint8_t)msgCode);
968 output->Append(params);
969 output->PushBack(MSGEND);
970 output->isTransmission = bIsTransmission;
971 output->expectControllerAck = bExpectAck;
972
973 if (bSendDirectly)
974 SendMessageToAdapter(output);
975 else
976 Write(output);
977
978 bool bWriteOk = output->state == (output->expectControllerAck ? ADAPTER_MESSAGE_STATE_SENT_ACKED : ADAPTER_MESSAGE_STATE_SENT);
979 cec_adapter_messagecode reply = output->reply;
980 delete output;
981
982 if (!bWriteOk)
983 {
984 CLibCEC::AddLog(CEC_LOG_ERROR, "'%s' failed", CCECAdapterMessage::ToString(msgCode));
985
986 if (!bIsRetry && reply == MSGCODE_COMMAND_REJECTED && msgCode != MSGCODE_SET_CONTROLLED)
987 {
988 CLibCEC::AddLog(CEC_LOG_DEBUG, "setting controlled mode and retrying");
989 if (SetControlledMode(true))
990 return SendCommand(msgCode, params, bExpectAck, bIsTransmission, bSendDirectly, true);
991 }
992 return false;
993 }
994
995 return true;
996 }
997
998 cec_datapacket CUSBCECAdapterCommunication::GetSetting(cec_adapter_messagecode msgCode, uint8_t iResponseLength)
999 {
1000 cec_datapacket retVal;
1001 retVal.Clear();
1002
1003 CCECAdapterMessage params;
1004 if (!SendCommand(msgCode, params, false))
1005 {
1006 CLibCEC::AddLog(CEC_LOG_ERROR, "%s failed", CCECAdapterMessage::ToString(msgCode));
1007 return retVal;
1008 }
1009
1010 CCECAdapterMessage input;
1011 if (Read(input, CEC_DEFAULT_TRANSMIT_WAIT, iResponseLength + 3 /* start + msgcode + iResponseLength + end */))
1012 {
1013 if (input.Message() != msgCode)
1014 CLibCEC::AddLog(CEC_LOG_ERROR, "invalid response to %s received (%s)", CCECAdapterMessage::ToString(msgCode), CCECAdapterMessage::ToString(input.Message()));
1015 else
1016 {
1017 for (uint8_t iPtr = 1; iPtr < input.Size(); iPtr++)
1018 retVal.PushBack(input[iPtr]);
1019 }
1020 }
1021 else
1022 {
1023 CLibCEC::AddLog(CEC_LOG_ERROR, "no response to %s received", CCECAdapterMessage::ToString(msgCode));
1024 }
1025
1026 return retVal;
1027 }
1028
1029 void *CAdapterPingThread::Process(void)
1030 {
1031 while (!IsStopped())
1032 {
1033 if (m_timeout.TimeLeft() == 0)
1034 {
1035 m_timeout.Init(CEC_ADAPTER_PING_TIMEOUT);
1036 m_com->PingAdapter();
1037 }
1038
1039 Sleep(500);
1040 }
1041 return NULL;
1042 }