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
76 changes: 66 additions & 10 deletions SerialPrograms/Source/Controllers/MgbaLink/MgbaLink_KeySender.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,27 @@ constexpr std::chrono::milliseconds CANCEL_POLL_PERIOD(50);
// 1.5 frames.
constexpr std::chrono::milliseconds ONE_FRAME(17);

// "GRANT 0" holds the emulator where it is and says which frame that is.
uint64_t hold_and_read_frame(Logger& logger, Connection& connection){
std::string reply = connection.command("GRANT 0");
std::optional<uint64_t> frame = parse_ok_frame_reply(reply);
if (!frame){
throw ConnectionException(&logger, std::format("MgbaLink: unexpected GRANT reply: {}", reply));
}
return *frame;
}

} // namespace


JumpCommand JumpCommand::load_state(std::string_view file){
return JumpCommand(std::format("LOAD {}", file));
}
JumpCommand JumpCommand::reset(){
return JumpCommand("RESET");
}


KeySender::KeySender(
Logger& logger,
ThreadPool& thread_pool,
Expand Down Expand Up @@ -69,7 +87,8 @@ KeySender::Attachment& KeySender::attach(){
));
}
if (m_attachment && m_attachment->serial == link->serial){
if (m_pacer && !m_pacer->running()){
// No pacer: a LOAD or RESET lost the connection before granting again.
if (!m_pacer || !m_pacer->running()){
throw ConnectionException(&m_logger, "MgbaLink: the connection to mGBA was lost.");
}
return *m_attachment;
Expand All @@ -80,23 +99,19 @@ KeySender::Attachment& KeySender::attach(){
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.
// The frame the emulator is held on 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);
uint64_t frame = hold_and_read_frame(m_logger, *link->connection);
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));
m_logger.log(std::format("MgbaLink: controller on {} anchored at frame {}.", m_address, frame));
return *m_attachment;
}

Expand Down Expand Up @@ -220,6 +235,47 @@ void KeySender::replace_on_next(){
m_cv.notify_all();
}

uint64_t KeySender::jump(const JumpCommand& command){
std::lock_guard<Mutex> lg(m_lock);
// What waits to be sent was meant for the frames before the jump.
m_epoch++;
m_replace_pending = false;
m_cv.notify_all();
Attachment& attachment = attach();
std::shared_ptr<Connection> link = connection(attachment);
std::string_view line = command.line();
std::string_view name = line.substr(0, line.find(' '));

// Stop granting first: a grant on the old frames would stall mGBA
// after a jump ahead, or let it run free after a jump back.
m_pacer.reset();
WallClock now;
uint64_t frame = 0;
try{
link->command(line);
now = current_time();
frame = hold_and_read_frame(m_logger, *link);
}catch (ConnectionException&){
// A refused command leaves mGBA where it was: the old clock holds.
m_pacer.emplace(m_logger, m_thread_pool, attachment.connection, attachment.clock, m_grant_period);
throw;
}

// The bridge dropped its queued KEYS but still holds the last keys it
// applied: release them on the first frame of the new timeline.
bool keys_sent = attachment.last_sent_frame.has_value();
attachment.clock = FrameClock(now, frame);
attachment.last_sent_frame.reset();
m_input_log = InputLog();
if (keys_sent){
send(attachment, KeysCommand{frame, 0});
}
restart_schedule(attachment);
m_pacer.emplace(m_logger, m_thread_pool, attachment.connection, attachment.clock, m_grant_period);
m_logger.log(std::format("MgbaLink: {} on {}: re-anchored at frame {}.", name, m_address, frame));
return frame;
}

std::string KeySender::input_log_text() const{
std::lock_guard<Mutex> lg(m_lock);
return m_input_log.to_text();
Expand Down
41 changes: 39 additions & 2 deletions SerialPrograms/Source/Controllers/MgbaLink/MgbaLink_KeySender.h
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,14 @@
* then. A cancel then drops what is not sent yet and releases the keys at
* the first frame no sent command can override.
*
* LOAD and RESET move mGBA to another frame, under the clock's anchor. The
* sender stops granting, drops what is not sent yet, sends the command
* (the bridge clears its queued KEYS and holds at the new frame), reads
* the new frame with "GRANT 0", anchors a new clock and input log there,
* releases the keys on that frame, and grants again.
*
* Qt-free. Thread-safe: push() and wait_for_all() come from the issuing
* thread, cancel() and replace_on_next() from any thread.
* thread; cancel(), replace_on_next() and jump() from any thread.
*
*/

Expand All @@ -27,6 +33,7 @@
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include "Common/Cpp/CancellableScope.h"
#include "Common/Cpp/Concurrency/ConditionVariable.h"
#include "Common/Cpp/Concurrency/Mutex.h"
Expand All @@ -41,6 +48,27 @@ namespace PokemonAutomation{
namespace MgbaLink{


// "LOAD <file>" or "RESET": a command that moves mGBA to another frame.
class JumpCommand{
public:
// Loads the mGBA save state "file" (a path on the Mac running mGBA).
static JumpCommand load_state(std::string_view file);
// Resets the GBA.
static JumpCommand reset();

const std::string& line() const{
return m_line;
}

private:
explicit JumpCommand(std::string line)
: m_line(std::move(line))
{}

std::string m_line;
};


// Sends one controller's key states to the mGBA published under an address.
class KeySender{
public:
Expand Down Expand Up @@ -86,7 +114,16 @@ class KeySender{
// and the keys it holds replace the current ones.
void replace_on_next();

// "<frame> <mask>" per change since the clock was anchored.
// Sends "command" and re-anchors the clock on the frame mGBA is on
// after it. Drops what is not sent yet: a waiting push() returns
// without sending. Returns the new anchor frame. Throws
// ConnectionException if no connection is published, it is lost, or
// the bridge refuses ("ERR load failed"); a refused command leaves the
// old clock running.
uint64_t jump(const JumpCommand& command);

// "<frame> <mask>" per change since the clock was anchored (at connect,
// or at the last LOAD or RESET).
std::string input_log_text() const;

private:
Expand Down
Loading
Loading