cmvr-es/include/hardware/serial_interface.h

120 lines
3.8 KiB
C
Raw Permalink Normal View History

//
// Created by xtkuang on 2025/5/6.
//
#ifndef CMVR_ES_SERIAL_INTERFACE_H
#define CMVR_ES_SERIAL_INTERFACE_H
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <boost/asio.hpp>
#include <iomanip>
#include <thread>
using namespace std;
using namespace boost::asio;
namespace cmvr {
// 定义通信模式枚举
enum class CommunicationMode {
RS485,
CAN
};
// 寄存器字典
const struct {
const char* name;
int address;
} regdict[] = {
{"defaultSpeedSet",1032},
{"defaultForceSet",1044},
{"posSet",1474},
{"angleSet", 1486},
{"forceSet", 1498},
{"speedSet", 1522},
{"angleAct", 1546},
{"posAct",1534},
{"forceAct", 1582},
{"current",1594},
{"error",1606},
{"temperature",1618},
{"finger_one_touch",3000},
{"finger_two_touch",3370},
{"finger_the_touch",3740},
{"finger_or_touch",4110},
{"finger_fiv_touch",4480},
{"finger_palm_touch",4900}
};
// 串口通信接口类
class serial_interface {
public:
serial_interface(const string& port, unsigned int baudrate, CommunicationMode mode);
void write(const vector<unsigned char>& data);
vector<unsigned char> read(size_t length);
bool isInitialized();
CommunicationMode getCommunicationMode();
private:
void on_timeout(const boost::system::error_code& ec);
void on_read_complete(const boost::system::error_code& ec
, size_t bytes_transferred, boost::system::error_code* out_ec, size_t* out_bytes_transferred);
private:
bool is_initialized = false;
io_context io;
std::shared_ptr<serial_port> serial;
CommunicationMode comm_mode;
steady_timer timer;
bool timeout;
};
// 根据寄存器名称获取地址
int getAddressByName(const string& reg_name);
// 写寄存器函数
void write_register(serial_interface& serial, int address_decimal, const string& id_value, const vector<int>& values_to_write);
/**
*
*
* @param serial
* @param address_decimal
* @param id_value ID字符串值
* @param register_length
* @param length_to_read
* @return
*/
std::vector<unsigned char> read_register(serial_interface& serial, int address_decimal, const string& id_value
,size_t register_length, size_t length_to_read);
std::vector<int> read_register_can(serial_interface& serial, int address_decimal, const std::string& id_value
, size_t register_length, size_t length_to_read, bool parse_as_short = true);
std::vector<unsigned char> read_register_can_single(serial_interface& serial, int address_decimal
, const string& id_value, size_t register_length, size_t length_to_read);
/**
*
*
* @param data
* @param start_byte
* @param register_length
* @param per_byte
* @return
*/
std::vector<int> parse_register(const std::vector<unsigned char>& data,int start_byte, size_t register_length,int per_byte);
/**
*
*
* @param errorCode
* @return
* @note
*/
std::vector<std::string> parse_error(unsigned char errorCode);
} // cmvr
#endif //CMVR_ES_SERIAL_INTERFACE_H