1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
|
#include "ipc_state.h"
#define _WEBSOCKETPP_CPP11_STRICT_
#include <fmt/core.h>
#include <chrono>
#include <memory>
#include <mutex>
#include <nlohmann/json.hpp>
#include <optional>
#include <set>
#include <string>
#include <thread>
#include <tuple>
#include <wswrap.hpp>
#include "ap_state.h"
#include "logger.h"
#include "tracker_frame.h"
namespace {
struct IPCState {
std::mutex state_mutex;
TrackerFrame* tracker_frame = nullptr;
// Protected state
bool initialized = false;
std::string address;
bool should_disconnect = false;
std::optional<std::string> status_message;
bool slot_matches = false;
std::string tracker_ap_server;
std::string tracker_ap_user;
std::string game_ap_server;
std::string game_ap_user;
std::optional<std::tuple<int, int>> player_position;
std::set<std::string> solved_panels;
// Thread state
std::unique_ptr<wswrap::WS> ws;
bool connected = false;
void SetTrackerFrame(TrackerFrame* frame) { tracker_frame = frame; }
void Connect(std::string a) {
// This is the main concurrency concern, as it mutates protected state in an
// important way. Thread() is documented with how it interacts with this
// function.
std::lock_guard state_guard(state_mutex);
if (!initialized) {
std::thread([this]() { Thread(); }).detach();
initialized = true;
} else if (address != a) {
should_disconnect = true;
}
address = a;
}
std::optional<std::string> GetStatusMessage() {
std::lock_guard state_guard(state_mutex);
return status_message;
}
void SetTrackerSlot(std::string server, std::string user) {
// This is function is called from the APState thread, not the main thread,
// and it mutates protected state. It only really competes with OnMessage(),
// when a "Connect" message is received. If this is called right before,
// and the tracker slot does not match the old game slot, it will initiate a
// disconnect, and then the OnMessage() handler will see should_disconnect
// and stop processing the "Connect" message. If this is called right after
// and the slot does not match, IPC will disconnect, which is tolerable.
std::lock_guard state_guard(state_mutex);
tracker_ap_server = std::move(server);
tracker_ap_user = std::move(user);
CheckIfSlotMatches();
if (!slot_matches) {
should_disconnect = true;
address.clear();
}
}
bool IsConnected() {
std::lock_guard state_guard(state_mutex);
return slot_matches;
}
std::optional<std::tuple<int, int>> GetPlayerPosition() {
std::lock_guard state_guard(state_mutex);
return player_position;
}
const std::set<std::string>& GetSolvedPanels() {
std::lock_guard state_guard(state_mutex);
return solved_panels;
}
private:
void Thread() {
for (;;) {
SetStatusMessage("Disconnected from game.");
// initialized is definitely true because it is set to true when the thread
// is created and only set to false within this block, when the thread is
// killed. Thus, a call to Connect would always at most set
// should_disconnect and address. If this happens before this block, it is
// as if we are starting from a new thread anyway because should_disconnect
// is immediately reset. If a call to Connect happens after this block,
// then a connection attempt will be made to the wrong address, but the
// thread will grab the mutex right after this and back out the wrong
// connection.
std::string ipc_address;
{
std::lock_guard state_guard(state_mutex);
should_disconnect = false;
slot_matches = false;
game_ap_server.clear();
game_ap_user.clear();
player_position = std::nullopt;
solved_panels.clear();
if (address.empty()) {
initialized = false;
return;
}
ipc_address = address;
}
int backoff_amount = 0;
SetStatusMessage("Connecting to game...");
TrackerLog(fmt::format("Looking for game over IPC ({})...", ipc_address));
while (!TryConnect(ipc_address) || !connected) {
int backoff_limit = (backoff_amount + 1) * 10;
for (int i = 0; i < backoff_limit && !connected; i++) {
// If Connect is called right before this block, we will see and handle
// should_disconnect. If it is called right after, we will do one bad
// poll, one sleep, and then grab the mutex again right after.
{
std::lock_guard state_guard(state_mutex);
if (should_disconnect) {
break;
}
}
ws->poll();
// Back off
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
backoff_amount++;
// If Connect is called right before this block, we will see and handle
// should_disconnect. If it is called right after, and the connection
// was unsuccessful, we will grab the mutex after one bad connection
// attempt. If the connection was successful, we grab the mutex right
// after exiting the loop.
{
std::lock_guard state_guard(state_mutex);
if (should_disconnect) {
break;
} else if (!connected) {
if (backoff_amount >= 10) {
should_disconnect = true;
address.clear();
TrackerLog("Giving up on IPC.");
SetStatusMessage("Disconnected from game.");
wxMessageBox("Connection to Lingo timed out.",
"Connection failed", wxOK | wxICON_ERROR);
break;
} else {
TrackerLog(fmt::format("Retrying IPC in {} second(s)...",
backoff_amount + 1));
}
}
}
}
// Pretty much every lock guard in the thread is the same. We check for
// should_disconnect, and if it gets set directly after the block, we do
// minimal bad work before checking for it again.
{
std::lock_guard state_guard(state_mutex);
if (should_disconnect) {
ws.reset();
continue;
}
}
while (connected) {
ws->poll();
std::this_thread::sleep_for(std::chrono::milliseconds(100));
{
std::lock_guard state_guard(state_mutex);
if (should_disconnect) {
ws.reset();
break;
}
}
}
}
}
bool TryConnect(std::string ipc_address) {
try {
ws = std::make_unique<wswrap::WS>(
ipc_address, [this]() { OnConnect(); }, [this]() { OnClose(); },
[this](const std::string& s) { OnMessage(s); },
[this](const std::string& s) { OnError(s); });
return true;
} catch (const std::exception& ex) {
ws.reset();
return false;
}
}
void OnConnect() {
connected = true;
{
std::lock_guard state_guard(state_mutex);
slot_matches = false;
player_position = std::nullopt;
solved_panels.clear();
}
}
void OnClose() {
connected = false;
{
std::lock_guard state_guard(state_mutex);
slot_matches = false;
}
}
void OnMessage(const std::string& s) {
TrackerLog(s);
auto msg = nlohmann::json::parse(s);
if (msg["cmd"] == "Connect") {
std::lock_guard state_guard(state_mutex);
if (should_disconnect) {
return;
}
game_ap_server = msg["slot"]["server"];
game_ap_user = msg["slot"]["player"];
CheckIfSlotMatches();
if (!slot_matches) {
tracker_frame->ConnectToAp(game_ap_server, game_ap_user,
msg["slot"]["password"]);
}
} else if (msg["cmd"] == "UpdatePosition") {
std::lock_guard state_guard(state_mutex);
player_position =
std::make_tuple<int, int>(msg["position"]["x"], msg["position"]["z"]);
tracker_frame->RedrawPosition();
} else if (msg["cmd"] == "SolvePanels") {
std::lock_guard state_guard(state_mutex);
for (std::string panel : msg["panels"]) {
solved_panels.insert(std::move(panel));
}
tracker_frame->UpdateIndicators(kUPDATE_ONLY_PANELS);
}
}
void OnError(const std::string& s) {}
void CheckIfSlotMatches() {
slot_matches = (tracker_ap_server == game_ap_server &&
tracker_ap_user == game_ap_user);
if (slot_matches) {
status_message = "Connected to game.";
Sync();
} else if (connected) {
status_message = "Local game doesn't match AP slot.";
}
tracker_frame->UpdateStatusMessage();
}
void SetStatusMessage(std::optional<std::string> msg) {
{
std::lock_guard state_guard(state_mutex);
status_message = msg;
}
tracker_frame->UpdateStatusMessage();
}
void Sync() {
nlohmann::json msg;
msg["cmd"] = "Sync";
ws->send_text(msg.dump());
}
};
IPCState& GetState() {
static IPCState* instance = new IPCState();
return *instance;
}
} // namespace
void IPC_SetTrackerFrame(TrackerFrame* tracker_frame) {
GetState().SetTrackerFrame(tracker_frame);
}
void IPC_Connect(std::string address) { GetState().Connect(address); }
std::optional<std::string> IPC_GetStatusMessage() {
return GetState().GetStatusMessage();
}
void IPC_SetTrackerSlot(std::string server, std::string user) {
GetState().SetTrackerSlot(server, user);
}
bool IPC_IsConnected() { return GetState().IsConnected(); }
std::optional<std::tuple<int, int>> IPC_GetPlayerPosition() {
return GetState().GetPlayerPosition();
}
const std::set<std::string>& IPC_GetSolvedPanels() {
return GetState().GetSolvedPanels();
}
|