-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJunoClient.cs
More file actions
411 lines (369 loc) · 16 KB
/
JunoClient.cs
File metadata and controls
411 lines (369 loc) · 16 KB
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
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace VizzyCode
{
/// <summary>
/// HTTP client that talks to the VizzyCode mod running inside Juno: New Origins.
/// The mod listens on http://127.0.0.1:7842/.
///
/// All methods return null / false on network error so callers can display
/// a friendly "not connected" message.
/// </summary>
internal static class JunoClient
{
public const string BaseUrl = "http://127.0.0.1:7842";
public const int TimeoutMs = 3000;
private static readonly HttpClient _http = new()
{
Timeout = TimeSpan.FromMilliseconds(TimeoutMs)
};
// ── DTOs ──────────────────────────────────────────────────────────────
public class StatusInfo
{
public bool Ok { get; set; }
public string? ModVersion { get; set; }
public string? Scene { get; set; } // "designer" | "flight" | "menu"
public string? CraftName { get; set; }
}
public class PartInfo
{
public int Id { get; set; }
public string? Name { get; set; }
public bool HasVizzy { get; set; }
}
public class CraftInfo
{
public string? Name { get; set; }
public PartInfo[]? Parts { get; set; }
}
public class VizzyInfo
{
public bool Ok { get; set; }
public int PartId { get; set; }
public string? PartName { get; set; }
public string? Xml { get; set; }
public string? Error { get; set; }
}
public class StagesInfo
{
public bool Ok { get; set; } = true;
public string? Error { get; set; }
public int CurrentStage { get; set; }
public int NumStages { get; set; }
public string[] ActivationGroupNames { get; set; } = Array.Empty<string>();
public bool[] ActivationGroupStates { get; set; } = Array.Empty<bool>();
}
// ── API calls ─────────────────────────────────────────────────────────
/// <summary>Ping the mod. Returns null if not running.</summary>
public static async Task<StatusInfo?> GetStatusAsync()
{
try
{
string json = await GetAsync("/status");
return ParseStatus(json);
}
catch { return null; }
}
/// <summary>Get the current craft's part list.</summary>
public static async Task<CraftInfo?> GetCraftAsync()
{
try
{
string json = await GetAsync("/craft");
return ParseCraft(json);
}
catch { return null; }
}
/// <summary>Get the Vizzy XML for a specific part.</summary>
public static async Task<VizzyInfo?> GetVizzyAsync(int partId)
{
try
{
string json = await GetAsync($"/vizzy/{partId}");
return ParseVizzy(json);
}
catch { return null; }
}
/// <summary>Push a Vizzy XML string to the game for a specific part.</summary>
public static async Task<VizzyInfo?> PutVizzyAsync(int partId, string xml)
{
try
{
// Escape XML for embedding in JSON
string escaped = xml.Replace("\\", "\\\\").Replace("\"", "\\\"")
.Replace("\n", "\\n").Replace("\r", "\\r").Replace("\t", "\\t");
string body = $"{{\"xml\":\"{escaped}\"}}";
string json = await PutAsync($"/vizzy/{partId}", body);
return ParseVizzy(json);
}
catch (Exception ex) { return new VizzyInfo { Ok = false, Error = ex.Message }; }
}
/// <summary>Get staging information for the active craft.</summary>
public static async Task<StagesInfo?> GetStagesAsync()
{
try
{
string json = await GetAsync("/stages");
return ParseStages(json);
}
catch { return null; }
}
/// <summary>Get the full bridge snapshot JSON for diagnostics and AI context.</summary>
public static async Task<string?> GetSnapshotJsonAsync()
{
try { return await GetAsync("/snapshot"); }
catch { return null; }
}
/// <summary>Get the live telemetry JSON for the active craft.</summary>
public static async Task<string?> GetTelemetryJsonAsync()
{
try { return await GetAsync("/telemetry"); }
catch { return null; }
}
/// <summary>Get the extended telemetry JSON (lat/lon, atmosphere, angular velocity, universal time).</summary>
public static async Task<string?> GetTelemetryFullJsonAsync()
{
try { return await GetAsync("/telemetry/full"); }
catch { return null; }
}
/// <summary>Trigger the next stage activation (flight scene only).</summary>
public static async Task<StagesInfo?> ActivateStageAsync()
{
try
{
string json = await PostAsync("/stages/activate", "{}");
return ParseStages(json);
}
catch { return null; }
}
// ── HTTP helpers ──────────────────────────────────────────────────────
private static async Task<string> GetAsync(string path)
{
var r = await _http.GetAsync(BaseUrl + path);
return await r.Content.ReadAsStringAsync();
}
private static async Task<string> PutAsync(string path, string json)
{
var content = new StringContent(json, Encoding.UTF8, "application/json");
var r = await _http.PutAsync(BaseUrl + path, content);
return await r.Content.ReadAsStringAsync();
}
private static async Task<string> PostAsync(string path, string json)
{
var content = new StringContent(json, Encoding.UTF8, "application/json");
var r = await _http.PostAsync(BaseUrl + path, content);
return await r.Content.ReadAsStringAsync();
}
// ── Minimal JSON parsers ──────────────────────────────────────────────
// We use simple field extraction to avoid taking a JSON library dependency.
private static StatusInfo? ParseStatus(string? j) => j == null ? null : new StatusInfo
{
Ok = JsonBool(j, "ok") ?? false,
ModVersion = JsonStr(j, "modVersion"),
Scene = JsonStr(j, "scene"),
CraftName = JsonStr(j, "craftName")
};
private static CraftInfo? ParseCraft(string? j)
{
if (j == null || j.Contains("\"error\"")) return null;
var parts = ParsePartArray(j);
return new CraftInfo { Name = JsonStr(j, "name"), Parts = parts };
}
private static PartInfo[] ParsePartArray(string j)
{
// Very simple: split on "}," within the "parts" array
int arrStart = j.IndexOf("\"parts\"", StringComparison.Ordinal);
if (arrStart < 0) return Array.Empty<PartInfo>();
int bracket = j.IndexOf('[', arrStart);
int bracketEnd = j.LastIndexOf(']');
if (bracket < 0 || bracketEnd < 0) return Array.Empty<PartInfo>();
string arr = j.Substring(bracket + 1, bracketEnd - bracket - 1);
var list = new System.Collections.Generic.List<PartInfo>();
// Split on object boundaries
int depth = 0, start = 0;
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] == '{') { if (depth++ == 0) start = i; }
else if (arr[i] == '}')
{
if (--depth == 0)
{
string obj = arr.Substring(start, i - start + 1);
list.Add(new PartInfo
{
Id = JsonInt(obj, "id") ?? 0,
Name = JsonStr(obj, "name") ?? "",
HasVizzy = JsonBool(obj, "hasVizzy") ?? false
});
}
}
}
return list.ToArray();
}
private static VizzyInfo? ParseVizzy(string? j) => j == null ? null : new VizzyInfo
{
Ok = JsonBool(j, "ok") ?? false,
PartId = JsonInt(j, "partId") ?? 0,
PartName = JsonStr(j, "partName"),
Xml = JsonStr(j, "xml"),
Error = JsonStr(j, "error")
};
private static StagesInfo? ParseStages(string? j) => j == null ? null : new StagesInfo
{
Ok = JsonBool(j, "ok") ?? !j.Contains("\"error\"", StringComparison.Ordinal),
Error = JsonStr(j, "error"),
CurrentStage = JsonInt(j, "currentStage") ?? 0,
NumStages = JsonInt(j, "numStages") ?? 0,
ActivationGroupNames = JsonStringArray(j, "activationGroupNames"),
ActivationGroupStates = JsonBoolArray(j, "activationGroupStates")
};
// ── Field extractors ──────────────────────────────────────────────────
private static string? JsonStr(string? j, string key)
{
if (j == null) return null;
int ki = j.IndexOf($"\"{key}\"", StringComparison.Ordinal);
if (ki < 0) return null;
int colon = j.IndexOf(':', ki);
if (colon < 0) return null;
// Skip whitespace
int pos = colon + 1;
while (pos < j.Length && j[pos] == ' ') pos++;
if (pos >= j.Length) return null;
if (j[pos] == 'n') return null; // null
if (j[pos] != '"') return null;
pos++;
var sb = new StringBuilder();
while (pos < j.Length)
{
char c = j[pos];
if (c == '\\' && pos + 1 < j.Length)
{
char n = j[pos + 1];
switch (n)
{
case '"': sb.Append('"'); pos += 2; continue;
case '\\': sb.Append('\\'); pos += 2; continue;
case 'n': sb.Append('\n'); pos += 2; continue;
case 'r': sb.Append('\r'); pos += 2; continue;
case 't': sb.Append('\t'); pos += 2; continue;
default: sb.Append(n); pos += 2; continue;
}
}
if (c == '"') break;
sb.Append(c); pos++;
}
return sb.ToString();
}
private static bool? JsonBool(string j, string key)
{
if (j == null) return null;
int ki = j.IndexOf($"\"{key}\"", StringComparison.Ordinal);
if (ki < 0) return null;
int colon = j.IndexOf(':', ki);
if (colon < 0) return null;
string rest = j.Substring(colon + 1).TrimStart();
if (rest.StartsWith("true", StringComparison.OrdinalIgnoreCase)) return true;
if (rest.StartsWith("false", StringComparison.OrdinalIgnoreCase)) return false;
return null;
}
private static int? JsonInt(string j, string key)
{
if (j == null) return null;
int ki = j.IndexOf($"\"{key}\"", StringComparison.Ordinal);
if (ki < 0) return null;
int colon = j.IndexOf(':', ki);
if (colon < 0) return null;
int pos = colon + 1;
while (pos < j.Length && j[pos] == ' ') pos++;
var sb = new StringBuilder();
while (pos < j.Length && (char.IsDigit(j[pos]) || j[pos] == '-')) { sb.Append(j[pos]); pos++; }
return int.TryParse(sb.ToString(), out int v) ? v : (int?)null;
}
private static string[] JsonStringArray(string j, string key)
{
string? arr = JsonArrayBody(j, key);
if (arr == null) return Array.Empty<string>();
var values = new System.Collections.Generic.List<string>();
int pos = 0;
while (pos < arr.Length)
{
while (pos < arr.Length && (char.IsWhiteSpace(arr[pos]) || arr[pos] == ',')) pos++;
if (pos >= arr.Length) break;
if (arr[pos] == 'n')
{
values.Add("");
pos += 4;
continue;
}
if (arr[pos] != '"') break;
pos++;
var sb = new StringBuilder();
while (pos < arr.Length)
{
char c = arr[pos];
if (c == '\\' && pos + 1 < arr.Length)
{
char n = arr[pos + 1];
switch (n)
{
case '"': sb.Append('"'); pos += 2; continue;
case '\\': sb.Append('\\'); pos += 2; continue;
case 'n': sb.Append('\n'); pos += 2; continue;
case 'r': sb.Append('\r'); pos += 2; continue;
case 't': sb.Append('\t'); pos += 2; continue;
default: sb.Append(n); pos += 2; continue;
}
}
if (c == '"') { pos++; break; }
sb.Append(c);
pos++;
}
values.Add(sb.ToString());
}
return values.ToArray();
}
private static bool[] JsonBoolArray(string j, string key)
{
string? arr = JsonArrayBody(j, key);
if (arr == null) return Array.Empty<bool>();
var values = new System.Collections.Generic.List<bool>();
foreach (string raw in arr.Split(','))
{
string s = raw.Trim();
if (s.StartsWith("true", StringComparison.OrdinalIgnoreCase)) values.Add(true);
else if (s.StartsWith("false", StringComparison.OrdinalIgnoreCase)) values.Add(false);
}
return values.ToArray();
}
private static string? JsonArrayBody(string? j, string key)
{
if (j == null) return null;
int ki = j.IndexOf($"\"{key}\"", StringComparison.Ordinal);
if (ki < 0) return null;
int bracket = j.IndexOf('[', ki);
if (bracket < 0) return null;
bool inString = false;
bool esc = false;
int depth = 0;
for (int i = bracket; i < j.Length; i++)
{
char c = j[i];
if (esc) { esc = false; continue; }
if (inString && c == '\\') { esc = true; continue; }
if (c == '"') { inString = !inString; continue; }
if (inString) continue;
if (c == '[') depth++;
else if (c == ']')
{
depth--;
if (depth == 0)
return j.Substring(bracket + 1, i - bracket - 1);
}
}
return null;
}
}
}