1 #ifndef _SERIAL_H 2 #define _SERIAL_H 3 4 #include <Core/Core.h> 5 6 // module to manage serial ports and discover attached devices 7 namespace Upp { 8 9 class Serial 10 { 11 private: 12 13 // the file descriptor 14 #ifdef PLATFORM_POSIX 15 int fd; 16 #else 17 HANDLE fd; 18 #endif 19 20 // error flag 21 bool isError; 22 23 // error code 24 short errCode; 25 26 // default baud rates 27 static dword stdBauds[]; 28 static int stdBaudsCount; 29 30 protected: 31 32 public: 33 34 // error codes 35 enum 36 { 37 Ok, 38 DeviceError, 39 InvalidSpeed, 40 InvalidParity, 41 InvalidSize, 42 InvalidStopBits 43 }; 44 45 // parities 46 enum 47 { 48 ParityNone, 49 ParityEven, 50 ParityOdd, 51 ParityMark, 52 ParitySpace 53 }; 54 55 // constructor 56 Serial(); 57 Serial(String const &port, dword speed, byte parity = ParityNone, byte bits = 8, byte stopBits = 1); 58 59 // destructor 60 ~Serial(); 61 62 // open the port 63 bool Open(String const &port, dword speed, byte parity = ParityNone, byte bits = 8, byte stopBits = 1); 64 65 // close the port 66 void Close(void); 67 68 // control DTR and RTS lines 69 bool SetDTR(bool on); 70 bool SetRTS(bool on); 71 72 // flush data 73 bool FlushInput(void); 74 bool FlushOutput(void); 75 bool FlushAll(void); 76 77 // check if data is available on serial port 78 int Avail(void); 79 80 // read a single byte, block 'timeout' milliseconds 81 bool Read(byte &c, uint32_t timeout = 0); 82 bool Read(char &c, uint32_t timeout = 0); 83 84 // read data, requested amount, blocks 'timeout' milliseconds 85 // return number of bytes got 86 uint32_t Read(uint8_t *buf, uint32_t reqSize, uint32_t timeout = 0); 87 88 // read data, requested amount, blocks 'timeout' milliseconds 89 // if reqSize == 0 just read all available data, waiting for 'timeout' if != 0 90 String Read(uint32_t reqSize = 0, uint32_t timeout = 0); 91 92 // write a single byte 93 bool Write(char c, uint32_t timeout = 0); 94 95 // writes data 96 bool Write(uint8_t const *buf, uint32_t len, uint32_t timeout = 0); 97 bool Write(String const &data, uint32_t timeout = 0); 98 99 // check if opened 100 bool IsOpened(void) const; 101 102 // check error flag IsError(void)103 bool IsError(void) const { return isError; } 104 operator bool(void) const { return !isError; } 105 bool operator!(void) const { return isError; } 106 107 // get error code GetErrorCode(void)108 short GetErrorCode(void) const { return errCode; } 109 110 // get a list of all serial ports 111 static ArrayMap<String, String> GetSerialPorts(void); 112 113 // get a list of standard baud rates 114 static Index<dword> const &GetStandardBaudRates(void); 115 }; 116 117 } // END_UPP_NAMESPACE 118 119 #endif 120