18#include <radio_tool/dfu/dfu.hpp>
19#include <radio_tool/dfu/dfu_exception.hpp>
27auto DFU::SetAddress(
const uint32_t &addr)
const ->
void
29 std::vector<uint8_t> data = {
30 static_cast<uint8_t
>(0x21),
31 static_cast<uint8_t
>(addr & 0xFF),
32 static_cast<uint8_t
>((addr >> 8) & 0xFF),
33 static_cast<uint8_t
>((addr >> 16) & 0xFF),
34 static_cast<uint8_t
>((addr >> 24) & 0xFF)};
39auto DFU::Erase(
const uint32_t &addr)
const ->
void
41 std::vector<uint8_t> data = {
42 static_cast<uint8_t
>(0x41),
43 static_cast<uint8_t
>(addr & 0xFF),
44 static_cast<uint8_t
>((addr >> 8) & 0xFF),
45 static_cast<uint8_t
>((addr >> 16) & 0xFF),
46 static_cast<uint8_t
>((addr >> 24) & 0xFF)};
51auto DFU::Download(
const std::vector<uint8_t> &data,
const uint16_t &wValue)
const ->
void
55 auto err = libusb_control_transfer(device, 0x21,
static_cast<uint8_t
>(DFURequest::DNLOAD), wValue, 0,
const_cast<unsigned char *
>(data.data()), data.size(), this->timeout);
56 if (err < LIBUSB_SUCCESS)
62 auto status = GetStatus();
63 if (status.state != DFUState::DFU_DOWNLOAD_BUSY)
67 else if (status.timeout > 0)
73 auto status2 = GetStatus();
74 if (status2.state != DFUState::DFU_DOWNLOAD_IDLE)
80auto DFU::Upload(
const uint16_t &size,
const uint8_t &wValue)
const -> std::vector<uint8_t>
83 auto data = std::vector<uint8_t>(size);
84 auto err = libusb_control_transfer(device, 0xa1,
static_cast<uint8_t
>(DFURequest::UPLOAD), wValue, 0, data.data(), data.size(), this->timeout);
85 if (err < LIBUSB_SUCCESS)
96auto DFU::GetState() const -> DFUState
100 auto err = libusb_control_transfer(device, 0xa1,
static_cast<uint8_t
>(
DFURequest::GETSTATE), 0, 0, &state, 1, this->timeout);
101 if (err < LIBUSB_SUCCESS)
107 auto s =
static_cast<DFUState
>((int)state);
116 auto constexpr StatusSize = 6;
118 unsigned char data[StatusSize];
119 auto err = libusb_control_transfer(device, 0xa1,
static_cast<uint8_t
>(
DFURequest::GETSTATUS), 0, 0, data, StatusSize, this->timeout);
120 if (err < LIBUSB_SUCCESS)
126 return DFUStatusReport::Parse(data);
128 return DFUStatusReport::Empty();
131auto DFU::Abort() const ->
void
134 auto err = libusb_control_transfer(device, 0x21,
static_cast<uint8_t
>(
DFURequest::ABORT), 0, 0,
nullptr, 0, this->timeout);
135 if (err < LIBUSB_SUCCESS)
141auto DFU::Detach() const ->
void
144 auto err = libusb_control_transfer(device, 0x21,
static_cast<uint8_t
>(
DFURequest::DETACH), 0, 0,
nullptr, 0, this->timeout);
145 if (err < LIBUSB_SUCCESS)
151auto DFU::CheckDevice() const ->
void
153 if (this->device ==
nullptr)
154 throw std::runtime_error(
"Device is not opened");
162 auto state = GetState();
165 case DFUState::DFU_DOWNLOAD_IDLE:
166 case DFUState::DFU_IDLE:
182 auto state = GetState();
185 case DFUState::DFU_UPLOAD_IDLE:
186 case DFUState::DFU_IDLE: