File: ser_posix.c

package info (click to toggle)
avrdude 5.2-2
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 2,284 kB
  • ctags: 1,520
  • sloc: ansic: 15,167; sh: 3,437; yacc: 1,051; lex: 240; makefile: 158
file content (488 lines) | stat: -rw-r--r-- 10,560 bytes parent folder | download
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
/*
 * avrdude - A Downloader/Uploader for AVR device programmers
 * Copyright (C) 2003-2004  Theodore A. Roth  <troth@openavr.org>
 * Copyright (C) 2006 Joerg Wunsch <j@uriah.heep.sax.de>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

/* $Id: ser_posix.c,v 1.15 2006/08/31 20:52:47 joerg_wunsch Exp $ */

/*
 * Posix serial interface for avrdude.
 */

#if !defined(WIN32NATIVE)


#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>

#include <fcntl.h>
#include <termios.h>
#include <unistd.h>

#include "serial.h"

extern char *progname;
extern int verbose;

long serial_recv_timeout = 5000; /* ms */

struct baud_mapping {
  long baud;
  speed_t speed;
};

/* There are a lot more baud rates we could handle, but what's the point? */

static struct baud_mapping baud_lookup_table [] = {
  { 1200,   B1200 },
  { 2400,   B2400 },
  { 4800,   B4800 },
  { 9600,   B9600 },
  { 19200,  B19200 },
  { 38400,  B38400 },
  { 57600,  B57600 },
  { 115200, B115200 },
  { 230400, B230400 },
  { 0,      0 }                 /* Terminator. */
};

static struct termios original_termios;
static int saved_original_termios;

static speed_t serial_baud_lookup(long baud)
{
  struct baud_mapping *map = baud_lookup_table;

  while (map->baud) {
    if (map->baud == baud)
      return map->speed;
    map++;
  }

  fprintf(stderr, "%s: serial_baud_lookup(): unknown baud rate: %ld\n",
          progname, baud);
  exit(1);
}

static int ser_setspeed(int fd, long baud)
{
  int rc;
  struct termios termios;
  speed_t speed = serial_baud_lookup (baud);
  
  if (!isatty(fd))
    return -ENOTTY;
  
  /*
   * initialize terminal modes
   */
  rc = tcgetattr(fd, &termios);
  if (rc < 0) {
    fprintf(stderr, "%s: ser_setspeed(): tcgetattr() failed",
            progname);
    return -errno;
  }

  /*
   * copy termios for ser_close if we haven't already
   */
  if (! saved_original_termios++) {
    original_termios = termios;
  }

  termios.c_iflag = IGNBRK;
  termios.c_oflag = 0;
  termios.c_lflag = 0;
  termios.c_cflag = (CS8 | CREAD | CLOCAL);
  termios.c_cc[VMIN]  = 1;
  termios.c_cc[VTIME] = 0;

  cfsetospeed(&termios, speed);
  cfsetispeed(&termios, speed);
  
  rc = tcsetattr(fd, TCSANOW | TCSAFLUSH, &termios);
  if (rc < 0) {
    fprintf(stderr, "%s: ser_setspeed(): tcsetattr() failed",
            progname);
    return -errno;
  }

  /*
   * Everything is now set up for a local line without modem control
   * or flow control, so clear O_NONBLOCK again.
   */
  rc = fcntl(fd, F_GETFL, 0);
  if (rc != -1)
    fcntl(fd, F_SETFL, rc & ~O_NONBLOCK);

  return 0;
}

/*
 * Given a port description of the form <host>:<port>, open a TCP
 * connection to the specified destination, which is assumed to be a
 * terminal/console server with serial parameters configured
 * appropriately (e. g. 115200-8-N-1 for a STK500.)
 */
