16static constexpr int kBaudRate = 9600;
19const std::string kComName[] = {
"",
46 Sleep(
static_cast<int>(
47 1000 * kThreadPeriod));
74 if (serial_handle_ == INVALID_HANDLE_VALUE) {
79 boost::mutex::scoped_lock lock(mutex_);
86 boost::mutex::scoped_lock lock(mutex_);
89 if (read_data_.empty()) {
93 return read_data_.back();
98 boost::mutex::scoped_lock lock(mutex_);
104 const int num)
const {
106 boost::mutex::scoped_lock lock(mutex_);
108 std::vector<std::string> ret;
111 if (read_data_.empty()) {
116 if (read_data_.size() <= num) {
121 for (
int i = 0; i < num; ++i) {
122 ret.push_back(read_data_[read_data_.size() - 1 - i]);
128bool SerialCommunicationThread::Initialize() {
131 CreateFile(kComName[kComPortNumber].c_str(), GENERIC_READ | GENERIC_WRITE,
132 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
134 if (serial_handle_ == INVALID_HANDLE_VALUE) {
139 SetupComm(serial_handle_, kBufferSize, kBufferSize);
140 PurgeComm(serial_handle_, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR |
145 GetCommState(serial_handle_, &dcb);
152 dcb.BaudRate = kBaudRate;
154 SetCommState(serial_handle_, &dcb);
157 COMMTIMEOUTS timeouts;
158 GetCommTimeouts(serial_handle_, &timeouts);
160 timeouts.ReadIntervalTimeout = 100;
161 timeouts.ReadTotalTimeoutMultiplier = 100;
162 timeouts.ReadTotalTimeoutConstant = 100;
163 timeouts.WriteTotalTimeoutMultiplier = 0;
164 timeouts.WriteTotalTimeoutConstant = 0;
166 SetCommTimeouts(serial_handle_, &timeouts);
171bool SerialCommunicationThread::Read() {
173 if (serial_handle_ == INVALID_HANDLE_VALUE) {
178 char read_buffer[kBufferSize] = {0};
180 if (!ReadFile(serial_handle_, read_buffer, kBufferSize, &read_size, NULL)) {
185 if (read_size == 0) {
192 std::string read_data(read_buffer, read_size);
200 boost::mutex::scoped_lock lock(mutex_);
202 for (
const auto& data : split_data) {
209 read_data_.push_back(data);
216bool SerialCommunicationThread::Write() {
218 if (serial_handle_ == INVALID_HANDLE_VALUE) {
223 if (write_data_ ==
"") {
227 DWORD write_size = 0;
229 if (!WriteFile(serial_handle_, write_data_.c_str(),
230 static_cast<DWORD
>(write_data_.size()), &write_size, NULL)) {
235 if (write_size == 0) {
void SetWriteData(const std::string &str)
指定した文字列をシリアル通信で送信する. この時,排他制御を行う.
void EndThread()
シリアル通信のスレッドを終了する.
std::string GetTopReadData() const
シリアル通信で受信した最新の文字列を取得する. この時,排他制御を行う.
std::vector< std::string > GetAllReadData() const
シリアル通信で受信した文字列を全て取得する. この時,排他制御を行う.
std::vector< std::string > GetReadData(const int num) const
シリアル通信で受信した文字列の中から指定した数だけ取得する. この時,排他制御を行う.
std::vector< std::string > Split(const std::string &str, const std::string &separator)
文字列を分割する関数.指定した文字で文字列を分割する. 分割した結果,空白が含まれる場合や文字列がない場合は,そのまま返す. 最後が区切り文字で終わる場合は,...