1 |
/*
|
2 |
* Serial.h & Serial.cpp - (C) 2007 by Torben H. Nielsen
|
3 |
*
|
4 |
* A wrapper class for communicating with a serial port
|
5 |
*/
|
6 |
|
7 |
#pragma once
|
8 |
|
9 |
#include <vector>
|
10 |
#include <string>
|
11 |
#include <stdexcept>
|
12 |
|
13 |
#ifndef _MSC_VER //
|
14 |
inline void Sleep(int x) { usleep(x*1000);}
|
15 |
#include <termios.h>
|
16 |
#endif
|
17 |
|
18 |
|
19 |
class CSerial
|
20 |
{
|
21 |
|
22 |
public: //public enumerations
|
23 |
enum Baudrate
|
24 |
{
|
25 |
Baud300,
|
26 |
Baud600,
|
27 |
Baud1200,
|
28 |
Baud2400,
|
29 |
Baud4800,
|
30 |
Baud9600,
|
31 |
Baud19200,
|
32 |
Baud38400,
|
33 |
Baud57600,
|
34 |
Baud115200
|
35 |
};
|
36 |
private: // member vars
|
37 |
#ifdef _MSC_VER
|
38 |
HANDLE mComport;
|
39 |
DCB mDcbRestore;
|
40 |
#else
|
41 |
int mFiledescriptor;
|
42 |
termios mOldtio;
|
43 |
#endif
|
44 |
|
45 |
char* mPortstr;
|
46 |
Baudrate mBitrate;
|
47 |
bool mIsopen;
|
48 |
|
49 |
public: //public methods
|
50 |
CSerial();
|
51 |
CSerial(char* port, Baudrate bitrate);
|
52 |
virtual ~CSerial(void);
|
53 |
|
54 |
void close();
|
55 |
void open(char* port, Baudrate bitrate);
|
56 |
|
57 |
int readByte();
|
58 |
void writeByte(unsigned char out);
|
59 |
|
60 |
void writeBytes(unsigned char* buf, unsigned int len);
|
61 |
int readBytes(unsigned char* buf, unsigned int maxLen);
|
62 |
|
63 |
#ifdef _MSC_VER
|
64 |
COMSTAT getComstat() const;
|
65 |
#endif
|
66 |
int bytesReady() const;
|
67 |
int outQueueSize() const;
|
68 |
char* getPort() const {return mPortstr;}
|
69 |
Baudrate getBitrate() const {return mBitrate;}
|
70 |
|
71 |
bool isOpen() { return mIsopen; }
|
72 |
|
73 |
protected:
|
74 |
|
75 |
void printByte(char* description, unsigned char byte);
|
76 |
int convertBaudrate(Baudrate rate);
|
77 |
|
78 |
#ifdef _MSC_VER
|
79 |
void openWindows();
|
80 |
int readBytesWindows(unsigned char*buf, unsigned int maxLen);
|
81 |
void writeBytesWindows(unsigned char* buf, unsigned int len);
|
82 |
#else
|
83 |
void openLinux();
|
84 |
int readBytesLinux(unsigned char* buf, unsigned int maxLen);
|
85 |
void writeBytesLinux(unsigned char* buf, unsigned int len);
|
86 |
#endif
|
87 |
};
|