generated from guanyuankai/bonus-edge-proxy
65 lines
1.5 KiB
C++
65 lines
1.5 KiB
C++
#pragma once
|
|
|
|
#include <atomic>
|
|
#include <functional>
|
|
#include <mutex>
|
|
#include <string>
|
|
#include <thread>
|
|
#include <vector>
|
|
|
|
#include "nlohmann/json.hpp"
|
|
|
|
// 定义数据结构 (保持字节对齐)
|
|
#pragma pack(push, 1)
|
|
struct BatteryPacket_t {
|
|
uint8_t battery_cap; // 1. 电量百分比
|
|
uint16_t time_to_full; // 2. 预测充满时间
|
|
uint16_t time_to_empty; // 3. 预测放电时间
|
|
uint8_t battery_status; // 4. 电池状态
|
|
int16_t temperature; // 5. 温度
|
|
uint8_t system_mode; // 6. 模式
|
|
uint8_t alarm_flag; // 7. 报警标志
|
|
};
|
|
#pragma pack(pop)
|
|
|
|
class BatteryService {
|
|
public:
|
|
BatteryService(const std::string& port, int baud_rate);
|
|
~BatteryService();
|
|
|
|
// 初始化串口并启动接收线程
|
|
bool start();
|
|
// 停止线程并关闭串口
|
|
void stop();
|
|
|
|
// API 调用的控制接口
|
|
void setMode(uint8_t mode);
|
|
void setAlarm(bool on);
|
|
|
|
// 获取当前缓存的电池数据 (JSON格式)
|
|
nlohmann::json getStatusJson();
|
|
|
|
private:
|
|
// 内部串口操作
|
|
bool openPort();
|
|
void receiveLoop();
|
|
int writeData(const uint8_t* data, size_t len);
|
|
void sendPacket(uint8_t cmd, const uint8_t* payload, uint8_t len);
|
|
uint32_t calculateCRC32(const uint8_t* data, size_t len);
|
|
void processFrame(const uint8_t* frame, size_t totalLen);
|
|
|
|
// 成员变量
|
|
std::string m_port_name;
|
|
int m_baud_rate;
|
|
int m_fd = -1;
|
|
|
|
std::atomic<bool> m_running;
|
|
std::thread m_rx_thread;
|
|
std::vector<uint8_t> m_rx_buffer;
|
|
|
|
// 数据缓存与线程安全
|
|
BatteryPacket_t m_latest_data;
|
|
std::mutex m_data_mutex;
|
|
bool m_has_data = false;
|
|
};
|