-
Notifications
You must be signed in to change notification settings - Fork 1
/
SpaceTrack.cs
442 lines (389 loc) · 12.2 KB
/
SpaceTrack.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Collections.Specialized;
using Zeptomoby.OrbitTools;
using System.Xml.Serialization;
namespace SpaceTrack
{
public class SpaceTrack
{
public class StatusEventArgs : EventArgs
{
public String Status { get; set; }
public StatusEventArgs()
{
}
public StatusEventArgs(string Status)
{
this.Status = Status;
}
}
public class ProgressEventArgs : EventArgs
{
public int MaxValue { get; set; }
public int CurrentValue { get; set; }
public ProgressEventArgs ()
{
}
public ProgressEventArgs(int Current, int Max)
{
MaxValue = Max;
CurrentValue = Current;
}
}
class NoAuthException : Exception
{ }
const int c_maxNumber = 2000;
string uriBase = "https://www.space-track.org";
string requestController = "/basicspacedata";
string requestAction = "/query";
public String UserName { get; set; }
public String Password { get; set; }
public List<Satellite> AllSats { get; set; }
private readonly string SatsDataFilePath = Environment.CurrentDirectory + "\\sats.bin";
private void SaveSats(List<Satellite> sats)
{
new BinSerializer.BinSerializer().SerializeObject<List<Satellite>>(SatsDataFilePath, sats);
}
private List<Satellite> LoadSats()
{
return new BinSerializer.BinSerializer().DeserializeObject<List<Satellite>>(SatsDataFilePath, (s, args) => { OnProgress(args); });
}
public SpaceTrack(String UserName, String Password)
{
this.UserName = UserName;
this.Password = Password;
}
public void Load(bool Refresh)
{
var CurDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
if (!File.Exists(CurDir + "/satdata.dat") || Refresh)
{
OnStatus("Загрузка данных из базы...");
AllSats = GetSatellites();
}
else
{
if (File.Exists(SatsDataFilePath))
{
OnStatus("Загрузка данных из файла...");
AllSats = LoadSats();
if (AllSats == null)
{
OnStatus("Ошибка загрузки данных из файла...");
File.Delete(SatsDataFilePath);
}
else
return;
}
using (var sr = new StreamReader(CurDir + "\\satdata.dat"))
{
OnStatus("Чтение последнего запроса к базе...");
AllSats = new List<Satellite>();
var data = new List<string>();
while (!sr.EndOfStream)
{
data.Add(sr.ReadLine()); // line 0
sr.ReadLine();
data.Add(sr.ReadLine()); // line 1
sr.ReadLine();
data.Add(sr.ReadLine()); // line 2
sr.ReadLine();
}
OnStatus("Генерация орбитальных данных...");
var fullCount = data.Count / 3;
var step = fullCount / c_maxNumber;
for (int i = 0; i < data.Count; i += 3)
{
if (i > c_maxNumber*3)
break;
if ((i / 3) == step)
continue;
try
{
Tle tle = new Tle(data[i], data[i+1], data[i+2]);
Satellite sat = new Satellite(tle);
AllSats.Add(sat);
OnProgress(new ProgressEventArgs(i, data.Count));
}
catch
{
}
}
OnStatus("Сохранение данных в файл...");
SaveSats(AllSats);
}
}
OnStatus("Загрузка завершена!");
}
public class WebClientEx : WebClient
{
// Create the container to hold all Cookie objects
private CookieContainer _cookieContainer = new CookieContainer();
// Override the WebRequest method so we can store the cookie
// container as an attribute of the Web Request object
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request is HttpWebRequest)
(request as HttpWebRequest).CookieContainer = _cookieContainer;
return request;
}
} // END WebClient Class
private Boolean Auth(WebClient client)
{
// Store the user authentication information
var data = new NameValueCollection
{
{ "identity", UserName },
{ "password", Password },
};
// Generate the URL for the API Query and return the response
try
{
var response2 = client.UploadValues(uriBase + "/auth/login", data);
string request = "https://www.space-track.org/basicspacedata/query/class/tle_latest/NORAD_CAT_ID/01317/orderby/NORAD_CAT_ID asc/limit/1/format/3le/metadata/false";
var response4 = client.DownloadData(request);
if (response4.Count() > 0)
return true;
else
return false;
}
catch
{
return false;
}
}
public Boolean Authentication()
{
OnStatus("Авторизация...");
using (var client = new WebClientEx())
{
return Auth(client);
}
}
private List<Satellite> GetSatellites(Double Perigee, Double Apogee)
{
var CurDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
string predicateValues = "/class/tle_latest/ORDINAL/1/EPOCH/%3Enow-30/APOGEE/>"+Perigee.ToString()+"/PERIGEE/<"+Apogee.ToString()+"/orderby/APOGEE%20asc/format/3le/distinct/true";
string request = uriBase + requestController + requestAction + predicateValues;
using (var client = new WebClientEx())
{
OnStatus("Соединение с базой NORAD...");
if (Auth(client))
{
OnStatus("Загрузка данных из базы...");
var response4 = client.DownloadData(request);
var stringData = System.Text.Encoding.Default.GetString(response4).Split('\n');
using (var sw = new StreamWriter(CurDir + "/lastrequest.dat"))
{
sw.Write(System.Text.Encoding.Default.GetString(response4));
}
OnStatus("Генерация орбитальных данных...");
var sats = new List<Satellite>();
for (Int32 i = 0; i < stringData.Length - 1; i += 3)
{
try
{
if (stringData[i].Contains("DEB"))
continue;
Tle tle = new Tle(stringData[i], stringData[i + 1], stringData[i + 2]);
Satellite sat = new Satellite(tle);
sats.Add(sat);
OnProgress(new ProgressEventArgs(i, stringData.Length - 1));
}
catch { }
}
OnStatus("Загрузка данных завершена!");
return (sats);
}
else
{
throw new NoAuthException();
}
}
}
private List<Satellite> GetSatellites(bool Cache = true)
{
var CurDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
string predicateValues = "/class/tle_latest/ORDINAL/1/EPOCH/%3Enow-30/orderby/APOGEE%20desc/format/3le/distinct/true";
string request = uriBase + requestController + requestAction + predicateValues;
using (var client = new WebClientEx())
{
if (Auth(client))
{
var response4 = client.DownloadData(request);
var stringData = System.Text.Encoding.Default.GetString(response4).Split('\n');
using (var sw = new StreamWriter(CurDir + "/lastrequest.dat"))
{
sw.Write(System.Text.Encoding.Default.GetString(response4));
}
var sats = new List<Satellite>();
using (var sw = new StreamWriter(CurDir + "/satdata.dat"))
{
for (Int32 i = 0; i < stringData.Length - 1; i+=3)
{
try
{
if (stringData[i].Contains("DEB"))
continue;
//if (sats.Count > c_maxNumber)
// break;
Tle tle = new Tle(stringData[i], stringData[i + 1], stringData[i + 2]);
sw.WriteLine(stringData[i]);
sw.WriteLine(stringData[i+1]);
sw.WriteLine(stringData[i+2]);
Satellite sat = new Satellite(tle);
sats.Add(sat);
OnProgress(new ProgressEventArgs(i, stringData.Length - 1));
}
catch { }
}
}
SaveSats(sats);
return (sats);
}
else
{
throw new NoAuthException();
}
}
}
public List<Satellite> GetSatellites(string LanuchYaer)
{
string predicateValues = "/class/tle_latest/LAUNCH_YEAR/=" + LanuchYaer + "/orderby/INTLDES asc/metadata/false";
string request = uriBase + requestController + requestAction + predicateValues;
// Create new WebClient object to communicate with the service
using (var client = new WebClientEx())
{
if (Auth(client))
{
var response4 = client.DownloadData(request);
var stringData = (System.Text.Encoding.Default.GetString(response4)).Split('\n');
List<Satellite> result = new List<Satellite>();
for (Int32 i = 0; i < stringData.Length - 1; i += 3)
{
Tle tle = new Tle(stringData[i], stringData[i + 1], stringData[i + 2]);
Satellite sat = new Satellite(tle);
result.Add(sat);
OnProgress(new ProgressEventArgs(i, stringData.Length - 1));
}
return result;
}
else
{
throw new NoAuthException();
}
}
}
public List<Satellite> GetSatellites(string[] Norad)
{
string predicateValues = "/class/tle_latest/ORDINAL/1/NORAD_CAT_ID/" + string.Join(",", Norad) + "/orderby/NORAD_CAT_ID%20ASC/format/3le";
string request = uriBase + requestController + requestAction + predicateValues;
// Create new WebClient object to communicate with the service
using (var client = new WebClientEx())
{
if (Auth(client))
{
var response4 = client.DownloadData(request);
var stringData = (System.Text.Encoding.Default.GetString(response4)).Split('\n');
List<Satellite> result = new List<Satellite>();
for (Int32 i = 0; i < stringData.Length - 1; i += 3)
{
Tle tle = new Tle(stringData[i], stringData[i + 1], stringData[i + 2]);
Satellite sat = new Satellite(tle);
result.Add(sat);
OnProgress(new ProgressEventArgs(i, stringData.Length - 1));
}
return result;
}
else
{
throw new NoAuthException();
}
}
}
public string GetSpaceTrack(string[] norad)
{
string predicateValues = "/class/tle_latest/ORDINAL/1/NORAD_CAT_ID/" + string.Join(",", norad) + "/orderby/NORAD_CAT_ID%20ASC/format/3le";
string request = uriBase + requestController + requestAction + predicateValues;
using (var client = new WebClientEx())
{
if (Auth(client))
{
var response4 = client.DownloadData(request);
return (System.Text.Encoding.Default.GetString(response4));
}
else
{
throw new NoAuthException();
}
}
}
public string GetSpaceTrack(string[] norad, DateTime dtstart, DateTime dtend)
{
string predicateValues = "/class/tle/EPOCH/" + dtstart.ToString("yyyy-MM-dd--") + dtend.ToString("yyyy-MM-dd") + "/NORAD_CAT_ID/" + string.Join(",", norad) + "/orderby/NORAD_CAT_ID%20ASC/format/3le";
string request = uriBase + requestController + requestAction + predicateValues;
// Create new WebClient object to communicate with the service
using (var client = new WebClientEx())
{
if (Auth(client))
{
var response4 = client.DownloadData(request);
return (System.Text.Encoding.Default.GetString(response4));
}
else
{
throw new NoAuthException();
}
}
}
public List<Satellite> GetOrbitData(string[] norad)
{
string predicateValues = "/class/omm/NORAD_CAT_ID/" + norad + "/orderby/NORAD_CAT_ID%20ASC/limit/1";
string request = uriBase + requestController + requestAction + predicateValues;
using (var client = new WebClientEx())
{
if (Auth(client))
{
var response4 = client.DownloadData(request);
var str = System.Text.Encoding.Default.GetString(response4).Split('\n');
for (Int32 i = str.Length - 4; i < str.Length - 1; i++)
{
}
return null;
}
else
{
throw new NoAuthException();
}
}
}
public event EventHandler<ProgressEventArgs> Progress;
public event EventHandler<StatusEventArgs> Status;
protected virtual void OnProgress(ProgressEventArgs args)
{
if (Progress != null)
Progress(this, args);
}
protected virtual void OnStatus(StatusEventArgs args)
{
if (Status != null)
Status(this, args);
}
protected virtual void OnStatus(String status)
{
if (Status != null)
Status(this, new StatusEventArgs(status));
}
internal void Load(double min, double max)
{
AllSats = GetSatellites(min, max);
SaveSats(AllSats);
}
}
}