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