Files

183 lines
6.7 KiB
Plaintext

// SPDX-License-Identifier: GPL-3.0-or-later
#include "devices/DriveWireTransport.h"
#import <Network/Network.h>
#include <algorithm>
#include <deque>
#include <mutex>
#include <vector>
namespace VCC::Devices {
namespace {
using State = DriveWireTransport::State;
constexpr size_t bufferLimit = 64 * 1024;
constexpr size_t receiveChunk = 8192;
class Stream : public std::enable_shared_from_this<Stream> {
public:
explicit Stream(nw_connection_t connection) : connection(connection) {}
void start() {
auto weak = weak_from_this();
nw_connection_set_queue(connection, queue);
nw_connection_set_state_changed_handler(connection, ^(nw_connection_state_t state, nw_error_t) {
auto stream = weak.lock();
if (!stream) return;
switch (state) {
case nw_connection_state_ready:
{
std::lock_guard lock(stream->mutex);
if (stream->status != State::connecting) return;
stream->status = State::connected;
}
stream->receive();
break;
case nw_connection_state_failed:
case nw_connection_state_waiting:
stream->finish(State::failed);
break;
default:
break;
}
});
nw_connection_start(connection);
}
void finish(State reason) {
{
std::lock_guard lock(mutex);
if (status == State::closed || status == State::failed) return;
status = reason;
outgoing.clear();
}
nw_connection_force_cancel(connection);
}
State state() {
std::lock_guard lock(mutex);
return status;
}
size_t read(uint8_t* bytes, size_t capacity) {
std::lock_guard lock(mutex);
size_t count = std::min(capacity, incoming.size());
if (!count) return 0;
bool wasFull = incoming.size() == bufferLimit;
std::copy_n(incoming.begin(), count, bytes);
incoming.erase(incoming.begin(), incoming.begin() + count);
if (wasFull && status == State::connected) {
auto weak = weak_from_this();
dispatch_async(queue, ^{ if (auto stream = weak.lock()) stream->receive(); });
}
return count;
}
bool write(const uint8_t* bytes, size_t count) {
std::lock_guard lock(mutex);
if (status != State::connected || count > bufferLimit - outgoing.size() - inFlight) return false;
if (!count) return true;
outgoing.insert(outgoing.end(), bytes, bytes + count);
if (!sending) {
sending = true;
auto weak = weak_from_this();
dispatch_async(queue, ^{ if (auto stream = weak.lock()) stream->send(); });
}
return true;
}
private:
// Only the private serial network queue calls receive() and send().
void receive() {
size_t room;
{
std::lock_guard lock(mutex);
room = bufferLimit - incoming.size();
if (receiving || !room || status != State::connected) return;
receiving = true;
}
auto weak = weak_from_this();
nw_connection_receive(connection, 1, static_cast<uint32_t>(std::min(room, receiveChunk)),
^(dispatch_data_t data, nw_content_context_t, bool complete, nw_error_t error) {
auto stream = weak.lock();
if (!stream) return;
stream->receiving = false;
if (data) {
std::lock_guard lock(stream->mutex);
dispatch_data_apply(data, ^bool(dispatch_data_t, size_t, const void* buffer, size_t size) {
const auto* first = static_cast<const uint8_t*>(buffer);
stream->incoming.insert(stream->incoming.end(), first, first + size);
return true;
});
}
if (error || complete) stream->finish(error ? State::failed : State::closed);
else stream->receive();
});
}
void send() {
std::vector<uint8_t> batch;
{
std::lock_guard lock(mutex);
if (status != State::connected || outgoing.empty()) {
sending = false;
return;
}
batch.swap(outgoing);
inFlight = batch.size();
}
// The default destructor copies our temporary batch into the dispatch data.
auto data = dispatch_data_create(batch.data(), batch.size(), nullptr, DISPATCH_DATA_DESTRUCTOR_DEFAULT);
auto weak = weak_from_this();
nw_connection_send(connection, data, NW_CONNECTION_DEFAULT_MESSAGE_CONTEXT, true, ^(nw_error_t error) {
auto stream = weak.lock();
if (!stream) return;
{
std::lock_guard lock(stream->mutex);
stream->inFlight = 0;
}
if (error) stream->finish(State::failed);
else stream->send();
});
}
nw_connection_t connection;
dispatch_queue_t queue = dispatch_queue_create("com.brianholman.vccplus.drivewire.tcp", DISPATCH_QUEUE_SERIAL);
std::mutex mutex;
State status = State::connecting;
std::deque<uint8_t> incoming;
std::vector<uint8_t> outgoing;
size_t inFlight = 0;
bool sending = false;
bool receiving = false;
};
class TCPTransport final : public DriveWireTransport {
public:
explicit TCPTransport(std::shared_ptr<Stream> stream) : stream(std::move(stream)) {}
~TCPTransport() override { stream->finish(State::closed); }
State state() override { return stream->state(); }
size_t read(uint8_t* bytes, size_t capacity) override { return stream->read(bytes, capacity); }
bool write(const uint8_t* bytes, size_t count) override { return stream->write(bytes, count); }
private:
std::shared_ptr<Stream> stream;
};
} // namespace
std::unique_ptr<DriveWireTransport> makeDriveWireTCPConnection(const std::string& host, uint16_t port) {
if (host.empty() || host.find('\0') != std::string::npos || !port) return {};
auto endpoint = nw_endpoint_create_host(host.c_str(), std::to_string(port).c_str());
auto parameters = nw_parameters_create_secure_tcp(NW_PARAMETERS_DISABLE_PROTOCOL, ^(nw_protocol_options_t tcp) {
nw_tcp_options_set_connection_timeout(tcp, 10);
nw_tcp_options_set_no_delay(tcp, true);
});
auto connection = nw_connection_create(endpoint, parameters);
if (!connection) return {};
auto stream = std::make_shared<Stream>(connection);
stream->start();
return std::make_unique<TCPTransport>(std::move(stream));
}
} // namespace VCC::Devices