/** * コムポートのためのヘッダファイル * * coded by fenrir(M.Naruoka) 2006. */ #ifndef __COM_IF_H__ #define __COM_IF_H__ #include #include #include #include #include #include #include #include #include #if _MSC_VER >= 1400 #define _CRT_SECURE_NO_WARNINGS // sprintf_s等への推奨を止める #endif #ifndef min #define min(x, y) (((x) < (y)) ? (x) : (y)) #else #define ALREADY_MIN_DEFINED #endif #ifndef max #define max(x, y) (((x) > (y)) ? (x) : (y)) #else #define ALREADY_MAX_DEFINED #endif #define concat_str(str1, str2) str1 ## str2 #define COM_STR "\\\\.\\COM" #define COM_DEFAULT 1 #define COM_INIT_BANDRATE CBR_9600 class COMIFException : public exception{ private: const string what_str; public: COMIFException(const string &what_arg) : what_str(what_arg){} ~COMIFException() throw(){} /** * エラー内容を取得します。 * * @return (chsr *) エラー内容 */ const char *what() const throw(){ return what_str.c_str(); } }; class COMIF{ private: HANDLE hComm; DCB dcb; void debug_print(const char data[], unsigned int size) const{ std::cout << std::hex; for(int i(0); i < size; i++){ std::cout << std::setfill('0') << std::setw(2) << (unsigned int)((unsigned char)data[i]) << ' '; } std::cout << std::dec; std::cout << std::endl; } public: /** * 送信処理を行う * * @param data パケットのうち、index = 1  */ bool write_to( const char *data, const unsigned int data_size) const{ DWORD size_TX; WriteFile(hComm, data, data_size, &size_TX, NULL); #if DEBUG std::cout << size_TX << "bytes TXed" << std::endl; debug_print(data, size_TX); #endif return size_TX == data_size; } unsigned int read_from( char *buf, unsigned int buf_size){ DWORD size_RX; ReadFile(hComm, buf, buf_size, &size_RX, NULL); #if DEBUG std::cout << size_RX << "bytes RXed." << std::endl; debug_print(buf, size_RX); #endif return size_RX; } private: void init(const int &com_port) throw(COMIFException){ char com_str[16]; sprintf(com_str, "%s%d", COM_STR, com_port); std::cout << "TARGET_PORT:\t" << com_str << std::endl; hComm = CreateFile( com_str, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0 ); if(hComm == INVALID_HANDLE_VALUE){ throw COMIFException("Couldn't open port."); } GetCommState(hComm, &dcb); // DCB を取得 dcb.BaudRate = COM_INIT_BANDRATE; dcb.ByteSize = 8; dcb.Parity = NOPARITY; dcb.fParity = FALSE; dcb.StopBits = ONESTOPBIT; dcb.fBinary = TRUE; // バイナリモード dcb.fNull = FALSE; // NULLバイトは破棄しない dcb.fOutX = FALSE; // XONなし dcb.fInX = FALSE; // XOFFなし //dcb.fOutxCtsFlow = FALSE; // CTSフロー制御なし //dcb.fOutxDsrFlow = FALSE; // DSRフロー制御なし //dcb.fDsrSensitivity = FALSE; // DSR制御なし SetCommState(hComm, &dcb); // DCB を設定 } public: COMIF(const int &com_port) throw(COMIFException){ init(com_port); } COMIF() throw(COMIFException){ init(COM_DEFAULT); } ~COMIF(){ CloseHandle(hComm); } }; #ifndef ALREADY_MIN_DEFINED #undef min #endif #ifndef ALREADY_MAX_DEFINED #undef max #endif #endif /* __COM_IF_H__ */