Skip to content
14 changes: 10 additions & 4 deletions SerialPrograms/Source/CommonFramework/Windows/Lab.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ START_SEGMENT = "0"` or the path of a saved screenshot.
seq=r3
state=RUNNING
program=PokemonBDSP:AutoStory
controller=ready
owner=lab-B
error=
```
Expand All @@ -65,6 +66,9 @@ error=
while the panel loads, `NO_PROGRAM` when the selected panel is not a
program (the settings page).
- `program` is the selected program's identifier (`<game>:<program>`).
- `controller` is `ready` when the console's controller can take commands,
`none` while it is not connected (after a program switch the app
reconnects it, which can stall), empty for a panel without a console.
- `owner` is the owner token, empty when the channel is unclaimed.
- `error` is the error of the last request, empty once a request succeeds.

Expand All @@ -76,10 +80,11 @@ error=
|---|---|
| `select GAME:PROGRAM` | Shows that program, as clicking it in the program list does. The identifier is the one in `state` and in the settings file's `99-Panels` section, e.g. `PokemonBDSP:AutoStory`, `NintendoSwitch:CommandFileRunner`. Refused while a program runs. |
| `set KEY JSON` | Sets one option of the selected program by its key in the settings file, live: `set START_SEGMENT "0"`, `set NEW_GAME_INTRO true`, `set NOTIFICATIONS.Enabled false` (dots walk into groups). The value is JSON, so strings need quotes. Prints `set KEY = <value the program now holds>`, which differs from what was sent when the program clamped or refused it. Refused while the program runs. |
| `start` | What clicking Start Program does. Refused unless the program is `STOPPED`. |
| `start [SECONDS]` | What clicking Start Program does. Refused unless the program is `STOPPED`. First waits up to `SECONDS` (default 30) for `controller=ready`, and refuses with `controller not connected` if it never is, instead of starting a program that would fail with "Incompatible Controller". |
| `stop` | What clicking Stop Program does. Refused unless the program is `RUNNING`. The request goes on; the program stops in the background. |
| `state` | Prints the state file's lines into the journal. (In the Command File Runner program, `state [image]` prints the detectors that fire instead; from the channel use `detect` per detector.) |
| `keepawake on\|off [seconds]` | While it is on and no program runs, presses B every `seconds` (default 15) so the console does not sleep. A running program pauses it. Off by default; off again when the app restarts. |
| `popups [close]` | Lists the app's open message boxes (title and text), such as the "Error" box a failed program leaves. `close` presses each one's default button. |
| `owner claim TOKEN`, `owner release` | The owner lock, below. |
| `help` | Prints every command and detector, including the ones games add. |

Expand Down Expand Up @@ -136,7 +141,7 @@ Games add their own commands and detectors with

