Split into main/net/tusb_config, extract ring_buffer and usb_cdc headers
This commit is contained in:
3
include/net.h
Normal file
3
include/net.h
Normal file
@@ -0,0 +1,3 @@
|
||||
#pragma once
|
||||
|
||||
bool net_init();
|
||||
44
include/ring_buffer.h
Normal file
44
include/ring_buffer.h
Normal file
@@ -0,0 +1,44 @@
|
||||
#pragma once
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <span>
|
||||
|
||||
template <uint16_t N>
|
||||
struct ring_buffer {
|
||||
std::array<uint8_t, N> data = {};
|
||||
uint16_t head = 0;
|
||||
uint16_t tail = 0;
|
||||
|
||||
uint16_t used() const { return tail - head; }
|
||||
uint16_t free() const { return N - used(); }
|
||||
bool empty() const { return head == tail; }
|
||||
|
||||
void push(std::span<const uint8_t> src) {
|
||||
if (src.size() > free()) return;
|
||||
for (auto b : src)
|
||||
data[(tail++) % N] = b;
|
||||
}
|
||||
|
||||
uint16_t peek(std::span<uint8_t> dst) const {
|
||||
uint16_t len = dst.size() < used() ? dst.size() : used();
|
||||
for (uint16_t i = 0; i < len; i++)
|
||||
dst[i] = data[(head + i) % N];
|
||||
return len;
|
||||
}
|
||||
|
||||
void consume(uint16_t len) {
|
||||
head += len;
|
||||
if (head >= N) {
|
||||
head -= N;
|
||||
tail -= N;
|
||||
}
|
||||
}
|
||||
|
||||
std::span<const uint8_t> read_contiguous() const {
|
||||
uint16_t offset = head % N;
|
||||
uint16_t contig = N - offset;
|
||||
uint16_t pending = used();
|
||||
uint16_t len = pending < contig ? pending : contig;
|
||||
return {data.data() + offset, len};
|
||||
}
|
||||
};
|
||||
31
include/usb_cdc.h
Normal file
31
include/usb_cdc.h
Normal file
@@ -0,0 +1,31 @@
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
#include <span>
|
||||
#include <vector>
|
||||
#include "tusb.h"
|
||||
#include "ring_buffer.h"
|
||||
|
||||
struct usb_cdc {
|
||||
ring_buffer<512> tx;
|
||||
|
||||
void send(std::span<const uint8_t> data) {
|
||||
tx.push(data);
|
||||
drain();
|
||||
}
|
||||
|
||||
void send(const std::vector<uint8_t>& data) {
|
||||
send(std::span<const uint8_t>{data});
|
||||
}
|
||||
|
||||
void drain() {
|
||||
while (!tx.empty()) {
|
||||
uint32_t avail = tud_cdc_write_available();
|
||||
if (avail == 0) break;
|
||||
auto chunk = tx.read_contiguous();
|
||||
if (chunk.size() > avail) chunk = chunk.first(avail);
|
||||
tud_cdc_write(chunk.data(), chunk.size());
|
||||
tx.consume(chunk.size());
|
||||
}
|
||||
tud_cdc_write_flush();
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user