-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBuddies.cs
1963 lines (1746 loc) · 78.7 KB
/
Buddies.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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.IO;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Serialization;
namespace OruxPals
{
public struct BroadCastInfo
{
public string user;
public byte[] data;
public BroadCastInfo(string user, byte[] data)
{
this.user = user;
this.data = data;
}
}
public class Buddies
{
public delegate bool CheckRUser(Buddie buddie);
private List<Buddie> buddies = new List<Buddie>();
private List<BroadCastInfo> broadcastAIS = new List<BroadCastInfo>();
private List<BroadCastInfo> broadcastAPRS = new List<BroadCastInfo>();
private List<BroadCastInfo> broadcastFRSS = new List<BroadCastInfo>();
private List<BroadCastInfo> broadcastWeb = new List<BroadCastInfo>();
private bool keepAlive = true;
private byte maxHours = 48;
private ushort greenMinutes = 60;
private int KMLObjectsRadius = 5;
private int KMLObjectsLimit = 50;
public delegate void BroadcastMethod(BroadCastInfo bdata);
public BroadcastMethod onBroadcastAIS;
public BroadcastMethod onBroadcastAPRS;
public BroadcastMethod onBroadcastFRS;
public BroadcastMethod onBroadcastWeb;
public List<PreloadedObject> Objects = new List<PreloadedObject>();
public Hashtable ObjectsFiles = new Hashtable();
public System.Data.SQLite.SQLiteConnection sqlc;
public void LoadFromTempFile(CheckRUser checkRegUser)
{
string tmpfile = OruxPalsServerConfig.GetCurrentDir() + @"\buddies.tmp";
try
{
if (!File.Exists(tmpfile)) return;
FileStream fs = new FileStream(tmpfile, FileMode.Open, FileAccess.Read);
if (fs.Length > 24)
{
byte[] hdr = new byte[24];
fs.Read(hdr, 0, hdr.Length);
string header = Encoding.ASCII.GetString(hdr);
if (header == "ORUXPALS BUDDIES LIST \r\n")
{
lock (buddies)
{
buddies.Clear();
while (fs.Position < fs.Length)
{
Buddie b = Buddie.FromFile(fs);
if (checkRegUser != null)
checkRegUser(b);
buddies.Add(b);
};
};
};
};
fs.Close();
File.Delete(tmpfile);
}
catch { };
}
public void SaveToTempFile()
{
if (buddies.Count == 0) return;
string tmpfile = OruxPalsServerConfig.GetCurrentDir() + @"\buddies.tmp";
try
{
FileStream fs = new FileStream(tmpfile, FileMode.Create, FileAccess.Write);
byte[] fh = Encoding.ASCII.GetBytes("ORUXPALS BUDDIES LIST \r\n"); // 24 bytes
fs.Write(fh, 0, fh.Length);
lock (buddies)
{
for (int i = 0; i < buddies.Count; i++)
{
if (buddies[i].IsVirtual) continue;
byte[] arr = buddies[i].ToFile();
fs.Write(arr, 0, arr.Length);
};
};
fs.Close();
}
catch { };
}
public Buddies(byte maxHours, ushort greenMinutes, int KMLObjectsRadius, int KMLObjectsLimit)
{
this.maxHours = maxHours;
this.greenMinutes = greenMinutes;
this.KMLObjectsRadius = KMLObjectsRadius;
this.KMLObjectsLimit = KMLObjectsLimit;
string sqlfn = OruxPalsServerConfig.GetCurrentDir() + @"\StaticObjects.db";
if(File.Exists(sqlfn))
{
sqlc = new System.Data.SQLite.SQLiteConnection(String.Format("Data Source={0};Version=3;",sqlfn));
try { sqlc.Open(); } catch (Exception ex) { Console.WriteLine(ex.Message); };
};
}
public void Init(CheckRUser checkRegUser)
{
LoadFromTempFile(checkRegUser);
try { PreloadObjects(); }
catch { };
(new Thread(ClearThread)).Start();
(new Thread(BroadcastThread)).Start();
}
public void Dispose()
{
keepAlive = false;
if (sqlc != null) try { sqlc.Close(); }
catch { };
}
~Buddies()
{
Dispose();
}
private void PreloadObjects()
{
string[] fls = null;
try { fls = Directory.GetFiles(PreloadedObjects.GetObjectsDir(), "*.?ml", SearchOption.TopDirectoryOnly); } catch { };
if ((fls != null) && (fls.Length > 0))
foreach (string fl in fls)
{
string shortFN = Path.GetFileName(fl);
DateTime lastMDF = (new FileInfo(fl)).LastWriteTimeUtc;
if ((ObjectsFiles[shortFN] == null) || (((PreloadedObjectsKml)ObjectsFiles[shortFN]).lastMDF != lastMDF))
{
string fileExt = Path.GetExtension(fl).ToLower();
string filePrefix = Transliteration.Front(shortFN.ToUpper().Substring(0, 2));
int StaticPoints = 0;
int EveytimePoints = 0;
lock (Objects)
if (Objects.Count > 0)
for (int i = Objects.Count - 1; i >= 0; i--)
if (Objects[i].fromFile == shortFN)
Objects.RemoveAt(i);
PreloadedObjects objs = null;
if (fileExt == ".xml")
{
try
{
objs = PreloadedObjects.LoadFile(fl);
if ((objs != null) && (objs.objects != null))
foreach (PreloadedObject po in objs.objects)
{ if (po.radius < 0) EveytimePoints++; else StaticPoints++; };
}
catch { };
};
if (fileExt == ".kml")
{
try
{
XmlDocument xd = new XmlDocument();
using (XmlTextReader tr = new XmlTextReader(fl))
{
tr.Namespaces = false;
xd.Load(tr);
};
string defSymbol = "\\C";
XmlNode NodeSymbol = xd.SelectSingleNode("/kml/symbol");
if (NodeSymbol != null) defSymbol = NodeSymbol.ChildNodes[0].Value;
string defFormat = "R{0:000}-{1}"; // {0} - id; {1} - file prefix; {2} - Placemark Name without spaces
XmlNode NodeFormat = xd.SelectSingleNode("/kml/format");
if (NodeFormat != null) defFormat = NodeFormat.ChildNodes[0].Value;
XmlNodeList nl = xd.GetElementsByTagName("Placemark");
List<PreloadedObject> fromKML = new List<PreloadedObject>();
StaticPoints = nl.Count;
if(nl.Count > 0)
for (int i = 0; i < nl.Count; i++)
{
try
{
string pName = System.Security.SecurityElement.Escape(Transliteration.Front(nl[i].SelectSingleNode("name").ChildNodes[0].Value));
pName = Regex.Replace(pName, "[\r\n\\(\\)\\[\\]\\{\\}\\^\\$\\&]+", "");
string pName2 = Regex.Replace(pName.ToUpper(), "[^A-Z0-9\\-]+", "");
string symbol = defSymbol;
if (nl[i].SelectSingleNode("symbol") != null)
symbol = nl[i].SelectSingleNode("symbol").ChildNodes[0].Value.Trim();
if (nl[i].SelectSingleNode("Point/coordinates") != null)
{
string pPos = nl[i].SelectSingleNode("Point/coordinates").ChildNodes[0].Value.Trim();
string[] xyz = pPos.Split(new char[] { ',' }, 3);
PreloadedObject po = new PreloadedObject(
String.Format(defFormat, i + 1, filePrefix, pName2), symbol,
double.Parse(xyz[1], System.Globalization.CultureInfo.InvariantCulture),
double.Parse(xyz[0], System.Globalization.CultureInfo.InvariantCulture),
KMLObjectsRadius,
pName,
shortFN);
fromKML.Add(po);
};
}
catch { };
};
if (fromKML.Count > 0)
{
objs = new PreloadedObjects();
objs.objects = fromKML.ToArray();
};
}
catch { };
};
if ((objs != null) && (objs.objects != null))
{
foreach (PreloadedObject po in objs.objects)
po.fromFile = shortFN;
lock (Objects)
Objects.AddRange(objs.objects);
};
ObjectsFiles[shortFN] = new PreloadedObjectsKml(shortFN, lastMDF, StaticPoints, EveytimePoints);
};
};
List<Buddie> toUp = new List<Buddie>();
lock (Objects)
foreach (PreloadedObject po in Objects)
if (po.radius < 0)
{
Buddie b = new Buddie(5, po.name, po.lat, po.lon, 0, 0);
b.IconSymbol = po.symbol;
b.Comment = po.comment;
toUp.Add(b);
};
if (toUp.Count > 0)
foreach (Buddie b in toUp)
Update(b);
}
public PreloadedObject[] GetNearest(double lat, double lon)
{
return GetNearest(lat, lon, null);
}
public PreloadedObject[] GetNearest(double lat, double lon, OruxPalsServer.ClientAPRSFilter filter)
{
List<PreloadedObject> objs = new List<PreloadedObject>();
int kmRadius = (filter == null) ? KMLObjectsRadius : filter.inMyRadiusKM;
int maxObjects = (filter == null) ? KMLObjectsLimit : filter.maxStaticObjectsCount;
// FROM FILES
PreloadedObject[] gfl;
lock (Objects) gfl = Objects.ToArray();
foreach (PreloadedObject obj in gfl)
{
if (obj.radius < 0) continue;
if ((obj.distance = GetLengthAB(lat, lon, obj.lat, obj.lon)) < ((kmRadius < 0 ? obj.radius : kmRadius) * 1000))
objs.Add(obj);
};
if (kmRadius < 0) kmRadius = KMLObjectsRadius;
if (maxObjects < 0) maxObjects = KMLObjectsLimit;
// FROM SQL //
if ((sqlc != null) && ((sqlc.State != System.Data.ConnectionState.Closed) && (sqlc.State != System.Data.ConnectionState.Broken)))
{
try
{
double dLat = kmRadius / (GetLengthAB(Math.Truncate(lat), Math.Truncate(lon), Math.Truncate(lat) + 1.0, Math.Truncate(lon)) / 1000.0);
double dLon = kmRadius / (GetLengthAB(Math.Truncate(lat), Math.Truncate(lon), Math.Truncate(lat), Math.Truncate(lon) + 1.0) / 1000.0);
double minLat = lat - dLat;
double maxLat = lat + dLat;
double minLon = lon - dLon;
double maxLon = lon + dLon;
lock (sqlc)
{
// Select In Square //
System.Data.SQLite.SQLiteCommand sc = new System.Data.SQLite.SQLiteCommand(
String.Format(System.Globalization.CultureInfo.InvariantCulture,"SELECT * FROM OBJECTS WHERE LAT >= {0} AND LAT <= {1} AND LON >= {2} AND LON <= {3}",
minLat, maxLat, minLon, maxLon), sqlc);
try
{
System.Data.SQLite.SQLiteDataReader dr = sc.ExecuteReader();
while (dr.Read())
{
PreloadedObject sqlo = new PreloadedObject(dr["NAME"].ToString(), dr["SYMBOL"].ToString(), (double)dr["LAT"], (double)dr["LON"],
kmRadius, dr["COMMENT"].ToString(), "SQL");
// Select in Radius //
if ((sqlo.distance = GetLengthAB(lat, lon, sqlo.lat, sqlo.lon)) < (sqlo.radius * 1000))
// use filter
if((filter == null) || (filter.PassName(sqlo.name)))
objs.Add(sqlo);
};
dr.Close();
}
catch { };
};
}
catch { };
};
objs.Sort(new PreloadedObjectComparer());
while (objs.Count > maxObjects) objs.RemoveAt(maxObjects);
return objs.ToArray();
}
/// <param name="StartLat">A lat</param>
/// <param name="StartLong">A lon</param>
/// <param name="EndLat">B lat</param>
/// <param name="EndLong">B lon</param>
/// <param name="radians">Radians or Degrees</param>
/// <returns>length in meters</returns>
private static float GetLengthAB(double alat, double alon, double blat, double blon)
{
double D2R = Math.PI / 180;
double dDistance = Double.MinValue;
double dLat1InRad = alat * D2R;
double dLong1InRad = alon * D2R;
double dLat2InRad = blat * D2R;
double dLong2InRad = blon * D2R;
double dLongitude = dLong2InRad - dLong1InRad;
double dLatitude = dLat2InRad - dLat1InRad;
double a = Math.Pow(Math.Sin(dLatitude / 2.0), 2.0) +
Math.Cos(dLat1InRad) * Math.Cos(dLat2InRad) *
Math.Pow(Math.Sin(dLongitude / 2.0), 2.0);
double c = 2.0 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1.0 - a));
const double kEarthRadiusKms = 6378137.0000;
dDistance = kEarthRadiusKms * c;
return (float)Math.Round(dDistance);
}
public string GetStaticObjectsInfo()
{
int ttlf = 0;
int ttlet = 0;
int ttlst = 0;
string txt = "";
lock(ObjectsFiles)
foreach (string key in ObjectsFiles.Keys)
{
ttlf++;
PreloadedObjectsKml fi = (PreloadedObjectsKml)ObjectsFiles[key];
ttlst += fi.StaticPoints;
ttlet += fi.EveryTimePoints;
txt += String.Format(" \"{0}\" - {1} static, {2} everytime objects<br/>", fi.shortFN, fi.StaticPoints, fi.EveryTimePoints);
};
txt += String.Format("<span style=\"color:green;\"> Total: {0} files, {1} static, {2} everytime objects</span><br/>", ttlf, ttlst, ttlet);
if ((sqlc != null) && ((sqlc.State != System.Data.ConnectionState.Closed) && (sqlc.State != System.Data.ConnectionState.Broken)))
lock (sqlc)
{
long count = 0;
System.Data.SQLite.SQLiteCommand sc = new System.Data.SQLite.SQLiteCommand("SELECT COUNT (*) FROM OBJECTS", sqlc);
try { count = (long)sc.ExecuteScalar(); } catch { };
txt += String.Format("<span style=\"color:orange;\"> SQLite DB \"StaticObjects.db\" - {0} static objects</span><br/>", count);
};
txt += String.Format("<span style=\"color:gray;\"> Show max {1} objects in radius: {0} km</span><br/>", KMLObjectsRadius, KMLObjectsLimit);
return txt;
}
public void Update(Buddie buddie)
{
if(buddie == null) return;
lock (buddies)
{
if (buddies.Count > 0)
for (int i = buddies.Count - 1; i >= 0; i--)
if (buddie.name == buddies[i].name)
{
Buddie.CopyData(buddies[i], buddie);
buddies.RemoveAt(i);
};
if (buddie.ID == 0)
buddie.ID = ++Buddie._id;
buddies.Add(buddie);
};
buddie.SetAPRS();
lock (broadcastAPRS)
broadcastAPRS.Add(new BroadCastInfo(buddie.source == 5 ? "" : buddie.name, buddie.APRSData));
// No tx everytime & static objects
if ((buddie.source != 5) && (buddie.source != 6))
{
lock (broadcastWeb)
broadcastWeb.Add(new BroadCastInfo(buddie.name, null));
buddie.SetAIS();
lock (broadcastAIS)
broadcastAIS.Add(new BroadCastInfo(buddie.name, buddie.AISNMEA));
buddie.SetFRS();
lock (broadcastFRSS)
broadcastFRSS.Add(new BroadCastInfo(buddie.name, buddie.FRPOSData));
};
}
public Buddie[] Current
{
get
{
lock(buddies)
return buddies.ToArray();
}
}
public Buddie GetBuddie(string name)
{
lock (buddies)
{
if (buddies.Count > 0)
for (int i = buddies.Count - 1; i >= 0; i--)
if (name == buddies[i].name)
return buddies[i];
};
return null;
}
public void Clear()
{
lock (buddies) buddies.Clear();
}
public void ClearKnown()
{
if (buddies.Count == 0) return;
lock (buddies)
for (int i = buddies.Count - 1; i >= 0; i--)
if (buddies[i].regUser != null)
buddies.RemoveAt(i);
}
public void ClearTemp()
{
if (buddies.Count == 0) return;
lock (buddies)
for (int i = buddies.Count - 1; i >= 0; i--)
if (buddies[i].name.StartsWith("T-"))
buddies.RemoveAt(i);
}
public void ClearUnknown()
{
if (buddies.Count == 0) return;
lock (buddies)
for (int i = buddies.Count - 1; i >= 0; i--)
if ((!buddies[i].IsStored) && (buddies[i].regUser == null))
buddies.RemoveAt(i);
}
public bool Kill(string user)
{
if(buddies.Count == 0) return false;
lock(buddies)
for(int i=buddies.Count-1;i>=0;i--)
if (buddies[i].name == user)
{
buddies.RemoveAt(i);
return true;
};
return false;
}
public bool UpdateComment(Buddie buddie, string newComment)
{
if (buddie == null) return false;
lock (buddies)
{
if (buddies.Count > 0)
for (int i = buddies.Count - 1; i >= 0; i--)
if ((buddie.name == buddies[i].name) || ((buddies[i].regUser != null) && (buddie.regUser != null) && (buddie.regUser.name == buddies[i].regUser.name)))
{
buddies[i].parsedComment = newComment;
if (buddies[i].regUser != null)
buddies[i].regUser.comment = newComment;
return true;
};
};
return false;
}
public bool UpdateStatus(Buddie buddie, string status)
{
if (buddie == null) return false;
lock (buddies)
{
if (buddies.Count > 0)
for (int i = buddies.Count - 1; i >= 0; i--)
if ((buddie.name == buddies[i].name) || ((buddies[i].regUser != null) && (buddie.regUser != null) && (buddie.regUser.name == buddies[i].regUser.name)))
{
buddies[i].Status = status;
return true;
};
};
return false;
}
private void ClearThread()
{
byte counter = 0;
ushort filectr = 0;
while (keepAlive)
{
if (filectr++ == 600) //each 10 min
try { filectr = 0; PreloadObjects(); } catch { };
if (++counter == 15)
{
lock (buddies)
if (buddies.Count > 0)
for (int i = buddies.Count - 1; i >= 0; i--)
{
if (!buddies[i].green)
if (DateTime.UtcNow.Subtract(buddies[i].last).TotalMinutes >= greenMinutes)
buddies[i].green = true;
if (DateTime.UtcNow.Subtract(buddies[i].last).TotalHours >= maxHours)
buddies.RemoveAt(i);
};
counter = 0;
};
Thread.Sleep(1000);
};
}
private void BroadcastThread()
{
while (keepAlive)
{
int bc = broadcastAIS.Count;
while (bc > 0)
{
BroadCastInfo bdata;
lock (broadcastAIS)
{
bdata = broadcastAIS[0];
broadcastAIS.RemoveAt(0);
};
bc--;
BroadcastAIS(bdata);
};
bc = broadcastAPRS.Count;
while (bc > 0)
{
BroadCastInfo bdata;
lock (broadcastAPRS)
{
bdata = broadcastAPRS[0];
broadcastAPRS.RemoveAt(0);
};
bc--;
BroadcastAPRS(bdata);
};
bc = broadcastFRSS.Count;
while (bc > 0)
{
BroadCastInfo bdata;
lock (broadcastFRSS)
{
bdata = broadcastFRSS[0];
broadcastFRSS.RemoveAt(0);
};
bc--;
BroadcastFRS(bdata);
};
bc = broadcastWeb.Count;
while (bc > 0)
{
BroadCastInfo bdata;
lock (broadcastWeb)
{
bdata = broadcastWeb[0];
broadcastWeb.RemoveAt(0);
};
bc--;
BroadcastWeb(bdata);
};
Thread.Sleep(1000);
};
}
private void BroadcastAIS(BroadCastInfo bdata)
{
if (onBroadcastAIS != null)
onBroadcastAIS(bdata);
}
private void BroadcastAPRS(BroadCastInfo bdata)
{
if (onBroadcastAPRS != null)
onBroadcastAPRS(bdata);
}
private void BroadcastFRS(BroadCastInfo bdata)
{
if (onBroadcastFRS != null)
onBroadcastFRS(bdata);
}
private void BroadcastWeb(BroadCastInfo bdata)
{
if (onBroadcastWeb != null)
onBroadcastWeb(bdata);
}
}
public class Buddie
{
public static Regex BuddieNameRegex = new Regex("^([A-Z0-9]{3,9})$");
public static Regex BuddieCallSignRegex = new Regex(@"^([A-Z0-9\-]{3,9})$");
public static string symbolAny = "123456789ABCDEFGHJKLMNOPRSTUVWXYZ";//"/*/</=/>/C/F/M/P/U/X/Y/Z/[/a/b/e/f/j/k/p/s/u/v\\O\\j\\k\\u\\v/0/1/2/3/4/5/6/7/8/9/'/O";
public static int symbolAnyLength = 33;//40;
internal static ulong _id = 0;
private ulong _ID = 0;
internal ulong ID
{
get { return _ID; }
set
{
_ID = value;
if ((_ID == 0) && (Buddie.IsNullIcon(IconSymbol)))
{
IconSymbol = "//";
return;
}
else if(Buddie.IsNullIcon(IconSymbol))
IconSymbol = Buddie.symbolAny.Substring((int)_ID % Buddie.symbolAnyLength, 1) + "s";
}
}
public static bool IsNullIcon(string symbol)
{
return (symbol == null) || (symbol == String.Empty) || (symbol == "//");
}
public byte source; // 0 - unknown; 1 - GPSGate Format; 2 - MapMyTracks Format; 3 - APRS; 4 - FRS; 5 - everytime; 6 - static; 7 - FlightRadar24; 8 - BigBrother GPS, 9 - Own Tracks, 10 - OsmAnd or Traccar
public string name;
public double lat;
public double lon;
/// <summary>
/// Speed in kmph;
/// mph = kmph * 0.62137119;
/// knots = kmph / 1.852;
/// mps = kmps / 3.6
/// </summary>
public short speed;
public short course;
public DateTime last;
public bool green;
private string aAIS = "";
private byte[] aAISNMEA = null;
private string bAIS = "";
private byte[] bAISNMEA = null;
public string AIS
{
get
{
return green ? bAIS : aAIS;
}
}
public byte[] AISNMEA
{
get
{
return green ? bAISNMEA : aAISNMEA;
}
}
public string APRS = "";
public byte[] APRSData = null;
public string FRPOS = "";
public byte[] FRPOSData = null;
public OruxPalsServerConfig.RegUser regUser;
public string IconSymbol = "//";
public string parsedComment = "";
public string Comment
{
get
{
if ((parsedComment != null) && (parsedComment != String.Empty)) return parsedComment;
if ((regUser != null) && (regUser.comment != null) && (regUser.comment != String.Empty)) return regUser.comment;
return "";
}
set
{
parsedComment = value;
}
}
public string Status = "";
public string lastPacket = "";
public bool PositionIsValid
{
get { return (lat != 0) && (lon != 0); }
}
public Buddie(byte source, string name, double lat, double lon, short speed, short course)
{
this.source = source;
this.name = name;
this.lat = lat;
this.lon = lon;
this.speed = speed;
this.course = course;
this.last = DateTime.UtcNow;
this.green = false;
}
internal void SetAIS()
{
CNBAsentense a = CNBAsentense.FromBuddie(this);
string ln1 = "!AIVDM,1,1,,A," + a.ToString() + ",0";
ln1 += "*" + AISTransCoder.Checksum(ln1);
AIVDMSentense ai = AIVDMSentense.FromBuddie(this);
string ln2 = "!AIVDM,1,1,,A," + ai.ToString() + ",0";
ln2 += "*" + AISTransCoder.Checksum(ln2);
aAIS = ln1 + "\r\n" + ln2 + "\r\n";
aAISNMEA = Encoding.ASCII.GetBytes(aAIS);
CNBBEsentense be = CNBBEsentense.FromBuddie(this);
string ln0 = "!AIVDM,1,1,,A," + be.ToString() + ",0";
ln0 += "*" + AISTransCoder.Checksum(ln0);
bAIS = ln0 + "\r\n";
bAISNMEA = Encoding.ASCII.GetBytes(bAIS);
}
internal void SetAPRS()
{
if (this.source == 3)
{
if (((this.parsedComment == null) || (this.parsedComment == String.Empty)) && (this.Comment != null))
{
this.APRS = this.APRS.Insert(this.APRS.Length - 2, " " + this.Comment);
this.APRSData = Encoding.ASCII.GetBytes(this.APRS);
};
return;
};
APRS =
name + ">APRS,TCPIP*:=" + // Position without timestamp + APRS message
Math.Truncate(lat).ToString("00") + ((lat - Math.Truncate(lat)) * 60).ToString("00.00").Replace(",", ".") +
(lat > 0 ? "N" : "S") +
IconSymbol[0] +
Math.Truncate(lon).ToString("000") + ((lon - Math.Truncate(lon)) * 60).ToString("00.00").Replace(",", ".") +
(lon > 0 ? "E" : "W") +
IconSymbol[1] +
course.ToString("000") + "/" + Math.Truncate(speed / 1.852).ToString("000") +
((this.Comment != null) && (this.Comment != String.Empty) ? " " + this.Comment : "") +
"\r\n";
APRSData = Encoding.ASCII.GetBytes(APRS);
}
internal void SetFRS()
{
FRPOS =
OruxPalsServer.ChecksumAdd2Line("$FRPOS," +
// $FRPOS,DDMM.mmmm,N,DDMM.mmmm,E,AA.a,SSS.ss,HHH.h,DDMMYY,hhmmss.dd,buddy*XX
Math.Truncate(lat).ToString("00") + ((lat - Math.Truncate(lat)) * 60.0).ToString("00.0000").Replace(",", ".") + "," +
(lat > 0 ? "N" : "S") + "," +
Math.Truncate(lon).ToString("000") + ((lon - Math.Truncate(lon)) * 60.0).ToString("00.0000").Replace(",", ".") + "," +
(lon > 0 ? "E" : "W") + "," +
"00.0" + "," +
(speed / 1.852).ToString("000.00", System.Globalization.CultureInfo.InvariantCulture) + "," +
course.ToString("000") + ".0" + "," +
DateTime.UtcNow.ToString("ddMMyy,HHmmss.00") + "," +
this.name)+
"\r\n";
FRPOSData = Encoding.ASCII.GetBytes(FRPOS);
}
public override string ToString()
{
return String.Format("{0} at {1}, {2} {3} {4}, {5}", new object[] { name, source, lat, lon, speed, course });
}
public static Buddie FromFile(Stream fs)
{
try
{
//Buddie b = new Buddie(0, "", 0, 0, 0, 0);
// SOURCE, NAME, LAT, LON, SPEED, COURSE, LAST, ICON, COMMENT, STATUS, LAST_PACKET
int source = fs.ReadByte();
int len = fs.ReadByte();
byte[] buff = new byte[len];
fs.Read(buff, 0, buff.Length);
string name = Encoding.ASCII.GetString(buff);
buff = new byte[8 + 8 + 2 + 2 + 8];
fs.Read(buff, 0, buff.Length);
double lat = BitConverter.ToDouble(buff, 0);
double lon = BitConverter.ToDouble(buff, 8);
short spd = BitConverter.ToInt16(buff, 8 + 8);
short crs = BitConverter.ToInt16(buff, 8 + 8 + 2);
DateTime lst = DateTime.FromOADate(BitConverter.ToDouble(buff, 8 + 8 + 2 + 2));
len = fs.ReadByte();
buff = new byte[len];
fs.Read(buff, 0, buff.Length);
string icon = Encoding.ASCII.GetString(buff);
Buddie b = new Buddie((byte)source, name, lat, lon, spd, crs);
b.ID = ++Buddie._id;
b.last = lst;
b.lastPacket = "NoData";
b.IconSymbol = icon;
len = fs.ReadByte();
if (len > 0)
{
buff = new byte[len];
fs.Read(buff, 0, buff.Length);
b.Comment = Encoding.UTF8.GetString(buff);
};
len = fs.ReadByte();
if (len > 0)
{
buff = new byte[len];
fs.Read(buff, 0, buff.Length);
b.Status = Encoding.UTF8.GetString(buff);
};
len = fs.ReadByte();
if (len > 0)
{
buff = new byte[len];
fs.Read(buff, 0, buff.Length);
b.lastPacket = Encoding.UTF8.GetString(buff);
};
return b;
}
catch { };
return null;
}
public byte[] ToFile()
{
List<byte> ba = new List<byte>();
byte[] bb = new byte[0];
// SOURCE, NAME, LAT, LON, SPEED, COURSE, LAST, ICON, COMMENT, STATUS, LAST_PACKET
ba.Add(source);
bb = Encoding.ASCII.GetBytes(name);
ba.Add((byte)bb.Length);
ba.AddRange(bb);
bb = BitConverter.GetBytes(lat);
ba.AddRange(bb);
bb = BitConverter.GetBytes(lon);
ba.AddRange(bb);
bb = BitConverter.GetBytes(speed);
ba.AddRange(bb);
bb = BitConverter.GetBytes(course);
ba.AddRange(bb);
bb = BitConverter.GetBytes(last.ToOADate());
ba.AddRange(bb);
bb = Encoding.ASCII.GetBytes(IconSymbol);
ba.Add((byte)bb.Length);
ba.AddRange(bb);
bb = Encoding.UTF8.GetBytes(Comment);
if (bb.Length <= 255)
{
ba.Add((byte)bb.Length);
ba.AddRange(bb);
}
else
ba.Add(0);
bb = Encoding.UTF8.GetBytes(Status);
if (bb.Length <= 255)
{
ba.Add((byte)bb.Length);
ba.AddRange(bb);
}
else
ba.Add(0);
bb = Encoding.UTF8.GetBytes(lastPacket);
if (bb.Length <= 255)
{
ba.Add((byte)bb.Length);
ba.AddRange(bb);
}
else
ba.Add(0);
return ba.ToArray();
}
public static int Hash(string name)
{
string upname = name == null ? "" : name;
int stophere = upname.IndexOf("-");
if (stophere > 0) upname = upname.Substring(0, stophere);
while (upname.Length < 9) upname += " ";
int hash = 0x2017;
int i = 0;
while (i < 9)
{
hash ^= (int)(upname.Substring(i, 1))[0] << 16;
hash ^= (int)(upname.Substring(i + 1, 1))[0] << 8;
hash ^= (int)(upname.Substring(i + 2, 1))[0];
i += 3;
};
return hash & 0x7FFFFF;
}
public static uint MMSI(string name)
{
string upname = name == null ? "" : name;
while (upname.Length < 9) upname += " ";
int hash = 2017;
int i = 0;
while (i < 9)
{
hash ^= (int)(upname.Substring(i, 1))[0] << 16;
hash ^= (int)(upname.Substring(i + 1, 1))[0] << 8;
hash ^= (int)(upname.Substring(i + 2, 1))[0];
i += 3;
};
return (uint)(hash & 0xFFFFFF);
}
public static void CopyData(Buddie copyFrom, Buddie copyTo)
{
if ((copyTo.source != 3) && (!Buddie.IsNullIcon(copyFrom.IconSymbol)))
copyTo.IconSymbol = copyFrom.IconSymbol;
if (Buddie.IsNullIcon(copyTo.IconSymbol))
copyTo.IconSymbol = copyFrom.IconSymbol;
if ((copyTo.parsedComment == null) || (copyTo.parsedComment == String.Empty))
{
copyTo.parsedComment = copyFrom.parsedComment;
if ((copyTo.source == 3) && (copyTo.parsedComment != null) && (copyTo.parsedComment != String.Empty))
{
copyTo.APRS = copyTo.APRS.Insert(copyTo.APRS.Length - 2, " " + copyTo.Comment);
copyTo.APRSData = Encoding.ASCII.GetBytes(copyTo.APRS);
};
};
copyTo.ID = copyFrom.ID;
copyTo.Status = copyFrom.Status;
}
public bool IsVirtual
{
get
{
if (source == 5) return true;
if (source == 6) return true;
if (source == 7) return true;
return false;