Two scripts driving one console would interleave their presses. A script
claims the channel with `owner claim TOKEN`; from then on every request that
changes anything (`select`, `set`, `start`, `stop`, `keepawake`, presses)
changes anything (`select`, `set`, `start`, `stop`, `keepawake`, `popups`, presses)
must start with the line `owner TOKEN`, or it is refused with
`owned by TOKEN`. Requests that only read (`state`, `help`, `shot`, `detect`,
...) need no token. `owner release`, with the owner line, frees the channel.
Expand Down Expand Up @@ -196,6 +201,7 @@ The state file while it runs, and after:
seq=r2 seq=r2
state=RUNNING state=STOPPED
program=PokemonBDSP:AutoStory
controller=ready
owner=lab-B
error=
```
Expand Down Expand Up @@ -261,13 +267,13 @@ point its folder at `Lab/`: the channel reads that one.

The `LabControl/` folder of earlier lab builds (files `start` and `stop`, a
two-line `state`) is gone. `start` and `stop` are lines in a request, and
`state` has the five lines above. Scripts move from
`state` has the six lines above. Scripts move from
`printf '' > LabControl/start` to a request file containing `start`.

## Tests

`add_tests_LabChannel()` covers the request format, the journal lines, the
state text, the owner lock and the keep-awake schedule (`LabChannel - ...`
state text, the owner lock, the keep-awake schedule and the controller wait before `start` (`LabChannel - ...`
unit tests); `add_tests_CommandFileRunner()` covers the console commands'
arguments. Run them with the app's `--command-line-test-mode`. Selecting,
setting, starting and the presses need a live app and console.
88 changes: 83 additions & 5 deletions SerialPrograms/Source/CommonFramework/Windows/LabChannel.cpp
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/* Lab Channel

Check warning on line 1 in SerialPrograms/Source/CommonFramework/Windows/LabChannel.cpp

View workflow job for this annotation

GitHub Actions / code-health

Code health (advisory)

<file>: file_lines=608 (advisory above 500, limit 1000)
*
* From: https://github.com/PokemonAutomation/
*
Expand All @@ -6,7 +6,10 @@

#include <exception>
#include <sstream>
#include <QApplication>
#include <QCoreApplication>
#include <QMessageBox>
#include <QPushButton>
#include "Common/Cpp/Color.h"
#include "Common/Cpp/Exceptions.h"
#include "Common/Cpp/ScopeExit.h"
Expand Down Expand Up @@ -317,10 +320,10 @@
" owner claim TOKEN | owner release (then start with a line \"owner TOKEN\")\n"
" select GAME:PROGRAM\n"
" set OPTION_KEY JSON\n"
" start | stop\n"
" start [SECONDS] | stop (start waits up to SECONDS, default 30, for the controller)\n"
" state\n"
" keepawake on|off [seconds]\n"
" help\n";
" popups [close] (the app's message boxes; close presses their default button)\n help\n";
m_console->help(output.out);
return "";
}
Expand All @@ -336,7 +339,7 @@
return error;
}
}
if (command == "select" || command == "set" || command == "start" || command == "stop"){
if (command == "select" || command == "set" || command == "start" || command == "stop" || command == "popups"){
return run_ui_command(line, output.out);
}
if (command == "keepawake"){
Expand Down Expand Up @@ -398,9 +401,12 @@
return "";
}

std::string LabChannel::run_ui_command(const LabRequestLine& line, std::ostream& out){

Check warning on line 404 in SerialPrograms/Source/CommonFramework/Windows/LabChannel.cpp

View workflow job for this annotation

GitHub Actions / code-health

Code health (advisory)

PokemonAutomation::LabChannel::run_ui_command( const LabRequestLine & line , std :: ostream & out): function_lines=44 (advisory above 25, limit 50)
const std::vector<std::string>& words = line.words;
const std::string& command = words[0];
if (command == "popups"){
return run_popups(words, out);
}
if (command == "select"){
if (words.size() < 2){
return "select: expected select GAME:PROGRAM";
Expand Down Expand Up @@ -432,15 +438,82 @@
}
return error;
}
const bool start = command == "start";
if (command == "start"){
return run_start(words);
}
return run_on_ui([&]{
return start_or_stop(m_callbacks.current_panel(), false);
});
}

// "start [SECONDS]": waits for the controller, then starts. The wait runs
// here on the worker, so the window stays responsive while it reconnects.
std::string LabChannel::run_start(const std::vector<std::string>& words){

Check warning on line 451 in SerialPrograms/Source/CommonFramework/Windows/LabChannel.cpp

View workflow job for this annotation

GitHub Actions / code-health

Code health (advisory)

PokemonAutomation::LabChannel::run_start( const std :: vector<std::string> & words): function_lines=31 (advisory above 25, limit 50)
Seconds timeout = CONTROLLER_WAIT_DEFAULT;
if (words.size() > 2){
return "start: expected start [SECONDS]";
}
if (words.size() == 2){
const std::optional<Seconds> seconds = parse_seconds(words[1]);
if (!seconds){
return "start: seconds must be a whole number of at least 1, got " + words[1];
}
timeout = *seconds;
}
const std::string error = wait_for_controller(
[this]{
std::lock_guard<Mutex> lg(m_panel_lock);
return read_controller_status();
},
[this](Milliseconds slice){
std::unique_lock<Mutex> lg(m_idle_lock);
m_idle_cv.wait_for(lg, slice);
return !m_stopping.load(std::memory_order_acquire);
},
timeout, POLL_INTERVAL
);
if (!error.empty()){
return error;
}
return run_on_ui([&]{
return start_or_stop(m_callbacks.current_panel(), start);
return start_or_stop(m_callbacks.current_panel(), true);
});
}

// Runs `body` on the UI thread and returns what it returns: "" or an error.
// Gives up with an error if the app is closing, since the UI thread would
// never run it.
// A failed program leaves a modal "Error" box, and nothing at the
// keyboard closes it on a lab console. "popups" lists the app's open
// message boxes; "popups close" presses each one's default button.
std::string LabChannel::run_popups(const std::vector<std::string>& words, std::ostream& out){

Check warning on line 489 in SerialPrograms/Source/CommonFramework/Windows/LabChannel.cpp

View workflow job for this annotation

GitHub Actions / code-health

Code health (advisory)

PokemonAutomation::LabChannel::run_popups( const std :: vector<std::string> & words , std :: ostream & out): function_lines=27 (advisory above 25, limit 50)
const bool close = words.size() >= 2 && words[1] == "close";
if (words.size() > 2 || (words.size() == 2 && !close)){
return "popups: expected popups, or popups close";
}
return run_on_ui([&]{
size_t count = 0;
for (QWidget* widget : QApplication::topLevelWidgets()){
QMessageBox* box = qobject_cast<QMessageBox*>(widget);
if (box == nullptr || !box->isVisible()){
continue;
}
count++;
out << "popup: " << box->windowTitle().toStdString() << ": " << box->text().toStdString() << "\n";
if (close){
QPushButton* button = box->defaultButton();
if (button != nullptr){
button->click();
}else{
box->done(0);
}
}
}
out << count << (close ? " closed" : " open") << "\n";
return std::string();
});
}

std::string LabChannel::run_on_ui(const std::function<std::string()>& body){
struct Call{
Mutex lock;
Expand Down Expand Up @@ -510,11 +583,16 @@
running = current != ProgramState::STOPPED;
}

std::string LabChannel::read_controller_status(){
return m_panel == nullptr ? "" : m_console->controller_status(*m_panel);
}

void LabChannel::write_state(){
{
std::lock_guard<Mutex> lg(m_panel_lock);
bool running;
read_program_state(m_state.state, m_state.program, running);
m_state.controller = read_controller_status();
}
m_state.owner = m_owner.token();
std::string text = lab_state_text(m_state);
Expand Down
9 changes: 9 additions & 0 deletions SerialPrograms/Source/CommonFramework/Windows/LabChannel.h
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,11 @@ class LabConsoleCommands{
const std::vector<std::string>& words, LabCommandOutput& output
) = 0;

// "ready" when the console's controller can take commands, "none" when
// it can't (not connected yet, or reconnecting after a program switch),
// "" when `panel` has no console. Read for the state file and by "start".
virtual std::string controller_status(PanelSession& panel) = 0;

// The press that keeps the console awake ("keepawake on").
virtual void keep_awake(PanelSession& panel, CancellableScope& scope) = 0;

Expand Down Expand Up @@ -123,12 +128,16 @@ class LabChannel{
std::string run_console_command(const std::vector<std::string>& words, LabCommandOutput& output);
std::string run_on_console(const std::function<void(PanelSession& panel, CancellableScope& scope)>& body);
std::string run_ui_command(const LabRequestLine& line, std::ostream& out);
std::string run_start(const std::vector<std::string>& words);
std::string run_popups(const std::vector<std::string>& words, std::ostream& out);
std::string run_on_ui(const std::function<std::string()>& body);
void keep_awake();
void write_state();

// The state of the selected program. Call under m_panel_lock.
void read_program_state(std::string& state, std::string& program, bool& running) const;
// The selected panel's LabConsoleCommands::controller_status(). Call under m_panel_lock.
std::string read_controller_status();


private:
Expand Down
64 changes: 59 additions & 5 deletions SerialPrograms/Source/CommonFramework/Windows/LabChannel_Tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
* From: https://github.com/PokemonAutomation/
*
* The channel's text formats, with no app: request files, the journal, the
* "state" file, the owner lock and the keep-awake schedule.
* "state" file, the owner lock, the keep-awake schedule and the wait for
* the controller before "start".
*
*/

Expand Down Expand Up @@ -139,12 +140,12 @@
}

UnitTestResult test_state_text(){
LabState state{"r1", "RUNNING", "PokemonBDSP:AutoStory", "lab-B", ""};
if (lab_state_text(state) != "seq=r1\nstate=RUNNING\nprogram=PokemonBDSP:AutoStory\nowner=lab-B\nerror=\n"){
LabState state{"r1", "RUNNING", "PokemonBDSP:AutoStory", "ready", "lab-B", ""};
if (lab_state_text(state) != "seq=r1\nstate=RUNNING\nprogram=PokemonBDSP:AutoStory\ncontroller=ready\nowner=lab-B\nerror=\n"){
return "Unexpected state text: " + lab_state_text(state);
}
state = {"", "NO_PROGRAM", "", "", "The selected panel is not a program."};
if (lab_state_text(state) != "seq=\nstate=NO_PROGRAM\nprogram=\nowner=\nerror=The selected panel is not a program.\n"){
state = {"", "NO_PROGRAM", "", "", "", "The selected panel is not a program."};
if (lab_state_text(state) != "seq=\nstate=NO_PROGRAM\nprogram=\ncontroller=\nowner=\nerror=The selected panel is not a program.\n"){
return "Unexpected state text: " + lab_state_text(state);
}
return true;
Expand Down Expand Up @@ -226,6 +227,58 @@
return true;
}

// A controller that reads "none" for `not_ready` checks, then `then`, with
// a fake sleep that only counts.
struct FakeController{
FakeController(int p_not_ready, std::string p_then, bool p_closing = false)
: not_ready(p_not_ready), then(std::move(p_then)), closing(p_closing)
{}

int not_ready;
std::string then;
bool closing;

std::string error;
Milliseconds slept = 0ms;

FakeController& wait(Milliseconds timeout){
int checks = 0;
error = wait_for_controller(
[&]{ return checks++ < not_ready ? std::string("none") : then; },
[&](Milliseconds slice){ slept += slice; return !closing; },
timeout, 500ms
);
return *this;
}
};

UnitTestResult test_controller_wait(){

Check warning on line 255 in SerialPrograms/Source/CommonFramework/Windows/LabChannel_Tests.cpp

View workflow job for this annotation

GitHub Actions / code-health

Code health (advisory)

PokemonAutomation::test_controller_wait(): function_lines=26 (advisory above 25, limit 50)
FakeController ready(0, "ready");
if (!ready.wait(30s).error.empty() || ready.slept != 0ms){
return "A ready controller starts at once.";
}
FakeController reconnecting(4, "ready");
if (!reconnecting.wait(30s).error.empty() || reconnecting.slept != 2000ms){
return std::format("A reconnecting controller is waited for; slept {} ms.", reconnecting.slept.count());
}
FakeController no_console(0, "");
if (!no_console.wait(30s).error.empty()){
return "A panel without a console does not wait.";
}
FakeController never(1000, "ready");
if (never.wait(3s).error != "controller not connected" || never.slept != 3000ms){
return std::format("A controller that never connects refuses the start after the timeout; slept {} ms.", never.slept.count());
}
FakeController closing(1000, "ready", true);
if (closing.wait(30s).error != "The app is closing."){
return "A closing app stops the wait.";
}
if (parse_seconds("30") != 30s || parse_seconds("0") || parse_seconds("soon") || parse_seconds("")){
return "parse_seconds() takes whole seconds of at least 1.";
}
return true;
}


class Test_LabChannel : public UnitTest{
public:
Expand Down Expand Up @@ -253,6 +306,7 @@
database.add<Test_LabChannel>("state text", test_state_text);
database.add<Test_LabChannel>("owner lock", test_owner);
database.add<Test_LabChannel>("keep-awake schedule", test_keep_awake);
database.add<Test_LabChannel>("controller wait", test_controller_wait);
}


Expand Down
40 changes: 34 additions & 6 deletions SerialPrograms/Source/CommonFramework/Windows/LabRequest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,17 @@ std::string line_after_words(const std::string& line, size_t count){
return text.substr(begin, end + 1 - begin);
}

std::optional<Seconds> parse_seconds(const std::string& word){
const char* begin = word.c_str();
char* end = nullptr;
errno = 0;
const long seconds = std::strtol(begin, &end, 10);
if (end == begin || *end != '\0' || errno == ERANGE || seconds < 1){
return std::nullopt;
}
return Seconds(seconds);
}

std::optional<Filesystem::Path> next_request_file(const std::string& inbox){
std::optional<Filesystem::Path> next;
for (const Filesystem::Path& path : Filesystem::list_directory(Filesystem::Path(inbox))){
Expand Down Expand Up @@ -118,11 +129,31 @@ std::string lab_state_text(const LabState& state){
"seq=" + state.seq + "\n" +
"state=" + state.state + "\n" +
"program=" + state.program + "\n" +
"controller=" + state.controller + "\n" +
"owner=" + state.owner + "\n" +
"error=" + state.error + "\n";
}


std::string wait_for_controller(
const std::function<std::string()>& status,
const std::function<bool(Milliseconds)>& sleep,
Milliseconds timeout, Milliseconds slice
){
Milliseconds waited(0);
while (status() == "none"){
if (waited >= timeout){
return "controller not connected";
}
if (!sleep(slice)){
return "The app is closing.";
}
waited += slice;
}
return "";
}


std::string LabOwner::claim(const std::string& request_owner, const std::string& token){
if (token.empty()){
return "owner claim: missing token";
Expand Down Expand Up @@ -157,14 +188,11 @@ std::string KeepAwakeSchedule::set(const std::vector<std::string>& words, WallCl
}
Seconds interval = DEFAULT_INTERVAL;
if (words.size() > 2){
const char* begin = words[2].c_str();
char* end = nullptr;
errno = 0;
const long seconds = std::strtol(begin, &end, 10);
if (end == begin || *end != '\0' || errno == ERANGE || seconds < 1){
const std::optional<Seconds> seconds = parse_seconds(words[2]);
if (!seconds){
return "keepawake: seconds must be a whole number of at least 1, got " + words[2];
}
interval = Seconds(seconds);
interval = *seconds;
}
m_on = words[1] == "on";
m_interval = interval;
Expand Down
Loading
Loading