00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024 #include "cinder/Cinder.h"
00025 #include "cinder/Exception.h"
00026
00027 #include <string>
00028 #include <vector>
00029
00030 #if defined( CINDER_MAC )
00031 #include <termios.h>
00032 #elif defined( CINDER_MSW )
00033 #include <windows.h>
00034 #endif
00035
00036 namespace cinder {
00037
00038 class Serial {
00039 public:
00040 class Device {
00041 public:
00042 Device() {}
00043 Device( const std::string &nameAndPath ) : mName( nameAndPath ), mPath( nameAndPath ) {}
00044 Device( const std::string &name, const std::string &path ) : mName( name ), mPath( path ) {}
00045
00046 const std::string& getName() const { return mName; }
00047 const std::string& getPath() const { return mPath; }
00048
00049 private:
00050 std::string mName;
00051 std::string mPath;
00052 };
00053
00055 static const std::vector<Serial::Device>& getDevices( bool forceRefresh = false );
00057 static Serial::Device findDeviceByName( const std::string &name, bool forceRefresh = false );
00059 static Serial::Device findDeviceByNameContains( const std::string &searchString, bool forceRefresh = false );
00060
00061
00062 Serial() {}
00063 Serial( const Serial::Device &device, int baudRate );
00064
00066 const Device& getDevice() const;
00067
00069 void readBytes( void *data, size_t numBytes );
00071 size_t readAvailableBytes( void *data, size_t maximumBytes );
00073 void writeBytes( const void *data, size_t numBytes );
00075 void writeByte( uint8_t data );
00077 uint8_t readByte();
00079 char readChar() { return static_cast<char>( readByte() ); }
00080
00082 std::string readStringUntil( char token, size_t maxLength = 0, double timeoutSeconds = -1.0 );
00084 void writeString( const std::string &str );
00085
00087 void flush( bool input = true, bool output = true );
00089 size_t getNumBytesAvailable() const;
00090
00091 protected:
00092 struct Obj {
00093 Obj();
00094 Obj( const Serial::Device &device, int baudRate );
00095 ~Obj();
00096
00097 Device mDevice;
00098
00099 #ifdef CINDER_MSW
00100 ::HANDLE mDeviceHandle;
00101 ::COMMTIMEOUTS mSavedTimeouts;
00102 #else
00103 int mFd;
00104 ::termios mSavedOptions;
00105 #endif
00106 };
00107
00108 shared_ptr<Obj> mObj;
00109
00110 private:
00111
00112 static bool sDevicesInited;
00113 static std::vector<Serial::Device> sDevices;
00114 };
00115
00116 class SerialExc : public Exception {
00117 };
00118
00119 class SerialExcOpenFailed : public SerialExc {
00120 };
00121
00122 class SerialExcDeviceEnumerationFailed : public SerialExc {
00123 };
00124
00125 class SerialExcReadFailure : public SerialExc {
00126 };
00127
00128 class SerialExcWriteFailure : public SerialExc {
00129 };
00130
00131 class SerialTimeoutExc : public SerialExc {
00132 };
00133
00134 }