-
-
Notifications
You must be signed in to change notification settings - Fork 59
/
ConnectionWrapper.cs
367 lines (307 loc) · 14.8 KB
/
ConnectionWrapper.cs
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
using PKHeX.Core;
using RaidCrawler.Core.Interfaces;
using RaidCrawler.Core.Structures;
using SysBot.Base;
using System.Net.Sockets;
using System.Text;
using static SysBot.Base.SwitchButton;
namespace RaidCrawler.Core.Connection
{
public class ConnectionWrapperAsync : Offsets
{
public readonly ISwitchConnectionAsync Connection;
public bool Connected { get => Connection is not null && IsConnected; }
private bool IsConnected { get; set; }
private readonly bool CRLF;
private readonly Action<string> _statusUpdate;
private static ulong BaseBlockKeyPointer = 0;
public ConnectionWrapperAsync(SwitchConnectionConfig config, Action<string> statusUpdate)
{
Connection = config.Protocol switch
{
SwitchProtocol.USB => new SwitchUSBAsync(config.Port),
_ => new SwitchSocketAsync(config),
};
CRLF = config.Protocol is SwitchProtocol.WiFi;
_statusUpdate = statusUpdate;
}
public async Task<(bool, string)> Connect(CancellationToken token)
{
if (Connected)
return (true, "");
try
{
_statusUpdate("Connecting...");
Connection.Connect();
BaseBlockKeyPointer = await Connection.PointerAll(BlockKeyPointer, token).ConfigureAwait(false);
IsConnected = true;
_statusUpdate("Connected!");
return (true, "");
}
catch (SocketException e)
{
IsConnected = false;
return (false, e.Message);
}
}
public async Task<(bool, string)> DisconnectAsync(CancellationToken token)
{
if (!Connected)
return (true, "");
try
{
_statusUpdate("Disconnecting controller...");
await Connection.SendAsync(SwitchCommand.DetachController(CRLF), token).ConfigureAwait(false);
_statusUpdate("Disconnecting...");
Connection.Disconnect();
IsConnected = false;
_statusUpdate("Disconnected!");
return (true, "");
}
catch (SocketException e)
{
IsConnected = false;
return (false, e.Message);
}
}
public async Task<int> GetStoryProgress(CancellationToken token)
{
for (int i = DifficultyFlags.Count - 1; i >= 0; i--)
{
// See https://github.com/Lincoln-LM/sv-live-map/pull/43
var block = await ReadSaveBlock(DifficultyFlags[i], 1, token).ConfigureAwait(false);
if (block[0] == 2)
return i + 1;
}
return 0;
}
private async Task<byte[]> ReadSaveBlock(uint key, int size, CancellationToken token)
{
var block_ofs = await SearchSaveKey(key, token).ConfigureAwait(false);
var data = await Connection.ReadBytesAbsoluteAsync(block_ofs + 8, 0x8, token).ConfigureAwait(false);
block_ofs = BitConverter.ToUInt64(data, 0);
var block = await Connection.ReadBytesAbsoluteAsync(block_ofs, size, token).ConfigureAwait(false);
return DecryptBlock(key, block);
}
private async Task<byte[]> ReadSaveBlockObject(uint key, CancellationToken token)
{
var header_ofs = await SearchSaveKey(key, token).ConfigureAwait(false);
var data = await Connection.ReadBytesAbsoluteAsync(header_ofs + 8, 8, token).ConfigureAwait(false);
header_ofs = BitConverter.ToUInt64(data);
var header = await Connection.ReadBytesAbsoluteAsync(header_ofs, 5, token).ConfigureAwait(false);
header = DecryptBlock(key, header);
var size = BitConverter.ToUInt32(header.AsSpan()[1..]);
var obj = await Connection.ReadBytesAbsoluteAsync(header_ofs, (int)size + 5, token).ConfigureAwait(false);
return DecryptBlock(key, obj)[5..];
}
public async Task<byte[]> ReadBlockDefault(uint key, string? cache, bool force, CancellationToken token)
{
var folder = Path.Combine(Directory.GetCurrentDirectory(), "cache");
Directory.CreateDirectory(folder);
var path = Path.Combine(folder, cache ?? "");
if (force is false && cache is not null && File.Exists(path))
return File.ReadAllBytes(path);
var bin = await ReadSaveBlockObject(key, token).ConfigureAwait(false);
File.WriteAllBytes(path, bin);
return bin;
}
public async Task<ulong> SearchSaveKey(uint key, CancellationToken token)
{
var data = await Connection.ReadBytesAbsoluteAsync(BaseBlockKeyPointer + 8, 16, token).ConfigureAwait(false);
var start = BitConverter.ToUInt64(data.AsSpan()[..8]);
var end = BitConverter.ToUInt64(data.AsSpan()[8..]);
while (start < end)
{
var block_ct = (end - start) / 48;
var mid = start + (block_ct >> 1) * 48;
data = await Connection.ReadBytesAbsoluteAsync(mid, 4, token).ConfigureAwait(false);
var found = BitConverter.ToUInt32(data);
if (found == key)
return mid;
if (found >= key)
end = mid;
else start = mid + 48;
}
return start;
}
private static byte[] DecryptBlock(uint key, byte[] block)
{
var rng = new SCXorShift32(key);
for (int i = 0; i < block.Length; i++)
block[i] = (byte)(block[i] ^ rng.Next());
return block;
}
public async Task Click(SwitchButton button, int delay, CancellationToken token)
{
await Connection.SendAsync(SwitchCommand.Click(button, CRLF), token).ConfigureAwait(false);
await Task.Delay(delay, token).ConfigureAwait(false);
}
public async Task Touch(int x, int y, int hold, int delay, CancellationToken token)
{
var command = Encoding.ASCII.GetBytes($"touchHold {x} {y} {hold}{(CRLF ? "\r\n" : "")}");
await Connection.SendAsync(command, token).ConfigureAwait(false);
await Task.Delay(delay, token).ConfigureAwait(false);
}
public async Task SetStick(SwitchStick stick, short x, short y, int hold, int delay, CancellationToken token)
{
await Connection.SendAsync(SwitchCommand.SetStick(stick, x, y, CRLF), token).ConfigureAwait(false);
await Task.Delay(hold, token).ConfigureAwait(false);
await Connection.SendAsync(SwitchCommand.SetStick(stick, 0, 0, CRLF), token).ConfigureAwait(false);
await Task.Delay(delay, token).ConfigureAwait(false);
}
// Thank you to Anubis for sharing a more optimized routine, as well as CloseGame(), StartGame(), and SaveGame()!
public async Task AdvanceDate(IDateAdvanceConfig config, CancellationToken token, Action<int>? action = null)
{
// Not great, but when adding/removing clicks, make sure to account for command count for an accurate StreamerView progress bar.
int steps = (config.UseTouch ? 19 : 25) + (config.UseOvershoot ? 2 : config.SystemDownPresses) + (config.DodgeSystemUpdate ? 2 : 0) + config.DaysToSkip;
_statusUpdate("Changing date...");
var BaseDelay = config.BaseDelay;
// Sometimes the first command drops, click twice with shorter delays for good measure.
await Click(B, 0_100, token).ConfigureAwait(false);
UpdateProgressBar(action, steps);
await Click(B, 0_100, token).ConfigureAwait(false);
UpdateProgressBar(action, steps);
// HOME Menu
await Click(HOME, config.OpenHomeDelay + BaseDelay, token).ConfigureAwait(false);
UpdateProgressBar(action, steps);
// Navigate to Settings
if (config.UseTouch)
{
await Touch(0_840, 0_540, 0_050, 0, token).ConfigureAwait(false);
UpdateProgressBar(action, steps);
}
else
{
await Click(DDOWN, config.NavigateToSettingsDelay + BaseDelay, token).ConfigureAwait(false);
UpdateProgressBar(action, steps);
for (int i = 0; i < 5; i++)
{
await Click(DRIGHT, config.NavigateToSettingsDelay + BaseDelay, token).ConfigureAwait(false);
UpdateProgressBar(action, steps);
}
}
await Click(A, config.OpenSettingsDelay + BaseDelay, token).ConfigureAwait(false);
UpdateProgressBar(action, steps);
// Scroll to bottom
await SetStick(SwitchStick.LEFT, 0, -30_000, config.HoldDuration, 0_100 + BaseDelay, token).ConfigureAwait(false);
UpdateProgressBar(action, steps);
// Navigate to "Date and Time"
_statusUpdate("Navigating to \"Date and Time\"...");
await Click(A, 0_300 + BaseDelay, token).ConfigureAwait(false);
UpdateProgressBar(action, steps);
// Hold down to overshoot Date/Time by one. DUP to recover.
if (config.UseOvershoot)
{
await SetStick(SwitchStick.LEFT, 0, -30_000, config.SystemOvershoot, 0_100 + BaseDelay, token).ConfigureAwait(false);
UpdateProgressBar(action, steps);
await Click(DUP, 0_500 + BaseDelay, token).ConfigureAwait(false);
UpdateProgressBar(action, steps);
}
else
{
for (int i = 0; i < config.SystemDownPresses; i++)
{
await Click(DDOWN, 0_100 + BaseDelay, token).ConfigureAwait(false);
UpdateProgressBar(action, steps);
}
}
// Enter Date/Time
await Click(A, config.Submenu + BaseDelay, token).ConfigureAwait(false);
UpdateProgressBar(action, steps);
// Open Date/Time settings
if (config.UseTouch)
{
await Touch(0_950, 0_400, 0_050, 0, token).ConfigureAwait(false);
UpdateProgressBar(action, steps);
}
else
{
for (int i = 0; i < 2; i++)
{
await Click(DDOWN, 0_100 + BaseDelay, token).ConfigureAwait(false);
UpdateProgressBar(action, steps);
}
}
await Click(A, config.DateChange + BaseDelay, token).ConfigureAwait(false);
UpdateProgressBar(action, steps);
for (int i = 0; i < config.DaysToSkip; i++)
{
await Click(DUP, 0_100 + BaseDelay, token).ConfigureAwait(false);
UpdateProgressBar(action, steps);
}
for (int i = 0; i < 6; i++)
{
await Click(DRIGHT, (i < 5 ? 0_050 : 0_100) + BaseDelay, token).ConfigureAwait(false);
UpdateProgressBar(action, steps);
}
await Click(A, 0_150 + config.DateChange + BaseDelay, token).ConfigureAwait(false);
UpdateProgressBar(action, steps);
// Return to game
await Click(HOME, config.ReturnHomeDelay + BaseDelay, token).ConfigureAwait(false);
UpdateProgressBar(action, steps);
await Click(HOME, (config.DodgeSystemUpdate ? 0_500 : config.ReturnGameDelay) + BaseDelay, token).ConfigureAwait(false);
UpdateProgressBar(action, steps);
if (config.DodgeSystemUpdate)
{
// Attempt to dodge an update prompt.
await Click(DUP, 0_600 + BaseDelay, token).ConfigureAwait(false);
UpdateProgressBar(action, steps);
await Click(A, config.ReturnGameDelay + BaseDelay, token).ConfigureAwait(false);
UpdateProgressBar(action, steps);
}
_statusUpdate("Back in the game...");
}
public async Task CloseGame(CancellationToken token)
{
// Close out of the game
_statusUpdate("Closing the game!");
await Click(B, 0_500, token).ConfigureAwait(false);
await Click(HOME, 2_000, token).ConfigureAwait(false);
await Click(X, 1_000, token).ConfigureAwait(false);
await Click(A, 5_500, token).ConfigureAwait(false);
_statusUpdate("Closed out of the game!");
}
public async Task StartGame(CancellationToken token)
{
// Open game.
_statusUpdate("Starting the game!");
await Click(A, 1_000, token).ConfigureAwait(false);
// Attempt to dodge an update prompt;
await Click(DUP, 0_600, token).ConfigureAwait(false);
await Click(A, 1_000, token).ConfigureAwait(false);
// If they have DLC on the system and can't use it, requires an UP + A to start the game.
// Should be harmless otherwise since they'll be in loading screen.
await Click(DUP, 0_600, token).ConfigureAwait(false);
await Click(A, 0_600, token).ConfigureAwait(false);
// Switch Logo and game load screen
await Task.Delay(17_000, token).ConfigureAwait(false);
for (int i = 0; i < 20; i++)
await Click(A, 1_000, token).ConfigureAwait(false);
_statusUpdate("Back in the overworld! Refreshing the base block key pointer...");
BaseBlockKeyPointer = await Connection.PointerAll(BlockKeyPointer, token).ConfigureAwait(false);
}
public async Task SaveGame(IDateAdvanceConfig config, CancellationToken token)
{
_statusUpdate("Saving the game...");
// B out in case we're in some menu.
for (int i = 0; i < 4; i++)
await Click(B, 0_500, token).ConfigureAwait(false);
// Open the menu and save.
await Click(X, 1_000, token).ConfigureAwait(false);
await Click(R, 1_000, token).ConfigureAwait(false);
await Click(A, 1_000, token).ConfigureAwait(false);
await Click(A, 1_000, token).ConfigureAwait(false);
await Click(A, 3_000 + config.SaveGameDelay, token).ConfigureAwait(false);
// Return to overworld.
for (int i = 0; i < 4; i++)
await Click(B, 0_500, token).ConfigureAwait(false);
_statusUpdate("Game saved!");
}
private static void UpdateProgressBar(Action<int>? action, int steps)
{
if (action is null)
return;
action.Invoke(steps);
}
}
}