cec: moved WaitForTransmitSucceeded() to CAdapterCommunication
[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
39 using namespace std;
40 using namespace CEC;
41 using namespace PLATFORM;
42
43 CAdapterCommunication::CAdapterCommunication(CCECProcessor *processor) :
44 m_port(NULL),
45 m_processor(processor),
46 m_iLineTimeout(0)
47 {
48 m_port = new PLATFORM::CSerialPort;
49 }
50
51 CAdapterCommunication::~CAdapterCommunication(void)
52 {
53 Close();
54
55 if (m_port)
56 {
57 delete m_port;
58 m_port = NULL;
59 }
60 }
61
62 bool CAdapterCommunication::Open(const char *strPort, uint16_t iBaudRate /* = 38400 */, uint32_t iTimeoutMs /* = 10000 */)
63 {
64 uint64_t iNow = GetTimeMs();
65 uint64_t iTimeout = iNow + iTimeoutMs;
66
67 CLockObject lock(m_mutex);
68
69 if (!m_port)
70 {
71 m_processor->AddLog(CEC_LOG_ERROR, "port is NULL");
72 return false;
73 }
74
75 if (IsOpen())
76 {
77 m_processor->AddLog(CEC_LOG_ERROR, "port is already open");
78 return true;
79 }
80
81 CStdString strError;
82 bool bConnected(false);
83 while (!bConnected && iNow < iTimeout)
84 {
85 if ((bConnected = m_port->Open(strPort, iBaudRate)) == false)
86 {
87 strError.Format("error opening serial port '%s': %s", strPort, m_port->GetError().c_str());
88 Sleep(250);
89 iNow = GetTimeMs();
90 }
91 }
92
93 if (!bConnected)
94 {
95 m_processor->AddLog(CEC_LOG_ERROR, strError);
96 return false;
97 }
98
99 m_processor->AddLog(CEC_LOG_DEBUG, "connection opened");
100
101 //clear any input bytes
102 uint8_t buff[1];
103 while (m_port->Read(buff, 1, 5) == 1) {}
104
105 if (CreateThread())
106 {
107 m_processor->AddLog(CEC_LOG_DEBUG, "communication thread started");
108 return true;
109 }
110 else
111 {
112 m_processor->AddLog(CEC_LOG_ERROR, "could not create a communication thread");
113 }
114
115 return false;
116 }
117
118 void CAdapterCommunication::Close(void)
119 {
120 CLockObject lock(m_mutex);
121 m_rcvCondition.Broadcast();
122 StopThread();
123 }
124
125 void *CAdapterCommunication::Process(void)
126 {
127 while (!IsStopped())
128 {
129 ReadFromDevice(50);
130 Sleep(5);
131 WriteNextCommand();
132 }
133
134 CCECAdapterMessage *msg(NULL);
135 if (m_outBuffer.Pop(msg))
136 msg->condition.Broadcast();
137
138 return NULL;
139 }
140
141 bool CAdapterCommunication::Write(CCECAdapterMessage *data)
142 {
143 data->state = ADAPTER_MESSAGE_STATE_WAITING;
144 m_outBuffer.Push(data);
145 return true;
146 }
147
148 bool CAdapterCommunication::Read(CCECAdapterMessage &msg, uint32_t iTimeout)
149 {
150 CLockObject lock(m_mutex);
151
152 msg.Clear();
153 uint64_t iNow = GetTimeMs();
154 uint64_t iTarget = iNow + iTimeout;
155 bool bGotFullMessage(false);
156 bool bNextIsEscaped(false);
157 bool bGotStart(false);
158
159 while(!bGotFullMessage && iNow < iTarget)
160 {
161 uint8_t buf = 0;
162 if (!m_inBuffer.Pop(buf))
163 {
164 if (!m_rcvCondition.Wait(m_mutex, (uint32_t) (iTarget - iNow)))
165 return false;
166 }
167
168 if (!bGotStart)
169 {
170 if (buf == MSGSTART)
171 bGotStart = true;
172 continue;
173 }
174 else if (buf == MSGSTART) //we found a msgstart before msgend, this is not right, remove
175 {
176 if (msg.Size() > 0)
177 m_processor->AddLog(CEC_LOG_WARNING, "received MSGSTART before MSGEND, removing previous buffer contents");
178 msg.Clear();
179 bGotStart = true;
180 }
181
182 if (buf == MSGEND)
183 {
184 bGotFullMessage = true;
185 }
186 else if (bNextIsEscaped)
187 {
188 msg.PushBack(buf + (uint8_t)ESCOFFSET);
189 bNextIsEscaped = false;
190 }
191 else if (buf == MSGESC)
192 bNextIsEscaped = true;
193 else
194 msg.PushBack(buf);
195 }
196
197 if (bGotFullMessage)
198 msg.state = ADAPTER_MESSAGE_STATE_RECEIVED;
199
200 return bGotFullMessage;
201 }
202
203 std::string CAdapterCommunication::GetError(void) const
204 {
205 return m_port->GetError();
206 }
207
208 bool CAdapterCommunication::StartBootloader(void)
209 {
210 bool bReturn(false);
211 if (!IsRunning())
212 return bReturn;
213
214 m_processor->AddLog(CEC_LOG_DEBUG, "starting the bootloader");
215 CCECAdapterMessage *output = new CCECAdapterMessage;
216
217 output->PushBack(MSGSTART);
218 output->PushEscaped(MSGCODE_START_BOOTLOADER);
219 output->PushBack(MSGEND);
220
221 CLockObject lock(output->mutex);
222 if (Write(output))
223 output->condition.Wait(output->mutex);
224 bReturn = output->state == ADAPTER_MESSAGE_STATE_SENT;
225 delete output;
226
227 return bReturn;
228 }
229
230 bool CAdapterCommunication::PingAdapter(void)
231 {
232 bool bReturn(false);
233 if (!IsRunning())
234 return bReturn;
235
236 m_processor->AddLog(CEC_LOG_DEBUG, "sending ping");
237 CCECAdapterMessage *output = new CCECAdapterMessage;
238
239 output->PushBack(MSGSTART);
240 output->PushEscaped(MSGCODE_PING);
241 output->PushBack(MSGEND);
242
243 CLockObject lock(output->mutex);
244 if (Write(output))
245 output->condition.Wait(output->mutex);
246 bReturn = output->state == ADAPTER_MESSAGE_STATE_SENT;
247 delete output;
248
249 return bReturn;
250 }
251
252 bool CAdapterCommunication::SetLineTimeout(uint8_t iTimeout)
253 {
254 bool bReturn(m_iLineTimeout != iTimeout);
255
256 if (!bReturn)
257 {
258 CCECAdapterMessage *output = new CCECAdapterMessage;
259
260 output->PushBack(MSGSTART);
261 output->PushEscaped(MSGCODE_TRANSMIT_IDLETIME);
262 output->PushEscaped(iTimeout);
263 output->PushBack(MSGEND);
264
265 if ((bReturn = Write(output)) == false)
266 m_processor->AddLog(CEC_LOG_ERROR, "could not set the idletime");
267 delete output;
268 }
269
270 return bReturn;
271 }
272
273 bool CAdapterCommunication::IsOpen(void)
274 {
275 return !IsStopped() && m_port->IsOpen() && IsRunning();
276 }
277
278 bool CAdapterCommunication::WaitForTransmitSucceeded(CCECAdapterMessage *message)
279 {
280 bool bError(false);
281 bool bTransmitSucceeded(false);
282 uint8_t iPacketsLeft(message->Size() / 4);
283
284 int64_t iNow = GetTimeMs();
285 int64_t iTargetTime = iNow + message->transmit_timeout;
286
287 while (!bTransmitSucceeded && !bError && (message->transmit_timeout == 0 || iNow < iTargetTime))
288 {
289 CCECAdapterMessage msg;
290
291 if (!Read(msg, message->transmit_timeout > 0 ? (int32_t)(iTargetTime - iNow) : 1000))
292 {
293 iNow = GetTimeMs();
294 continue;
295 }
296
297 if (msg.Message() == MSGCODE_FRAME_START && msg.IsACK())
298 {
299 m_processor->HandlePoll(msg.Initiator(), msg.Destination());
300 iNow = GetTimeMs();
301 continue;
302 }
303
304 if (msg.Message() == MSGCODE_RECEIVE_FAILED &&
305 m_processor->HandleReceiveFailed())
306 {
307 iNow = GetTimeMs();
308 continue;
309 }
310
311 bError = msg.IsError();
312 if (bError)
313 {
314 message->reply = msg.Message();
315 m_processor->AddLog(CEC_LOG_DEBUG, msg.ToString());
316 }
317 else
318 {
319 switch(msg.Message())
320 {
321 case MSGCODE_COMMAND_ACCEPTED:
322 m_processor->AddLog(CEC_LOG_DEBUG, msg.ToString());
323 if (iPacketsLeft > 0)
324 iPacketsLeft--;
325 break;
326 case MSGCODE_TRANSMIT_SUCCEEDED:
327 m_processor->AddLog(CEC_LOG_DEBUG, msg.ToString());
328 bTransmitSucceeded = (iPacketsLeft == 0);
329 bError = !bTransmitSucceeded;
330 message->reply = MSGCODE_TRANSMIT_SUCCEEDED;
331 break;
332 default:
333 // ignore other data while waiting
334 break;
335 }
336
337 iNow = GetTimeMs();
338 }
339 }
340
341 return bTransmitSucceeded && !bError;
342 }
343
344 void CAdapterCommunication::AddData(uint8_t *data, uint8_t iLen)
345 {
346 CLockObject lock(m_mutex);
347 for (uint8_t iPtr = 0; iPtr < iLen; iPtr++)
348 m_inBuffer.Push(data[iPtr]);
349
350 m_rcvCondition.Signal();
351 }
352
353 bool CAdapterCommunication::ReadFromDevice(uint32_t iTimeout)
354 {
355 int32_t iBytesRead;
356 uint8_t buff[1024];
357 if (!m_port)
358 return false;
359
360 iBytesRead = m_port->Read(buff, sizeof(buff), iTimeout);
361 if (iBytesRead < 0 || iBytesRead > 256)
362 {
363 CStdString strError;
364 strError.Format("error reading from serial port: %s", m_port->GetError().c_str());
365 m_processor->AddLog(CEC_LOG_ERROR, strError);
366 return false;
367 }
368 else if (iBytesRead > 0)
369 AddData(buff, (uint8_t) iBytesRead);
370
371 return iBytesRead > 0;
372 }
373
374 void CAdapterCommunication::SendMessageToAdapter(CCECAdapterMessage *msg)
375 {
376 CLockObject lock(msg->mutex);
377 if (m_port->Write(msg->packet.data, msg->Size()) != (int32_t) msg->Size())
378 {
379 CStdString strError;
380 strError.Format("error writing to serial port: %s", m_port->GetError().c_str());
381 m_processor->AddLog(CEC_LOG_ERROR, strError);
382 msg->state = ADAPTER_MESSAGE_STATE_ERROR;
383 }
384 else
385 {
386 m_processor->AddLog(CEC_LOG_DEBUG, "command sent");
387 msg->state = ADAPTER_MESSAGE_STATE_SENT;
388 }
389 msg->condition.Signal();
390 }
391
392 void CAdapterCommunication::WriteNextCommand(void)
393 {
394 CCECAdapterMessage *msg(NULL);
395 if (m_outBuffer.Pop(msg))
396 SendMessageToAdapter(msg);
397 }