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