cec: retry to get the firmware version when it failed. wait for active tranmission...
[deb_libcec.git] / src / lib / adapter / AdapterCommunication.cpp
1 /*
2 * This file is part of the libCEC(R) library.
3 *
4 * libCEC(R) is Copyright (C) 2011 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 "AdapterCommunication.h"
34
35 #include "AdapterMessage.h"
36 #include "../CECProcessor.h"
37 #include "../platform/serialport/serialport.h"
38 #include "../LibCEC.h"
39
40 using namespace std;
41 using namespace CEC;
42 using namespace PLATFORM;
43
44 CAdapterCommunication::CAdapterCommunication(CCECProcessor *processor) :
45 m_port(NULL),
46 m_processor(processor),
47 m_iLineTimeout(0),
48 m_iFirmwareVersion(CEC_FW_VERSION_UNKNOWN)
49 {
50 m_port = new PLATFORM::CSerialPort;
51 }
52
53 CAdapterCommunication::~CAdapterCommunication(void)
54 {
55 Close();
56
57 if (m_port)
58 {
59 delete m_port;
60 m_port = NULL;
61 }
62 }
63
64 bool CAdapterCommunication::Open(const char *strPort, uint16_t iBaudRate /* = 38400 */, uint32_t iTimeoutMs /* = 10000 */)
65 {
66 uint64_t iNow = GetTimeMs();
67 uint64_t iTimeout = iNow + iTimeoutMs;
68
69 CLockObject lock(m_mutex);
70
71 if (!m_port)
72 {
73 CLibCEC::AddLog(CEC_LOG_ERROR, "port is NULL");
74 return false;
75 }
76
77 if (IsOpen())
78 {
79 CLibCEC::AddLog(CEC_LOG_ERROR, "port is already open");
80 return true;
81 }
82
83 CStdString strError;
84 bool bConnected(false);
85 while (!bConnected && iNow < iTimeout)
86 {
87 if ((bConnected = m_port->Open(strPort, iBaudRate)) == false)
88 {
89 strError.Format("error opening serial port '%s': %s", strPort, m_port->GetError().c_str());
90 Sleep(250);
91 iNow = GetTimeMs();
92 }
93 }
94
95 if (!bConnected)
96 {
97 CLibCEC::AddLog(CEC_LOG_ERROR, strError);
98 return false;
99 }
100
101 CLibCEC::AddLog(CEC_LOG_DEBUG, "connection opened, clearing any previous input and waiting for active transmissions to end before starting");
102
103 //clear any input bytes
104 uint8_t buff[1024];
105 while (m_port->Read(buff, 1024, 100) > 0)
106 {
107 CLibCEC::AddLog(CEC_LOG_DEBUG, "data received, clearing it");
108 Sleep(250);
109 }
110
111 if (CreateThread())
112 {
113 CLibCEC::AddLog(CEC_LOG_DEBUG, "communication thread started");
114 return true;
115 }
116 else
117 {
118 CLibCEC::AddLog(CEC_LOG_ERROR, "could not create a communication thread");
119 }
120
121 return false;
122 }
123
124 void CAdapterCommunication::Close(void)
125 {
126 CLockObject lock(m_mutex);
127 m_rcvCondition.Broadcast();
128 StopThread();
129 }
130
131 void *CAdapterCommunication::Process(void)
132 {
133 while (!IsStopped())
134 {
135 ReadFromDevice(50);
136 Sleep(5);
137 WriteNextCommand();
138 }
139
140 CCECAdapterMessage *msg(NULL);
141 if (m_outBuffer.Pop(msg))
142 msg->condition.Broadcast();
143
144 return NULL;
145 }
146
147 bool CAdapterCommunication::Write(CCECAdapterMessage *data)
148 {
149 bool bReturn(false);
150
151 CLockObject lock(data->mutex);
152 data->state = ADAPTER_MESSAGE_STATE_WAITING_TO_BE_SENT;
153 m_outBuffer.Push(data);
154 data->condition.Wait(data->mutex);
155
156 if (data->state != ADAPTER_MESSAGE_STATE_SENT)
157 {
158 CLibCEC::AddLog(CEC_LOG_ERROR, "command was not sent");
159 }
160 else if (data->expectControllerAck)
161 {
162 bReturn = WaitForAck(*data);
163 if (bReturn)
164 {
165 if (data->isTransmission)
166 data->state = ADAPTER_MESSAGE_STATE_SENT_ACKED;
167 }
168 else
169 {
170 data->state = ADAPTER_MESSAGE_STATE_SENT_NOT_ACKED;
171 CLibCEC::AddLog(CEC_LOG_DEBUG, "did not receive ack");
172 }
173 }
174 else
175 {
176 bReturn = true;
177 }
178
179 return bReturn;
180 }
181
182 bool CAdapterCommunication::Read(CCECAdapterMessage &msg, uint32_t iTimeout)
183 {
184 CLockObject lock(m_mutex);
185
186 msg.Clear();
187 uint64_t iNow = GetTimeMs();
188 uint64_t iTarget = iNow + iTimeout;
189 bool bGotFullMessage(false);
190 bool bNextIsEscaped(false);
191 bool bGotStart(false);
192
193 while(!bGotFullMessage && iNow < iTarget)
194 {
195 uint8_t buf = 0;
196 if (!m_inBuffer.Pop(buf))
197 {
198 if (!m_rcvCondition.Wait(m_mutex, (uint32_t) (iTarget - iNow)))
199 return false;
200 }
201
202 if (!bGotStart)
203 {
204 if (buf == MSGSTART)
205 bGotStart = true;
206 continue;
207 }
208 else if (buf == MSGSTART) //we found a msgstart before msgend, this is not right, remove
209 {
210 if (msg.Size() > 0)
211 CLibCEC::AddLog(CEC_LOG_WARNING, "received MSGSTART before MSGEND, removing previous buffer contents");
212 msg.Clear();
213 bGotStart = true;
214 }
215
216 if (buf == MSGEND)
217 {
218 bGotFullMessage = true;
219 }
220 else if (bNextIsEscaped)
221 {
222 msg.PushBack(buf + (uint8_t)ESCOFFSET);
223 bNextIsEscaped = false;
224 }
225 else if (buf == MSGESC)
226 bNextIsEscaped = true;
227 else
228 msg.PushBack(buf);
229 }
230
231 if (bGotFullMessage)
232 msg.state = ADAPTER_MESSAGE_STATE_INCOMING;
233
234 return bGotFullMessage;
235 }
236
237 std::string CAdapterCommunication::GetError(void) const
238 {
239 return m_port->GetError();
240 }
241
242 bool CAdapterCommunication::StartBootloader(void)
243 {
244 bool bReturn(false);
245 if (!IsRunning())
246 return bReturn;
247
248 CLibCEC::AddLog(CEC_LOG_DEBUG, "starting the bootloader");
249 CCECAdapterMessage *output = new CCECAdapterMessage;
250
251 output->PushBack(MSGSTART);
252 output->PushEscaped(MSGCODE_START_BOOTLOADER);
253 output->PushBack(MSGEND);
254 output->isTransmission = false;
255 output->expectControllerAck = false;
256
257 if ((bReturn = Write(output)) == false)
258 CLibCEC::AddLog(CEC_LOG_ERROR, "could not start the bootloader");
259 delete output;
260
261 return bReturn;
262 }
263
264 bool CAdapterCommunication::PingAdapter(void)
265 {
266 bool bReturn(false);
267 if (!IsRunning())
268 return bReturn;
269
270 CLibCEC::AddLog(CEC_LOG_DEBUG, "sending ping");
271 CCECAdapterMessage *output = new CCECAdapterMessage;
272
273 output->PushBack(MSGSTART);
274 output->PushEscaped(MSGCODE_PING);
275 output->PushBack(MSGEND);
276 output->isTransmission = false;
277
278 if ((bReturn = Write(output)) == false)
279 CLibCEC::AddLog(CEC_LOG_ERROR, "could not ping the adapter");
280 delete output;
281
282 return bReturn;
283 }
284
285 uint16_t CAdapterCommunication::GetFirmwareVersion(void)
286 {
287 uint16_t iReturn(m_iFirmwareVersion);
288 if (!IsRunning())
289 return iReturn;
290
291 if (iReturn == CEC_FW_VERSION_UNKNOWN)
292 {
293 CLibCEC::AddLog(CEC_LOG_DEBUG, "requesting the firmware version");
294 CCECAdapterMessage *output = new CCECAdapterMessage;
295
296 output->PushBack(MSGSTART);
297 output->PushEscaped(MSGCODE_FIRMWARE_VERSION);
298 output->PushBack(MSGEND);
299 output->isTransmission = false;
300 output->expectControllerAck = false;
301
302 SendMessageToAdapter(output);
303 delete output;
304
305 CCECAdapterMessage input;
306 if (!Read(input, CEC_DEFAULT_TRANSMIT_WAIT) || input.Message() != MSGCODE_FIRMWARE_VERSION || input.Size() != 3)
307 CLibCEC::AddLog(CEC_LOG_ERROR, "no or invalid firmware version (size = %d, message = %d)", input.Size(), input.Message());
308 else
309 {
310 m_iFirmwareVersion = (input[1] << 8 | input[2]);
311 iReturn = m_iFirmwareVersion;
312 }
313 }
314
315 return iReturn;
316 }
317
318 bool CAdapterCommunication::SetLineTimeout(uint8_t iTimeout)
319 {
320 bool bReturn(m_iLineTimeout != iTimeout);
321
322 if (!bReturn)
323 {
324 CCECAdapterMessage *output = new CCECAdapterMessage;
325
326 output->PushBack(MSGSTART);
327 output->PushEscaped(MSGCODE_TRANSMIT_IDLETIME);
328 output->PushEscaped(iTimeout);
329 output->PushBack(MSGEND);
330 output->isTransmission = false;
331
332 if ((bReturn = Write(output)) == false)
333 CLibCEC::AddLog(CEC_LOG_ERROR, "could not set the idletime");
334 delete output;
335 }
336
337 return bReturn;
338 }
339
340 bool CAdapterCommunication::SetAckMask(uint16_t iMask)
341 {
342 bool bReturn(false);
343 CStdString strLog;
344 strLog.Format("setting ackmask to %2x", iMask);
345 CLibCEC::AddLog(CEC_LOG_DEBUG, strLog.c_str());
346
347 CCECAdapterMessage *output = new CCECAdapterMessage;
348
349 output->PushBack(MSGSTART);
350 output->PushEscaped(MSGCODE_SET_ACK_MASK);
351 output->PushEscaped(iMask >> 8);
352 output->PushEscaped((uint8_t)iMask);
353 output->PushBack(MSGEND);
354 output->isTransmission = false;
355
356 if ((bReturn = Write(output)) == false)
357 CLibCEC::AddLog(CEC_LOG_ERROR, "could not set the ackmask");
358 delete output;
359
360 return bReturn;
361 }
362
363 bool CAdapterCommunication::IsOpen(void)
364 {
365 return !IsStopped() && m_port->IsOpen() && IsRunning();
366 }
367
368 bool CAdapterCommunication::WaitForAck(CCECAdapterMessage &message)
369 {
370 bool bError(false);
371 bool bTransmitSucceeded(false);
372 uint8_t iPacketsLeft(message.Size() / 4);
373
374 int64_t iNow = GetTimeMs();
375 int64_t iTargetTime = iNow + message.transmit_timeout;
376
377 while (!bTransmitSucceeded && !bError && (message.transmit_timeout == 0 || iNow < iTargetTime))
378 {
379 CCECAdapterMessage msg;
380 int32_t iWait = (int32_t)(iTargetTime - iNow);
381 if (iWait <= 5 || message.transmit_timeout <= 5)
382 iWait = CEC_DEFAULT_TRANSMIT_WAIT;
383
384 if (!Read(msg, iWait))
385 {
386 iNow = GetTimeMs();
387 continue;
388 }
389
390 if (msg.Message() == MSGCODE_FRAME_START && msg.IsACK())
391 {
392 m_processor->HandlePoll(msg.Initiator(), msg.Destination());
393 iNow = GetTimeMs();
394 continue;
395 }
396
397 if (msg.Message() == MSGCODE_RECEIVE_FAILED &&
398 m_processor->HandleReceiveFailed())
399 {
400 iNow = GetTimeMs();
401 continue;
402 }
403
404 bError = msg.IsError();
405 if (bError)
406 {
407 message.reply = msg.Message();
408 CLibCEC::AddLog(CEC_LOG_DEBUG, msg.ToString());
409 }
410 else
411 {
412 switch(msg.Message())
413 {
414 case MSGCODE_COMMAND_ACCEPTED:
415 CLibCEC::AddLog(CEC_LOG_DEBUG, msg.ToString());
416 if (iPacketsLeft > 0)
417 iPacketsLeft--;
418 if (!message.isTransmission && iPacketsLeft == 0)
419 bTransmitSucceeded = true;
420 break;
421 case MSGCODE_TRANSMIT_SUCCEEDED:
422 CLibCEC::AddLog(CEC_LOG_DEBUG, msg.ToString());
423 bTransmitSucceeded = (iPacketsLeft == 0);
424 bError = !bTransmitSucceeded;
425 message.reply = MSGCODE_TRANSMIT_SUCCEEDED;
426 break;
427 default:
428 // ignore other data while waiting
429 break;
430 }
431
432 iNow = GetTimeMs();
433 }
434 }
435
436 return bTransmitSucceeded && !bError;
437 }
438
439 void CAdapterCommunication::AddData(uint8_t *data, uint8_t iLen)
440 {
441 CLockObject lock(m_mutex);
442 for (uint8_t iPtr = 0; iPtr < iLen; iPtr++)
443 m_inBuffer.Push(data[iPtr]);
444
445 m_rcvCondition.Signal();
446 }
447
448 bool CAdapterCommunication::ReadFromDevice(uint32_t iTimeout)
449 {
450 int32_t iBytesRead;
451 uint8_t buff[1024];
452 if (!m_port)
453 return false;
454
455 CLockObject lock(m_mutex);
456 iBytesRead = m_port->Read(buff, sizeof(buff), iTimeout);
457 if (iBytesRead < 0 || iBytesRead > 256)
458 {
459 CStdString strError;
460 strError.Format("error reading from serial port: %s", m_port->GetError().c_str());
461 CLibCEC::AddLog(CEC_LOG_ERROR, strError);
462 return false;
463 }
464 else if (iBytesRead > 0)
465 AddData(buff, (uint8_t) iBytesRead);
466
467 return iBytesRead > 0;
468 }
469
470 void CAdapterCommunication::SendMessageToAdapter(CCECAdapterMessage *msg)
471 {
472 CLockObject adapterLock(m_mutex);
473 CLockObject lock(msg->mutex);
474 if (m_port->Write(msg->packet.data, msg->Size()) != (int32_t) msg->Size())
475 {
476 CStdString strError;
477 strError.Format("error writing to serial port: %s", m_port->GetError().c_str());
478 CLibCEC::AddLog(CEC_LOG_ERROR, strError);
479 msg->state = ADAPTER_MESSAGE_STATE_ERROR;
480 }
481 else
482 {
483 CLibCEC::AddLog(CEC_LOG_DEBUG, "command sent");
484 msg->state = ADAPTER_MESSAGE_STATE_SENT;
485 }
486 msg->condition.Signal();
487 }
488
489 void CAdapterCommunication::WriteNextCommand(void)
490 {
491 CCECAdapterMessage *msg(NULL);
492 if (m_outBuffer.Pop(msg))
493 SendMessageToAdapter(msg);
494 }