forked from ArduPilot/MissionPlanner
-
Notifications
You must be signed in to change notification settings - Fork 1
/
MagCalib.cs
1529 lines (1250 loc) · 64 KB
/
MagCalib.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 log4net;
using MissionPlanner.Controls;
using MissionPlanner.Utilities;
using netDxf.Entities;
using netDxf.Tables;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MissionPlanner
{
public class MagCalib
{
private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
static double error = 99;
static double error2 = 99;
static double error3 = 99;
static double[] ans;
static double[] ans2;
static double[] ans3;
static string GetColour(int pitch, int yaw)
{
// yaw doesnt matter with these 2
if (pitch == 0)
return "DarkBlue";
if (pitch == 180)
return "Yellow";
// select hemisphere
if (pitch < 90)
{
if (yaw < 90 || yaw > 270)
return "DarkBlue-Red";
if (yaw < 180)
return "DarkBlue-Blue";
if (yaw < 270)
return "DarkBlue-Pink";
}
else
{
if (yaw < 90 || yaw > 270)
return "Yellow-Green";
if (yaw < 180)
return "Yellow-Blue";
if (yaw < 270)
return "Yellow-Pink";
}
return "";
}
/*
* // pitch, yaw
// 0 , 0 is directly up dark blue axis
// 60, 360 is red and blue
// 60, 180 is dark blue and blue
// 90, 180 is light blue axis
// 90, 90 green axis
// 90, 270 pink axis
// 90, 360 red axis
// 180, 0 yellow axis
0,0,
0,120,
0,240,
0,360,
60,0,
60,120,
60,240,
60,360,
120,0,
120,120,
120,240,
120,360,
180,0,
180,120,
180,240,
180,360,
*/
/// <summary>
/// Self contained process tlog and save/display offsets
/// </summary>
public static async Task ProcessLog(int throttleThreshold = 0)
{
using (OpenFileDialog openFileDialog1 = new OpenFileDialog())
{
openFileDialog1.Filter = "Log Files|*.tlog;*.log;*.bin";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
openFileDialog1.Multiselect = true;
try
{
openFileDialog1.InitialDirectory = Settings.Instance.LogDir + Path.DirectorySeparatorChar;
}
catch
{
} // incase dir doesnt exist
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
double[] ans;
if (openFileDialog1.FileName.ToLower().EndsWith("tlog"))
{
ans = await getOffsets(openFileDialog1.FileName, throttleThreshold).ConfigureAwait(true);
}
else
{
ans = getOffsetsLog(openFileDialog1.FileName);
}
if (ans.Length != 1)
SaveOffsets(ans);
}
catch (Exception ex)
{
log.Debug(ex.ToString());
}
}
}
}
public static void DoGUIMagCalib(bool dointro = true)
{
ans = null;
filtercompass1.Clear();
datacompass1.Clear();
datacompass2.Clear();
filtercompass2.Clear();
filtercompass3.Clear();
datacompass3.Clear();
error = 99;
error2 = 99;
error3 = 99;
if (dointro)
CustomMessageBox.Show(Strings.MagCalibMsg);
using (ProgressReporterSphere prd = new ProgressReporterSphere())
{
prd.btnCancel.Text = "Done";
Utilities.ThemeManager.ApplyThemeTo(prd);
prd.DoWork += prd_DoWork;
prd.RunBackgroundOperationAsync();
}
if (ans != null)
MagCalib.SaveOffsets(ans);
if (ans2 != null)
MagCalib.SaveOffsets2(ans2);
if (ans3 != null)
MagCalib.SaveOffsets3(ans3);
}
// filter data points to only x number per quadrant
static int div = 20;
static Hashtable filtercompass1 = new Hashtable();
static Hashtable filtercompass2 = new Hashtable();
static Hashtable filtercompass3 = new Hashtable();
// list of x,y,z 's
static List<Tuple<float, float, float>> datacompass1 = new List<Tuple<float, float, float>>();
// list no 2
static List<Tuple<float, float, float>> datacompass2 = new List<Tuple<float, float, float>>();
static List<Tuple<float, float, float>> datacompass3 = new List<Tuple<float, float, float>>();
private static object _locker = new object();
static bool ReceviedPacket(MAVLink.MAVLinkMessage rawpacket)
{
if (rawpacket.msgid == (byte)MAVLink.MAVLINK_MSG_ID.SCALED_IMU2)
{
MAVLink.mavlink_scaled_imu2_t packet = rawpacket.ToStructure<MAVLink.mavlink_scaled_imu2_t>();
// filter dataset
string item = (int)(packet.xmag / div) + "," +
(int)(packet.ymag / div) + "," +
(int)(packet.zmag / div);
if (filtercompass2.ContainsKey(item))
{
filtercompass2[item] = (int)filtercompass2[item] + 1;
if ((int)filtercompass2[item] > 3)
return false;
}
else
{
filtercompass2[item] = 1;
}
// values - offsets are 0
float rawmx = packet.xmag;
float rawmy = packet.ymag;
float rawmz = packet.zmag;
// add data
lock (_locker)
{
if (rawmx == 0 || rawmy == 0 || rawmz == 0)
return true;
datacompass2.Add(new Tuple<float, float, float>(rawmx, rawmy, rawmz));
}
return true;
}
else if (rawpacket.msgid == (byte)MAVLink.MAVLINK_MSG_ID.SCALED_IMU3)
{
MAVLink.mavlink_scaled_imu3_t packet = rawpacket.ToStructure<MAVLink.mavlink_scaled_imu3_t>();
// filter dataset
string item = (int)(packet.xmag / div) + "," +
(int)(packet.ymag / div) + "," +
(int)(packet.zmag / div);
if (filtercompass3.ContainsKey(item))
{
filtercompass3[item] = (int)filtercompass3[item] + 1;
if ((int)filtercompass3[item] > 3)
return false;
}
else
{
filtercompass3[item] = 1;
}
// values - offsets are 0
float rawmx = packet.xmag;
float rawmy = packet.ymag;
float rawmz = packet.zmag;
// add data
lock (_locker)
{
if (rawmx == 0 || rawmy == 0 || rawmz == 0)
return true;
datacompass3.Add(new Tuple<float, float, float>(rawmx, rawmy, rawmz));
}
return true;
}
else if (rawpacket.msgid == (byte)MAVLink.MAVLINK_MSG_ID.RAW_IMU)
{
MAVLink.mavlink_raw_imu_t packet = rawpacket.ToStructure<MAVLink.mavlink_raw_imu_t>();
if (packet.xmag == 0 && packet.ymag == 0)
return false;
// filter dataset
string item = (int)(packet.xmag / div) + "," +
(int)(packet.ymag / div) + "," +
(int)(packet.zmag / div);
if (filtercompass1.ContainsKey(item))
{
filtercompass1[item] = (int)filtercompass1[item] + 1;
if ((int)filtercompass1[item] > 3)
return false;
}
else
{
filtercompass1[item] = 1;
}
// values
float rawmx = packet.xmag;
float rawmy = packet.ymag;
float rawmz = packet.zmag;
// add data
lock (_locker)
{
datacompass1.Add(new Tuple<float, float, float>(rawmx, rawmy, rawmz));
}
return true;
}
return true;
}
public static async Task test(string file = @"C:\Users\mich1\Documents\Mission Planner\logs\ADSB\1\2022-07-26 22-25-37.tlog")
{
await getOffsets(file);
CompassCalibrator com = new CompassCalibrator();
com.start(true, 0, 999);
bool test = false;
using (MAVLinkInterface mine = new MAVLinkInterface())
{
try
{
mine.logplaybackfile =
new BinaryReader(File.Open(file, FileMode.Open, FileAccess.Read, FileShare.Read));
}
catch (Exception ex)
{
log.Debug(ex.ToString());
CustomMessageBox.Show("Log Can not be opened. Are you still connected?");
return;
}
mine.logreadmode = true;
Vector3f offsets = null;
Vector3f diagonals = null;
Vector3f offdiagonals = null;
// gather data
while (mine.logplaybackfile.BaseStream.Position < mine.logplaybackfile.BaseStream.Length)
{
MAVLink.MAVLinkMessage packetraw = await mine.readPacketAsync().ConfigureAwait(false);
if (packetraw.msgid == (int)MAVLink.MAVLINK_MSG_ID.RAW_IMU)
{
var imu = packetraw.ToStructure<MAVLink.mavlink_raw_imu_t>();
com.new_sample(new Vector3f(imu.xmag, imu.ymag, imu.zmag));
com.update(ref test);
Console.WriteLine("get_completion_percent {0} {1}", com.get_completion_percent(),
com.get_completion_mask().ToHexString());
}
com.get_calibration(ref offsets, ref diagonals, ref offdiagonals);
if (com.get_completion_percent() == 100)
{
Console.WriteLine("{0} {1} {2} {3}", com.get_completion_percent(), offsets.ToString(),
diagonals.ToString(), offdiagonals.ToString());
break;
}
}
Console.WriteLine("get_completion_percent {0}", com.get_completion_percent());
}
}
static void prd_DoWork(IProgressReporterDialogue sender)
{
var prsphere = sender as ProgressReporterSphere;
// turn learning off
MainV2.comPort.setParam((byte)MainV2.comPort.sysidcurrent, (byte)MainV2.comPort.compidcurrent, "COMPASS_LEARN", 0);
bool havecompass2 = false;
bool havecompass3 = false;
if (MainV2.comPort.MAV.param.ContainsKey("COMPASS_OFS_X"))
{
MainV2.comPort.setParam((byte)MainV2.comPort.sysidcurrent, (byte)MainV2.comPort.compidcurrent, "COMPASS_OFS_X", 0, true);
MainV2.comPort.setParam((byte)MainV2.comPort.sysidcurrent, (byte)MainV2.comPort.compidcurrent, "COMPASS_OFS_Y", 0, true);
MainV2.comPort.setParam((byte)MainV2.comPort.sysidcurrent, (byte)MainV2.comPort.compidcurrent, "COMPASS_OFS_Z", 0, true);
MainV2.comPort.setParam((byte)MainV2.comPort.sysidcurrent, (byte)MainV2.comPort.compidcurrent, "COMPASS_DIA_X", 1, true);
MainV2.comPort.setParam((byte)MainV2.comPort.sysidcurrent, (byte)MainV2.comPort.compidcurrent, "COMPASS_DIA_Y", 1, true);
MainV2.comPort.setParam((byte)MainV2.comPort.sysidcurrent, (byte)MainV2.comPort.compidcurrent, "COMPASS_DIA_Z", 1, true);
MainV2.comPort.setParam((byte)MainV2.comPort.sysidcurrent, (byte)MainV2.comPort.compidcurrent, "COMPASS_ODI_X", 0, true);
MainV2.comPort.setParam((byte)MainV2.comPort.sysidcurrent, (byte)MainV2.comPort.compidcurrent, "COMPASS_ODI_Y", 0, true);
MainV2.comPort.setParam((byte)MainV2.comPort.sysidcurrent, (byte)MainV2.comPort.compidcurrent, "COMPASS_ODI_Z", 0, true);
}
//compass2 get mag2 offsets
if (MainV2.comPort.MAV.param.ContainsKey("COMPASS_OFS2_X"))
{
MainV2.comPort.setParam((byte)MainV2.comPort.sysidcurrent, (byte)MainV2.comPort.compidcurrent, "COMPASS_OFS2_X", 0, true);
MainV2.comPort.setParam((byte)MainV2.comPort.sysidcurrent, (byte)MainV2.comPort.compidcurrent, "COMPASS_OFS2_Y", 0, true);
MainV2.comPort.setParam((byte)MainV2.comPort.sysidcurrent, (byte)MainV2.comPort.compidcurrent, "COMPASS_OFS2_Z", 0, true);
MainV2.comPort.setParam((byte)MainV2.comPort.sysidcurrent, (byte)MainV2.comPort.compidcurrent, "COMPASS_DIA2_X", 1, true);
MainV2.comPort.setParam((byte)MainV2.comPort.sysidcurrent, (byte)MainV2.comPort.compidcurrent, "COMPASS_DIA2_Y", 1, true);
MainV2.comPort.setParam((byte)MainV2.comPort.sysidcurrent, (byte)MainV2.comPort.compidcurrent, "COMPASS_DIA2_Z", 1, true);
MainV2.comPort.setParam((byte)MainV2.comPort.sysidcurrent, (byte)MainV2.comPort.compidcurrent, "COMPASS_ODI2_X", 0, true);
MainV2.comPort.setParam((byte)MainV2.comPort.sysidcurrent, (byte)MainV2.comPort.compidcurrent, "COMPASS_ODI2_Y", 0, true);
MainV2.comPort.setParam((byte)MainV2.comPort.sysidcurrent, (byte)MainV2.comPort.compidcurrent, "COMPASS_ODI2_Z", 0, true);
havecompass2 = true;
}
//compass3
if (MainV2.comPort.MAV.param.ContainsKey("COMPASS_OFS3_X"))
{
MainV2.comPort.setParam((byte)MainV2.comPort.sysidcurrent, (byte)MainV2.comPort.compidcurrent, "COMPASS_OFS3_X", 0, true);
MainV2.comPort.setParam((byte)MainV2.comPort.sysidcurrent, (byte)MainV2.comPort.compidcurrent, "COMPASS_OFS3_Y", 0, true);
MainV2.comPort.setParam((byte)MainV2.comPort.sysidcurrent, (byte)MainV2.comPort.compidcurrent, "COMPASS_OFS3_Z", 0, true);
MainV2.comPort.setParam((byte)MainV2.comPort.sysidcurrent, (byte)MainV2.comPort.compidcurrent, "COMPASS_DIA3_X", 1, true);
MainV2.comPort.setParam((byte)MainV2.comPort.sysidcurrent, (byte)MainV2.comPort.compidcurrent, "COMPASS_DIA3_Y", 1, true);
MainV2.comPort.setParam((byte)MainV2.comPort.sysidcurrent, (byte)MainV2.comPort.compidcurrent, "COMPASS_DIA3_Z", 1, true);
MainV2.comPort.setParam((byte)MainV2.comPort.sysidcurrent, (byte)MainV2.comPort.compidcurrent, "COMPASS_ODI3_X", 0, true);
MainV2.comPort.setParam((byte)MainV2.comPort.sysidcurrent, (byte)MainV2.comPort.compidcurrent, "COMPASS_ODI3_Y", 0, true);
MainV2.comPort.setParam((byte)MainV2.comPort.sysidcurrent, (byte)MainV2.comPort.compidcurrent, "COMPASS_ODI3_Z", 0, true);
havecompass3 = true;
}
int hittarget = 14; // int.Parse(File.ReadAllText("magtarget.txt"));
// old method
float minx = 0;
float maxx = 0;
float miny = 0;
float maxy = 0;
float minz = 0;
float maxz = 0;
// backup current rate and set
var backupratesens = MainV2.comPort.MAV.cs.ratesensors;
var backuprateatt = MainV2.comPort.MAV.cs.rateattitude;
var backupratepos = MainV2.comPort.MAV.cs.rateposition;
MainV2.comPort.MAV.cs.ratesensors = 2;
MainV2.comPort.MAV.cs.rateattitude = 0;
MainV2.comPort.MAV.cs.rateposition = 0;
MainV2.comPort.requestDatastream(MAVLink.MAV_DATA_STREAM.ALL, 0);
MainV2.comPort.requestDatastream(MAVLink.MAV_DATA_STREAM.RAW_SENSORS, 50);
// subscribe to data packets
var sub = MainV2.comPort.SubscribeToPacketType(MAVLink.MAVLINK_MSG_ID.RAW_IMU, ReceviedPacket, (byte)MainV2.comPort.sysidcurrent, (byte)MainV2.comPort.compidcurrent);
var sub2 = MainV2.comPort.SubscribeToPacketType(MAVLink.MAVLINK_MSG_ID.SCALED_IMU2, ReceviedPacket, (byte)MainV2.comPort.sysidcurrent, (byte)MainV2.comPort.compidcurrent);
var sub3 = MainV2.comPort.SubscribeToPacketType(MAVLink.MAVLINK_MSG_ID.SCALED_IMU3, ReceviedPacket, (byte)MainV2.comPort.sysidcurrent, (byte)MainV2.comPort.compidcurrent);
string extramsg = "";
// clear any old data
prsphere.sphere1.Clear();
prsphere.sphere2.Clear();
prsphere.sphere3.Clear();
// keep track of data count and last lsq run
int lastcount = 0;
DateTime lastlsq = DateTime.MinValue;
DateTime lastlsq2 = DateTime.MinValue;
DateTime lastlsq3 = DateTime.MinValue;
Vector3 centre = new Vector3();
while (true)
{
// slow down execution
System.Threading.Thread.Sleep(10);
string str = "Got + " + datacompass1.Count + " samples\n" +
"Compass 1 error: " + error;
if (havecompass2)
str += "\nCompass 2 error: " + error2;
if (havecompass3)
str += "\nCompass 3 error: " + error3;
str += "\n" + extramsg;
prsphere.UpdateProgressAndStatus(-1, str);
if (sender.doWorkArgs.CancelRequested)
{
sender.doWorkArgs.CancelAcknowledged = false;
sender.doWorkArgs.CancelRequested = false;
break;
}
if (datacompass1.Count == 0)
continue;
float rawmx = datacompass1[datacompass1.Count - 1].Item1;
float rawmy = datacompass1[datacompass1.Count - 1].Item2;
float rawmz = datacompass1[datacompass1.Count - 1].Item3;
// for old method
setMinorMax(rawmx, ref minx, ref maxx);
setMinorMax(rawmy, ref miny, ref maxy);
setMinorMax(rawmz, ref minz, ref maxz);
// get the current estimated centerpoint
//new HIL.Vector3((float)-((maxx + minx) / 2), (float)-((maxy + miny) / 2), (float)-((maxz + minz) / 2));
//Console.WriteLine("1 " + DateTime.Now.Millisecond);
// run lsq every second when more than 100 datapoints
if (datacompass1.Count > 100 && lastlsq.Second != DateTime.Now.Second)
{
MainV2.comPort.requestDatastream(MAVLink.MAV_DATA_STREAM.RAW_SENSORS, 50);
lastlsq = DateTime.Now;
lock (_locker)
{
try
{
var lsq = MagCalib.LeastSq(datacompass1, false);
// simple validation
if (Math.Abs(lsq[0]) < 999)
{
centre = new Vector3(lsq[0], lsq[1], lsq[2]);
log.Info("new centre " + centre.ToString());
prsphere.sphere1.CenterPoint = new Vector3(
(float) centre.x, (float) centre.y, (float) centre.z);
}
}
catch
{
}
}
}
// run lsq every second when more than 100 datapoints
if (datacompass2.Count > 100 && lastlsq2.Second != DateTime.Now.Second)
{
lastlsq2 = DateTime.Now;
lock (_locker)
{
try
{
var lsq = MagCalib.LeastSq(datacompass2, false);
// simple validation
if (Math.Abs(lsq[0]) < 999)
{
Vector3 centre2 = new Vector3(lsq[0], lsq[1], lsq[2]);
log.Info("new centre2 " + centre2.ToString());
prsphere.sphere2.CenterPoint = new Vector3(
(float) centre2.x, (float) centre2.y, (float) centre2.z);
}
}
catch
{
}
}
}
// run lsq every second when more than 100 datapoints
if (datacompass3.Count > 100 && lastlsq3.Second != DateTime.Now.Second)
{
lastlsq3 = DateTime.Now;
lock (_locker)
{
try
{
var lsq = MagCalib.LeastSq(datacompass3, false);
// simple validation
if (Math.Abs(lsq[0]) < 999)
{
Vector3 centre3 = new Vector3(lsq[0], lsq[1], lsq[2]);
log.Info("new centre2 " + centre3.ToString());
prsphere.sphere3.CenterPoint = new Vector3(
(float) centre3.x, (float) centre3.y, (float) centre3.z);
}
}
catch
{
}
}
}
//Console.WriteLine("1a " + DateTime.Now.Millisecond);
// dont use dup data
if (lastcount == datacompass1.Count)
continue;
lastcount = datacompass1.Count;
// add to sphere with center correction
prsphere.sphere1.AddPoint(new Vector3(rawmx, rawmy, rawmz));
prsphere.sphere1.AimClear();
if (datacompass2.Count > 30)
{
float raw2mx = datacompass2[datacompass2.Count - 1].Item1;
float raw2my = datacompass2[datacompass2.Count - 1].Item2;
float raw2mz = datacompass2[datacompass2.Count - 1].Item3;
prsphere.sphere2.AddPoint(new Vector3(raw2mx, raw2my, raw2mz));
prsphere.sphere2.AimClear();
}
if (datacompass3.Count > 30)
{
float raw3mx = datacompass3[datacompass3.Count - 1].Item1;
float raw3my = datacompass3[datacompass3.Count - 1].Item2;
float raw3mz = datacompass3[datacompass3.Count - 1].Item3;
prsphere.sphere3.AddPoint(new Vector3(raw3mx, raw3my, raw3mz));
prsphere.sphere3.AimClear();
}
//Console.WriteLine("2 " + DateTime.Now.Millisecond);
Vector3 point;
point = new Vector3(rawmx, rawmy, rawmz) + centre;
//find the mean radius
float radius = 0;
for (int i = 0; i < datacompass1.Count; i++)
{
point = new Vector3(datacompass1[i].Item1, datacompass1[i].Item2, datacompass1[i].Item3);
radius += (float) (point + centre).length();
}
radius /= datacompass1.Count;
//test that we can find one point near a set of points all around the sphere surface
int pointshit = 0;
string displayresult = "";
int factor = 3; // pitch
int factor2 = 4; // yaw
float max_distance = radius / 3; //pretty generouse
for (int j = 0; j <= factor; j++)
{
double theta = (Math.PI * (j + 0.5)) / factor;
for (int i = 0; i <= factor2; i++)
{
double phi = (2 * Math.PI * i) / factor2;
Vector3 point_sphere = new Vector3(
(float) (Math.Sin(theta) * Math.Cos(phi) * radius),
(float) (Math.Sin(theta) * Math.Sin(phi) * radius),
(float) (Math.Cos(theta) * radius)) - centre;
//log.InfoFormat("magcalib check - {0} {1} dist {2}", theta * MathHelper.rad2deg, phi * MathHelper.rad2deg, max_distance);
bool found = false;
for (int k = 0; k < datacompass1.Count; k++)
{
point = new Vector3(datacompass1[k].Item1, datacompass1[k].Item2, datacompass1[k].Item3);
double d = (point_sphere - point).length();
if (d < max_distance)
{
pointshit++;
found = true;
break;
}
}
// draw them all
//((ProgressReporterSphere)sender).sphere1.AimFor(new OpenTK.Vector3((float)point_sphere.x, (float)point_sphere.y, (float)point_sphere.z));
if (!found)
{
displayresult = "more data needed Aim For " +
GetColour((int) (theta * MathHelper.rad2deg),
(int) (phi * MathHelper.rad2deg));
prsphere.sphere1.AimFor(new Vector3((float) point_sphere.x,
(float) point_sphere.y, (float) point_sphere.z));
//j = factor;
//break;
}
}
}
extramsg = displayresult;
//Console.WriteLine("3 "+ DateTime.Now.Millisecond);
// check primary compass error
if (error < 0.2 && pointshit > hittarget && prsphere.autoaccept)
{
extramsg = "";
break;
}
}
MainV2.comPort.UnSubscribeToPacketType(sub);
MainV2.comPort.UnSubscribeToPacketType(sub2);
MainV2.comPort.UnSubscribeToPacketType(sub3);
// restore old sensor rate
MainV2.comPort.MAV.cs.ratesensors = backupratesens;
MainV2.comPort.MAV.cs.rateattitude = backuprateatt;
MainV2.comPort.MAV.cs.rateposition = backupratepos;
MainV2.comPort.requestDatastream(MAVLink.MAV_DATA_STREAM.RAW_SENSORS, MainV2.comPort.MAV.cs.ratesensors);
MainV2.comPort.requestDatastream(MAVLink.MAV_DATA_STREAM.POSITION, MainV2.comPort.MAV.cs.rateposition);
// request gps
MainV2.comPort.requestDatastream(MAVLink.MAV_DATA_STREAM.EXTRA1, MainV2.comPort.MAV.cs.rateattitude);
// request attitude
MainV2.comPort.requestDatastream(MAVLink.MAV_DATA_STREAM.EXTRA2, MainV2.comPort.MAV.cs.rateattitude);
// request vfr
MainV2.comPort.requestDatastream(MAVLink.MAV_DATA_STREAM.EXTRA3, MainV2.comPort.MAV.cs.ratesensors);
// request extra stuff - tridge
MainV2.comPort.requestDatastream(MAVLink.MAV_DATA_STREAM.RAW_SENSORS, MainV2.comPort.MAV.cs.ratesensors);
// request raw sensor
MainV2.comPort.requestDatastream(MAVLink.MAV_DATA_STREAM.RC_CHANNELS, MainV2.comPort.MAV.cs.raterc);
// request rc info
if (MainV2.speechEnable)
{
MainV2.speechEngine.SpeakAsync("Compass Calibration Complete");
}
else
{
Console.Beep();
}
if (minx > 0 && maxx > 0 || minx < 0 && maxx < 0 || miny > 0 && maxy > 0 || miny < 0 && maxy < 0 ||
minz > 0 && maxz > 0 || minz < 0 && maxz < 0)
{
sender.doWorkArgs.ErrorMessage = "Bad compass raw values. Check for magnetic interferance.";
ans = null;
ans2 = null;
return;
}
if (extramsg != "")
{
if (CustomMessageBox.Show(Strings.MissingDataPoints, Strings.RunAnyway, MessageBoxButtons.YesNo) ==
(int)DialogResult.No)
{
sender.doWorkArgs.CancelAcknowledged = true;
sender.doWorkArgs.CancelRequested = true;
ans = null;
ans2 = null;
ans3 = null;
return;
}
}
// remove outlyers
RemoveOutliers(ref datacompass1);
if (havecompass2 && datacompass2.Count > 0)
{
RemoveOutliers(ref datacompass2);
}
if (havecompass3 && datacompass3.Count > 0)
{
RemoveOutliers(ref datacompass3);
}
if (datacompass1.Count < 10)
{
sender.doWorkArgs.ErrorMessage = "Log does not contain enough data";
ans = null;
ans2 = null;
return;
}
bool ellipsoid = false;
if (MainV2.comPort.MAV.param.ContainsKey("COMPASS_DIA_X"))
{
ellipsoid = true;
}
log.Info("Compass 1");
ans = MagCalib.LeastSq(datacompass1, ellipsoid);
if (havecompass2 && datacompass2.Count > 0)
{
log.Info("Compass 2");
ans2 = MagCalib.LeastSq(datacompass2, ellipsoid);
}
if (havecompass3 && datacompass3.Count > 0)
{
log.Info("Compass 3");
ans3 = MagCalib.LeastSq(datacompass3, ellipsoid);
}
}
static void RemoveOutliers(ref List<Tuple<float, float, float>> data)
{
// remove outlyers
data.Sort(
delegate (Tuple<float, float, float> d1, Tuple<float, float, float> d2)
{
// get distance from 0,0,0
double ans1 = Math.Sqrt(d1.Item1 * d1.Item1 + d1.Item2 * d1.Item2 + d1.Item3 * d1.Item3);
double ans2 = Math.Sqrt(d2.Item1 * d2.Item1 + d2.Item2 * d2.Item2 + d2.Item3 * d2.Item3);
if (ans1 > ans2)
return 1;
if (ans1 < ans2)
return -1;
return 0;
}
);
data.RemoveRange(data.Count - (data.Count / 16), data.Count / 16);
}
public static double[] getOffsetsLog(string fn)
{
// this is for a dxf
PolylineVertex vertex;
List<PolylineVertex> vertexes = new List<PolylineVertex>();
List<Tuple<float, float, float>> data = new List<Tuple<float, float, float>>();
List<Tuple<float, float, float>> data2 = new List<Tuple<float, float, float>>();
List<Tuple<float, float, float>> data3 = new List<Tuple<float, float, float>>();
double[] ofsDoubles = new double[3];
double[] ofsDoubles2 = new double[3];
double[] ofsDoubles3 = new double[3];
DFLogBuffer logdata = new DFLogBuffer(File.OpenRead(fn));
var dflog = logdata.dflog;
foreach (var line in logdata.GetEnumeratorType(new[] { "MAG", "MAG2", "MAG3" }))
{
if (line.msgtype == "MAG" || line.msgtype == "MAG2" || line.msgtype == "MAG3")
{
int indexmagx = dflog.FindMessageOffset(line.msgtype, "MagX");
int indexmagy = dflog.FindMessageOffset(line.msgtype, "MagY");
int indexmagz = dflog.FindMessageOffset(line.msgtype, "MagZ");
int indexoffsetx = dflog.FindMessageOffset(line.msgtype, "OfsX");
int indexoffsety = dflog.FindMessageOffset(line.msgtype, "OfsY");
int indexoffsetz = dflog.FindMessageOffset(line.msgtype, "OfsZ");
if (indexmagx != -1 && indexoffsetx != -1)
{
float magx = float.Parse(line.items[indexmagx]);
float magy = float.Parse(line.items[indexmagy]);
float magz = float.Parse(line.items[indexmagz]);
float offsetx = float.Parse(line.items[indexoffsetx]);
float offsety = float.Parse(line.items[indexoffsety]);
float offsetz = float.Parse(line.items[indexoffsetz]);
//offsetx = offsety = offsetz = 0;
if (line.msgtype == "MAG")
{
data.Add(new Tuple<float, float, float>(
magx - offsetx,
magy - offsety,
magz - offsetz));
ofsDoubles[0] = offsetx;
ofsDoubles[1] = offsety;
ofsDoubles[2] = offsetz;
// fox dxf
vertex = new PolylineVertex(new netDxf.Vector3(magx - offsetx,
magy - offsety,
magz - offsetz)
);
vertexes.Add(vertex);
}
else if (line.msgtype == "MAG2")
{
data2.Add(new Tuple<float, float, float>(
magx - offsetx,
magy - offsety,
magz - offsetz));
ofsDoubles2[0] = offsetx;
ofsDoubles2[1] = offsety;
ofsDoubles2[2] = offsetz;
}
else if (line.msgtype == "MAG3")
{
data3.Add(new Tuple<float, float, float>(
magx - offsetx,
magy - offsety,
magz - offsetz));
ofsDoubles3[0] = offsetx;
ofsDoubles3[1] = offsety;
ofsDoubles3[2] = offsetz;
}
}
}
}
double[] x = LeastSq(data, false);
log.InfoFormat("magcal 1 ofs {0},{1},{2} strength {3} old ofs {4},{5},{6}", x[0], x[1], x[2], x[3], ofsDoubles[0], ofsDoubles[1], ofsDoubles[2]);
x = LeastSq(data, true);
log.InfoFormat("magcalel 1 ofs {0},{1},{2} strength {3} old ofs {4},{5},{6}", x[0], x[1], x[2], x[3], ofsDoubles[0], ofsDoubles[1], ofsDoubles[2]);
if (data2.Count > 0)
{
double[] x2 = LeastSq(data2, false);
log.InfoFormat("magcal 2 ofs {0},{1},{2} strength {3} old ofs {4},{5},{6}", x2[0], x2[1], x2[2], x2[3], ofsDoubles2[0], ofsDoubles2[1], ofsDoubles2[2]);
x2 = LeastSq(data2, true);
log.InfoFormat("magcalel 2 ofs {0},{1},{2} strength {3} old ofs {4},{5},{6}", x2[0], x2[1], x2[2], x2[3], ofsDoubles2[0], ofsDoubles2[1], ofsDoubles2[2]);
}
if (data3.Count > 0)
{
double[] x3 = LeastSq(data3, false);
log.InfoFormat("magcal 3 ofs {0},{1},{2} strength {3} old ofs {4},{5},{6}", x3[0], x3[1], x3[2], x3[3], ofsDoubles3[0], ofsDoubles3[1], ofsDoubles3[2]);
x3 = LeastSq(data3, true);
log.InfoFormat("magcalel 3 ofs {0},{1},{2} strength {3} old ofs {4},{5},{6}", x3[0], x3[1], x3[2], x3[3], ofsDoubles3[0], ofsDoubles3[1], ofsDoubles3[2]);
}
log.Info("Least Sq Done " + DateTime.Now);
doDXF(vertexes, x);
Array.Resize<double>(ref x, 3);
return x;
}
/// <summary>
/// Processes a tlog to get the offsets - creates dxf of data
/// </summary>
/// <param name="fn">Filename</param>
/// <returns>Offsets</returns>
public static async Task<double[]> getOffsets(string fn, int throttleThreshold = 0)
{
// based off tridge's work
string logfile = fn;
// old method
float minx = 0;
float maxx = 0;
float miny = 0;
float maxy = 0;
float minz = 0;
float maxz = 0;
// this is for a dxf
PolylineVertex vertex;
List<PolylineVertex> vertexes = new List<PolylineVertex>();
// data storage
Tuple<float, float, float> offset = new Tuple<float, float, float>(0, 0, 0);
List<Tuple<float, float, float>> data = new List<Tuple<float, float, float>>();
Hashtable filter = new Hashtable();
// track data to use
bool useData = false;
if (throttleThreshold <= 0)
useData = true;
log.Info("Start log: " + DateTime.Now);
using (MAVLinkInterface mine = new MAVLinkInterface())
{
try
{
mine.logplaybackfile =
new BinaryReader(File.Open(logfile, FileMode.Open, FileAccess.Read, FileShare.Read));
}
catch (Exception ex)
{
log.Debug(ex.ToString());
CustomMessageBox.Show("Log Can not be opened. Are you still connected?");
return new double[] { 0 };
}
mine.logreadmode = true;
// gather data
while (mine.logplaybackfile.BaseStream.Position < mine.logplaybackfile.BaseStream.Length)
{
MAVLink.MAVLinkMessage packetraw = await mine.readPacketAsync().ConfigureAwait(false);
var packet = mine.DebugPacket(packetraw, false);
// this is for packets we dont know about
if (packet == null)
continue;
if (packet.GetType() == typeof(MAVLink.mavlink_vfr_hud_t))
{
if (((MAVLink.mavlink_vfr_hud_t)packet).throttle >= throttleThreshold)