Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
#include <QWidget>
#include "Common/Cpp/Color.h"
#include "Common/Cpp/Exceptions.h"
#include "Controllers/MgbaLink/MgbaLink_SharedLink.h"
#include "CommonFramework/ImageTypes/ImageRGB32_Qt.h"
#include "CommonFramework/Tools/GlobalThreadPools.h"
#include "CommonFramework/VideoPipeline/Backends/VideoFrameQt.h"
Expand Down Expand Up @@ -221,17 +222,21 @@ void VideoSource_MgbaLink::poll_loop(){
}

void VideoSource_MgbaLink::run_connection(Logger& logger, const std::string& host, uint16_t port){
Connection connection(logger, GlobalThreadPools::unlimited_realtime(), host, port);
// Shared: a controller for the same address sends its commands on it.
std::shared_ptr<Connection> connection = std::make_shared<Connection>(
logger, GlobalThreadPools::unlimited_realtime(), host, port
);
{
std::lock_guard<Mutex> lg(m_lock);
if (m_stopping){
return;
}
m_connection = &connection;
m_connection = connection.get();
}
try{
connection.open();
poll_connected(logger, connection);
connection->open();
LinkRegistry::Publication publication = link_registry().publish(m_address, connection);
poll_connected(logger, *connection);
}catch (...){
std::lock_guard<Mutex> lg(m_lock);
m_connection = nullptr;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,9 +98,10 @@ class VideoSourceDescriptor_MgbaLink : public VideoSourceDescriptor{
// drops it when the connection is lost, so a dead bridge shows no video.
//
// The bridge holds one client at a time, so this source takes its only
// slot. A controller for the same mGBA (slice 2: KEYS, GRANT) must not open
// a second connection: it has to share this one (Connection serializes
// commands from several threads).
// slot. While open, the connection is published in MgbaLink::link_registry()
// under the source's address; the mGBA controller for the same address
// sends KEYS and GRANT on it (Connection serializes commands from several
// threads).
class VideoSource_MgbaLink : public VideoSource{
public:
VideoSource_MgbaLink(Logger& logger, std::string address);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
#include "CommonFramework/Windows/LabChannel_Tests.h"
#include "CommonFramework/VideoPipeline/Sources/VideoSource_MgbaLink_Tests.h"
#include "Controllers/MgbaLink/MgbaLink_Keys_Tests.h"
#include "Controllers/MgbaLink/MgbaLink_KeySender_Tests.h"
#include "Controllers/MgbaLink/MgbaLink_Tests.h"
#include "NintendoSwitch/Controllers/MgbaLink/NintendoSwitch_MgbaLink_KeyMap_Tests.h"
#include "CommonFramework/Windows/LabSnapshot_Tests.h"
Expand Down Expand Up @@ -77,6 +78,7 @@ UnitTestDatabase make_UNIT_TESTS_ALL(){
add_tests_LabChannel(ret);
MgbaLink::add_tests(ret);
MgbaLink::add_key_tests(ret);
MgbaLink::add_key_sender_tests(ret);
NintendoSwitch::add_tests_MgbaLinkKeyMap(ret);
add_tests_VideoSource_MgbaLink(ret);
add_tests_LabSnapshot(ret);
Expand Down
25 changes: 19 additions & 6 deletions SerialPrograms/Source/Controllers/ControllerSelectorWidget.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
#include <QMessageBox>
#include "Common/Qt/NoWheelComboBox.h"
#include "CommonFramework/Panels/ConsoleSettingsStretch.h"
#include "CommonFramework/StaticGlobals.h"
#include "Controllers/ControllerTypeStrings.h"
#include "ControllerSelectorWidget.h"

Expand All @@ -22,6 +23,23 @@ namespace PokemonAutomation{
template class RegisterUiStateQtWidget<ControllerSelectorWidget>;


namespace{

// The interfaces the dropdown offers; mGBA Link only in Developer mode.
std::vector<ControllerInterface> supported_interfaces(){
std::vector<ControllerInterface> interfaces{
ControllerInterface::SerialPABotBase2,
ControllerInterface::TcpSysbotBase,
// ControllerInterface::UsbSysbotBase,
};
if (STATIC_GLOBALS.DEVELOPER_MODE){
interfaces.emplace_back(ControllerInterface::MgbaLink);
}
return interfaces;
}

} // namespace




Expand Down Expand Up @@ -81,12 +99,7 @@ ControllerSelectorWidget::ControllerSelectorWidget(
m_dropdowns->addWidget(m_interface_dropdown);


// Add all the supported interfaces.
{
m_interface_list.emplace_back(ControllerInterface::SerialPABotBase2);
m_interface_list.emplace_back(ControllerInterface::TcpSysbotBase);
// m_interface_list.emplace_back(ControllerInterface::UsbSysbotBase);
}
m_interface_list = supported_interfaces();


for (ControllerInterface item : m_interface_list){
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const EnumStringMap<ControllerInterface> CONTROLLER_INTERFACE_STRINGS{
{ControllerInterface::SerialPABotBase2, "Serial: PABotBase2"},
{ControllerInterface::TcpSysbotBase, "TCP: sys-botbase"},
// {ControllerInterface::UsbSysbotBase, "USB: sys-botbase"},
{ControllerInterface::MgbaLink, "TCP: mGBA Link"},
};

const EnumStringMap<ControllerType> CONTROLLER_TYPE_STRINGS{
Expand Down
1 change: 1 addition & 0 deletions SerialPrograms/Source/Controllers/ControllerTypes.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ enum class ControllerInterface{
SerialPABotBase2,
TcpSysbotBase,
// UsbSysbotBase,
MgbaLink, // Developer mode only (fork lab tooling).
};

enum class ControllerPerformanceClass{
Expand Down
230 changes: 230 additions & 0 deletions SerialPrograms/Source/Controllers/MgbaLink/MgbaLink_KeySender.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,230 @@
/* MgbaLink Key Sender
*
* From: https://github.com/PokemonAutomation/
*
*/

#include <algorithm>
#include <format>
#include "Common/Cpp/Color.h"
#include "Common/Cpp/Exceptions.h"
#include "MgbaLink_KeySender.h"

namespace PokemonAutomation{
namespace MgbaLink{

namespace{

// How long a wait sleeps before it looks at its Cancellable again.
constexpr std::chrono::milliseconds CANCEL_POLL_PERIOD(50);

// A release lasts one frame: frames_for_duration() of anything under
// 1.5 frames.
constexpr std::chrono::milliseconds ONE_FRAME(17);

} // namespace


KeySender::KeySender(
Logger& logger,
ThreadPool& thread_pool,
LinkRegistry& registry,
std::string address,
std::chrono::milliseconds grant_period
)
: m_logger(logger)
, m_thread_pool(thread_pool)
, m_registry(registry)
, m_address(std::move(address))
, m_grant_period(grant_period)
{}
KeySender::~KeySender(){
std::lock_guard<Mutex> lg(m_lock);
m_pacer.reset();
// With the connection closed, the bridge has released keys and grant.
if (!m_attachment || m_attachment->connection.expired()){
return;
}
try{
if (m_attachment->held_mask.value_or(0) != 0){
restart_schedule(*m_attachment);
push_now(*m_attachment, 0, ONE_FRAME);
}
connection(*m_attachment)->command(std::format("GRANT {}", RUN_ON_GRANT));
}catch (Exception& e){
m_logger.log("MgbaLink: could not release mGBA: " + e.message(), COLOR_ORANGE);
}
}

bool KeySender::is_ready() const{
return m_registry.find(m_address).has_value();
}

KeySender::Attachment& KeySender::attach(){
std::optional<LinkRegistry::Link> link = m_registry.find(m_address);
if (!link){
throw ConnectionException(&m_logger, std::format(
"MgbaLink: no connection to {}. Select \"mGBA ({})\" as the video source.",
m_address, m_address
));
}
if (m_attachment && m_attachment->serial == link->serial){
if (m_pacer && !m_pacer->running()){
throw ConnectionException(&m_logger, "MgbaLink: the connection to mGBA was lost.");
}
return *m_attachment;
}

// A new connection (first use, or the video source reconnected).
m_pacer.reset();
m_attachment.reset();
m_input_log = InputLog();

// "GRANT 0" holds the emulator where it is and says which frame that
// is: the anchor. The pacer releases it from there.
WallClock now = current_time();
std::string reply = link->connection->command("GRANT 0");
std::optional<uint64_t> frame = parse_ok_frame_reply(reply);
if (!frame){
throw ConnectionException(&m_logger, "MgbaLink: unexpected GRANT reply: " + reply);
}
FrameClock clock(now, *frame);
m_attachment.emplace(Attachment{
.serial = link->serial,
.connection = link->connection,
.clock = clock,
.schedule = KeySchedule(clock),
});
m_pacer.emplace(m_logger, m_thread_pool, link->connection, clock, m_grant_period);
m_logger.log(std::format("MgbaLink: controller on {} anchored at frame {}.", m_address, *frame));
return *m_attachment;
}

std::shared_ptr<Connection> KeySender::connection(const Attachment& attachment){
std::shared_ptr<Connection> locked = attachment.connection.lock();
if (!locked){
throw ConnectionException(&m_logger, "MgbaLink: the connection to mGBA was closed.");
}
return locked;
}

void KeySender::restart_schedule(Attachment& attachment){
// Commands already sent stay queued in the bridge, and the last one
// queued for a frame wins: start after the last one sent.
uint64_t next = attachment.last_sent_frame
? *attachment.last_sent_frame + 1
: attachment.clock.anchor_frame();
attachment.schedule = KeySchedule(FrameClock(attachment.clock.timestamp(next), next));
attachment.held_mask.reset();
}

void KeySender::push_now(Attachment& attachment, uint16_t mask, WallDuration duration){
std::optional<KeysCommand> command = attachment.schedule.push(current_time(), mask, duration);
if (duration > WallDuration::zero()){
attachment.held_mask = mask;
}
if (command){
send(attachment, *command);
}
}

void KeySender::send(Attachment& attachment, const KeysCommand& command){
uint64_t late = connection(attachment)->keys(command.frame, command.mask);
m_input_log.record(command, late);
attachment.last_sent_frame = std::max(attachment.last_sent_frame.value_or(0), command.frame + late);
if (late != 0){
m_logger.log(
std::format("MgbaLink: KEYS for frame {} landed {} frame(s) late.", command.frame, late),
COLOR_ORANGE
);
}
}

bool KeySender::wait_for_frame(
std::unique_lock<Mutex>& lg, Cancellable* cancellable, uint64_t frame, uint64_t epoch
){
while (true){
if (cancellable != nullptr){
cancellable->throw_if_cancelled();
}
if (m_epoch != epoch || !m_attachment){
return false;
}
WallClock now = current_time();
WallClock target = m_attachment->clock.timestamp(frame);
if (now >= target){
return true;
}
WallDuration remaining = target - now;
m_cv.wait_for(lg, std::min<WallDuration>(remaining, CANCEL_POLL_PERIOD));
}
}

void KeySender::push(Cancellable* cancellable, uint16_t mask, WallDuration duration){
std::unique_lock<Mutex> lg(m_lock);
uint64_t epoch = m_epoch;
Attachment* attachment = &attach();

uint64_t start = attachment->schedule.end_frame();
if (start > SEND_AHEAD_FRAMES){
if (!wait_for_frame(lg, cancellable, start - SEND_AHEAD_FRAMES, epoch)){
return;
}
// The connection may have changed while waiting.
attachment = &attach();
}
if (m_replace_pending){
m_replace_pending = false;
restart_schedule(*attachment);
}
push_now(*attachment, mask, duration);
}

void KeySender::wait_for_all(Cancellable* cancellable){
bool holding = false;
{
std::lock_guard<Mutex> lg(m_lock);
holding = m_attachment && m_attachment->held_mask.value_or(0) != 0;
}
if (holding){
push(cancellable, 0, ONE_FRAME);
}
std::unique_lock<Mutex> lg(m_lock);
if (!m_attachment){
return;
}
wait_for_frame(lg, cancellable, m_attachment->schedule.end_frame(), m_epoch);
}

void KeySender::cancel(){
std::lock_guard<Mutex> lg(m_lock);
m_epoch++;
m_replace_pending = false;
m_cv.notify_all();
if (!m_attachment){
return;
}
restart_schedule(*m_attachment);
try{
push_now(*m_attachment, 0, ONE_FRAME);
}catch (ConnectionException&){
// Logged by the exception. With the connection gone, the bridge
// has released the keys itself.
}
}

void KeySender::replace_on_next(){
std::lock_guard<Mutex> lg(m_lock);
m_epoch++;
m_replace_pending = true;
m_cv.notify_all();
}

std::string KeySender::input_log_text() const{
std::lock_guard<Mutex> lg(m_lock);
return m_input_log.to_text();
}


} // namespace MgbaLink
} // namespace PokemonAutomation
Loading
Loading