summaryrefslogtreecommitdiff
path: root/peripheral/libupm/src/grovescam/grovescam.cxx
blob: 1a78a3a4fab94118ed911b250eee5481949131f5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
/*
 * Author: Jon Trulson <jtrulson@ics.com>
 * Copyright (c) 2015 Intel Corporation.
 *
 * Thanks to Seeed Studio for a working arduino sketch
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include <iostream>
#include <string>
#include <stdexcept>
#include <errno.h>

#include "grovescam.hpp"

using namespace upm;
using namespace std;

static const int maxRetries = 100;

GROVESCAM::GROVESCAM(int uart, uint8_t camAddr)
{
  m_ttyFd = -1;

  // save our shifted camera address, we'll need it a lot
  m_camAddr = (camAddr << 5);

  m_picTotalLen = 0;

  if ( !(m_uart = mraa_uart_init(uart)) )
    {
      throw std::invalid_argument(std::string(__FUNCTION__) +
                                  ": mraa_uart_init() failed");
      return;
    }

  // This requires a recent MRAA (1/2015)
  const char *devPath = mraa_uart_get_dev_path(m_uart);

  if (!devPath)
    {
      throw std::runtime_error(std::string(__FUNCTION__) +
                               ": mraa_uart_get_dev_path() failed");
      return;
    }

  // now open the tty
  if ( (m_ttyFd = open(devPath, O_RDWR)) == -1)
    {
      throw std::runtime_error(std::string(__FUNCTION__) +
                               ": open of " +
                               string(devPath) + " failed:" +
                               string(strerror(errno)));
      return;
    }
}

GROVESCAM::~GROVESCAM()
{
  if (m_ttyFd != -1)
    close(m_ttyFd);
}

bool GROVESCAM::dataAvailable(unsigned int millis)
{
  if (m_ttyFd == -1)
    return false;

  struct timeval timeout;

  if (millis == 0)
    {
      // no waiting
      timeout.tv_sec = 0;
      timeout.tv_usec = 0;
    }
  else
    {
      timeout.tv_sec = millis / 1000;
      timeout.tv_usec = (millis % 1000) * 1000;
    }

  int nfds;
  fd_set readfds;

  FD_ZERO(&readfds);

  FD_SET(m_ttyFd, &readfds);

  if (select(m_ttyFd + 1, &readfds, NULL, NULL, &timeout) > 0)
    return true;                // data is ready
  else
    return false;
}

int GROVESCAM::readData(uint8_t *buffer, int len)
{
  if (m_ttyFd == -1)
    return(-1);

  int rv = read(m_ttyFd, (char *)buffer, len);

  if (rv < 0)
    {
      throw std::runtime_error(std::string(__FUNCTION__) +
                               ": read() failed: " +
                               string(strerror(errno)));
      return rv;
    }

  return rv;
}

int GROVESCAM::writeData(uint8_t *buffer, int len)
{
  if (m_ttyFd == -1)
    return(-1);

  // first, flush any pending but unread input

  tcflush(m_ttyFd, TCIFLUSH);

  int rv = write(m_ttyFd, (char *)buffer, len);

  if (rv < 0)
    {
      throw std::runtime_error(std::string(__FUNCTION__) +
                               ": write() failed: " +
                               string(strerror(errno)));
      return rv;
    }

  tcdrain(m_ttyFd);

  return rv;
}

bool GROVESCAM::setupTty(speed_t baud)
{
  if (m_ttyFd == -1)
    return(false);

  struct termios termio;

  // get current modes
  tcgetattr(m_ttyFd, &termio);

  // setup for a 'raw' mode.  81N, no echo or special character
  // handling, such as flow control.
  cfmakeraw(&termio);

  // set our baud rates
  cfsetispeed(&termio, baud);
  cfsetospeed(&termio, baud);

  // make it so
  if (tcsetattr(m_ttyFd, TCSAFLUSH, &termio) < 0)
    {
      throw std::runtime_error(std::string(__FUNCTION__) +
                               ": tcsetattr() failed: " +
                               string(strerror(errno)));
      return false;
    }

  return true;
}

void GROVESCAM::drainInput()
{
  uint8_t ch;

  while (dataAvailable(0))
    readData(&ch, 1);
}

bool GROVESCAM::init()
{
  const unsigned int pktLen = 6;
  uint8_t cmd[pktLen] = {0xaa, static_cast<uint8_t>(0x0d|m_camAddr), 0x00,
                         0x00, 0x00, 0x00};
  uint8_t resp[pktLen];
  int retries = 0;

  while (true)
    {
      if (retries++ > maxRetries)
        {
          throw std::runtime_error(std::string(__FUNCTION__) +
                                   ": maximum retries exceeded");
          return false;
        }

      writeData(cmd, pktLen);

      if (!dataAvailable(500))
        continue;

      if (readData(resp, pktLen) != pktLen)
        continue;

      if (resp[0] == 0xaa
          && resp[1] == (0x0e | m_camAddr)
          && resp[2] == 0x0d
          && resp[4] == 0
          && resp[5] == 0)
        {
          if (readData(resp, pktLen) != pktLen)
            continue;
          else
            {
              if (resp[0] == 0xaa
                  && resp[1] == (0x0d | m_camAddr)
                  && resp[2] == 0
                  && resp[3] == 0
                  && resp[4] == 0
                  && resp[5] == 0)
                break;
            }
        }
    }

  cmd[1] = 0x0e | m_camAddr;
  cmd[2] = 0x0d;
  writeData(cmd, pktLen);

  return true;
}

bool GROVESCAM::preCapture(PIC_FORMATS_T fmt)
{
  const unsigned int pktLen = 6;
  uint8_t cmd[pktLen] = { 0xaa, static_cast<uint8_t>(0x01 | m_camAddr), 0x00,
                          0x07, 0x00, static_cast<uint8_t>(fmt) };
  uint8_t resp[pktLen];
  int retries = 0;

  while (true)
    {
      if (retries++ > maxRetries)
        {
          throw std::runtime_error(std::string(__FUNCTION__) +
                                   ": maximum retries exceeded");
          return false;
        }

      drainInput();

      writeData(cmd, pktLen);

      if (!dataAvailable(100))
        continue;

      if (readData(resp, pktLen) != pktLen)
        continue;

      if (resp[0] == 0xaa
          && resp[1] == (0x0e | m_camAddr)
          && resp[2] == 0x01
          && resp[4] == 0
          && resp[5] == 0) break;
    }

  return true;
}

bool GROVESCAM::doCapture()
{
  const unsigned int pktLen = 6;
  uint8_t cmd[pktLen] = { 0xaa, static_cast<uint8_t>(0x06 | m_camAddr), 0x08,
                          static_cast<uint8_t>(MAX_PKT_LEN & 0xff),
                          static_cast<uint8_t>((MAX_PKT_LEN >> 8)) & 0xff, 0};
  uint8_t resp[pktLen];
  int retries = 0;

  m_picTotalLen = 0;

  while (true)
    {
      if (retries++ > maxRetries)
        {
          throw std::runtime_error(std::string(__FUNCTION__) +
                                   ": maximum retries exceeded");
          return false;
        }

      drainInput();
      writeData(cmd, pktLen);
      usleep(100000);

      if (!dataAvailable(100))
        continue;

      if (readData(resp, pktLen) != pktLen)
        continue;

      if (resp[0] == 0xaa
          && resp[1] == (0x0e | m_camAddr)
          && resp[2] == 0x06
          && resp[4] == 0
          && resp[5] == 0)
        break;
    }

  cmd[1] = 0x05 | m_camAddr;
  cmd[2] = 0;
  cmd[3] = 0;
  cmd[4] = 0;
  cmd[5] = 0;

  retries = 0;
  while (true)
    {
      if (retries++ > maxRetries)
        {
          throw std::runtime_error(std::string(__FUNCTION__) +
                                   ": maximum retries exceeded");
          return false;
        }

      drainInput();
      writeData(cmd, pktLen);
      if (readData(resp, pktLen) != pktLen)
        continue;

      if (resp[0] == 0xaa
          && resp[1] == (0x0e | m_camAddr)
          && resp[2] == 0x05
          && resp[4] == 0
          && resp[5] == 0)
        break;
    }

  cmd[1] = 0x04 | m_camAddr;
  cmd[2] = 0x01;

  retries = 0;
  while (true)
    {
      if (retries++ > maxRetries)
        {
          throw std::runtime_error(std::string(__FUNCTION__) +
                                   ": maximum retries exceeded");
          return false;
        }

      drainInput();
      writeData(cmd, 6);

      if (readData(resp, pktLen) != pktLen)
        continue;

      if (resp[0] == 0xaa
          && resp[1] == (0x0e | m_camAddr)
          && resp[2] == 0x04
          && resp[4] == 0
          && resp[5] == 0)
        {
          if (!dataAvailable(1000))
            continue;

          if (readData(resp, pktLen) != pktLen)
            continue;

          if (resp[0] == 0xaa
              && resp[1] == (0x0a | m_camAddr)
              && resp[2] == 0x01)
            {
              m_picTotalLen = (resp[3]) | (resp[4] << 8) | (resp[5] << 16);
              break;
            }
        }
    }

  return true;
}

bool GROVESCAM::storeImage(const char *fname)
{
  if (!fname)
    {
      throw std::invalid_argument(std::string(__FUNCTION__) +
                                  ": filename is NULL");
      return false;
    }

  if (!m_picTotalLen)
    {
      throw std::runtime_error(std::string(__FUNCTION__) +
                    ": Picture length is zero, you need to capture first.");

      return false;
    }

  FILE *file = fopen(fname, "wb");

  if (!file)
    {
      throw std::runtime_error(std::string(__FUNCTION__) +
                               ": fopen() failed: " +
                               string(strerror(errno)));
      return false;
    }

  /// let the games begin...
  const unsigned int pktLen = 6;
  unsigned int pktCnt = (m_picTotalLen) / (MAX_PKT_LEN - 6);
  if ((m_picTotalLen % (MAX_PKT_LEN-6)) != 0)
    pktCnt += 1;

  uint8_t cmd[pktLen] = { 0xaa, static_cast<uint8_t>(0x0e | m_camAddr), 0x00,
                          0x00, 0x00, 0x00 };
  uint8_t pkt[MAX_PKT_LEN];
  int retries = 0;

  for (unsigned int i = 0; i < pktCnt; i++)
    {
      cmd[4] = i & 0xff;
      cmd[5] = (i >> 8) & 0xff;

      retries = 0;

    retry:

      usleep(10000);

      drainInput();
      writeData(cmd, pktLen);

      if (!dataAvailable(1000))
        {
          if (retries++ > maxRetries)
            {
              throw std::runtime_error(std::string(__FUNCTION__) +
                                       ": timeout, maximum retries exceeded");
              return false;
            }
          goto retry;
        }

      uint16_t cnt = readData(pkt, MAX_PKT_LEN);

      unsigned char sum = 0;
      for (int y = 0; y < cnt - 2; y++)
        {
          sum += pkt[y];
        }
      if (sum != pkt[cnt-2])
        {
          if (retries++ <= maxRetries)
            goto retry;
          else
            {
              throw std::runtime_error(std::string(__FUNCTION__) +
                                       ": cksum error, maximum retries exceeded");
              return false;
            }
        }

      fwrite((const uint8_t *)&pkt[4], cnt - 6, 1, file);
    }

  cmd[4] = 0xf0;
  cmd[5] = 0xf0;
  writeData(cmd, pktLen);

  fclose(file);

  // reset the pic length to 0 for another run.
  m_picTotalLen = 0;

  return true;
}