bd367ffca0a34412f8e1380f7ca0d65398945476
[profile/ivi/automotive-message-broker.git] / plugins / common / serialport.hpp
1 #ifndef _SERIALPORT_H_
2 #define _SERIALPORT_H_
3
4 #include "abstractio.hpp"
5 #include "debugout.h"
6
7 #include <stdlib.h>
8 #include <stdio.h>
9 #include <unistd.h>
10 #include <sys/types.h>
11 #include <sys/stat.h>
12 #include <fcntl.h>
13 #include <termios.h>
14 #include <errno.h>
15
16 class SerialPort: public AbstractIo
17 {
18 public:
19         SerialPort(std::string _tty)
20                 :tty(_tty)
21         {
22
23         }
24
25         ~SerialPort()
26         {
27                 close();
28         }
29
30         bool open()
31         {
32                 fd = ::open(tty.c_str(), O_RDWR, O_NOCTTY);
33
34                 if(fd == -1)
35                 {
36                         DebugOut()<<"Cannot open serial device."<<endl;
37                         return false;
38                 }
39
40                 struct termios oldtio;
41                 tcgetattr(fd,&oldtio);
42
43                 oldtio.c_cflag |= CS8 | CLOCAL | CREAD;
44
45                 oldtio.c_iflag |= IGNPAR;
46                 oldtio.c_iflag &= ~(ICRNL | IMAXBEL);
47
48
49                 oldtio.c_oflag &= ~OPOST;
50
51                 oldtio.c_lflag |= ECHOE | ECHOK | ECHOCTL | ECHOKE;
52                 oldtio.c_lflag &= ~(ECHO | ICANON | ISIG);
53
54                 //oldtio.c_cc[VEOL]     = '\r';
55
56                 cfsetispeed(&oldtio, B9600);
57                 cfsetospeed(&oldtio, B9600);
58
59                 tcflush(fd, TCIFLUSH);
60                 tcsetattr(fd, TCSANOW, &oldtio);
61
62                 fcntl(fd,F_SETFL,O_NONBLOCK);
63
64                 return true;
65         }
66
67         int fileDescriptor() { return fd; }
68
69         bool close()
70         {
71                 ::close(fd);
72         }
73
74         std::string read()
75         {
76                 char buff;
77                 std::string result;
78                 int bytesread = 0;
79                 while( bytesread = ::read(fd,&buff,1) > 0 )
80                 {
81                         result += buff;
82                 }
83
84
85                 if(bytesread == -1)
86                         perror("Error while reading: ");
87
88                 return result;
89         }
90
91         void write(std::string data)
92         {
93                 int written = ::write(fd,data.c_str(),data.length());
94                 if(written == -1)
95                 {
96                         DebugOut()<<"Unable to write"<<endl;
97                 }
98         }
99
100 private:
101         int fd;
102         std::string tty;
103
104 };
105
106
107 #endif