static int
net_open(const char *port)
{
  char *hstr, *pstr, *end;
  unsigned int pnum;
  int fd;
  struct sockaddr_in sockaddr;
  struct hostent *hp;

  if ((hstr = strdup(port)) == NULL) {
    fprintf(stderr, "%s: net_open(): Out of memory!\n",
	    progname);
    exit(1);
  }

  if (((pstr = strchr(hstr, ':')) == NULL) || (pstr == hstr)) {
    fprintf(stderr, "%s: net_open(): Mangled host:port string \"%s\"\n",
	    progname, hstr);
    free(hstr);
    exit(1);
  }

  /*
   * Terminate the host section of the description.
   */
  *pstr++ = '\0';

  pnum = strtoul(pstr, &end, 10);

  if ((*pstr == '\0') || (*end != '\0') || (pnum == 0) || (pnum > 65535)) {
    fprintf(stderr, "%s: net_open(): Bad port number \"%s\"\n",
	    progname, pstr);
    free(hstr);
    exit(1);
  }

  if ((hp = gethostbyname(hstr)) == NULL) {
    fprintf(stderr, "%s: net_open(): unknown host \"%s\"\n",
	    progname, hstr);
    free(hstr);
    exit(1);
  }

  free(hstr);

  if ((fd = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
    fprintf(stderr, "%s: net_open(): Cannot open socket: %s\n",
	    progname, strerror(errno));
    exit(1);
  }

  memset(&sockaddr, 0, sizeof(struct sockaddr_in));
  sockaddr.sin_family = AF_INET;
  sockaddr.sin_port = htons(pnum);
  memcpy(&(sockaddr.sin_addr.s_addr), hp->h_addr, sizeof(struct in_addr));

  if (connect(fd, (struct sockaddr *)&sockaddr, sizeof(sockaddr))) {
    fprintf(stderr, "%s: net_open(): Connect failed: %s\n",
	    progname, strerror(errno));
    exit(1);
  }

  return fd;
}

static int ser_open(char * port, long baud)
{
  int rc;
  int fd;

  /*
   * If the port is of the form "net:<host>:<port>", then
   * handle it as a TCP connection to a terminal server.
   */
  if (strncmp(port, "net:", strlen("net:")) == 0) {
    return net_open(port + strlen("net:"));
  }

  /*
   * open the serial port
   */
  fd = open(port, O_RDWR | O_NOCTTY | O_NONBLOCK);
  if (fd < 0) {
    fprintf(stderr, "%s: ser_open(): can't open device \"%s\": %s\n",
            progname, port, strerror(errno));
    exit(1);
  }

  /*
   * set serial line attributes
   */
  rc = ser_setspeed(fd, baud);
  if (rc) {
    fprintf(stderr, 
            "%s: ser_open(): can't set attributes for device \"%s\": %s\n",
            progname, port, strerror(-rc));
    exit(1);
  }

  return fd;
}


static void ser_close(int fd)
{
  /*
   * restore original termios settings from ser_open
   */
  if (saved_original_termios) {
    int rc = tcsetattr(fd, TCSANOW | TCSADRAIN, &original_termios);
    if (rc) {
      fprintf(stderr, 
              "%s: ser_close(): can't reset attributes for device: %s\n",
              progname, strerror(errno));
    }
    saved_original_termios = 0;
  }

  close(fd);
}


static int ser_send(int fd, unsigned char * buf, size_t buflen)
{
  struct timeval timeout, to2;
  fd_set wfds;
  int nfds;
  int rc;
  unsigned char * p = buf;
  size_t len = buflen;

  if (!len)
    return 0;

  if (verbose > 3)
  {
      fprintf(stderr, "%s: Send: ", progname);

      while (buflen) {
        unsigned char c = *buf;
        if (isprint(c)) {
          fprintf(stderr, "%c ", c);
        }
        else {
          fprintf(stderr, ". ");
        }
        fprintf(stderr, "[%02x] ", c);

        buf++;
        buflen--;
      }

      fprintf(stderr, "\n");
  }

  timeout.tv_sec = 0;
  timeout.tv_usec = 500000;
  to2 = timeout;

  while (len) {
  reselect:
    FD_ZERO(&wfds);
    FD_SET(fd, &wfds);

    nfds = select(fd+1, NULL, &wfds, NULL, &to2);
    if (nfds == 0) {
      if (verbose >= 1)
	fprintf(stderr,
		"%s: ser_send(): programmer is not responding\n",
		progname);
      exit(1);
    }
    else if (nfds == -1) {
      if (errno == EINTR || errno == EAGAIN) {
        goto reselect;
      }
      else {
        fprintf(stderr, "%s: ser_send(): select(): %s\n",
                progname, strerror(errno));
        exit(1);
      }
    }

    rc = write(fd, p, (len > 1024) ? 1024 : len);
    if (rc < 0) {
      fprintf(stderr, "%s: ser_send(): write error: %s\n",
              progname, strerror(errno));
      exit(1);
    }
    p += rc;
    len -= rc;
  }

  return 0;
}


static int ser_recv(int fd, unsigned char * buf, size_t buflen)
{
  struct timeval timeout, to2;
  fd_set rfds;
  int nfds;
  int rc;
  unsigned char * p = buf;
  size_t len = 0;

  timeout.tv_sec  = serial_recv_timeout / 1000L;
  timeout.tv_usec = (serial_recv_timeout % 1000L) * 1000;
  to2 = timeout;

  while (len < buflen) {
  reselect:
    FD_ZERO(&rfds);
    FD_SET(fd, &rfds);

    nfds = select(fd+1, &rfds, NULL, NULL, &to2);
    if (nfds == 0) {
      if (verbose > 1)
	fprintf(stderr,
		"%s: ser_recv(): programmer is not responding\n",
		progname);
      return -1;
    }
    else if (nfds == -1) {
      if (errno == EINTR || errno == EAGAIN) {
	fprintf(stderr,
		"%s: ser_recv(): programmer is not responding,reselecting\n",
		progname);
        goto reselect;
      }
      else {
        fprintf(stderr, "%s: ser_recv(): select(): %s\n",
                progname, strerror(errno));
        exit(1);
      }
    }

    rc = read(fd, p, (buflen - len > 1024) ? 1024 : buflen - len);
    if (rc < 0) {
      fprintf(stderr, "%s: ser_recv(): read error: %s\n",
              progname, strerror(errno));
      exit(1);
    }
    p += rc;
    len += rc;
  }

  p = buf;

  if (verbose > 3)
  {
      fprintf(stderr, "%s: Recv: ", progname);

      while (len) {
        unsigned char c = *p;
        if (isprint(c)) {
          fprintf(stderr, "%c ", c);
        }
        else {
          fprintf(stderr, ". ");
        }
        fprintf(stderr, "[%02x] ", c);

        p++;
        len--;
      }
      fprintf(stderr, "\n");
  }

  return 0;
}


static int ser_drain(int fd, int display)
{
  struct timeval timeout;
  fd_set rfds;
  int nfds;
  int rc;
  unsigned char buf;

  timeout.tv_sec = 0;
  timeout.tv_usec = 250000;

  if (display) {
    fprintf(stderr, "drain>");
  }

  while (1) {
    FD_ZERO(&rfds);
    FD_SET(fd, &rfds);

  reselect:
    nfds = select(fd+1, &rfds, NULL, NULL, &timeout);
    if (nfds == 0) {
      if (display) {
        fprintf(stderr, "<drain\n");
      }
      
      break;
    }
    else if (nfds == -1) {
      if (errno == EINTR) {
        goto reselect;
      }
      else {
        fprintf(stderr, "%s: ser_drain(): select(): %s\n",
                progname, strerror(errno));
        exit(1);
      }
    }

    rc = read(fd, &buf, 1);
    if (rc < 0) {
      fprintf(stderr, "%s: ser_drain(): read error: %s\n",
              progname, strerror(errno));
      exit(1);
    }
    if (display) {
      fprintf(stderr, "%02x ", buf);
    }
  }

  return 0;
}

struct serial_device serial_serdev =
{
  .open = ser_open,
  .setspeed = ser_setspeed,
  .close = ser_close,
  .send = ser_send,
  .recv = ser_recv,
  .drain = ser_drain,
};

struct serial_device *serdev = &serial_serdev;

#endif  /* WIN32NATIVE */