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