1 |
torben |
38 |
/*
|
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 |
torben |
47 |
#include <string>
|
11 |
|
|
#include <stdexcept>
|
12 |
torben |
38 |
|
13 |
torben |
49 |
#ifndef _MSC_VER //
|
14 |
torben |
44 |
inline void Sleep(int x) { usleep(x*1000);}
|
15 |
torben |
46 |
#include <termios.h>
|
16 |
torben |
44 |
#endif
|
17 |
|
|
|
18 |
|
|
|
19 |
torben |
38 |
class CSerial
|
20 |
|
|
{
|
21 |
torben |
54 |
|
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 |
torben |
38 |
|
37 |
torben |
54 |
public: //public methods
|
38 |
torben |
38 |
CSerial();
|
39 |
torben |
54 |
CSerial(char* port, Baudrate bitrate);
|
40 |
torben |
48 |
virtual ~CSerial(void);
|
41 |
torben |
38 |
|
42 |
|
|
void close();
|
43 |
torben |
54 |
void open(char* port, Baudrate bitrate);
|
44 |
torben |
38 |
|
45 |
torben |
47 |
int readByte();
|
46 |
torben |
38 |
void writeByte(unsigned char out);
|
47 |
|
|
|
48 |
torben |
76 |
void writeBytes(unsigned char* buf, unsigned int len);
|
49 |
|
|
int readBytes(unsigned char* buf, unsigned int maxLen);
|
50 |
|
|
|
51 |
torben |
49 |
#ifdef _MSC_VER
|
52 |
torben |
38 |
COMSTAT getComstat() const;
|
53 |
torben |
44 |
#endif
|
54 |
torben |
38 |
int bytesReady() const;
|
55 |
|
|
int outQueueSize() const;
|
56 |
torben |
44 |
char* getPort() const {return mPortstr;}
|
57 |
torben |
54 |
Baudrate getBitrate() const {return mBitrate;}
|
58 |
torben |
38 |
|
59 |
|
|
bool isOpen() { return mIsopen; }
|
60 |
|
|
|
61 |
|
|
protected:
|
62 |
torben |
44 |
|
63 |
torben |
46 |
void printByte(char* description, unsigned char byte);
|
64 |
torben |
54 |
int convertBaudrate(Baudrate rate);
|
65 |
torben |
76 |
|
66 |
torben |
49 |
#ifdef _MSC_VER
|
67 |
torben |
44 |
void openWindows();
|
68 |
torben |
76 |
int readBytesWindows(unsigned char*buf, unsigned int maxLen);
|
69 |
|
|
void writeBytesWindows(unsigned char* buf, unsigned int len);
|
70 |
torben |
44 |
#else
|
71 |
|
|
void openLinux();
|
72 |
torben |
76 |
int readBytesLinux(unsigned char* buf, unsigned int maxLen);
|
73 |
|
|
void writeBytesLinux(unsigned char* buf, unsigned int len);
|
74 |
torben |
44 |
#endif
|
75 |
torben |
77 |
|
76 |
|
|
|
77 |
|
|
private: // member vars
|
78 |
|
|
#ifdef _MSC_VER
|
79 |
|
|
HANDLE mComport;
|
80 |
|
|
DCB mDcbRestore;
|
81 |
|
|
#else
|
82 |
|
|
int mFiledescriptor;
|
83 |
|
|
termios mOldtio;
|
84 |
|
|
#endif
|
85 |
|
|
|
86 |
|
|
char* mPortstr;
|
87 |
|
|
Baudrate mBitrate;
|
88 |
|
|
bool mIsopen;
|
89 |
torben |
38 |
};
|