diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..c678627 --- /dev/null +++ b/.clang-format @@ -0,0 +1,246 @@ +--- +Language: Cpp +# BasedOnStyle: LLVM +AccessModifierOffset: -2 +AlignAfterOpenBracket: Align +AlignArrayOfStructures: None +AlignConsecutiveAssignments: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: true +AlignConsecutiveBitFields: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveDeclarations: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveMacros: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveShortCaseStatements: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCaseColons: false +AlignEscapedNewlines: Right +AlignOperands: Align +AlignTrailingComments: + Kind: Always + OverEmptyLines: 0 +AllowAllArgumentsOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowBreakBeforeNoexceptSpecifier: Never +AllowShortBlocksOnASingleLine: Never +AllowShortCaseLabelsOnASingleLine: false +AllowShortCompoundRequirementOnASingleLine: true +AllowShortEnumsOnASingleLine: true +AllowShortFunctionsOnASingleLine: All +AllowShortIfStatementsOnASingleLine: Never +AllowShortLambdasOnASingleLine: All +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: MultiLine +AttributeMacros: + - __capability +BinPackArguments: true +BinPackParameters: true +BitFieldColonSpacing: Both +BraceWrapping: + AfterCaseLabel: false + AfterClass: false + AfterControlStatement: Never + AfterEnum: false + AfterExternBlock: false + AfterFunction: false + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: false + AfterUnion: false + BeforeCatch: false + BeforeElse: false + BeforeLambdaBody: false + BeforeWhile: false + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakAdjacentStringLiterals: true +BreakAfterAttributes: Leave +BreakAfterJavaFieldAnnotations: false +BreakArrays: true +BreakBeforeBinaryOperators: None +BreakBeforeConceptDeclarations: Always +BreakBeforeBraces: Attach +BreakBeforeInlineASMColon: OnlyMultiline +BreakBeforeTernaryOperators: true +BreakConstructorInitializers: BeforeColon +BreakInheritanceList: BeforeColon +BreakStringLiterals: true +ColumnLimit: 120 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DerivePointerAlignment: false +DisableFormat: false +EmptyLineAfterAccessModifier: Never +EmptyLineBeforeAccessModifier: LogicalBlock +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: true +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IfMacros: + - KJ_IF_MAYBE +IncludeBlocks: Preserve +IncludeCategories: + - Regex: '^"(llvm|llvm-c|clang|clang-c)/' + Priority: 2 + SortPriority: 0 + CaseSensitive: false + - Regex: '^(<|"(gtest|gmock|isl|json)/)' + Priority: 3 + SortPriority: 0 + CaseSensitive: false + - Regex: '.*' + Priority: 1 + SortPriority: 0 + CaseSensitive: false +IncludeIsMainRegex: '(Test)?$' +IncludeIsMainSourceRegex: '' +IndentAccessModifiers: false +IndentCaseBlocks: false +IndentCaseLabels: false +IndentExternBlock: AfterExternBlock +IndentGotoLabels: true +IndentPPDirectives: None +IndentRequiresClause: true +IndentWidth: 4 +IndentWrappedFunctionNames: false +InsertBraces: false +InsertNewlineAtEOF: false +InsertTrailingCommas: None +IntegerLiteralSeparator: + Binary: 0 + BinaryMinDigits: 0 + Decimal: 0 + DecimalMinDigits: 0 + Hex: 0 + HexMinDigits: 0 +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: true +KeepEmptyLinesAtEOF: false +LambdaBodyIndentation: Signature +LineEnding: DeriveLF +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +ObjCBinPackProtocolList: Auto +ObjCBlockIndentWidth: 2 +ObjCBreakBeforeNestedBlockParam: true +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: true +PackConstructorInitializers: BinPack +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakOpenParenthesis: 0 +PenaltyBreakScopeResolution: 500 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyIndentedWhitespace: 0 +PenaltyReturnTypeOnItsOwnLine: 60 +PointerAlignment: Right +PPIndentWidth: -1 +QualifierAlignment: Leave +ReferenceAlignment: Pointer +ReflowComments: true +RemoveBracesLLVM: false +RemoveParentheses: Leave +RemoveSemicolon: false +RequiresClausePosition: OwnLine +RequiresExpressionIndentation: OuterScope +SeparateDefinitionBlocks: Leave +ShortNamespaceLines: 1 +SkipMacroDefinitionBody: false +SortIncludes: CaseSensitive +SortJavaStaticImport: Before +SortUsingDeclarations: LexicographicNumeric +SpaceAfterCStyleCast: false +SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: true +SpaceAroundPointerQualifiers: Default +SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeJsonColon: false +SpaceBeforeParens: ControlStatements +SpaceBeforeParensOptions: + AfterControlStatements: true + AfterForeachMacros: true + AfterFunctionDefinitionName: false + AfterFunctionDeclarationName: false + AfterIfMacros: true + AfterOverloadedOperator: false + AfterPlacementOperator: true + AfterRequiresInClause: false + AfterRequiresInExpression: false + BeforeNonEmptyParentheses: false +SpaceBeforeRangeBasedForLoopColon: true +SpaceBeforeSquareBrackets: false +SpaceInEmptyBlock: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: Never +SpacesInContainerLiterals: true +SpacesInLineCommentPrefix: + Minimum: 1 + Maximum: -1 +SpacesInParens: Never +SpacesInParensOptions: + InCStyleCasts: false + InConditionalStatements: false + InEmptyParentheses: false + Other: false +SpacesInSquareBrackets: false +Standard: Latest +StatementAttributeLikeMacros: + - Q_EMIT +StatementMacros: + - Q_UNUSED + - QT_REQUIRE_VERSION +TabWidth: 8 +UseTab: Never +VerilogBreakBetweenInstancePorts: true +WhitespaceSensitiveMacros: + - BOOST_PP_STRINGIZE + - CF_SWIFT_NAME + - NS_SWIFT_NAME + - PP_STRINGIZE + - STRINGIZE +... + diff --git a/ceserial.h b/ceserial.h index 9641596..dbcce79 100644 --- a/ceserial.h +++ b/ceserial.h @@ -12,237 +12,269 @@ #ifndef CESERIAL_H #define CESERIAL_H -#include -#include +#include #include +#include #include -#include +#include -#if defined(_WIN64) || defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(__WINDOWS__) || defined(__TOS_WIN__) || defined(__CYGWIN__) - #ifndef CE_WINDOWS - #define CE_WINDOWS - #endif +#if defined(_WIN64) || defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(__WINDOWS__) || \ + defined(__TOS_WIN__) || defined(__CYGWIN__) +#ifndef CE_WINDOWS +#define CE_WINDOWS +#endif #elif defined(__linux__) || defined(unix) || defined(__unix) || defined(__unix__) - #ifndef CE_LINUX - #define CE_LINUX - #endif +#ifndef CE_LINUX +#define CE_LINUX +#endif #else - #ifndef CE_NOS - #define CE_NOS - #endif +#ifndef CE_NOS +#define CE_NOS +#endif #endif #ifdef CE_WINDOWS - #include +#include #endif class ceSerial { -private: - char rxchar; - std::string port; - long baud; - long dsize; - char parity; - float stopbits; - bool stdbaud; + private: + char rxchar; + std::string port; + long baud; + long dsize; + char parity; + float stopbits; + bool stdbaud; #ifdef CE_WINDOWS - HANDLE hComm; //handle - OVERLAPPED osReader; - OVERLAPPED osWrite; - BOOL fWaitingOnRead; - COMMTIMEOUTS timeouts_ori; + HANDLE hComm; // handle + OVERLAPPED osReader; + OVERLAPPED osWrite; + BOOL fWaitingOnRead; + COMMTIMEOUTS timeouts_ori; #else - long fd;//serial_fd + long fd; // serial_fd #endif -public: - static void Delay(unsigned long ms); - ceSerial(); - ceSerial(std::string Device, long BaudRate, long DataSize, char ParityType, float NStopBits); - ~ceSerial(); - long Open(void);//return 0 if success - void Close(); - char ReadChar(bool& success);//return read char if success - bool WriteChar(const char ch);////return success flag - bool Write(const char *data);//write null terminated string and return success flag - bool Write(const char *data,long n); - bool WriteArr(const uint8_t *data,long n); - bool SetRTS(bool value);//return success flag - bool SetDTR(bool value);//return success flag - bool GetCTS(bool& success); - bool GetDSR(bool& success); - bool GetRI(bool& success); - bool GetCD(bool& success); - bool IsOpened(); - void SetPortName(std::string Port); - std::string GetPort(); - void SetBaudRate(long baudrate); - long GetBaudRate(); - void SetDataSize(long nbits); - long GetDataSize(); - void SetParity(char p); - char GetParity(); - void SetStopBits(float nbits); - float GetStopBits(); + public: + static void Delay(unsigned long ms); + ceSerial(); + ceSerial(std::string Device, long BaudRate, long DataSize, char ParityType, float NStopBits); + ~ceSerial(); + ceSerial(const ceSerial &) = delete; // owns a handle/fd; copying would double-close it + ceSerial &operator=(const ceSerial &) = delete; + long Open(void); // return 0 if success + void Close(); + char ReadChar(bool &success); // return read char if success + bool WriteChar(const char ch); ////return success flag + bool Write(const char *data); // write null terminated string and return success flag + bool Write(const char *data, long n); + bool WriteArr(const uint8_t *data, long n); + bool SetRTS(bool value); // return success flag + bool SetDTR(bool value); // return success flag + bool GetCTS(bool &success); + bool GetDSR(bool &success); + bool GetRI(bool &success); + bool GetCD(bool &success); + bool IsOpened(); + void SetPortName(std::string Port); + std::string GetPort(); + void SetBaudRate(long baudrate); + long GetBaudRate(); + void SetDataSize(long nbits); + long GetDataSize(); + void SetParity(char p); + char GetParity(); + void SetStopBits(float nbits); + float GetStopBits(); }; //----------------------------------------------------------------------------- #ifdef CE_WINDOWS - #define READ_TIMEOUT 10 // milliseconds +#define READ_TIMEOUT 10 // milliseconds #else - #include - #include - #include - #include - #include +#include +#include +#include +#include +#include #endif inline void ceSerial::Delay(unsigned long ms) { #ifdef CE_WINDOWS - Sleep(ms); + Sleep(ms); #else - usleep(ms*1000); + usleep(ms * 1000); #endif } -inline ceSerial::ceSerial() : +inline ceSerial::ceSerial() + : #ifdef CE_WINDOWS - ceSerial("\\\\.\\COM1", 9600, 8, 'N', 1) + ceSerial("\\\\.\\COM1", 9600, 8, 'N', 1) #else - ceSerial("/dev/ttyS0", 9600, 8, 'N', 1) + ceSerial("/dev/ttyS0", 9600, 8, 'N', 1) #endif { - } -inline ceSerial::ceSerial(std::string Device, long BaudRate,long DataSize,char ParityType,float NStopBits):stdbaud(true) { +inline ceSerial::ceSerial(std::string Device, long BaudRate, long DataSize, char ParityType, float NStopBits) + : stdbaud(true) { #ifdef CE_WINDOWS - hComm = INVALID_HANDLE_VALUE; + hComm = INVALID_HANDLE_VALUE; #else - fd = -1; + fd = -1; #endif // defined - SetBaudRate(BaudRate); - SetDataSize(DataSize); - SetParity(ParityType); - SetStopBits(NStopBits); - SetPortName(Device); + SetBaudRate(BaudRate); + SetDataSize(DataSize); + SetParity(ParityType); + SetStopBits(NStopBits); + SetPortName(Device); } -inline ceSerial::~ceSerial() { - Close(); -} +inline ceSerial::~ceSerial() { Close(); } -inline void ceSerial::SetPortName(std::string Device) { - port = Device; -} +inline void ceSerial::SetPortName(std::string Device) { port = Device; } -inline std::string ceSerial::GetPort() { - return port; -} +inline std::string ceSerial::GetPort() { return port; } inline void ceSerial::SetDataSize(long nbits) { - if ((nbits < 5) || (nbits > 8)) nbits = 8; - dsize=nbits; + if ((nbits < 5) || (nbits > 8)) + nbits = 8; + dsize = nbits; } -inline long ceSerial::GetDataSize() { - return dsize; -} +inline long ceSerial::GetDataSize() { return dsize; } inline void ceSerial::SetParity(char p) { - if ((p != 'N') && (p != 'E') && (p != 'O')) { + if ((p != 'N') && (p != 'E') && (p != 'O')) { #ifdef CE_WINDOWS - if ((p != 'M') && (p != 'S')) p = 'N'; + if ((p != 'M') && (p != 'S')) + p = 'N'; #else - p = 'N'; + p = 'N'; #endif - } - parity = p; + } + parity = p; } -inline char ceSerial::GetParity() { - return parity; -} +inline char ceSerial::GetParity() { return parity; } inline void ceSerial::SetStopBits(float nbits) { - if (nbits >= 2) stopbits = 2; + if (nbits >= 2) + stopbits = 2; #ifdef CE_WINDOWS - else if(nbits >= 1.5) stopbits = 1.5; + else if (nbits >= 1.5) + stopbits = 1.5; #endif - else stopbits = 1; -} - -inline float ceSerial::GetStopBits() { - return stopbits; + else + stopbits = 1; } +inline float ceSerial::GetStopBits() { return stopbits; } #ifdef CE_WINDOWS inline void ceSerial::SetBaudRate(long baudrate) { - stdbaud = true; - if (baudrate == 110) baud = CBR_110; - else if (baudrate == 300) baud = CBR_300; - else if (baudrate == 600) baud = CBR_600; - else if (baudrate == 1200) baud = CBR_1200; - else if (baudrate == 2400) baud = CBR_2400; - else if (baudrate == 4800) baud = CBR_4800; - else if (baudrate == 9600) baud = CBR_9600; - else if (baudrate == 14400) baud = CBR_14400; - else if (baudrate == 19200) baud = CBR_19200; - else if (baudrate == 38400) baud = CBR_38400; - else if (baudrate == 57600) baud = CBR_57600; - else if (baudrate == 115200) baud = CBR_115200; - else if (baudrate == 128000) baud = CBR_128000; - else if (baudrate == 256000) baud = CBR_256000; - else { - baud = baudrate; - stdbaud = false; - } -} - -inline long ceSerial::GetBaudRate() { - return baud; -} + stdbaud = true; + if (baudrate == 110) + baud = CBR_110; + else if (baudrate == 300) + baud = CBR_300; + else if (baudrate == 600) + baud = CBR_600; + else if (baudrate == 1200) + baud = CBR_1200; + else if (baudrate == 2400) + baud = CBR_2400; + else if (baudrate == 4800) + baud = CBR_4800; + else if (baudrate == 9600) + baud = CBR_9600; + else if (baudrate == 14400) + baud = CBR_14400; + else if (baudrate == 19200) + baud = CBR_19200; + else if (baudrate == 38400) + baud = CBR_38400; + else if (baudrate == 57600) + baud = CBR_57600; + else if (baudrate == 115200) + baud = CBR_115200; + else if (baudrate == 128000) + baud = CBR_128000; + else if (baudrate == 256000) + baud = CBR_256000; + else { + baud = baudrate; + stdbaud = false; + } +} + +inline long ceSerial::GetBaudRate() { return baud; } inline long ceSerial::Open() { - if (IsOpened()) return 0; + if (IsOpened()) + return 0; #ifdef UNICODE - std::wstring wtext(port.begin(),port.end()); + std::wstring wtext(port.begin(), port.end()); #else - std::string wtext = port; + std::string wtext = port; #endif - hComm = CreateFile(wtext.c_str(), - GENERIC_READ | GENERIC_WRITE, - 0, - 0, - OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, - 0); - if (hComm == INVALID_HANDLE_VALUE) {return -1;} - - if (PurgeComm(hComm, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR) == 0) {return -1;}//purge - - //get initial state + hComm = CreateFile(wtext.c_str(), GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, 0); + if (hComm == INVALID_HANDLE_VALUE) { + return -1; + } + + osReader = {0}; + osWrite = {0}; + // Close whatever was opened so far and reset hComm; avoids a leaked/stale + // handle that would make a later Open() short-circuit via IsOpened(). + auto fail = [&]() -> long { + if (osWrite.hEvent) + CloseHandle(osWrite.hEvent); + if (osReader.hEvent) + CloseHandle(osReader.hEvent); + CloseHandle(hComm); + hComm = INVALID_HANDLE_VALUE; + return -1; + }; + + if (PurgeComm(hComm, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR) == 0) { + return fail(); + } // purge + + // get initial state DCB dcbOri; bool fSuccess; fSuccess = GetCommState(hComm, &dcbOri); - if (!fSuccess) {return -1;} + if (!fSuccess) { + return fail(); + } DCB dcb1 = dcbOri; dcb1.BaudRate = baud; - if (parity == 'E') dcb1.Parity = EVENPARITY; - else if (parity == 'O') dcb1.Parity = ODDPARITY; - else if (parity == 'M') dcb1.Parity = MARKPARITY; - else if (parity == 'S') dcb1.Parity = SPACEPARITY; - else dcb1.Parity = NOPARITY; + if (parity == 'E') + dcb1.Parity = EVENPARITY; + else if (parity == 'O') + dcb1.Parity = ODDPARITY; + else if (parity == 'M') + dcb1.Parity = MARKPARITY; + else if (parity == 'S') + dcb1.Parity = SPACEPARITY; + else + dcb1.Parity = NOPARITY; dcb1.ByteSize = (BYTE)dsize; - if(stopbits==2) dcb1.StopBits = TWOSTOPBITS; - else if (stopbits == 1.5) dcb1.StopBits = ONE5STOPBITS; - else dcb1.StopBits = ONESTOPBIT; + if (stopbits == 2) + dcb1.StopBits = TWOSTOPBITS; + else if (stopbits == 1.5) + dcb1.StopBits = ONE5STOPBITS; + else + dcb1.StopBits = ONESTOPBIT; dcb1.fOutxCtsFlow = false; dcb1.fOutxDsrFlow = false; @@ -251,434 +283,525 @@ inline long ceSerial::Open() { dcb1.fRtsControl = RTS_CONTROL_DISABLE; fSuccess = SetCommState(hComm, &dcb1); this->Delay(60); - if (!fSuccess) {return -1;} + if (!fSuccess) { + return fail(); + } fSuccess = GetCommState(hComm, &dcb1); - if (!fSuccess) {return -1;} + if (!fSuccess) { + return fail(); + } - osReader = { 0 };// Create the overlapped event. - // Must be closed before exiting to avoid a handle leak. + // Create the overlapped event. osReader.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); - if (osReader.hEvent == NULL) {return -1;}// Error creating overlapped event; abort. + if (osReader.hEvent == NULL) { + return fail(); + } // Error creating overlapped event; abort. fWaitingOnRead = FALSE; - osWrite = { 0 }; osWrite.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); - if (osWrite.hEvent == NULL) {return -1;} + if (osWrite.hEvent == NULL) { + return fail(); + } - if (!GetCommTimeouts(hComm, &timeouts_ori)) { return -1; } // Error getting time-outs. + if (!GetCommTimeouts(hComm, &timeouts_ori)) { + return fail(); + } // Error getting time-outs. COMMTIMEOUTS timeouts; timeouts.ReadIntervalTimeout = 20; timeouts.ReadTotalTimeoutMultiplier = 15; timeouts.ReadTotalTimeoutConstant = 100; timeouts.WriteTotalTimeoutMultiplier = 15; timeouts.WriteTotalTimeoutConstant = 100; - if (!SetCommTimeouts(hComm, &timeouts)) { return -1;} // Error setting time-outs. - return 0; + if (!SetCommTimeouts(hComm, &timeouts)) { + return fail(); + } // Error setting time-outs. + return 0; } inline void ceSerial::Close() { - if (IsOpened()) - { - SetCommTimeouts(hComm, &timeouts_ori); - CloseHandle(osReader.hEvent); - CloseHandle(osWrite.hEvent); - CloseHandle(hComm);//close comm port - hComm = INVALID_HANDLE_VALUE; - } + if (IsOpened()) { + SetCommTimeouts(hComm, &timeouts_ori); + CloseHandle(osReader.hEvent); + CloseHandle(osWrite.hEvent); + CloseHandle(hComm); // close comm port + hComm = INVALID_HANDLE_VALUE; + } } inline bool ceSerial::IsOpened() { - if(hComm == INVALID_HANDLE_VALUE) return false; - else return true; + if (hComm == INVALID_HANDLE_VALUE) + return false; + else + return true; } inline bool ceSerial::Write(const char *data) { - if (!IsOpened()) { - return false; - } - BOOL fRes; - DWORD dwWritten; - long n = strlen(data); - if (n < 0) n = 0; - else if(n > 1024) n = 1024; - - // Issue write. - if (!WriteFile(hComm, data, n, &dwWritten, &osWrite)) { + if (!IsOpened() || !data) { + return false; + } + BOOL fRes; + DWORD dwWritten; + long n = strlen(data); + if (n < 0) + n = 0; + else if (n > 1024) + n = 1024; + + // Issue write. + if (!WriteFile(hComm, data, n, &dwWritten, &osWrite)) { // WriteFile failed, but it isn't delayed. Report error and abort. - if (GetLastError() != ERROR_IO_PENDING) {fRes = FALSE;} - else {// Write is pending. - if (!GetOverlappedResult(hComm, &osWrite, &dwWritten, TRUE)) fRes = FALSE; - else fRes = TRUE;// Write operation completed successfully. - } - } - else fRes = TRUE;// WriteFile completed immediately. - return fRes; -} - -inline bool ceSerial::Write(const char *data,long n) { - if (!IsOpened()) { - return false; - } - BOOL fRes; - DWORD dwWritten; - if (n < 0) n = 0; - else if(n > 1024) n = 1024; - - // Issue write. - if (!WriteFile(hComm, data, n, &dwWritten, &osWrite)) { + if (GetLastError() != ERROR_IO_PENDING) { + fRes = FALSE; + } else { // Write is pending. + if (!GetOverlappedResult(hComm, &osWrite, &dwWritten, TRUE)) + fRes = FALSE; + else + fRes = TRUE; // Write operation completed successfully. + } + } else + fRes = TRUE; // WriteFile completed immediately. + return fRes; +} + +inline bool ceSerial::Write(const char *data, long n) { + if (!IsOpened()) { + return false; + } + BOOL fRes; + DWORD dwWritten; + if (n < 0) + n = 0; + else if (n > 1024) + n = 1024; + + // Issue write. + if (!WriteFile(hComm, data, n, &dwWritten, &osWrite)) { // WriteFile failed, but it isn't delayed. Report error and abort. - if (GetLastError() != ERROR_IO_PENDING) {fRes = FALSE;} - else {// Write is pending. - if (!GetOverlappedResult(hComm, &osWrite, &dwWritten, TRUE)) fRes = FALSE; - else fRes = TRUE;// Write operation completed successfully. - } - } - else fRes = TRUE;// WriteFile completed immediately. - return fRes; -} - -inline bool ceSerial::WriteArr(const uint8_t *data,long n) { - if (!IsOpened()) { - return false; - } - BOOL fRes; - DWORD dwWritten; - if (n < 0) n = 0; - else if(n > 1024) n = 1024; - - // Issue write. - if (!WriteFile(hComm, data, n, &dwWritten, &osWrite)) { + if (GetLastError() != ERROR_IO_PENDING) { + fRes = FALSE; + } else { // Write is pending. + if (!GetOverlappedResult(hComm, &osWrite, &dwWritten, TRUE)) + fRes = FALSE; + else + fRes = TRUE; // Write operation completed successfully. + } + } else + fRes = TRUE; // WriteFile completed immediately. + return fRes; +} + +inline bool ceSerial::WriteArr(const uint8_t *data, long n) { + if (!IsOpened()) { + return false; + } + BOOL fRes; + DWORD dwWritten; + if (n < 0) + n = 0; + else if (n > 1024) + n = 1024; + + // Issue write. + if (!WriteFile(hComm, data, n, &dwWritten, &osWrite)) { // WriteFile failed, but it isn't delayed. Report error and abort. - if (GetLastError() != ERROR_IO_PENDING) {fRes = FALSE;} - else {// Write is pending. - if (!GetOverlappedResult(hComm, &osWrite, &dwWritten, TRUE)) fRes = FALSE; - else fRes = TRUE;// Write operation completed successfully. - } - } - else fRes = TRUE;// WriteFile completed immediately. - return fRes; -} - -inline bool ceSerial::WriteChar(const char ch) { - return Write((char*)&ch, 1); -} - -inline char ceSerial::ReadChar(bool& success) { - success = false; - if (!IsOpened()) {return 0;} - - DWORD dwRead; - DWORD length=1; - BYTE* data = (BYTE*)(&rxchar); - //the creation of the overlapped read operation - if (!fWaitingOnRead) { - // Issue read operation. - if (!ReadFile(hComm, data, length, &dwRead, &osReader)) { - if (GetLastError() != ERROR_IO_PENDING) { /*Error*/} - else { fWaitingOnRead = TRUE; /*Waiting*/} - } - else {if(dwRead==length) success = true;}//success - } - - - //detection of the completion of an overlapped read operation - DWORD dwRes; - if (fWaitingOnRead) { - dwRes = WaitForSingleObject(osReader.hEvent, READ_TIMEOUT); - switch (dwRes) - { - // Read completed. - case WAIT_OBJECT_0: - if (!GetOverlappedResult(hComm, &osReader, &dwRead, FALSE)) {/*Error*/ } - else { - if (dwRead == length) success = true; - fWaitingOnRead = FALSE; - // Reset flag so that another opertion can be issued. - }// Read completed successfully. - break; - - case WAIT_TIMEOUT: - // Operation isn't complete yet. - break; - - default: - // Error in the WaitForSingleObject; - break; - } - } - return rxchar; + if (GetLastError() != ERROR_IO_PENDING) { + fRes = FALSE; + } else { // Write is pending. + if (!GetOverlappedResult(hComm, &osWrite, &dwWritten, TRUE)) + fRes = FALSE; + else + fRes = TRUE; // Write operation completed successfully. + } + } else + fRes = TRUE; // WriteFile completed immediately. + return fRes; +} + +inline bool ceSerial::WriteChar(const char ch) { return Write(&ch, 1); } + +inline char ceSerial::ReadChar(bool &success) { + success = false; + if (!IsOpened()) { + return 0; + } + + DWORD dwRead; + DWORD length = 1; + BYTE *data = (BYTE *)(&rxchar); + // the creation of the overlapped read operation + if (!fWaitingOnRead) { + // Issue read operation. + if (!ReadFile(hComm, data, length, &dwRead, &osReader)) { + if (GetLastError() != ERROR_IO_PENDING) { /*Error*/ + } else { + fWaitingOnRead = TRUE; /*Waiting*/ + } + } else { + if (dwRead == length) + success = true; + } // success + } + + // detection of the completion of an overlapped read operation + DWORD dwRes; + if (fWaitingOnRead) { + dwRes = WaitForSingleObject(osReader.hEvent, READ_TIMEOUT); + switch (dwRes) { + // Read completed. + case WAIT_OBJECT_0: + if (!GetOverlappedResult(hComm, &osReader, &dwRead, FALSE)) { /*Error*/ + } else { + if (dwRead == length) + success = true; + fWaitingOnRead = FALSE; + // Reset flag so that another opertion can be issued. + } // Read completed successfully. + break; + + case WAIT_TIMEOUT: + // Operation isn't complete yet; cancel it so a fresh ReadFile can be issued next call. + CancelIo(hComm); + fWaitingOnRead = FALSE; + break; + + default: + // Error in the WaitForSingleObject; + break; + } + } + return rxchar; } inline bool ceSerial::SetRTS(bool value) { - bool r = false; - if (IsOpened()) { - if (value) { - if (EscapeCommFunction(hComm, SETRTS)) r = true; - } - else { - if (EscapeCommFunction(hComm, CLRRTS)) r = true; - } - } - return r; + bool r = false; + if (IsOpened()) { + if (value) { + if (EscapeCommFunction(hComm, SETRTS)) + r = true; + } else { + if (EscapeCommFunction(hComm, CLRRTS)) + r = true; + } + } + return r; } inline bool ceSerial::SetDTR(bool value) { - bool r = false; - if (IsOpened()) { - if (value) { - if (EscapeCommFunction(hComm, SETDTR)) r = true; - } - else { - if (EscapeCommFunction(hComm, CLRDTR)) r = true; - } - } - return r; -} - -inline bool ceSerial::GetCTS(bool& success) { - success = false; - bool r = false; - if (IsOpened()) { - DWORD dwModemStatus; - if (GetCommModemStatus(hComm, &dwModemStatus)){ - r = MS_CTS_ON & dwModemStatus; - success = true; - } - } - return r; -} - -inline bool ceSerial::GetDSR(bool& success) { - success = false; - bool r = false; - if (IsOpened()) { - DWORD dwModemStatus; - if (GetCommModemStatus(hComm, &dwModemStatus)) { - r = MS_DSR_ON & dwModemStatus; - success = true; - } - } - return r; -} - -inline bool ceSerial::GetRI(bool& success) { - success = false; - bool r = false; - if (IsOpened()) { - DWORD dwModemStatus; - if (GetCommModemStatus(hComm, &dwModemStatus)) { - r = MS_RING_ON & dwModemStatus; - success = true; - } - } - return r; -} - -inline bool ceSerial::GetCD(bool& success) { - success = false; - bool r = false; - if (IsOpened()) { - DWORD dwModemStatus; - if (GetCommModemStatus(hComm, &dwModemStatus)) { - r = MS_RLSD_ON & dwModemStatus; - success = true; - } - } - return r; -} - -#else //for POSIX + bool r = false; + if (IsOpened()) { + if (value) { + if (EscapeCommFunction(hComm, SETDTR)) + r = true; + } else { + if (EscapeCommFunction(hComm, CLRDTR)) + r = true; + } + } + return r; +} + +inline bool ceSerial::GetCTS(bool &success) { + success = false; + bool r = false; + if (IsOpened()) { + DWORD dwModemStatus; + if (GetCommModemStatus(hComm, &dwModemStatus)) { + r = MS_CTS_ON & dwModemStatus; + success = true; + } + } + return r; +} + +inline bool ceSerial::GetDSR(bool &success) { + success = false; + bool r = false; + if (IsOpened()) { + DWORD dwModemStatus; + if (GetCommModemStatus(hComm, &dwModemStatus)) { + r = MS_DSR_ON & dwModemStatus; + success = true; + } + } + return r; +} + +inline bool ceSerial::GetRI(bool &success) { + success = false; + bool r = false; + if (IsOpened()) { + DWORD dwModemStatus; + if (GetCommModemStatus(hComm, &dwModemStatus)) { + r = MS_RING_ON & dwModemStatus; + success = true; + } + } + return r; +} + +inline bool ceSerial::GetCD(bool &success) { + success = false; + bool r = false; + if (IsOpened()) { + DWORD dwModemStatus; + if (GetCommModemStatus(hComm, &dwModemStatus)) { + r = MS_RLSD_ON & dwModemStatus; + success = true; + } + } + return r; +} + +#else // for POSIX inline long ceSerial::Open(void) { - struct serial_struct serinfo; - struct termios settings; - memset(&settings, 0, sizeof(settings)); - settings.c_iflag = 0; - settings.c_oflag = 0; - - settings.c_cflag = CREAD | CLOCAL;//see termios.h for more information - if(dsize==5) settings.c_cflag |= CS5;//no change - else if (dsize == 6) settings.c_cflag |= CS6; - else if (dsize == 7) settings.c_cflag |= CS7; - else settings.c_cflag |= CS8; - - if(stopbits==2) settings.c_cflag |= CSTOPB; - - if(parity!='N') settings.c_cflag |= PARENB; - - if (parity == 'O') settings.c_cflag |= PARODD; - - settings.c_lflag = 0; - settings.c_cc[VMIN] = 1; - settings.c_cc[VTIME] = 0; - - fd = open(port.c_str(), O_RDWR | O_NONBLOCK); - if (fd == -1) { - return -1; - } - - if (!stdbaud) { - // serial driver to interpret the value B38400 differently - serinfo.reserved_char[0] = 0; - if (ioctl(fd, TIOCGSERIAL, &serinfo) < 0) { return -1;} - serinfo.flags &= ~ASYNC_SPD_MASK; - serinfo.flags |= ASYNC_SPD_CUST; - serinfo.custom_divisor = (serinfo.baud_base + (baud / 2)) / baud; - if (serinfo.custom_divisor < 1) serinfo.custom_divisor = 1; - if (ioctl(fd, TIOCSSERIAL, &serinfo) < 0) { return -1; } - if (ioctl(fd, TIOCGSERIAL, &serinfo) < 0) { return -1; } - if (serinfo.custom_divisor * baud != serinfo.baud_base) { - /* - warnx("actual baudrate is %d / %d = %f\n", - serinfo.baud_base, serinfo.custom_divisor, - (float)serinfo.baud_base / serinfo.custom_divisor); - */ - } - cfsetospeed(&settings, B38400); - cfsetispeed(&settings, B38400); - } - else { - cfsetospeed(&settings, baud); - cfsetispeed(&settings, baud); - } - tcsetattr(fd, TCSANOW, &settings); - int flags = fcntl(fd, F_GETFL, 0); - fcntl(fd, F_SETFL, flags | O_NONBLOCK); - - if (!stdbaud) { - // driver to interpret B38400 as 38400 baud again - ioctl(fd, TIOCGSERIAL, &serinfo); - serinfo.flags &= ~ASYNC_SPD_MASK; - ioctl(fd, TIOCSSERIAL, &serinfo); - } - return 0; + struct serial_struct serinfo; + struct termios settings; + memset(&settings, 0, sizeof(settings)); + settings.c_iflag = 0; + settings.c_oflag = 0; + + settings.c_cflag = CREAD | CLOCAL; // see termios.h for more information + if (dsize == 5) + settings.c_cflag |= CS5; // no change + else if (dsize == 6) + settings.c_cflag |= CS6; + else if (dsize == 7) + settings.c_cflag |= CS7; + else + settings.c_cflag |= CS8; + + if (stopbits == 2) + settings.c_cflag |= CSTOPB; + + if (parity != 'N') + settings.c_cflag |= PARENB; + + if (parity == 'O') + settings.c_cflag |= PARODD; + + settings.c_lflag = 0; + settings.c_cc[VMIN] = 1; + settings.c_cc[VTIME] = 0; + + fd = open(port.c_str(), O_RDWR | O_NONBLOCK); + if (fd == -1) { + return -1; + } + + // Close fd and reset it so a failed Open() doesn't leak it or leave + // IsOpened() reporting true. + auto fail = [&]() -> long { + close(fd); + fd = -1; + return -1; + }; + + if (!stdbaud) { + // serial driver to interpret the value B38400 differently + serinfo.reserved_char[0] = 0; + if (ioctl(fd, TIOCGSERIAL, &serinfo) < 0) { + return fail(); + } + serinfo.flags &= ~ASYNC_SPD_MASK; + serinfo.flags |= ASYNC_SPD_CUST; + serinfo.custom_divisor = (serinfo.baud_base + (baud / 2)) / baud; + if (serinfo.custom_divisor < 1) + serinfo.custom_divisor = 1; + if (ioctl(fd, TIOCSSERIAL, &serinfo) < 0) { + return fail(); + } + if (ioctl(fd, TIOCGSERIAL, &serinfo) < 0) { + return fail(); + } + if (serinfo.custom_divisor * baud != serinfo.baud_base) { + /* + warnx("actual baudrate is %d / %d = %f\n", + serinfo.baud_base, serinfo.custom_divisor, + (float)serinfo.baud_base / serinfo.custom_divisor); + */ + } + cfsetospeed(&settings, B38400); + cfsetispeed(&settings, B38400); + } else { + cfsetospeed(&settings, baud); + cfsetispeed(&settings, baud); + } + tcsetattr(fd, TCSANOW, &settings); + int flags = fcntl(fd, F_GETFL, 0); + fcntl(fd, F_SETFL, flags | O_NONBLOCK); + + if (!stdbaud) { + // driver to interpret B38400 as 38400 baud again + ioctl(fd, TIOCGSERIAL, &serinfo); + serinfo.flags &= ~ASYNC_SPD_MASK; + ioctl(fd, TIOCSSERIAL, &serinfo); + } + return 0; } inline void ceSerial::Close() { - if(IsOpened()) close(fd); - fd=-1; + if (IsOpened()) + close(fd); + fd = -1; } inline bool ceSerial::IsOpened() { - if(fd== (-1)) return false; - else return true; + if (fd == (-1)) + return false; + else + return true; } inline void ceSerial::SetBaudRate(long baudrate) { - stdbaud = true; - if (baudrate == 0) baud = B0; - else if (baudrate == 50) baud = B50; - else if (baudrate == 75) baud = B75; - else if (baudrate == 110) baud = B110; - else if (baudrate == 134) baud = B134; - else if (baudrate == 150) baud = B150; - else if (baudrate == 200) baud = B200; - else if (baudrate == 300) baud = B300; - else if (baudrate == 600) baud = B600; - else if (baudrate == 1200) baud = B1200; - else if (baudrate == 2400) baud = B2400; - else if (baudrate == 4800) baud = B4800; - else if (baudrate == 9600) baud = B9600; - else if (baudrate == 19200) baud = B19200; - else if (baudrate == 38400) baud = B38400; - else if (baudrate == 57600) baud = B57600; - else if (baudrate == 115200) baud = B115200; - else if (baudrate == 230400) baud = B230400; - else { - baud = baudrate; - stdbaud = false; - } -} - -inline long ceSerial::GetBaudRate() { - return baud; -} - -inline char ceSerial::ReadChar(bool& success) { - success=false; - if (!IsOpened()) {return 0; } - success=read(fd, &rxchar, 1)==1; - return rxchar; + stdbaud = true; + if (baudrate == 0) + baud = B0; + else if (baudrate == 50) + baud = B50; + else if (baudrate == 75) + baud = B75; + else if (baudrate == 110) + baud = B110; + else if (baudrate == 134) + baud = B134; + else if (baudrate == 150) + baud = B150; + else if (baudrate == 200) + baud = B200; + else if (baudrate == 300) + baud = B300; + else if (baudrate == 600) + baud = B600; + else if (baudrate == 1200) + baud = B1200; + else if (baudrate == 2400) + baud = B2400; + else if (baudrate == 4800) + baud = B4800; + else if (baudrate == 9600) + baud = B9600; + else if (baudrate == 19200) + baud = B19200; + else if (baudrate == 38400) + baud = B38400; + else if (baudrate == 57600) + baud = B57600; + else if (baudrate == 115200) + baud = B115200; + else if (baudrate == 230400) + baud = B230400; + else { + baud = baudrate; + stdbaud = false; + } +} + +inline long ceSerial::GetBaudRate() { return baud; } + +inline char ceSerial::ReadChar(bool &success) { + success = false; + if (!IsOpened()) { + return 0; + } + success = read(fd, &rxchar, 1) == 1; + return rxchar; } inline bool ceSerial::Write(const char *data) { - if (!IsOpened()) {return false; } - long n = strlen(data); - if (n < 0) n = 0; - else if(n > 1024) n = 1024; - return (write(fd, data, n)==n); -} - -inline bool ceSerial::Write(const char *data,long n) { - if (!IsOpened()) {return false; } - if (n < 0) n = 0; - else if(n > 1024) n = 1024; - return (write(fd, data, n)==n); -} - -inline bool ceSerial::WriteArr(const uint8_t *data,long n) { - if (!IsOpened()) {return false; } - if (n < 0) n = 0; - else if(n > 1024) n = 1024; - return (write(fd, data, n)==n); -} - -inline bool ceSerial::WriteChar(const char ch) { - return Write((char*)&ch, 1); -} + if (!IsOpened() || !data) { + return false; + } + long n = strlen(data); + if (n < 0) + n = 0; + else if (n > 1024) + n = 1024; + return (write(fd, data, n) == n); +} + +inline bool ceSerial::Write(const char *data, long n) { + if (!IsOpened()) { + return false; + } + if (n < 0) + n = 0; + else if (n > 1024) + n = 1024; + return (write(fd, data, n) == n); +} + +inline bool ceSerial::WriteArr(const uint8_t *data, long n) { + if (!IsOpened()) { + return false; + } + if (n < 0) + n = 0; + else if (n > 1024) + n = 1024; + return (write(fd, data, n) == n); +} + +inline bool ceSerial::WriteChar(const char ch) { return Write(&ch, 1); } inline bool ceSerial::SetRTS(bool value) { - long RTS_flag = TIOCM_RTS; - bool success=true; - if (value) {//Set RTS pin - if (ioctl(fd, TIOCMBIS, &RTS_flag) == -1) success=false; - } - else {//Clear RTS pin - if (ioctl(fd, TIOCMBIC, &RTS_flag) == -1) success=false; - } - return success; + long RTS_flag = TIOCM_RTS; + bool success = true; + if (value) { // Set RTS pin + if (ioctl(fd, TIOCMBIS, &RTS_flag) == -1) + success = false; + } else { // Clear RTS pin + if (ioctl(fd, TIOCMBIC, &RTS_flag) == -1) + success = false; + } + return success; } inline bool ceSerial::SetDTR(bool value) { - long DTR_flag = TIOCM_DTR; - bool success=true; - if (value) {//Set DTR pin - if (ioctl(fd, TIOCMBIS, &DTR_flag) == -1) success=false; - } - else {//Clear DTR pin - if (ioctl(fd, TIOCMBIC, &DTR_flag) == -1) success=false; - } - return success; -} - -inline bool ceSerial::GetCTS(bool& success) { - success=true; - long status; - if(ioctl(fd, TIOCMGET, &status)== -1) success=false; - return ((status & TIOCM_CTS) != 0); -} - -inline bool ceSerial::GetDSR(bool& success) { - success=true; - long status; - if(ioctl(fd, TIOCMGET, &status)== -1) success=false; - return ((status & TIOCM_DSR) != 0); -} - -inline bool ceSerial::GetRI(bool& success) { - success=true; - long status; - if(ioctl(fd, TIOCMGET, &status)== -1) success=false; - return ((status & TIOCM_RI) != 0); -} - -inline bool ceSerial::GetCD(bool& success) { - success=true; - long status; - if(ioctl(fd, TIOCMGET, &status)== -1) success=false; - return ((status & TIOCM_CD) != 0); + long DTR_flag = TIOCM_DTR; + bool success = true; + if (value) { // Set DTR pin + if (ioctl(fd, TIOCMBIS, &DTR_flag) == -1) + success = false; + } else { // Clear DTR pin + if (ioctl(fd, TIOCMBIC, &DTR_flag) == -1) + success = false; + } + return success; +} + +inline bool ceSerial::GetCTS(bool &success) { + success = true; + long status; + if (ioctl(fd, TIOCMGET, &status) == -1) + success = false; + return ((status & TIOCM_CTS) != 0); +} + +inline bool ceSerial::GetDSR(bool &success) { + success = true; + long status; + if (ioctl(fd, TIOCMGET, &status) == -1) + success = false; + return ((status & TIOCM_DSR) != 0); +} + +inline bool ceSerial::GetRI(bool &success) { + success = true; + long status; + if (ioctl(fd, TIOCMGET, &status) == -1) + success = false; + return ((status & TIOCM_RI) != 0); +} + +inline bool ceSerial::GetCD(bool &success) { + success = true; + long status; + if (ioctl(fd, TIOCMGET, &status) == -1) + success = false; + return ((status & TIOCM_CD) != 0); } #endif diff --git a/serialgui/test_frame.cpp b/serialgui/test_frame.cpp index 67efb62..32bb8f3 100644 --- a/serialgui/test_frame.cpp +++ b/serialgui/test_frame.cpp @@ -6,9 +6,9 @@ using namespace std; // ---------------------------------------------------------------------------- // frame constructor -MyFrame::MyFrame(const wxString& title) - : wxFrame(NULL, wxID_ANY, title,wxDefaultPosition,wxSize(390, 280), wxDEFAULT_FRAME_STYLE ^ wxRESIZE_BORDER),m_timer(this, ID_TIMER) -{ +MyFrame::MyFrame(const wxString &title) + : wxFrame(NULL, wxID_ANY, title, wxDefaultPosition, wxSize(390, 280), wxDEFAULT_FRAME_STYLE ^ wxRESIZE_BORDER), + m_timer(this, ID_TIMER) { // set the frame icon SetIcon(wxICON(sample)); @@ -16,28 +16,27 @@ MyFrame::MyFrame(const wxString& title) // create a menu bar wxMenu *fileMenu = new wxMenu; - //Edit menu - wxMenu *editMenu = new wxMenu; + // Edit menu + wxMenu *editMenu = new wxMenu; // the "About" item should be in the help menu wxMenu *helpMenu = new wxMenu; helpMenu->Append(Minimal_About, wxT("&About\tF1"), wxT("Show about dialog")); fileMenu->Append(Serial_Open, wxT("&Open\tAlt-O"), wxT("Open serial port")); - fileMenu->Append(Serial_Close, wxT("&Close\tAlt-C"), wxT("Close serial port")); - editMenu->Append(Txt_Clear, wxT("Clea&r\tAlt-R"), wxT("Clear text")); - fileMenu->Append(Serial_Port, wxT("&Serial Port\tAlt-S"), wxT("Select serial port")); - fileMenu->Append(Serial_Baud, wxT("&Baud Rate\tAlt-B"), wxT("Set baud rate")); - fileMenu->Append(Serial_DataSize, wxT("&Data Size\tAlt-D"), wxT("Set data size")); - fileMenu->Append(Serial_Parity, wxT("&Parity\tAlt-P"), wxT("Set parity")); - fileMenu->Append(Serial_StopBits, wxT("S&top Bits\tAlt-t"), wxT("Set stop bits")); - fileMenu->Append(Minimal_Quit, wxT("E&xit\tAlt-X"), wxT("Quit this program")); - + fileMenu->Append(Serial_Close, wxT("&Close\tAlt-C"), wxT("Close serial port")); + editMenu->Append(Txt_Clear, wxT("Clea&r\tAlt-R"), wxT("Clear text")); + fileMenu->Append(Serial_Port, wxT("&Serial Port\tAlt-S"), wxT("Select serial port")); + fileMenu->Append(Serial_Baud, wxT("&Baud Rate\tAlt-B"), wxT("Set baud rate")); + fileMenu->Append(Serial_DataSize, wxT("&Data Size\tAlt-D"), wxT("Set data size")); + fileMenu->Append(Serial_Parity, wxT("&Parity\tAlt-P"), wxT("Set parity")); + fileMenu->Append(Serial_StopBits, wxT("S&top Bits\tAlt-t"), wxT("Set stop bits")); + fileMenu->Append(Minimal_Quit, wxT("E&xit\tAlt-X"), wxT("Quit this program")); // now append the freshly created menu to the menu bar... wxMenuBar *menuBar = new wxMenuBar(); menuBar->Append(fileMenu, wxT("&File")); - menuBar->Append(editMenu, wxT("&Edit")); + menuBar->Append(editMenu, wxT("&Edit")); menuBar->Append(helpMenu, wxT("&Help")); // ... and attach this menu bar to the frame @@ -49,204 +48,186 @@ MyFrame::MyFrame(const wxString& title) CreateStatusBar(2); SetStatusText(wxT("Serial Communication")); #endif // wxUSE_STATUSBAR - btnSend = new wxButton(this,Button_Send,wxT( "Send"), wxPoint(5, 5), wxSize(100, 25)); - txtSend = new wxTextCtrl(this,Txt_Send,wxT("Hello!"),wxPoint(120,5),wxSize(250,25)); - //lblRx = new wxStaticText(this, ID_LBLRX, wxT("Rx:"), wxPoint(5, 75), wxSize(35, 25)); - txtRx = new wxTextCtrl(this, Txt_Rx, wxT(""), wxPoint(5, 35), wxSize(365, 125), wxTE_MULTILINE); - chkRTS = new wxCheckBox(this, Chk_RTS, wxT("RTS"), wxPoint(5, 170), wxDefaultSize); - chkDTR = new wxCheckBox(this, Chk_DTR, wxT("DTR"), wxPoint(55, 170), wxDefaultSize); - chkCTS = new wxCheckBox(this, ID_CHKCTS, wxT("CTS"), wxPoint(155, 170), wxDefaultSize); - chkDSR = new wxCheckBox(this, ID_CHKDSR, wxT("DSR"), wxPoint(205, 170), wxDefaultSize); - chkRI = new wxCheckBox(this, ID_CHKRI, wxT("RI"), wxPoint(255, 170), wxDefaultSize); - chkCD = new wxCheckBox(this, ID_CHKCD, wxT("CD"), wxPoint(305, 170), wxDefaultSize); - - Connect(Button_Send, wxEVT_COMMAND_BUTTON_CLICKED,wxCommandEventHandler(MyFrame::OnSend)); - Connect(Minimal_About,wxEVT_COMMAND_MENU_SELECTED,wxCommandEventHandler(MyFrame::OnAbout)); - Connect(Minimal_Quit,wxEVT_COMMAND_MENU_SELECTED,wxCommandEventHandler(MyFrame::OnQuit)); - Connect(Serial_Open,wxEVT_COMMAND_MENU_SELECTED,wxCommandEventHandler(MyFrame::OnOpen)); - Connect(Serial_Close,wxEVT_COMMAND_MENU_SELECTED,wxCommandEventHandler(MyFrame::OnClose)); - Connect(Serial_Port, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::SelPort)); - Connect(Serial_Baud, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::SetBaud)); - Connect(Serial_DataSize, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::SetDataSize)); - Connect(Serial_Parity, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::SetParity)); - Connect(Serial_StopBits, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::SetStopBits)); - Connect(Timer1,wxEVT_TIMER, wxTimerEventHandler(MyFrame::OnTimer)); - Connect(Txt_Clear, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::ClearText)); - Connect(Chk_RTS,wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler(MyFrame::OnChkRTS)); - Connect(Chk_DTR,wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler(MyFrame::OnChkDTR)); - //Bind(wxEVT_MENU, &MyFrame::OnClose, this, Serial_Close); - m_timer.Start(250); - chkCTS->Disable(); - chkDSR->Disable(); - chkRI->Disable(); - chkCD->Disable(); + btnSend = new wxButton(this, Button_Send, wxT("Send"), wxPoint(5, 5), wxSize(100, 25)); + txtSend = new wxTextCtrl(this, Txt_Send, wxT("Hello!"), wxPoint(120, 5), wxSize(250, 25)); + // lblRx = new wxStaticText(this, ID_LBLRX, wxT("Rx:"), wxPoint(5, 75), wxSize(35, 25)); + txtRx = new wxTextCtrl(this, Txt_Rx, wxT(""), wxPoint(5, 35), wxSize(365, 125), wxTE_MULTILINE); + chkRTS = new wxCheckBox(this, Chk_RTS, wxT("RTS"), wxPoint(5, 170), wxDefaultSize); + chkDTR = new wxCheckBox(this, Chk_DTR, wxT("DTR"), wxPoint(55, 170), wxDefaultSize); + chkCTS = new wxCheckBox(this, ID_CHKCTS, wxT("CTS"), wxPoint(155, 170), wxDefaultSize); + chkDSR = new wxCheckBox(this, ID_CHKDSR, wxT("DSR"), wxPoint(205, 170), wxDefaultSize); + chkRI = new wxCheckBox(this, ID_CHKRI, wxT("RI"), wxPoint(255, 170), wxDefaultSize); + chkCD = new wxCheckBox(this, ID_CHKCD, wxT("CD"), wxPoint(305, 170), wxDefaultSize); + + Connect(Button_Send, wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(MyFrame::OnSend)); + Connect(Minimal_About, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::OnAbout)); + Connect(Minimal_Quit, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::OnQuit)); + Connect(Serial_Open, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::OnOpen)); + Connect(Serial_Close, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::OnClose)); + Connect(Serial_Port, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::SelPort)); + Connect(Serial_Baud, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::SetBaud)); + Connect(Serial_DataSize, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::SetDataSize)); + Connect(Serial_Parity, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::SetParity)); + Connect(Serial_StopBits, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::SetStopBits)); + Connect(Timer1, wxEVT_TIMER, wxTimerEventHandler(MyFrame::OnTimer)); + Connect(Txt_Clear, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::ClearText)); + Connect(Chk_RTS, wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler(MyFrame::OnChkRTS)); + Connect(Chk_DTR, wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler(MyFrame::OnChkDTR)); + // Bind(wxEVT_MENU, &MyFrame::OnClose, this, Serial_Close); + m_timer.Start(250); + chkCTS->Disable(); + chkDSR->Disable(); + chkRI->Disable(); + chkCD->Disable(); } - // event handlers -void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event)) -{ +void MyFrame::OnQuit(wxCommandEvent &WXUNUSED(event)) { // true is to force the frame to close Close(true); } -void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event)) -{ - wxMessageBox(wxString::Format( - wxT("Serial Communication! \n ") - wxT("Author: Yan Naing Aye \n ") - wxT("Web: https://github.com/yan9a/serial") - ), - wxT("About Serial Comm"), - wxOK | wxICON_INFORMATION, - this); +void MyFrame::OnAbout(wxCommandEvent &WXUNUSED(event)) { + wxMessageBox(wxString::Format(wxT("Serial Communication! \n ") wxT("Author: Yan Naing Aye \n ") + wxT("Web: https://github.com/yan9a/serial")), + wxT("About Serial Comm"), wxOK | wxICON_INFORMATION, this); } -void MyFrame::OnOpen(wxCommandEvent& WXUNUSED(event)) -{ - if(com.Open()) txtRx->AppendText(wxString::Format(wxT("Error opening port %s.\n"),com.GetPort())); - else txtRx->AppendText(wxString::Format(wxT("Port %s is opened.\n"), com.GetPort())); +void MyFrame::OnOpen(wxCommandEvent &WXUNUSED(event)) { + if (com.Open()) + txtRx->AppendText(wxString::Format(wxT("Error opening port %s.\n"), com.GetPort())); + else + txtRx->AppendText(wxString::Format(wxT("Port %s is opened.\n"), com.GetPort())); } -void MyFrame::OnClose(wxCommandEvent& WXUNUSED(event)) -{ - com.Close(); - txtRx->AppendText(wxString::Format(wxT("Port %s is closed.\n"), com.GetPort())); +void MyFrame::OnClose(wxCommandEvent &WXUNUSED(event)) { + com.Close(); + txtRx->AppendText(wxString::Format(wxT("Port %s is closed.\n"), com.GetPort())); } -void MyFrame::SelPort(wxCommandEvent& WXUNUSED(event)) -{ - if (com.IsOpened()) { - txtRx->AppendText(wxString::Format(wxT("Close Port %s first.\n"), com.GetPort())); - } - else { - wxString cdev=wxString::Format(wxT("%s"), com.GetPort()); - wxString device = wxGetTextFromUser(wxT("Enter the port"), wxT("Set Port"), cdev); - string str = device.ToStdString(); - if (str.length() > 0) { - com.SetPortName(str); - } +void MyFrame::SelPort(wxCommandEvent &WXUNUSED(event)) { + if (com.IsOpened()) { + txtRx->AppendText(wxString::Format(wxT("Close Port %s first.\n"), com.GetPort())); + } else { + wxString cdev = wxString::Format(wxT("%s"), com.GetPort()); + wxString device = wxGetTextFromUser(wxT("Enter the port"), wxT("Set Port"), cdev); + string str = device.ToStdString(); + if (str.length() > 0) { + com.SetPortName(str); + } txtRx->AppendText(wxString::Format(wxT("Port: %s\n"), com.GetPort())); - } + } } -void MyFrame::SetParity(wxCommandEvent& WXUNUSED(event)) -{ - if (com.IsOpened()) { - txtRx->AppendText(wxString::Format(wxT("Close Port %s first.\n"), com.GetPort())); - } - else { - wxString cdev = wxString::Format(wxT("%c"), com.GetParity()); +void MyFrame::SetParity(wxCommandEvent &WXUNUSED(event)) { + if (com.IsOpened()) { + txtRx->AppendText(wxString::Format(wxT("Close Port %s first.\n"), com.GetPort())); + } else { + wxString cdev = wxString::Format(wxT("%c"), com.GetParity()); #if defined(__WINDOWS__) - wxString parity = wxGetTextFromUser(wxT("Enter the parity ( N, E, O, M, or S )"), wxT("Set Parity"), cdev); + wxString parity = wxGetTextFromUser(wxT("Enter the parity ( N, E, O, M, or S )"), wxT("Set Parity"), cdev); #else - wxString parity = wxGetTextFromUser(wxT("Enter the parity ( N, E, or O )"), wxT("Set Parity"), cdev); + wxString parity = wxGetTextFromUser(wxT("Enter the parity ( N, E, or O )"), wxT("Set Parity"), cdev); #endif - string pstr = parity.ToStdString(); - if (pstr.length() > 0) { - com.SetParity(pstr.at(0)); - } - txtRx->AppendText(wxString::Format(wxT("Parity: %c\n"), com.GetParity())); - } -} - -void MyFrame::SetBaud(wxCommandEvent& WXUNUSED(event)) -{ - if (com.IsOpened()) { - txtRx->AppendText(wxString::Format(wxT("Close port %s first.\n"), com.GetPort())); - } - else { - long n = wxGetNumberFromUser(wxT("Enter the baud rate"), wxT("Baud rate"), wxT("Set Baud Rate"),com.GetBaudRate(),0, 1000000); - if (n >= 0) { - com.SetBaudRate(n); - } - txtRx->AppendText(wxString::Format(wxT("Baud rate: %ld\n"), com.GetBaudRate())); - } -} - -void MyFrame::SetDataSize(wxCommandEvent& WXUNUSED(event)) -{ - if (com.IsOpened()) { - txtRx->AppendText(wxString::Format(wxT("Close port %s first.\n"), com.GetPort())); - } - else { - long n = wxGetNumberFromUser(wxT("Enter the data size"), wxT("Data Size"), wxT("Set Data Size"), com.GetDataSize(), 5, 8); - if (n >= 0) { - com.SetDataSize(n); - } - txtRx->AppendText(wxString::Format(wxT("Data size: %ld\n"), com.GetDataSize())); - } -} - -void MyFrame::SetStopBits(wxCommandEvent& WXUNUSED(event)) -{ - if (com.IsOpened()) { - txtRx->AppendText(wxString::Format(wxT("Close port %s first.\n"), com.GetPort())); - } - else { - long n = wxGetNumberFromUser(wxT("Enter the number of stop bits"), wxT("Data Size"), wxT("Set stop bits"), long(com.GetStopBits()), 1, 2); - if (n > 0) { - com.SetStopBits(float(n)); - } - txtRx->AppendText(wxString::Format(wxT("Stop bits: %ld\n"), long(com.GetStopBits()))); - } -} - -void MyFrame::OnSend(wxCommandEvent& WXUNUSED(event)) -{ - wxString str = txtSend->GetValue(); - wxCharBuffer buffer = str.ToUTF8(); - if (com.Write(buffer.data())) { - txtRx->AppendText(str); - } - else { - txtRx->AppendText(wxT("Write error.\n")); - } -} - -void MyFrame::OnTimer(wxTimerEvent& WXUNUSED(event)) -{ - char ch; bool r; - do {ch = com.ReadChar(r);if (r) ProcessChar(ch);} while (r); - UpdateCommStatus(); -} - -void MyFrame::ProcessChar(char ch) -{ - txtRx->AppendText(wxString::Format(wxT("%c"), ch)); -} - -void MyFrame::ClearText(wxCommandEvent& WXUNUSED(event)) -{ - txtRx->Clear(); -} - -void MyFrame::OnChkRTS(wxCommandEvent& WXUNUSED(event)) -{ - if (!com.SetRTS(chkRTS->IsChecked())) { - txtRx->AppendText(wxT("RTS error.\n")); - } -} - -void MyFrame::OnChkDTR(wxCommandEvent& WXUNUSED(event)) -{ - if (!com.SetDTR(chkDTR->IsChecked())) { - txtRx->AppendText(wxT("DTR error.\n")); - } -} - -void MyFrame::UpdateCommStatus() -{ - bool s; - bool v; - v = com.GetCTS(s); - if (s) chkCTS->SetValue(v); - v = com.GetDSR(s); - if (s) chkDSR->SetValue(v); - v = com.GetRI(s); - if (s) chkRI->SetValue(v); - v = com.GetCD(s); - if (s) chkCD->SetValue(v); + string pstr = parity.ToStdString(); + if (pstr.length() > 0) { + com.SetParity(pstr.at(0)); + } + txtRx->AppendText(wxString::Format(wxT("Parity: %c\n"), com.GetParity())); + } +} + +void MyFrame::SetBaud(wxCommandEvent &WXUNUSED(event)) { + if (com.IsOpened()) { + txtRx->AppendText(wxString::Format(wxT("Close port %s first.\n"), com.GetPort())); + } else { + long n = wxGetNumberFromUser(wxT("Enter the baud rate"), wxT("Baud rate"), wxT("Set Baud Rate"), + com.GetBaudRate(), 0, 1000000); + if (n >= 0) { + com.SetBaudRate(n); + } + txtRx->AppendText(wxString::Format(wxT("Baud rate: %ld\n"), com.GetBaudRate())); + } +} + +void MyFrame::SetDataSize(wxCommandEvent &WXUNUSED(event)) { + if (com.IsOpened()) { + txtRx->AppendText(wxString::Format(wxT("Close port %s first.\n"), com.GetPort())); + } else { + long n = wxGetNumberFromUser(wxT("Enter the data size"), wxT("Data Size"), wxT("Set Data Size"), + com.GetDataSize(), 5, 8); + if (n >= 0) { + com.SetDataSize(n); + } + txtRx->AppendText(wxString::Format(wxT("Data size: %ld\n"), com.GetDataSize())); + } +} + +void MyFrame::SetStopBits(wxCommandEvent &WXUNUSED(event)) { + if (com.IsOpened()) { + txtRx->AppendText(wxString::Format(wxT("Close port %s first.\n"), com.GetPort())); + } else { + long n = wxGetNumberFromUser(wxT("Enter the number of stop bits"), wxT("Data Size"), wxT("Set stop bits"), + long(com.GetStopBits()), 1, 2); + if (n > 0) { + com.SetStopBits(float(n)); + } + txtRx->AppendText(wxString::Format(wxT("Stop bits: %ld\n"), long(com.GetStopBits()))); + } +} + +void MyFrame::OnSend(wxCommandEvent &WXUNUSED(event)) { + wxString str = txtSend->GetValue(); + wxCharBuffer buffer = str.ToUTF8(); + if (com.Write(buffer.data())) { + txtRx->AppendText(str); + } else { + txtRx->AppendText(wxT("Write error.\n")); + } +} + +void MyFrame::OnTimer(wxTimerEvent &WXUNUSED(event)) { + char ch; + bool r; + do { + ch = com.ReadChar(r); + if (r) + ProcessChar(ch); + } while (r); + UpdateCommStatus(); +} + +void MyFrame::ProcessChar(char ch) { txtRx->AppendText(wxString::Format(wxT("%c"), ch)); } + +void MyFrame::ClearText(wxCommandEvent &WXUNUSED(event)) { txtRx->Clear(); } + +void MyFrame::OnChkRTS(wxCommandEvent &WXUNUSED(event)) { + if (!com.SetRTS(chkRTS->IsChecked())) { + txtRx->AppendText(wxT("RTS error.\n")); + } +} + +void MyFrame::OnChkDTR(wxCommandEvent &WXUNUSED(event)) { + if (!com.SetDTR(chkDTR->IsChecked())) { + txtRx->AppendText(wxT("DTR error.\n")); + } +} + +void MyFrame::UpdateCommStatus() { + bool s; + bool v; + v = com.GetCTS(s); + if (s) + chkCTS->SetValue(v); + v = com.GetDSR(s); + if (s) + chkDSR->SetValue(v); + v = com.GetRI(s); + if (s) + chkRI->SetValue(v); + v = com.GetCD(s); + if (s) + chkCD->SetValue(v); } diff --git a/serialgui/test_gui.cpp b/serialgui/test_gui.cpp index 2d18fea..414c41a 100644 --- a/serialgui/test_gui.cpp +++ b/serialgui/test_gui.cpp @@ -1,7 +1,7 @@ // ---------------------------------------------------------------------------- // private classes -#include "ceserial.h" #include "test_gui.h" +#include "ceserial.h" using namespace std; // ---------------------------------------------------------------------------- // Create a new application object: this macro will allow wxWidgets to create @@ -20,11 +20,10 @@ IMPLEMENT_APP(MyApp) // ---------------------------------------------------------------------------- // 'Main program' equivalent: the program execution "starts" here -bool MyApp::OnInit() -{ +bool MyApp::OnInit() { // call the base class initialization method, currently it only parses a // few common command-line options but it could be do more in the future - if ( !wxApp::OnInit() ) + if (!wxApp::OnInit()) return false; // create the main application window diff --git a/serialgui/test_gui.h b/serialgui/test_gui.h index ee54319..4bf73c9 100644 --- a/serialgui/test_gui.h +++ b/serialgui/test_gui.h @@ -1,25 +1,25 @@ -//Description: Serial communication for wxWidgets -//WebSite: http://cool-emerald.blogspot.sg/2017/05/serial-port-programming-in-c-with.html -//MIT License (https://opensource.org/licenses/MIT) -//Copyright (c) 2017 Yan Naing Aye +// Description: Serial communication for wxWidgets +// WebSite: http://cool-emerald.blogspot.sg/2017/05/serial-port-programming-in-c-with.html +// MIT License (https://opensource.org/licenses/MIT) +// Copyright (c) 2017 Yan Naing Aye // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ - #pragma hdrstop +#pragma hdrstop #endif // for all others, include the necessary headers (this file is usually all you // need because it includes almost all "standard" wxWidgets headers) #ifndef WX_PRECOMP - #include "wx/wx.h" +#include "wx/wx.h" #endif // the application icon (under Windows and OS/2 it is in resources and even // though we could still include the XPM here it would be unused) #ifndef wxHAS_IMAGES_IN_RESOURCES - #include "sample.xpm" +#include "sample.xpm" #endif #include @@ -30,9 +30,8 @@ using namespace std; // ---------------------------------------------------------------------------- // Define a new application type, each program should derive a class from wxApp -class MyApp : public wxApp -{ -public: +class MyApp : public wxApp { + public: // override base class virtuals // ---------------------------- @@ -43,41 +42,40 @@ class MyApp : public wxApp }; // Define a new frame type: this is going to be our main frame -class MyFrame : public wxFrame -{ -public: +class MyFrame : public wxFrame { + public: // ctor(s) - MyFrame(const wxString& title); - wxButton *btnSend; - wxTextCtrl *txtSend; - ceSerial com; - wxTimer m_timer; - wxTextCtrl *txtRx; - wxCheckBox *chkRTS; - wxCheckBox *chkDTR; - wxCheckBox *chkCTS; - wxCheckBox *chkDSR; - wxCheckBox *chkRI; - wxCheckBox *chkCD; + MyFrame(const wxString &title); + wxButton *btnSend; + wxTextCtrl *txtSend; + ceSerial com; + wxTimer m_timer; + wxTextCtrl *txtRx; + wxCheckBox *chkRTS; + wxCheckBox *chkDTR; + wxCheckBox *chkCTS; + wxCheckBox *chkDSR; + wxCheckBox *chkRI; + wxCheckBox *chkCD; // event handlers (these functions should _not_ be virtual) - void OnQuit(wxCommandEvent& event); - void OnAbout(wxCommandEvent& event); - void OnOpen(wxCommandEvent& event); - void OnClose(wxCommandEvent& event); - void SelPort(wxCommandEvent& event); - void SetDataSize(wxCommandEvent& event); - void SetParity(wxCommandEvent& event); - void SetStopBits(wxCommandEvent& event); - void SetBaud(wxCommandEvent& event); - void OnSend(wxCommandEvent& event); - void OnTimer(wxTimerEvent& event); - void ProcessChar(char ch); - void ClearText(wxCommandEvent& event); - void OnChkRTS(wxCommandEvent& event); - void OnChkDTR(wxCommandEvent& event); - void UpdateCommStatus(); -private: + void OnQuit(wxCommandEvent &event); + void OnAbout(wxCommandEvent &event); + void OnOpen(wxCommandEvent &event); + void OnClose(wxCommandEvent &event); + void SelPort(wxCommandEvent &event); + void SetDataSize(wxCommandEvent &event); + void SetParity(wxCommandEvent &event); + void SetStopBits(wxCommandEvent &event); + void SetBaud(wxCommandEvent &event); + void OnSend(wxCommandEvent &event); + void OnTimer(wxTimerEvent &event); + void ProcessChar(char ch); + void ClearText(wxCommandEvent &event); + void OnChkRTS(wxCommandEvent &event); + void OnChkDTR(wxCommandEvent &event); + void UpdateCommStatus(); + private: }; // constants // ---------------------------------------------------------------------------- @@ -99,23 +97,22 @@ const int ID_DATASIZE = 112; const int ID_PARITY = 113; const int ID_STOPBITS = 114; -enum -{ - Button_Send = ID_BTNSEND, - Txt_Send = ID_TXTSEND, - Chk_RTS = ID_CHKRTS, - Serial_Baud = ID_BAUDRATE, - Timer1 = ID_TIMER, - Txt_Rx =ID_TXTRX, - Chk_DTR = ID_CHKDTR, - Serial_Port = ID_SELPORT, - Serial_DataSize=ID_DATASIZE, - Serial_Parity=ID_PARITY, - Serial_StopBits=ID_STOPBITS, - Txt_Clear = wxID_CLEAR, - Serial_Open = wxID_OPEN, - Serial_Close = wxID_CLOSE, - Minimal_Quit = wxID_EXIT, +enum { + Button_Send = ID_BTNSEND, + Txt_Send = ID_TXTSEND, + Chk_RTS = ID_CHKRTS, + Serial_Baud = ID_BAUDRATE, + Timer1 = ID_TIMER, + Txt_Rx = ID_TXTRX, + Chk_DTR = ID_CHKDTR, + Serial_Port = ID_SELPORT, + Serial_DataSize = ID_DATASIZE, + Serial_Parity = ID_PARITY, + Serial_StopBits = ID_STOPBITS, + Txt_Clear = wxID_CLEAR, + Serial_Open = wxID_OPEN, + Serial_Close = wxID_CLOSE, + Minimal_Quit = wxID_EXIT, // it is important for the id corresponding to the "About" command to have // this standard value as otherwise it won't be handled properly under Mac diff --git a/test_console.cpp b/test_console.cpp index 10aa02a..107c8cb 100644 --- a/test_console.cpp +++ b/test_console.cpp @@ -3,41 +3,40 @@ // MIT License (https://opensource.org/licenses/MIT) // Copyright (c) 2018 Yan Naing Aye -#include #include "ceserial.h" +#include using namespace std; -int main() -{ +int main() { #ifdef CE_WINDOWS - ceSerial com("\\\\.\\COM4",9600,8,'N',1); // Windows + ceSerial com("\\\\.\\COM4", 9600, 8, 'N', 1); // Windows #else - ceSerial com("/dev/ttyS0",9600,8,'N',1); // Linux + ceSerial com("/dev/ttyS0", 9600, 8, 'N', 1); // Linux #endif - printf("Opening port %s.\n",com.GetPort().c_str()); - if (com.Open() == 0) { - printf("OK.\n"); - } - else { - printf("Error.\n"); - return 1; - } + printf("Opening port %s.\n", com.GetPort().c_str()); + if (com.Open() == 0) { + printf("OK.\n"); + } else { + printf("Error.\n"); + return 1; + } - bool successFlag; - printf("Writing.\n"); - char s[]="Hello"; - successFlag=com.Write(s); // write string - successFlag=com.WriteChar('!'); // write a character + bool successFlag; + printf("Writing.\n"); + char s[] = "Hello"; + successFlag = com.Write(s); // write string + successFlag = com.WriteChar('!'); // write a character - printf("Waiting 3 seconds.\n"); - ceSerial::Delay(3000); // delay to wait for a character + printf("Waiting 3 seconds.\n"); + ceSerial::Delay(3000); // delay to wait for a character - printf("Reading.\n"); - char c=com.ReadChar(successFlag); // read a char - if(successFlag) printf("Rx: %c\n",c); + printf("Reading.\n"); + char c = com.ReadChar(successFlag); // read a char + if (successFlag) + printf("Rx: %c\n", c); - printf("Closing port %s.\n",com.GetPort().c_str()); - com.Close(); - return 0; + printf("Closing port %s.\n", com.GetPort().c_str()); + com.Close(); + return 0; }