CARMA C++
SerialPortAccessor.h
1 /*
2  * Simple Serial Port Accessor
3  *
4  * Copyright (c) 2011 Ira W. Snyder <iws@ovro.caltech.edu>
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License as published by the
8  * Free Software Foundation; either version 2 of the License, or (at your
9  * option) any later version.
10  */
11 
12 #ifndef SERIAL_PORT_ACCESSOR_H
13 #define SERIAL_PORT_ACCESSOR_H
14 
15 #include <string>
16 #include <fcntl.h>
17 #include <termios.h>
18 
19 namespace carma {
20 namespace environment {
21 
22 class SerialPortAccessor
23 {
24  public:
25  SerialPortAccessor(const std::string &device, const int mode = O_RDWR | O_NOCTTY | O_NONBLOCK);
26  virtual ~SerialPortAccessor();
27 
28  /*
29  * open and close the device
30  *
31  * These are "smart": they will ignore subsequent attempts to
32  * open or close the device once it has reached the correct state
33  */
34  void open();
35  void close();
36 
37  /* recv or send some bytes: timeout is for poll() */
38  ssize_t recv(char *buf, size_t len, int timeout = 5000);
39  ssize_t send(const char *buf, size_t len, int timeout = 5000);
40 
41  /* recv or send exactly len bytes: will block until all bytes are sent */
42  ssize_t recv_n(char *buf, size_t len, int timeout = 5000);
43  ssize_t send_n(const char *buf, size_t len, int timeout = 5000);
44 
45  protected:
46 
47  /*
48  * setup the serial device
49  *
50  * This is automatically called during SerialPortAccessor::open(). It
51  * should be overridden with the settings you wish to use.
52  */
53  virtual void setup(struct termios *tio);
54 
55  private:
56  const std::string device_;
57  const int mode_;
58  int fd_;
59 };
60 
61 } // namespace environment
62 } // namespace carma
63 
64 
65 #endif /* SERIAL_PORT_ACCESSOR_H */
66 
67 /* vim: set ts=4 sts=4 sw=4 et tw=92: */