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