您好,登錄后才能下訂單哦!
備忘使用。
- #include <boost/bind.hpp>
- #include <boost/asio.hpp>
- #include <boost/thread.hpp>
- using boost::asio::io_service;
- using boost::system::error_code;
- using boost::asio::serial_port;
- using boost::asio::deadline_timer;
- using boost::asio::buffer;
- class MyCom
- {
- public:
- MyCom(void)
- {
- _pSerialPort= new serial_port(_ios);
- _pTimer = new deadline_timer(_ios);
- }
- ~MyCom(void)
- {
- if (_pTimer != NULL)
- {
- delete _pTimer;
- _pTimer = NULL;
- }
- if (_pSerialPort != NULL)
- {
- delete _pSerialPort;
- _pSerialPort = NULL;
- }
- }
- void Open(const string& comName);
- {
- _pSerialPort->open(comName);
- _pSerialPort->set_option(serial_port::flow_control(serial_port::flow_control::none)); //流量控制為none
- _pSerialPort->set_option(serial_port::parity(serial_port::parity::none)); //奇偶檢驗(yàn)為none
- _pSerialPort->set_option(serial_port::stop_bits(serial_port::stop_bits::one)); //停止位為1
- _pSerialPort->set_option(serial_port::character_size(8)); //字符大小(數(shù)據(jù)位)為8
- _pSerialPort->set_option(serial_port::baud_rate(115200));//波特率
- }
- void Send(const string& data)
- {//同步發(fā)數(shù)據(jù)
- _mutex.lock();
- _pSerialPort->write_some(buffer(data, data.size()));
- _mutex.unlock();
- }
- string Recv()
- {//異步收數(shù)據(jù)
- _mutex.lock();
- memset(_buf, 0, sizeof(_buf));
- _pSerialPort->async_read_some(buffer(_buf, 256),
- boost::bind(&MyCom::RecvHandle, this,
- boost::asio::placeholders::error,//傳送錯(cuò)誤碼
- boost::asio::placeholders::bytes_transferred//傳送字節(jié)數(shù)
- ));
- _mutex.unlock();
- _pTimer->expires_from_now(boost::posix_time::millisec(SLEEP_TIME));
- _pTimer->async_wait(boost::bind(&serial_port::cancel, _pSerialPort));
- _ios.run();//異步情況下使用詞句才開始執(zhí)行
- _ios.reset();//還原狀態(tài)
- return string(_buf, _ret);
- }
- void Close()
- {
- _mutex.lock();
- if (_pSerialPort->is_open())
- _pSerialPort->close();
- _mutex.unlock();
- }
- protected:
- void RecvHandle(const error_code& error, size_t bytes_transferred)
- {
- if (!error)
- _pTimer->cancel();//沒有錯(cuò)誤就結(jié)束定時(shí)器
- _ret = bytes_transferred;
- }
- private:
- boost::asio::io_service _ios;
- serial_port* _pSerialPort;
- deadline_timer* _pTimer;
- char _buf[256];
- size_t _ret;
- boost::mutex _mutex;
- };
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。