-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPPSSPP.cs
539 lines (456 loc) · 12.6 KB
/
PPSSPP.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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
using System.Diagnostics;
using System.Net.WebSockets;
using System.Reactive.Linq;
using System.Runtime.Serialization;
using System.Text.Json;
using System.Text.Json.Serialization;
using ppsspp_api.Endpoints;
using Websocket.Client;
namespace ppsspp_api;
/// <summary>
///
/// </summary>
public sealed class Ppsspp : IAsyncDisposable
{
/// <summary>
/// Error levels as reported by the debugger
/// </summary>
public enum ErrorLevels
{
/// <summary>
/// Default error level when severity is indeterminate
/// </summary>
Unknown = 0,
/// <summary>
/// VERY important information that is NOT errors. Like startup and debugprintfs from the game itself.
/// </summary>
Notice = 1,
/// <summary>
/// Important errors.
/// </summary>
Error = 2,
/// <summary>
/// Something is suspicious.
/// </summary>
Warn = 3,
/// <summary>
/// General information.
/// </summary>
Info = 4,
/// <summary>
/// Detailed debugging - might make things slow.
/// </summary>
Debug = 5,
/// <summary>
/// Noisy debugging - sometimes needed but usually unimportant.
/// </summary>
Verbose = 6,
}
private const string PpssppMatchApi = "https://report.ppsspp.org/match/list";
private const string PpssppSubProtocol = "debugger.ppsspp.org";
private const string PpssppDefaultPath = "/debugger";
/// <summary>
/// string indicating name of app or tool
/// </summary>
internal string ClientName { get; init; }
/// <summary>
/// string indicating version of app or tool
/// </summary>
internal string ClientVersion { get; init; }
/// <summary>
/// Requires a client name and version for handshake with the debugger
/// </summary>
/// <param name="clientName"><see cref="ClientName"/></param>
/// <param name="clientVersion"><inheritdoc cref="ClientVersion"/></param>
public Ppsspp(string clientName, string clientVersion)
{
ClientName = clientName;
ClientVersion = clientVersion;
Game = new Game(this);
Cpu = new Cpu(this);
Memory = new Memory(this);
Hle = new Hle(this);
Input = new Input(this);
}
/// <summary>
/// Set this to a function receiving (message, level) for errors.
/// </summary>
public event EventHandler<ResultMessage>? OnError;
/// <summary>
/// Set this to a function with no parameters called on disconnect.
/// </summary>
public event EventHandler? OnClose;
private WebsocketClient? _socket;
private readonly Dictionary<string, EventHandler<JsonElement>> _pendingTickets = new();
private readonly string[] _noResponseEvents = { "cpu.stepping", "cpu.resume" };
/// <inheritdoc cref="Game"/>
public readonly Game Game;
/// <inheritdoc cref="Cpu"/>
public readonly Cpu Cpu;
/// <inheritdoc cref="Memory"/>
public readonly Memory Memory;
/// <inheritdoc cref="Hle"/>
public readonly Hle Hle;
/// <inheritdoc cref="Input"/>
public readonly Input Input;
/// <summary>
/// The autoConnect() function tries to find a nearby PPSSPP instance.
/// If you have multiple, it may be the wrong one.
/// </summary>
/// <returns></returns>
/// <exception cref="FailedConnectionException">Throws when client is unable to connect to a nearby instance</exception>
/// <exception cref="AlreadyConnectedException">Throws when the socket already exists</exception>
public async Task AutoConnectAsync()
{
if (_socket != null)
{
throw new AlreadyConnectedException();
}
using var client = new HttpClient();
await using var stream = await client.GetStreamAsync(PpssppMatchApi);
var listing = await JsonSerializer.DeserializeAsync<Endpoint[]>(stream);
_socket = await TryNextEndpointAsync(listing);
try
{
SetupSocket(_socket);
}
catch (Exception e)
{
throw new FailedConnectionException(_socket.Url, innerException: e);
}
}
/// <summary>
/// Connect to a specific WebSocket URI (ie. ws://127.0.0.1:45333/debugger)
/// </summary>
/// <param name="uri">The PPSSPP debugger endpoint</param>
/// <returns>A subscribed <see cref="WebsocketClient"/> with a subprotocol and listeners</returns>
/// <exception cref="AlreadyConnectedException">Throws when client is already connected to the debugger</exception>
/// <exception cref="FailedConnectionException">Throws when client is unable to connect to <paramref name="uri"/></exception>
public async Task<WebsocketClient> ConnectAsync(Uri uri)
{
if (uri.Scheme != "ws")
{
throw new UriFormatException("Provided endpoint is not a websocket url");
}
if (_socket != null)
{
throw new AlreadyConnectedException();
}
var possibleSocket = new WebsocketClient(uri, () =>
{
var clientWebSocket = new ClientWebSocket();
clientWebSocket.Options.AddSubProtocol(PpssppSubProtocol);
return clientWebSocket;
}
);
await possibleSocket.StartOrFail();
if (!possibleSocket.IsStarted)
{
throw new FailedConnectionException(uri);
}
_socket = possibleSocket;
try
{
SetupSocket(_socket);
}
catch (Exception e)
{
throw new FailedConnectionException(uri, innerException: e);
}
return _socket;
}
private async Task DisconnectAsync()
{
if (_socket == null)
{
throw new NotConnectedException();
}
FailAllPending("Disconnected from PPSSPP");
await _socket.Stop(WebSocketCloseStatus.NormalClosure, "Disconnected from PPSSPP");
_socket.Dispose();
_socket = null;
OnClose?.Invoke(this, EventArgs.Empty);
}
internal Task<T> SendAsync<T>(ResultMessage data)
where T : MessageEventArgs, new()
{
if (_socket == null)
{
throw new NotConnectedException();
}
if (_noResponseEvents.Contains(data.Event))
{
_socket.Send(JsonSerializer.Serialize(data, new JsonSerializerOptions
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
}));
}
var ticket = MakeTicket();
var tcs = new TaskCompletionSource<T>();
_pendingTickets[ticket] = (_, args) =>
{
if (args.GetProperty("event").GetString() == "error")
{
tcs.SetException(new Exception(args.GetProperty("message").GetString())
{
Data =
{
["ReceivedMessage"] = args.GetRawText(),
},
});
}
else
{
var result = args.Deserialize<T>() ?? new T();
result.Data = args;
tcs.SetResult(result);
}
};
data.Ticket = ticket;
_socket.Send(JsonSerializer.Serialize(data, new JsonSerializerOptions
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
}));
return tcs.Task;
}
private void SetupSocket(IWebsocketClient? websocketClient)
{
websocketClient?.DisconnectionHappened.Subscribe(info =>
{
OnClose?.Invoke(this, EventArgs.Empty);
FailAllPending($"PPSSPP disconnected {info.Exception?.Message}");
}
);
websocketClient?.MessageReceived.Select(message => Observable.FromAsync(async () =>
{
JsonElement root = new();
try
{
using var doc = JsonDocument.Parse(message.Text);
root = doc.RootElement;
if (root.GetProperty("event").GetString() == "error")
{
await HandleErrorAsync(root.GetProperty("message").GetString() ?? "Unknown Error", (ErrorLevels)root.GetProperty("level").GetByte());
}
var handled = false;
if (root.TryGetProperty("ticket", out var ticket))
{
if (!string.IsNullOrWhiteSpace(ticket.GetString()) && _pendingTickets.TryGetValue(ticket.GetString()!, out var handler))
{
_pendingTickets.Remove(ticket.GetString()!);
handler.Invoke(this, root);
handled = true;
}
if (!handled)
{
await HandleErrorAsync("Received mismatched ticket: " + ticket.GetString(), ErrorLevels.Error);
}
}
if (!handled)
{
var eventName = root.GetProperty("event").GetString();
switch (eventName)
{
case "game.start":
Game.Started(root);
break;
case "game.quit":
Game.Quit(root);
break;
case "game.resume":
Game.Resumed(root);
break;
case "game.pause":
Game.Paused(root);
break;
case "cpu.stepping":
Cpu.Stepped(root);
break;
case "input.buttons":
Input.ButtonChanged(root);
break;
case "input.analog":
Input.AnalogChanged(root);
break;
case "cpu.resume":
Cpu.Resumed(root);
break;
default:
await Console.Error.WriteLineAsync($"{eventName} is unsupported");
Debug.WriteLine(root.GetRawText());
break;
}
}
}
catch (Exception ex)
{
await HandleErrorAsync($"Failed to parse message from PPSSPP: {ex.Message}", ErrorLevels.Error);
Debug.WriteLine(root.GetRawText());
throw;
}
}))
.Merge()
.Subscribe();
}
private async Task<WebsocketClient> TryNextEndpointAsync(IEnumerable<Endpoint>? listing)
{
while (true)
{
var endpoints = listing as Endpoint[] ?? listing?.ToArray();
if (endpoints == null || !endpoints.Any())
{
throw new NoEndpointsException();
}
var ipAddress = endpoints.First().IpAddress;
if (ipAddress.Contains(':'))
{
ipAddress = $"[{ipAddress}]";
}
var endpoint = new Uri($"ws://{ipAddress}:{endpoints.First().Port}{PpssppDefaultPath}");
var socket = await ConnectAsync(endpoint);
if (socket.IsRunning)
{
return socket;
}
if (endpoints.Length > 1)
{
listing = endpoints.Skip(1);
continue;
}
break;
}
return default!;
}
private async Task HandleErrorAsync(string message, ErrorLevels level = ErrorLevels.Unknown)
{
if (OnError != null && OnError.GetInvocationList().Any())
{
OnError?.Invoke(this, new ResultMessage
{
Message = message,
Level = level,
});
}
else if (level is ErrorLevels.Unknown or ErrorLevels.Error)
{
await Console.Error.WriteLineAsync($"{level}: {message}");
}
else
{
Console.WriteLine($"{level}: {message}");
}
}
private string MakeTicket()
{
const string chars = "0123456789abcdefghijklmnopqrstuvwxyz";
var random = new Random();
while (true)
{
var ticket = new string(Enumerable.Repeat(chars, 11)
.Select(s => s[random.Next(s.Length)])
.ToArray());
if (_pendingTickets.ContainsKey(ticket))
{
continue;
}
return ticket;
}
}
private void FailAllPending(string message)
{
var data = new ResultMessage { Event = "error", Message = message, Level = ErrorLevels.Error };
foreach (var pendingTicket in _pendingTickets.ToArray())
{
_pendingTickets[pendingTicket.Key].Invoke(this, JsonSerializer.SerializeToElement(data));
}
_pendingTickets.Clear();
}
/// <summary>
/// Once this object is disposed the connection is cleaned up with events triggered
/// </summary>
public async ValueTask DisposeAsync()
{
if (_socket != null && (_socket.IsStarted || _socket.IsRunning))
{
await DisconnectAsync();
}
GC.SuppressFinalize(this);
}
}
/// <summary>
///
/// </summary>
[Serializable]
public class FailedConnectionException : Exception
{
public FailedConnectionException() : base()
{
}
public FailedConnectionException(string? message) : base(message)
{
}
public FailedConnectionException(Uri url) : base($"Couldn't connect to {url}")
{
}
public FailedConnectionException(Uri url, Exception? innerException) : base($"Couldn't connect to {url}", innerException)
{
}
public FailedConnectionException(string? message, Exception? innerException) : base(message, innerException)
{
}
protected FailedConnectionException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
/// <summary>
///
/// </summary>
[Serializable]
public class NotConnectedException : Exception
{
public NotConnectedException() : base("Not connected")
{
}
public NotConnectedException(string? message) : base(message)
{
}
public NotConnectedException(string? message, Exception? innerException) : base(message, innerException)
{
}
protected NotConnectedException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
/// <summary>
///
/// </summary>
[Serializable]
public class NoEndpointsException : Exception
{
public NoEndpointsException() : base("Couldn't connect automatically. Is PPSSPP connected to the same network?")
{
}
public NoEndpointsException(string? message) : base(message)
{
}
public NoEndpointsException(string? message, Exception? innerException) : base(message, innerException)
{
}
protected NoEndpointsException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
/// <summary>
///
/// </summary>
[Serializable]
public class AlreadyConnectedException : Exception
{
/// <inheritdoc cref="AlreadyConnectedException"/>
public AlreadyConnectedException() : base("Already connected, disconnect first")
{
}
protected AlreadyConnectedException(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext)
{
}
}