/*
 * Serial I/O helper routines
 *
 * Jim Paris <jim@jtan.com>
 * $Id$
 */
#ifndef SERIAL_UTIL_H
#define SERIAL_UTIL_H

#include <unistd.h>

/* Open serial port in raw mode, with custom baudrate if necessary */
int serial_open(const char *device, int rate);

/* Like read(), but restarts after EINTR, and reads until count bytes
   are received or a timeout occurs. */
int saferead_timeout(int fd, void *buf, size_t count, int timeout_ms);

static inline int saferead(int fd, void *buf, size_t count) {
	return saferead_timeout(fd, buf, count, -1);
}

/* Like write(), but restarts after EINTR */
ssize_t safewrite(int fd, const void *buf, size_t count);

/* Read bytes until no more are available for specified time */
int drain_timeout(int fd, int msec);

/* Read bytes until no more are available for 0.1 sec */
static inline int drain(int fd) {
	return drain_timeout(fd, 100);
}

/* Like fprintf, but to a fd, using safewrite */
int fdprintf(int fd, const char *fmt, ...);

/* Like fgets, but from a fd, using saferead_timeout. */
char *fdgets(char *s, int size, int fd, int timeout_ms);

/* Like perl chomp. */
void chomp(char *s);

#endif
