Switch Controller
Loading...
Searching...
No Matches
SerialPort.h
Go to the documentation of this file.
1#pragma once
2
3#include "pch.h"
4
5#include <boost/asio/io_service.hpp>
6#include <boost/asio/read.hpp>
7#include <boost/asio/serial_port.hpp>
8#include <boost/asio/write.hpp>
9#include <boost/bind/bind.hpp>
10
11std::unique_ptr<boost::asio::serial_port>
12initializeSerialPort(std::string serialPort, unsigned int baud,
13 boost::asio::io_service &io) {
14 try {
15 spdlog::info("Intializing serial communication");
16 auto port = std::make_unique<boost::asio::serial_port>(io);
17 port->open(serialPort);
18 port->set_option(boost::asio::serial_port_base::baud_rate(baud));
19 spdlog::info("Serial communication intialized");
20 return port;
21 } catch (const std::exception &e) {
22 throw std::runtime_error("Fatal error opening serial port: \"" +
23 std::string(e.what()) +
24 "\" Does the port exist?");
25 }
26}
27
28static void asyncHandler(const boost::system::error_code &error,
29 std::size_t bytes_transferred, int *res) {
30 if (error) {
31 spdlog::error("Error in serial port async handler: {}", error.what());
32 *res = -1;
33 }
34 *res += static_cast<int>(bytes_transferred);
35};
36
37void testSerialPort(std::unique_ptr<boost::asio::serial_port> &serialPort,
38 boost::asio::io_service &io) {
39 spdlog::info("Testing serial connection");
40
41 // sending a nuetral signal
42 unsigned char writeData[8] = {85, 0, 0, 128, 128, 128, 128, 8};
43 unsigned char readData[1];
44 auto writeLen = sizeof(writeData);
45 auto readLen = sizeof(readData);
46 int writeRes = 0;
47 int readRes = 0;
48 boost::asio::async_write(*serialPort,
49 boost::asio::buffer(writeData, writeLen),
50 boost::bind(&asyncHandler, boost::placeholders::_1,
51 boost::placeholders::_2, &writeRes));
52 boost::asio::async_read(*serialPort, boost::asio::buffer(readData, readLen),
53 boost::bind(&asyncHandler, boost::placeholders::_1,
54 boost::placeholders::_2, &readRes));
55
56 io.run_for(std::chrono::milliseconds(1000));
57 serialPort->cancel();
58 if (writeRes <= 0 || readRes <= 0) {
59 throw std::runtime_error("Unable to establish serial connection.");
60 }
61 spdlog::info("Serial communication established");
62}
void testSerialPort(std::unique_ptr< boost::asio::serial_port > &serialPort, boost::asio::io_service &io)
Definition: SerialPort.h:37
std::unique_ptr< boost::asio::serial_port > initializeSerialPort(std::string serialPort, unsigned int baud, boost::asio::io_service &io)
Definition: SerialPort.h:12