#ifndef RS485_DRIVER_HPP
#define RS485_DRIVER_HPP

#include <string>
#include <vector>
#include <termios.h>
#include <mutex>

namespace motor_dev
{
    class RS485Driver
    {
    public:
        RS485Driver();
        ~RS485Driver();
        
        // 打开串口
        bool openPort(const std::string &port_name, int baud_rate = 115200);
        
        // 关闭串口
        void closePort();
        
        // 发送数据
        bool sendData(const std::vector<uint8_t> &data);
        
        // 接收数据
        bool receiveData(std::vector<uint8_t> &data, size_t max_length, int timeout_ms = 100);
        //本末
        int bm_set_enable(uint8_t motor_id,uint8_t enable);
        int bm_set_mode(uint8_t motor_id, uint8_t mode);
        int bm_set_pos(float angle1, float angle2);
        int bm_set_speed(float speed1, float speed2);
        float bm_get_pos(uint8_t motor_id);
        float bm_get_speed(uint8_t motor_id);
        int bm_query_id();
        int bm_set_param(uint8_t motor_id, uint8_t param,uint32_t val);
        
        //脉塔
        int mt_query_id();
        void add_crc16(std::vector<uint8_t> &data);
        int mt_set_pos(uint8_t motor_id, float angle);
        float mt_get_pos(uint8_t motor_id);
        
    private:
        int com_fd_;
        //bool is_open_;
        struct termios original_termios_;
        std::mutex uart_mutex;
        //size_t max_motors_;

        //size_t control_index_;
        
        // 转换波特率
        speed_t convertBaudRate(int baud_rate);

        // 电机协议常量
        // static constexpr uint8_t START_BYTE = 0x64;
        // static constexpr uint8_t STOP_BYTE = 0x55;
        // static constexpr uint8_t CONTROL_CMD = 0x64;
        // static constexpr uint8_t ZERO_CMD = 0x00;
        // static constexpr uint8_t SPEED_CMD = 0x14;
        // static constexpr uint8_t DEFAULT_TIME = 0x64;
        // static constexpr uint8_t STOP_CMD = 0x02;
        // static constexpr uint8_t ALL_MOTORS_CMD = 0x03;
    };
}

#endif // RS485_DRIVER_HPP
