IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Lazarus Pascal Discussion :

Utilisation de TLazSerial : freeze après quelques lectures. Comment utiliser ce composant ? [Lazarus]


Sujet :

Lazarus Pascal

  1. #1
    Membre confirmé

    Homme Profil pro
    Développeur informatique
    Inscrit en
    Novembre 2013
    Messages
    342
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Gironde (Aquitaine)

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : Administration - Collectivité locale

    Informations forums :
    Inscription : Novembre 2013
    Messages : 342
    Points : 536
    Points
    536
    Billets dans le blog
    2
    Par défaut Utilisation de TLazSerial : freeze après quelques lectures. Comment utiliser ce composant ?
    Bjr à tous, et merci à Jurassic Pork pour le composant TLazSerial.

    J'utilise ce composant pour dialoguer avec un lasermètre et j'ai défini une classe TPilotageDistoX dérivée de TLazSerial.

    Ouverture du DistoX: OK
    Lecture des informations du DistoX: OK

    TPilotageDistoX contient un TTimer auquel est acccrochée à l'évenement OnTimer la fonction de lecture
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
    procedure TPilotageDistoX.ProcTimer(Sender: TObject);
    begin
      AfficherMessageErreur('ProcTimer');
      self.LireEtDepilerTrameDe8OctetsData;
    end;
    J'ai un 'freeze' après quelques appels de LireEtDepilerTrameDe8OctetsData().

    Comment s'y prendre vu que je ne connais pas bien TLazSerial ?

    Cdlt

    Fonction LireEtDepilerTrameDe8OctetsData :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
     
     
    function TPilotageDistoX.LireEtDepilerTrameDe8OctetsData: boolean;
    var
      EWE: String;
      MyBuffer: TDistoXDataBuffer; //array[0..7] of Byte;
      i, Nb: Integer;
      qtype: integer;
      op   : integer;
      X, Y, Z: Integer;
      Dist: Integer;
      MesureG, MesureM: TPoint3Df;
      AbsG, AbsM, DipAngle: Integer;
      myMesureVisee: TMesureViseeDistoX;
      P: float;
      NbV: Integer;
      NbG: Integer;
      NbM: Integer;
      function ConvFromDistoX(const valeur: integer): integer;
      begin
        Result := valeur;
        if (Result > 32767) then Result := Result - 65536;
      end;
    begin
      Application.ProcessMessages;
      Result := False;
      try
         MyBuffer := MakeBufferVierge();
         if (FIsReadingTopoData) then
         begin
           myMesureVisee.TypeMesure := tmdxUNKNOWN;
           myMesureVisee.Longueur := 0.00;
           myMesureVisee.Azimut   := 0.00;
           myMesureVisee.Pente    := 0.00;
           myMesureVisee.IsMarked := false;
           myMesureVisee.HexaData := '';
           Nb := High(MyBuffer);
           EWE := '';
     
           // lire 8 octets - version OK
           (*
           for i := 0 to Nb do
           begin
             MyBuffer[i] := self.ReadByte; //READBYTE();
             EWE         += Format('%.2X', [MyBuffer[i]]);
           end;
           //*)
           // lire 8 octets - TODO: version à valider
           self.ReadBuffer8bytes(MyBuffer);
           //----------------
           qtype := MyBuffer[0];
           op    := (qtype and $3F);
           // acquitter bonne réception et vider la première visée de la file du DistoX
           Acknowledge(qtype);
           // Ce sont des données ?
           if (op < $20) then
           begin
             X := MyBuffer[1] + (MyBuffer[2] shl 8);
             Y := MyBuffer[3] + (MyBuffer[4] shl 8);
             Z := MyBuffer[5] + (MyBuffer[6] shl 8);
             if ((oldtype <> qtype) and
                 (oldX    <> X) and
                 (oldY    <> Y) and
                 (oldZ    <> Z)) then
             begin
               case op of
                 1: // données topo
                 begin
                   // distances exprimées en mm si < 100 m, sinon en cm
                   Dist := X + ((qtype and $40) shr 10);     // OK
                   //myMesureVisee.TypeMesure := op;
                   myMesureVisee.TypeMesure := tmdxUNKNOWN;
                   myMesureVisee.Longueur := Dist * 0.001; // TODO: Cas où Dist > 100 m
                   myMesureVisee.Azimut   := radtodeg(Y * HEX_TO_RAD);                   // OK
                   P  := radtodeg(Z * HEX_TO_RAD);
                   if (Not InRange(P, -0.001, 90.001)) then P := P - 360.00;
                   myMesureVisee.Pente := P;
                   myMesureVisee.HexaData := EWE;
                   myMesureVisee.TimeStamp:= Now();
                   self.AddMesureVisee(myMesureVisee);
                   myMesureVisee := GetLastMesureVisee();
                   AfficherMessage(Format('%d: qtype = %.2X; op = %.2X; L = %.3f m; Az = %.2f; P = %.2f - EWE = %s',
                                         [GetNbViseesAcquises(),
                                          qtype, op,
                                          myMesureVisee.Longueur,
                                          myMesureVisee.Azimut,
                                          myMesureVisee.Pente,
                                          myMesureVisee.HexaData
                                          ]));
                   // on appelle le callback
                   if (Assigned(fProcTransmitMesureVisee)) then fProcTransmitMesureVisee();
                 end;
                 2: // Données de calibration G (accéléromètres)
                 begin
                   self.SetHeaderGrdGM;
                   MesureG := MakeTPoint3Df(ConvFromDistoX(X), ConvFromDistoX(Y), ConvFromDistoX(Z));
                   AddMesureG(MesureG);
                   FNbMesuresCalibration += 1;
                   NbG := self.GetNbMesuresG;
                   MesureG := self.GetMesureG(NbG - 1);
                   AfficherMessage(Format('%d: qtype = %.2X; op = %.2X; Gx = %.0f; Gy = %.0f; Gz = %.0f - EWE = %s',
                                   [FNbMesuresCalibration, qtype, op,
                                    MesureG.X, MesureG.Y, MesureG.Z,
                                    EWE]));
                   if (Assigned(FGridDataGMDistoX)) then
                   begin
                     FGridDataGMDistoX.Cells[1, FNbMesuresCalibration] := Format('%.0f', [MesureG.X]);
                     FGridDataGMDistoX.Cells[2, FNbMesuresCalibration] := Format('%.0f', [MesureG.Y]);
                     FGridDataGMDistoX.Cells[3, FNbMesuresCalibration] := Format('%.0f', [MesureG.Z]);
                   end;
                 end;
                 3: // Données de calibration M (magnétomètres)
                 begin
                   self.SetHeaderGrdGM;
                   MesureM := MakeTPoint3Df(ConvFromDistoX(X), ConvFromDistoX(Y), ConvFromDistoX(Z));
                   self.AddMesureM(MesureM);
                   NbM := self.GetNbMesuresM;
                   MesureM := self.GetMesureM(NbM - 1);
                   //FNbMesuresCalibration += 1;
                   AfficherMessage(Format('%d: qtype = %.2X; op = %.2X; Mx = %.0f; My = %.0f; Mz = %.0f - EWE = %s',
                                          [FNbMesuresCalibration, qtype, op,
                                          MesureM.X, MesureM.Y, MesureM.Z, EWE]));
                   if (Assigned(FGridDataGMDistoX)) then
                   begin
                     FGridDataGMDistoX.Cells[4, FNbMesuresCalibration] := Format('%.0f', [MesureM.X]);
                     FGridDataGMDistoX.Cells[5, FNbMesuresCalibration] := Format('%.0f', [MesureM.Y]);
                     FGridDataGMDistoX.Cells[6, FNbMesuresCalibration] := Format('%.0f', [MesureM.Z]);
                   end;
                 end;
                 4: // Vecteur
                 begin
                   AbsG     := X;  // norme de G
                   AbsM     := y;  // norme de M
                   DipAngle := Z; // angle de plongée
                   if (Assigned(FGridDataGMDistoX)) then
                   begin
                     FGridDataGMDistoX.Cells[7, FNbMesuresCalibration] := Format('%d', [AbsG]);
                     FGridDataGMDistoX.Cells[8, FNbMesuresCalibration] := Format('%d', [AbsM]);
                     FGridDataGMDistoX.Cells[9, FNbMesuresCalibration] := Format('%d', [DipAngle]);
                   end;
                 end;
               otherwise
                 ;
               end;
               oldtype := qtype;
               oldX    := X;
               oldY    := Y;
               oldZ    := Z;
             end;
           end;
         end;
       except
         ; //on E: Exception do AfficherMessageErreur(Format('[%s] %s.ProcTimer: [%d] %s', [UnitName, ClassName, E.Message]));
       end;
     
    end;
    A l'utilisation, j'ai un 'freeze'



    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    1001
    1002
    1003
    1004
    1005
    1006
    1007
    1008
    1009
    1010
    1011
    1012
    1013
    1014
    1015
    1016
    1017
    1018
    1019
    1020
    1021
    1022
    1023
    1024
    1025
    1026
    1027
    1028
    1029
    1030
    1031
    1032
    1033
    1034
    1035
    1036
    1037
    1038
    1039
    1040
    1041
    1042
    1043
    1044
    1045
    1046
    1047
    1048
    1049
    1050
    1051
    1052
    1053
    1054
    1055
    1056
    1057
    1058
    1059
    1060
    1061
    1062
    1063
    1064
    1065
    1066
    1067
    1068
    1069
    1070
    1071
    1072
    1073
    1074
    1075
    1076
    1077
    1078
    1079
    1080
    1081
    1082
    1083
    1084
    1085
    1086
    1087
    1088
    1089
    1090
    1091
    1092
    1093
    1094
    1095
    1096
    1097
    1098
    1099
    1100
    1101
    1102
    1103
    1104
    1105
    1106
    1107
    1108
    1109
    1110
    1111
    1112
    1113
    1114
    1115
    1116
    1117
    1118
    1119
    1120
    1121
    1122
    1123
    1124
    1125
    1126
    1127
    1128
    1129
    1130
    1131
    1132
    1133
    1134
    1135
    1136
    1137
    1138
    1139
    1140
    1141
    1142
    1143
    1144
    1145
    1146
    1147
    1148
    1149
    1150
    1151
    1152
    1153
    1154
    1155
    1156
    1157
    1158
    1159
    1160
    1161
    1162
    1163
    1164
    1165
    1166
    1167
    1168
    1169
    1170
    1171
    1172
    1173
    1174
    1175
    1176
    1177
    1178
    1179
    1180
    1181
    1182
    1183
    1184
    1185
    1186
    1187
    1188
    1189
    1190
    1191
    1192
    1193
    1194
    1195
    1196
    1197
    1198
    1199
    1200
    1201
    1202
    1203
    1204
    1205
    1206
    1207
    1208
    1209
    1210
    1211
    1212
    1213
    1214
    1215
    1216
    1217
    1218
    1219
    1220
    1221
    1222
    1223
    1224
    1225
    1226
    1227
    1228
    1229
    1230
    1231
    1232
    1233
    1234
    1235
    1236
    1237
    1238
    1239
    1240
    1241
    1242
    1243
    1244
    1245
    1246
    1247
    1248
    1249
    1250
    1251
    1252
    1253
    1254
    1255
    1256
    1257
    1258
    1259
    1260
    1261
    1262
    1263
    1264
    1265
    1266
    1267
    1268
    1269
    1270
    1271
    1272
    1273
    1274
    1275
    1276
    1277
    1278
    1279
    1280
    1281
    1282
    1283
    1284
    1285
    1286
    1287
    1288
    1289
    1290
    1291
    1292
    1293
    1294
    1295
    1296
    1297
    1298
    1299
    1300
    1301
    1302
    1303
    1304
    1305
    1306
    1307
    1308
    1309
    1310
    1311
    1312
    1313
    1314
    1315
    1316
    1317
    1318
    1319
    1320
    1321
    1322
    1323
    1324
    1325
    1326
    1327
    1328
    1329
    1330
    1331
    1332
    1333
    1334
    1335
    1336
    1337
    1338
    1339
    1340
    1341
    1342
    1343
    1344
    1345
    1346
    1347
    1348
    1349
    1350
    1351
    1352
    1353
    1354
    1355
    1356
    1357
    1358
    1359
    1360
    1361
    1362
    1363
    1364
    1365
    1366
    1367
    1368
    1369
    1370
    1371
    1372
    1373
    1374
    1375
    1376
    1377
    1378
    1379
    1380
    1381
    1382
    1383
    1384
    1385
    1386
    1387
    1388
    1389
    1390
    1391
    1392
    1393
    1394
    1395
    1396
    1397
    1398
    1399
    1400
    1401
    1402
    1403
    1404
    1405
    1406
    1407
    1408
    1409
    1410
    1411
    1412
    1413
    1414
    1415
    1416
    1417
    1418
    1419
    1420
    1421
    1422
    1423
    1424
    1425
    1426
    1427
    1428
    1429
    1430
    1431
    1432
    1433
    1434
    1435
    1436
    1437
    1438
    1439
    1440
    1441
    1442
    1443
    1444
    1445
    1446
    1447
    1448
    1449
    1450
    1451
    1452
    1453
    1454
    1455
    1456
    1457
    1458
    1459
    1460
    1461
    1462
    1463
    1464
    1465
    1466
    1467
    1468
    1469
    1470
    1471
    1472
    1473
    1474
    1475
    1476
    1477
    1478
    1479
    1480
    1481
    1482
    1483
    1484
    1485
    1486
    1487
    1488
    1489
    1490
    1491
    1492
    1493
    1494
    1495
    1496
    1497
    1498
    1499
    1500
    1501
    1502
    1503
    1504
    1505
    1506
    1507
    1508
    1509
    1510
    1511
    1512
    1513
    1514
    1515
    1516
    1517
    1518
    1519
    1520
    1521
    1522
    1523
    1524
    1525
    1526
    1527
    1528
    1529
    1530
    1531
    1532
    1533
    1534
    1535
    1536
    1537
    1538
    1539
    1540
    1541
    1542
    1543
    1544
    1545
    1546
    1547
    1548
    1549
    1550
    1551
    1552
    1553
    1554
    1555
    1556
    1557
    1558
    1559
    1560
    1561
    1562
    1563
    1564
    1565
    1566
    1567
    1568
    1569
    1570
    1571
    1572
    1573
    1574
    1575
    1576
    1577
    1578
    1579
    1580
    1581
    1582
    1583
    1584
    1585
    1586
    1587
    1588
    1589
    1590
    1591
    1592
    1593
    1594
    1595
    1596
    1597
    1598
    1599
    1600
    1601
    1602
    1603
    1604
    1605
    1606
    1607
    1608
    1609
    1610
    1611
    1612
    1613
    1614
    1615
    1616
    1617
    1618
    1619
    1620
    1621
    1622
    1623
    1624
    1625
    1626
    1627
    1628
    1629
    1630
    1631
    1632
    1633
    1634
    1635
    1636
    1637
    1638
    1639
    1640
    1641
    1642
    1643
    1644
    1645
    1646
    1647
    1648
    1649
    1650
    1651
    1652
    1653
    1654
    1655
    1656
    1657
    1658
    1659
    1660
    1661
    1662
    1663
    1664
    1665
    1666
    1667
    1668
    1669
    1670
    1671
    1672
    1673
    1674
    1675
    1676
    1677
    1678
    1679
    1680
    1681
    1682
    1683
    1684
    1685
    1686
    1687
    1688
    1689
    1690
    1691
    1692
    1693
    1694
    1695
    1696
    1697
    1698
    1699
    1700
    1701
    1702
    1703
    1704
    1705
    1706
    1707
    1708
    1709
    1710
    1711
    1712
    1713
    1714
    1715
    1716
    1717
    1718
    1719
    1720
    1721
    1722
    1723
    1724
    1725
    1726
    1727
    1728
    1729
    1730
    1731
    1732
    1733
    1734
    1735
    1736
    1737
    1738
    1739
    1740
    1741
    1742
    1743
    1744
    1745
    1746
    1747
    1748
    1749
    1750
    1751
    1752
    1753
    1754
    1755
    1756
    1757
    1758
    1759
    1760
    1761
    1762
    1763
    1764
    1765
    1766
    1767
    1768
    1769
    1770
    1771
    1772
    1773
    1774
    1775
    1776
    1777
    1778
    1779
    1780
    1781
    1782
    1783
    1784
    1785
    1786
    1787
    1788
    1789
    1790
    1791
    1792
    1793
    1794
    1795
    1796
    1797
    1798
    1799
    1800
    1801
    1802
    1803
    1804
    1805
    1806
    1807
    1808
    1809
    1810
    1811
    1812
    1813
    1814
    1815
    1816
    1817
    1818
    1819
    1820
    1821
    1822
    1823
    1824
    1825
    1826
    1827
    1828
    1829
    1830
    1831
    1832
    1833
    1834
    1835
    1836
    1837
    1838
    1839
    1840
    1841
    1842
    1843
    1844
    1845
    1846
    1847
    1848
    1849
    1850
    1851
    1852
    1853
    1854
    1855
    1856
    1857
    1858
    1859
    1860
    1861
    1862
    1863
    1864
    1865
    1866
    1867
    1868
    1869
    1870
    1871
    1872
    1873
    1874
    1875
    1876
    1877
    1878
    1879
    1880
    1881
    1882
    1883
    1884
    1885
    1886
    1887
    1888
    1889
    1890
    1891
    1892
    1893
    1894
    1895
    1896
    1897
    1898
    1899
    1900
    1901
    1902
    1903
     
     
    unit unitdistox;
    // 05/02/2015: Calcul de calibration OK (méthode standard)
    // 20/05/2015: Bug à la libération de TPilotageDistoX fixé
    // 07/12/2015: Lecture de la mémoire du DistoX: OK, mais lent.
    // 08/06/2016: Les listes passent aux génériques
    {$INCLUDE CompilationParameters.inc}
     
    interface
     
    uses
      Classes, SysUtils, Math,
      StructuresDonnees,
      {$IFDEF USE_GENERIC_TYPES}
      UnitListesSimplesWithGeneriques,
      {$ELSE}
      UnitListesSimplesWithoutGeneriques,
      {$ENDIF}
      Common,
      {$IFDEF MSWINDOWS}
      LazSerial, //synaser,  // Pour la version Linux, retirer la dépendance
      LazSynaSer,
      {$ENDIF}
      {$IFDEF LINUX}
      LazSerial,
      {$ENDIF}
      {$IFDEF MAC_OS_X_VERSION_MIN_REQUIRED}
      {$ENDIF}
      StdCtrls,
      ExtCtrls, // pour Timer
      CalculMatriciel3x3,
      Grids,
      Forms;
    const
      // axes
      mrX_AXIS = 1;
      mrY_AXIS = 2;
      mrZ_AXIS = 3;
      // mappage de la mémoire du DistoX
      //ADDR_START_SECTION_CONFIGURATION   = $B000; // calibration coefficients, Ox00B000 -> Ox00B3FF
      //ADDR_START_SECTION_DATA_STORE      = $B400; // data segment            , Ox00B400 -> Ox00FFFF
      // commandes DistoX
      DISTOX_COMMAND_EXTINCTION             =  52;  // $34: extinction du Disto
      DISTOX_COMMAND_READ_MEMORY_AT_ADDRESS =  56;  // $38: b111000 ; conflict with measure trigging command
      DISTOX_COMMAND_CALIBRATION_ON         =  49;  // $31: b110001: Calibration ON
      DISTOX_COMMAND_CALIBRATION_OFF        =  48;  // $30: b110000: Calibration OFF
      DISTOX_COMMAND_LASER_ON               =  54;  // $36: b110110: Laser ON
      DISTOX_COMMAND_LASER_OFF              =  55;  // $37: b110111: Laser OFF
      DISTOX_COMMAND_READ_DATA_SHOT         =  56;  // $38: lecture d'une visée
      DISTOX_COMMAND_BOOTLOADER_READ_DATA_AT_ADDRESS =  58;  // $38: b111010 ; conflict with measure trigging command
     
      ERR_MSG_NO_CONNEXION                  = '** No Connexion **';
     
    type TDistoXDataBuffer = array[0..7] of Byte;
    type TBootloaderModeDataBuffer = array[0..263] of Byte;
    type
     
    { TPilotageDistoX }
     
     TPilotageDistoX = class(TLazSerial)
      private
        // Identité du DistoX
        FDistoXSerialNumber   : integer;
        FDistoXVersionHardware: integer;
        FDistoXVersionFirmware: integer;
        // composant LazSerial
        FCalibrationModeON  : boolean;
        FLaserON            : boolean;
        FIsReadingTopoData  : boolean;
        FNbMesuresCalibration : integer;
        FDoNonLinearCalibration: boolean;
        // controles d'affichages
        FLabelActionsProcessing: TStaticText;
        FGridDataViseesDistoX : TStringGrid;
        FGridDataGMDistoX     : TStringGrid;
        FTimer                : TTimer;
        oldtype, oldX, oldY, oldZ: Integer;
        // listes des mesures
        FListeMesuresTopo     : TListeMesuresTopoDistoX; //TListeSimple<TMesureViseeDistoX>;
        // outils de calibration (fusion de TPilotageDistoX)
        FListeMesuresDeG      : TListePoints3Df;
        FListeMesuresDeM      : TListePoints3Df;
        fMatrix_aG  : TMatrix3x3;
        fMatrix_aM  : TMatrix3x3;
        fVecteur_bG : TPoint3Df;
        fVecteur_bM : TPoint3Df;
        fDelta      : double;
        fNbIters    : integer;
        // callback de transmission de visée lors de sa réception
        fProcTransmitMesureVisee: TProcTransmitMesureVisee; //procedure (var V: TMesureViseeDistoX) of object;
        FProcAfficherProgression: TProcDisplayProgression;
        // procedure de notification de succès de la connexion
        FProcNotifyDistoXConnected: TProcedureOfObject;
     
        // flag d'interruption des transfert
        FDoAbortTransfer: boolean;
     
        // flag indiquant si le DistoX doit rester connecté
        // Si une déconnexion intempestive survient, ce flag ordonnera la reconnexion
        // Ce flag doit être armé par la function  OpenDistoXConnexion()
        // et être désarmé par CloseDistoXConnexion();
        FDistoXMustBeReady: boolean;
        // Envoi d'une commande au DistoX (via opcode et buffer de 3 octets)
        //procedure ProcOnStatus(Sender: TObject; Reason: THookSerialReason; const Value: string);
        procedure SendReadCommandAtAddress(var MyBuffer: TDistoXDataBuffer;const QCmd: word; const QAddress: word);
        // Buffers vierges
        function  MakeBootloaderBufferVierge(): TBootloaderModeDataBuffer;
        function  MakeBufferVierge(): TDistoXDataBuffer;
        function  MakeContentBuffer(const B: TDistoXDataBuffer): string;
        // Communication avec le DistoX (acquittement)
        function  Acknowledge(const B: byte): boolean;
        // extraction des données du buffer
        function  MakeTMesureViseeDistoXFromDataBuffer(const QBlock, QSegment: integer; const MyBuffer: TDistoXDataBuffer): TMesureViseeDistoX;
     
        // Fonctions de lecture/ecriture
        function  ReadBufferAtAddress(const QAddr: integer; var MyBuffer: TDistoXDataBuffer): boolean;
        function  ReadBuffer8bytes(var MyBuffer: TDistoXDataBuffer): integer;
        procedure WriteByteOfData(const B: byte); inline;
        function  WriteByte(const B: byte): Integer;
     
     
        function  ReadAnPacket(const QAddr: word; var QBuffer: TDistoXDataBuffer): boolean;
        function  LireEtDepilerTrameDe8OctetsData: boolean;
        // lecture du buffer 264 bits
        function  BootloaderReadBuffer264bytes(var MyBuffer: TBootloaderModeDataBuffer; const Nb: integer): integer;
        procedure BootloaderSendReadCommandAtAddress(var MyBuffer: TBootloaderModeDataBuffer;const QCmd: word; const QAddress: word);
        function  BootloaderReadAnPacket264(const QAddr: word; var QBuffer: TBootloaderModeDataBuffer): boolean;
        //-------------------------------------
        procedure ProcTimer(Sender: TObject);
        procedure SetHeaderGrdGM;
        function  getEmptyMesure(const QTypeMesure: TTypeMesureDistoX): TMesureViseeDistoX;
        //*******************************************************************
        // calculs de calibration
        procedure setJeuDeDonneesExemple();
        procedure OptVectors(const gr, mr: TPoint3Df; const alpha: double; out gx, mx: TPoint3Df);
        procedure TurnVectors(const gxp, mxp, gr, mr: TPoint3Df; out gx, mx: TPoint3Df);
        procedure CheckOverflow(var M: TMatrix3x3; var V: TPoint3Df);
        // matrices
        function GetMatrix_aG()  : TMatrix3x3;
        function GetMatrix_aM()  : TMatrix3x3;
        function GetVecteur_bG() : TPoint3Df;
        function GetVecteur_bM() : TPoint3Df;
        function GetNbIters()    : integer;
     
      public
        constructor Create(AOwner: TComponent); override;
        destructor Destroy; override;
     
        function  OpenDistoXConnexion(): boolean;              // ouverture du port
        procedure CloseDistoXConnexion();                      // fermeture du port
        procedure ExtinctDevice();
     
        // procédures d'objet rattachées
        procedure SetProcNotifySuccessConnexion(const P: TProcedureOfObject);
     
        //**************************************************************************
        //**************************************************************************
        // Fonctions à utiliser par l'appelant
        //************************************
        //  Fonctions n'ayant pas besoin de la connexion BT
        // --------------------------------------------------
        // widgets utilisés par TPilotageDistoX
        procedure SetLabelActionsProcessing(const L: TStaticText);
        // callbacks de transmission de valeur de mesure de visées
        procedure SetProcProgression(const P: TProcDisplayProgression);
     
        // vider les tables de données
        procedure ViderListesMesuresGM();
        procedure ViderListeMesuresTopo(const DoAddViseeBidon: boolean);  // vider liste des mesures topo
     
        // données de visées (mesures)
     
        procedure ChargerDonneesViseesBrutes(const Filename: string);
        procedure SauverDonneesViseesBrutes(const Filename: string);
        function  GetNbViseesAcquises(): integer;
        procedure AddMesureVisee(const V : TMesureViseeDistoX);
        function  GetMesureVisee(const Idx: integer): TMesureViseeDistoX;
        procedure PutMesureVisee(const Idx: integer; const V: TMesureViseeDistoX);
        procedure RemoveMesureVisee(const Idx: integer);
        function  GetLastMesureVisee(): TMesureViseeDistoX;
        procedure RemoveLastMesureVisee;
     
     
        // données de calibration
        procedure SetNonLinearCalibration(const o: boolean);
        function  CheckMethodeCalibration(): boolean;         // contrôle de la méthode de calibration avec un dataset d'exemple
        function  GetDataGMFromGrid(const grd: TStringGrid): boolean;
        function  SetDataGMInGrid(const grd: TStringGrid): boolean;
     
        procedure AddMesureG(const MG: TPoint3Df);
        procedure AddMesureM(const MG: TPoint3Df);
        procedure AddMesuresGMByValues(const gx, gy, gz, mx, my, mz: double);
        function  GetMesureG(const Idx: integer): TPoint3Df;
        function  GetMesureM(const Idx: integer): TPoint3Df;
        function  GetNbMesuresG(): integer;
        function  GetNbMesuresM(): integer;
        function  GetDelta()      : double;
     
        function  IsReadyForCalibrate: boolean;
        procedure CalculerCalibration();
        //--------------------------------------------------------------------------
        //  Fonctions nécessitant la connextion BT
        // --------------------------------------------------
        // initialisation
     
        procedure ProcOnRXData(Sender: TObject);
        //procedure ProcOnStatus(Sender: TObject; Reason: THookSerialReason; const Value: string);
     
        procedure SetLazSerialDevice(const D: string);   // Device: ex: COM1:
        procedure SetDelay(const D: integer);            // délai en millisecondes
        function  GetDelay(): integer;
        // numéro de série du DistoX
        function  ExtractNumSerieFromDistoX(): integer;
        function  ExtractVersionFirmWareFromDistoX(): integer;
        function  ExtractVersionHardwareFromDistoX(): integer;
     
        // lire / écrire les paramètres de calibrage
        procedure ReadCalibrationParametersFromDistoX();
        function  SendCalibrationParametersToDistoX: integer;
     
        // définir les statuts
        procedure SetReadingTopoData(const B: boolean);
        procedure SetLaserOn(const o: boolean);
        procedure SetCalibrationOn(const o: boolean);
     
     
        // obtenir les statuts
        function  IsDistoXConnexionReady() : boolean;
        function  IsLaserON()              : boolean;
        function  IsInCalibrationMode()    : boolean;
        function  IsAcquiringTopoData()    : boolean;
     
        // armer le flag d'abandon de transfert
        procedure SetFlagAbort(const F: boolean);
        // dump de la zone de données
        function ReadDataSection(const NumBlockDebut, NumBlockFin: integer): integer;
        // envoi d'un ordre de mesure (télécommande du bouton Mesure)
        procedure DemanderUneMesure();
    end;
     
    implementation
     
    const
      FV = 24000.00;
      FM = 16384.00;
     
      MAX_IT = 500;
      EPS    = 1E-8;
      HEX_TO_RAD = 2 * PI / 65536;
     
     
    { TPilotageDistoX }
    constructor TPilotageDistoX.Create(AOwner: TComponent);
    begin
      (*
      2 - Linux
    To simulate  a paired serial ports on linux : socat
    ex :  socat -d -d PTY: PTY:
     
    To connect to a bluetooth GPS on Linux
    echo connection to a  bluetooth GPS(/dev/rfcomm0)
     
    sudo rfcomm bind  0 xx:xx:xx:xx:xx:xx 1
    //*)
      inherited Create(AOwner);
      FDistoXMustBeReady     := false;
      FDistoXSerialNumber    := -1;
      FDistoXVersionHardware := -1;
      FDistoXVersionFirmware := -1;
      FDoNonLinearCalibration := true;
      FProcNotifyDistoXConnected := nil;
      FProcAfficherProgression   := nil;
      fProcTransmitMesureVisee   := nil;
      AfficherMessage(Format('%s.Create',[self.ClassName]));
      FTimer := TTimer.Create(Application);
      FListeMesuresTopo  := TListeMesuresTopoDistoX.Create;
      FListeMesuresDeG   := TListePoints3Df.Create;
      FListeMesuresDeM   := TListePoints3Df.Create;
      FDoAbortTransfer   := false;
      FNbMesuresCalibration := 0;
      OnRxData := ProcOnRXData;
      //OnStatus := ProcOnStatus;
      try
        ViderListeMesuresTopo(True);
        ViderListesMesuresGM();
      finally
      end;
    end;
     
    destructor TPilotageDistoX.Destroy;
    begin
      AfficherMessage(Format('%s.Destroy',[self.ClassName]));
      try
        ViderListeMesuresTopo(false);
        ViderListesMesuresGM;
        //self.CloseLazSerial;
        AfficherMessage('TPilotageDistoX destroyed');
      finally
        // /!\ Les objets instanciés par Application ne doivent jamais être libérés explicitement
        // Laisser le parent faire ce travail
        //FListeMesuresTopo.Free;
        //FListeMesuresDeG.Free;
        //FListeMesuresDeM.Free;
        // FTimer.Free;
      end;
      inherited Destroy;
      //*)
    end;
     
    // FONCTIONS DE BASE
    //******************************************************************************
    procedure TPilotageDistoX.WriteByteOfData(const B: byte);
    begin
      self.WriteByte(B);     // TODO: A valider
    end;
     
    function TPilotageDistoX.WriteByte(const B: byte): Integer;
    begin
      try
        Result := 0;
        //if SynSer.Handle = INVALID_HANDLE_VALUE then ComException('can not write to a closed port.');
        SynSer.SendByte(B);
      except
      end;
    end;
     
     
    function TPilotageDistoX.ReadBufferAtAddress(const QAddr: integer; var MyBuffer: TDistoXDataBuffer): boolean;
    var
      t0, t1: TDateTime;
    begin
      result := False;
      try
        // on boucle tant que la lecture des paquets n'a pas réussi
        while (not ReadAnPacket(QAddr, MyBuffer)) do
          ;
        Result := True;
      except
        FDistoXSerialNumber := -1;
      end;
    end;
    //******************************************************************************
     
    // INFOS SUR LE MATERIEL
     
     
    // numéro de série du DistoX
    function TPilotageDistoX.ExtractNumSerieFromDistoX(): integer;
    var
      MyBuffer: TDistoXDataBuffer;
    begin
      Application.ProcessMessages;
      if (FDistoXSerialNumber = -1) then          // si FDistoXSerialNumber = - 1, on fait une tentative d'extraction;
      begin
        if (ReadBufferAtAddress($8008, MyBuffer)) then  FDistoXSerialNumber := MyBuffer[3] + MyBuffer[4] shl 8; // retourne 2395 pour le DistoX de JPC
      end;
      Result := FDistoXSerialNumber;
    end;
    // version de firmware
    function TPilotageDistoX.ExtractVersionFirmWareFromDistoX(): integer;
    var
      MyBuffer: TDistoXDataBuffer;
    begin
      Application.ProcessMessages;
      if (FDistoXVersionFirmware = -1) then     // si FDistoXVersionFirmware = - 1, on fait une tentative d'extraction;
      begin
        if (ReadBufferAtAddress($E000, MyBuffer)) then FDistoXVersionFirmware := 100 * MyBuffer[3] + MyBuffer[4];
      end;
      Result := FDistoXVersionFirmware;
    end;
    // version de harware
    function TPilotageDistoX.ExtractVersionHardwareFromDistoX(): integer;
    var
      MyBuffer: TDistoXDataBuffer;
    begin
      Application.ProcessMessages;
      if (FDistoXVersionHardware = -1) then
      begin
        if (ReadBufferAtAddress($E004, MyBuffer)) then FDistoXVersionHardware := 10 * MyBuffer[3] + MyBuffer[4];     // byte 3 = major; byte 4 = minor, bytes 5 et 6 = 0
      end;
      Result := FDistoXVersionHardware;
    end;
     
    function TPilotageDistoX.Acknowledge(const B: byte): boolean;
    begin
      Result := (WriteByte((B and $80) or $55) = 0);
    end;
     
     
     
    function TPilotageDistoX.LireEtDepilerTrameDe8OctetsData: boolean;
    var
      EWE: String;
      MyBuffer: TDistoXDataBuffer; //array[0..7] of Byte;
      i, Nb: Integer;
      qtype: integer;
      op   : integer;
      X, Y, Z: Integer;
      Dist: Integer;
      MesureG, MesureM: TPoint3Df;
      AbsG, AbsM, DipAngle: Integer;
      myMesureVisee: TMesureViseeDistoX;
      P: float;
      NbV: Integer;
      NbG: Integer;
      NbM: Integer;
      function ConvFromDistoX(const valeur: integer): integer;
      begin
        Result := valeur;
        if (Result > 32767) then Result := Result - 65536;
      end;
    begin
      Application.ProcessMessages;
      Result := False;
      try
         MyBuffer := MakeBufferVierge();
         if (FIsReadingTopoData) then
         begin
           myMesureVisee.TypeMesure := tmdxUNKNOWN;
           myMesureVisee.Longueur := 0.00;
           myMesureVisee.Azimut   := 0.00;
           myMesureVisee.Pente    := 0.00;
           myMesureVisee.IsMarked := false;
           myMesureVisee.HexaData := '';
           Nb := High(MyBuffer);
           EWE := '';
     
           // lire 8 octets - version OK
           (*
           for i := 0 to Nb do
           begin
             MyBuffer[i] := self.ReadByte; //READBYTE();
             EWE         += Format('%.2X', [MyBuffer[i]]);
           end;
           //*)
           // lire 8 octets - TODO: version à valider
           self.ReadBuffer8bytes(MyBuffer);
           //----------------
           qtype := MyBuffer[0];
           op    := (qtype and $3F);
           // acquitter bonne réception et vider la première visée de la file du DistoX
           Acknowledge(qtype);
           // Ce sont des données ?
           if (op < $20) then
           begin
             X := MyBuffer[1] + (MyBuffer[2] shl 8);
             Y := MyBuffer[3] + (MyBuffer[4] shl 8);
             Z := MyBuffer[5] + (MyBuffer[6] shl 8);
             if ((oldtype <> qtype) and
                 (oldX    <> X) and
                 (oldY    <> Y) and
                 (oldZ    <> Z)) then
             begin
               case op of
                 1: // données topo
                 begin
                   // distances exprimées en mm si < 100 m, sinon en cm
                   Dist := X + ((qtype and $40) shr 10);     // OK
                   //myMesureVisee.TypeMesure := op;
                   myMesureVisee.TypeMesure := tmdxUNKNOWN;
                   myMesureVisee.Longueur := Dist * 0.001; // TODO: Cas où Dist > 100 m
                   myMesureVisee.Azimut   := radtodeg(Y * HEX_TO_RAD);                   // OK
                   P  := radtodeg(Z * HEX_TO_RAD);
                   if (Not InRange(P, -0.001, 90.001)) then P := P - 360.00;
                   myMesureVisee.Pente := P;
                   myMesureVisee.HexaData := EWE;
                   myMesureVisee.TimeStamp:= Now();
                   self.AddMesureVisee(myMesureVisee);
                   myMesureVisee := GetLastMesureVisee();
                   AfficherMessage(Format('%d: qtype = %.2X; op = %.2X; L = %.3f m; Az = %.2f; P = %.2f - EWE = %s',
                                         [GetNbViseesAcquises(),
                                          qtype, op,
                                          myMesureVisee.Longueur,
                                          myMesureVisee.Azimut,
                                          myMesureVisee.Pente,
                                          myMesureVisee.HexaData
                                          ]));
                   // on appelle le callback
                   if (Assigned(fProcTransmitMesureVisee)) then fProcTransmitMesureVisee();
                 end;
                 2: // Données de calibration G (accéléromètres)
                 begin
                   self.SetHeaderGrdGM;
                   MesureG := MakeTPoint3Df(ConvFromDistoX(X), ConvFromDistoX(Y), ConvFromDistoX(Z));
                   AddMesureG(MesureG);
                   FNbMesuresCalibration += 1;
                   NbG := self.GetNbMesuresG;
                   MesureG := self.GetMesureG(NbG - 1);
                   AfficherMessage(Format('%d: qtype = %.2X; op = %.2X; Gx = %.0f; Gy = %.0f; Gz = %.0f - EWE = %s',
                                   [FNbMesuresCalibration, qtype, op,
                                    MesureG.X, MesureG.Y, MesureG.Z,
                                    EWE]));
                   if (Assigned(FGridDataGMDistoX)) then
                   begin
                     FGridDataGMDistoX.Cells[1, FNbMesuresCalibration] := Format('%.0f', [MesureG.X]);
                     FGridDataGMDistoX.Cells[2, FNbMesuresCalibration] := Format('%.0f', [MesureG.Y]);
                     FGridDataGMDistoX.Cells[3, FNbMesuresCalibration] := Format('%.0f', [MesureG.Z]);
                   end;
                 end;
                 3: // Données de calibration M (magnétomètres)
                 begin
                   self.SetHeaderGrdGM;
                   MesureM := MakeTPoint3Df(ConvFromDistoX(X), ConvFromDistoX(Y), ConvFromDistoX(Z));
                   self.AddMesureM(MesureM);
                   NbM := self.GetNbMesuresM;
                   MesureM := self.GetMesureM(NbM - 1);
                   //FNbMesuresCalibration += 1;
                   AfficherMessage(Format('%d: qtype = %.2X; op = %.2X; Mx = %.0f; My = %.0f; Mz = %.0f - EWE = %s',
                                          [FNbMesuresCalibration, qtype, op,
                                          MesureM.X, MesureM.Y, MesureM.Z, EWE]));
                   if (Assigned(FGridDataGMDistoX)) then
                   begin
                     FGridDataGMDistoX.Cells[4, FNbMesuresCalibration] := Format('%.0f', [MesureM.X]);
                     FGridDataGMDistoX.Cells[5, FNbMesuresCalibration] := Format('%.0f', [MesureM.Y]);
                     FGridDataGMDistoX.Cells[6, FNbMesuresCalibration] := Format('%.0f', [MesureM.Z]);
                   end;
                 end;
                 4: // Vecteur
                 begin
                   AbsG     := X;  // norme de G
                   AbsM     := y;  // norme de M
                   DipAngle := Z; // angle de plongée
                   if (Assigned(FGridDataGMDistoX)) then
                   begin
                     FGridDataGMDistoX.Cells[7, FNbMesuresCalibration] := Format('%d', [AbsG]);
                     FGridDataGMDistoX.Cells[8, FNbMesuresCalibration] := Format('%d', [AbsM]);
                     FGridDataGMDistoX.Cells[9, FNbMesuresCalibration] := Format('%d', [DipAngle]);
                   end;
                 end;
               otherwise
                 ;
               end;
               oldtype := qtype;
               oldX    := X;
               oldY    := Y;
               oldZ    := Z;
             end;
           end;
         end;
       except
         ; //on E: Exception do AfficherMessageErreur(Format('[%s] %s.ProcTimer: [%d] %s', [UnitName, ClassName, E.Message]));
       end;
     
    end;
     
     
     
     
    function TPilotageDistoX.IsDistoXConnexionReady(): boolean;
    begin
      Result := self.Active;
    end;
     
    procedure TPilotageDistoX.SetCalibrationOn(const o: boolean);
    var
      EWE: byte;
    begin
     
      AfficherMessage(Format('%s.SetCalibrationOn %s', [ClassName, IIF(o, 'ON', 'OFF')]));
      // Valeur de la commande de calibration:
      // 00110001 = ON; 0011000 = OFF
      EWE := IIF(o, DISTOX_COMMAND_CALIBRATION_ON, DISTOX_COMMAND_CALIBRATION_OFF);
      self.WriteByteOfData(EWE);
      FCalibrationModeON := o;
    end;
    procedure TPilotageDistoX.SetLaserOn(const o: boolean);
    var
      EWE: Byte;
    begin
      Application.ProcessMessages;
      if (self.Active) then
        begin
     
        AfficherMessage(Format('%s.SetLaserOn %s', [ClassName, IIF(o, 'ON', 'OFF')]));
        // Valeur de la commande de laser:
        // 00110110 = ON; 00110111 = OFF
        EWE := IIF(o, DISTOX_COMMAND_LASER_ON, DISTOX_COMMAND_LASER_OFF);
        self.WriteByteOfData(EWE);
        FLaserON := o;
      end
      else
      begin
        AfficherMessage(Format('%s.SetLaserOn %s: ** NO CONNEXION **', [ClassName, IIF(o, 'ON', 'OFF')]));
      end;
    end;
     
    procedure TPilotageDistoX.ExtinctDevice;
    var
      EWE: byte;
    begin
      Application.ProcessMessages;
      AfficherMessage(Format('%s.ExtinctDevice', [ClassName]));
      // Valeur de la commande d'extinction: 00110100
      EWE := DISTOX_COMMAND_EXTINCTION;//  $34;
      self.WriteByteOfData(EWE);
      self.CloseDistoXConnexion();
    end;
     
    procedure TPilotageDistoX.SetProcNotifySuccessConnexion(const P: TProcedureOfObject);
    begin
      FProcNotifyDistoXConnected := P;
    end;
     
    // acquisition d'une mesure
    procedure TPilotageDistoX.DemanderUneMesure(); // OK
    var
      EWE: byte;
    begin
      if (not IsDistoXConnexionReady()) then Exit;
      Application.ProcessMessages;
      AfficherMessage(Format('%s.TrigMesure', [ClassName]));
      // Valeur de la commande trig mesure: 00111000
      EWE := DISTOX_COMMAND_READ_MEMORY_AT_ADDRESS;//$38;
      self.WriteByteOfData(EWE);
    end;
     
     
     
    function TPilotageDistoX.OpenDistoXConnexion: boolean;
    begin
      Application.ProcessMessages;
      FDistoXMustBeReady := false;
      Result := false;
      AfficherMessage(Format('%s.OpenLazSerial: %s', [ClassName, self.Device]));
      Result := False;
      FCalibrationModeON := False;
      FLaserON           := False;
      FIsReadingTopoData := false;
      oldtype  := 0;
      oldX     := 0;
      oldY     := 0;
      oldZ     := 0;
     
      // TLazserial présumé fonctionner sur Win et Linux
      try
        FTimer.OnTimer     := self.ProcTimer;
        self.Active        := true;
     
        Result             := self.Active; // ouverture de la connexion. Ne pas utiliser self.Open et consorts
        FDistoXMustBeReady := result;
     
      except
        on E: Exception do AfficherMessageErreur(Format('Connexion sur port "%s" impossible' + #13#10 + 'Message: %s',
              [self.Device, E.Message]));
      end;
     
     
     
    end;
     
    procedure TPilotageDistoX.CloseDistoXConnexion;
    begin
      AfficherMessage(Format('%s.CloseLazSerial', [ClassName]));
      Application.ProcessMessages;
      oldtype  := 0;
      oldX     := 0;
      oldY     := 0;
      oldZ     := 0;
     
      try
        FDistoXMustBeReady := false;
     
        FTimer.OnTimer := nil;
        //SetCalibrationOn(False);
        FIsReadingTopoData := False;
     
     
        FCalibrationModeON := False;
        FLaserON           := False;
        FIsReadingTopoData := false;
        FDistoXSerialNumber    := -1;
        FDistoXVersionHardware := -1;
        FDistoXVersionFirmware := -1;
        self.Active := false;
      finally
      end;
    end;
    //------------------------------------------------------------------------------
     
     
     
    procedure TPilotageDistoX.ReadCalibrationParametersFromDistoX();
    var
      AddressParamCalibG: word;
      EWE: array[0 .. 2] of byte;
      MyBuffer: TDistoXDataBuffer;
      k: integer;
      Nb: Integer;
      QTimeOut: Integer;
      reply_addr: Cardinal;
      QIsOK: Boolean;
      WU: Integer;
      AddressParamCalibM: Integer;
    begin
      if (not self.Active) then Exit;
      AfficherMessage(Format('%s.ReadCalibrationParametersFromDistoX()', [ClassName]));
      AddressParamCalibG := $8010;
      for k := 0 to 11 do
      begin
        MyBuffer := MakeBufferVierge();
     
        while (not ReadAnPacket(AddressParamCalibG + k * 2, MyBuffer)) do
          ;
        WU := MyBuffer[3] + MyBuffer[4] shl 8;
        AfficherMessage(Format('%d: Addr = %X  - Buff[0] = %X - Buffer = %s - Value of G = %d',
                              [k, AddressParamCalibG + k * 2, MyBuffer[0], MakeContentBuffer(MyBuffer), WU]));
        // traitement
        //+++++++++++
        //AddMesureG();
        //AddressParamCalib := AddressParamCalib + 4;
      end;
     
      AddressParamCalibM := $8028;
      for k := 0 to 11 do
      begin
        MyBuffer := MakeBufferVierge();
        while (not ReadAnPacket(AddressParamCalibM + k * 2, MyBuffer)) do
          ;
        WU := MyBuffer[3] + MyBuffer[4] shl 8;
        AfficherMessage(Format('%d: Addr = %X  - Buff[0] = %X - Buffer = %s - Value of M = %d',
                              [k, AddressParamCalibM + k * 2, MyBuffer[0], MakeContentBuffer(MyBuffer), WU]));
        // traitement
        //+++++++++++
     
        //AddressParamCalib := AddressParamCalib + 4;
      end;
     
     
     
    end;
     
    function TPilotageDistoX.SendCalibrationParametersToDistoX: integer;
    begin
      Result := -1;
      if (not self.Active) then Exit;
      AfficherMessage(Format('%s.SendCalibrationParametersToDistoX()', [ClassName]));
    end;
     
     
    (*
    // type for DistoX buffer
    type TDistoXDataBuffer = array[0..7] of Byte;
     
    // DistoX memory map
    ADDR_START_SECTION_CONFIGURATION   = $B000; // calibration coefficients, Ox00B000 -> Ox00B3FF
    ADDR_START_SECTION_DATA_STORE      = $B400; // data segment            , Ox00B400 -> Ox00FFFF
     
    // commandes DistoX
    DISTOX_COMMAND_EXTINCTION             =  52;  // $34: extinction du Disto
    DISTOX_COMMAND_READ_MEMORY_AT_ADDRESS =  56;  // $38: b111000 ; conflict with measure trigging command
    DISTOX_COMMAND_CALIBRATION_ON         =  49;  // $31: b110001: Calibration ON
    DISTOX_COMMAND_CALIBRATION_OFF        =  48;  // $30: b110000: Calibration OFF
    DISTOX_COMMAND_LASER_ON               =  54;  // $36: b110110: Laser ON
    DISTOX_COMMAND_LASER_OFF              =  55;  // $37: b110111: Laser OFF
    DISTOX_COMMAND_READ_DATA_SHOT         =  56;  // $38: lecture d'une visée
    //*)
     
     
     
     
    // lecture d'un paquet (retourne 4 octets)
    // TODO: A valider - Non testé
    function TPilotageDistoX.ReadAnPacket(const QAddr: word; var QBuffer: TDistoXDataBuffer): boolean;
    var
       Nb: Integer;
       reply_addr: Integer;
    begin
      Result   := false;
      if (not self.Active) then Exit;
      QBuffer := MakeBufferVierge();
      SendReadCommandAtAddress(QBuffer, DISTOX_COMMAND_READ_MEMORY_AT_ADDRESS, QAddr);
      Nb := ReadBuffer8bytes(QBuffer);
      if (Nb > 0) then
      begin
        if (QBuffer[0] = DISTOX_COMMAND_READ_MEMORY_AT_ADDRESS) then
        begin
          // contrôle de l'adresse lue
          reply_addr := (QBuffer[2] shl 8) OR QBuffer[1];
          Result := (reply_addr = QAddr);
        end;
      end;
      Application.ProcessMessages();
    end;
    // lecture d'un paquet (retourne 4 octets)
    function TPilotageDistoX.BootloaderReadAnPacket264(const QAddr: word; var QBuffer: TBootloaderModeDataBuffer): boolean;
    var
      Nb: Integer;
      reply_addr: Integer;
    begin
      Result   := false;
      if (not self.Active) then Exit;
      QBuffer := MakeBootloaderBufferVierge();
      AfficherMessage(Format('BootloaderReadAnPacket264 : Adresse: %X: Commande: %X', [QAddr, DISTOX_COMMAND_BOOTLOADER_READ_DATA_AT_ADDRESS]));
      BootloaderSendReadCommandAtAddress(QBuffer, DISTOX_COMMAND_BOOTLOADER_READ_DATA_AT_ADDRESS, QAddr);
      AfficherMessage('--- 00');
      Nb := BootloaderReadBuffer264bytes(QBuffer, 264);
      AfficherMessage(Format('--- 01: %d bytes read',  [Nb]));
      if (Nb > 0) then
      begin
        if (QBuffer[0] = DISTOX_COMMAND_BOOTLOADER_READ_DATA_AT_ADDRESS) then
        begin
          // contrôle de l'adresse lue
          reply_addr := (QBuffer[2] shl 8) OR QBuffer[1];
          Result := (reply_addr = QAddr);
          AfficherMessage(Format('BootloaderReadAnPacket264 : Adresse: %X (%X): Commande: %X - Taille: %d', [QAddr, reply_addr, DISTOX_COMMAND_BOOTLOADER_READ_DATA_AT_ADDRESS, Nb]));
        end;
      end;
      Application.ProcessMessages();
     
    end;
    // TODO: A tester
    function TPilotageDistoX.ReadBuffer8bytes(var MyBuffer: TDistoXDataBuffer): integer;
    var
      WU, Nb: Integer;
    begin
      result := -1;
      Nb := Max(1 + High(MyBuffer), 8);
      if (not self.Active) then Exit;
      Result := self.SynSer.RecvBuffer(@MyBuffer, Nb);
      WU := self.SynSer.LastError;
      AfficherMessageErreur(self.SynSer.GetErrorDesc(WU));
    end;
     
    function TPilotageDistoX.BootloaderReadBuffer264bytes(var MyBuffer: TBootloaderModeDataBuffer; const Nb: integer): integer;
    var
      WU: Integer;
    begin
      result := -1;
      if (not self.Active) then Exit;
      Result := self.SynSer.RecvBuffer(@MyBuffer, Nb);
      WU := self.SynSer.LastError;
      AfficherMessageErreur(self.SynSer.GetErrorDesc(WU));
    end;
     
    //******************************************************************************
    // lecture de la zone de données
     
    function TPilotageDistoX.ReadDataSection(const NumBlockDebut, NumBlockFin: integer): integer;
    const
      NB_BLOCKS   = 19;
      NB_SEGMENTS = 56;
    var
      AdresseDataZone: Integer;
      QNumBlock: Integer;
      NbDataToRead: Integer;
      NbDataAlreadyRead: Integer;
      NbStart: Integer;
      procedure LireUneVisee(const QBlock, QSegment: integer; const QAddressDebutVisee: word);
      var
        MyTrame  : TDistoXDataBuffer;
        MyBuffer1: TDistoXDataBuffer;
        MyBuffer2: TDistoXDataBuffer;
        i: Integer;
        EWE: String;
        myMesureVisee: TMesureViseeDistoX;
      begin
        // on boucle tant que la lecture des paquets n'a pas réussi
        while (not ReadAnPacket(QAddressDebutVisee, MyBuffer1)) do
          ;
        while (not ReadAnPacket(QAddressDebutVisee + 4, MyBuffer2)) do
          ;
        // construction des trames
        for i := 0 to 3 do MyTrame[i]   := MyBuffer1[3+i];
        for i := 0 to 3 do MyTrame[i+4] := MyBuffer2[3+i];
        EWE := MakeContentBuffer(MyTrame);
        // construction de la visée
        myMesureVisee := MakeTMesureViseeDistoXFromDataBuffer(QBlock, QSegment,MyTrame);
        AfficherMessage(Format('%d: %d:%d: L = %.3f m; Az = %.2f; P = %.2f - EWE = %s',
                                         [0,
                                          myMesureVisee.Block, myMesureVisee.Segment,
                                          myMesureVisee.Longueur,
                                          myMesureVisee.Azimut,
                                          myMesureVisee.Pente,
                                          myMesureVisee.HexaData
                                          ]));
        AddMesureVisee(myMesureVisee);
     
     
      end;
      // Un segment contient 18 octets mais seuls les 8 premiers contiennent une visée
      procedure LireUnSegment(const AddressBlock: word; const NumeroBlock, NumeroSegment: integer);
      var
        MyAddressSegment: Integer;
      begin
        MyAddressSegment := AddressBlock + 18 * NumeroSegment;
        // lecture de la visée
        LireUneVisee(NumeroBlock, NumeroSegment, MyAddressSegment);
        // le reste du segment est ignoré
        Application.ProcessMessages;
     
      end;
      // Un block a une taille de 1024 octets
      procedure LireUnBlock1024(const NumeroBlock: integer);
      var
        QNumSegment: Integer;
        T0, T1, dT: TDateTime;
        WU : String;
        EWE: String;
      begin
        for QNumSegment := 0 to NB_SEGMENTS - 1 do
        begin
          if (FDoAbortTransfer) then Exit;
          T0 := Now();
          LireUnSegment(1024 * NumeroBlock, NumeroBlock, QNumSegment);
          T1 := Now();
          dT := T1 - T0;
          if (Assigned(FProcAfficherProgression)) then
          begin
            // estimation du temps restant
            EWE := TimeToStr(dT * (NbDataToRead - NbDataAlreadyRead));
            WU  := Format('Block %d/%d  - Segment: %d/%d - Temps restant: %s', [NumeroBlock + 1, NB_BLOCKS,
                                                                                QNumSegment + 1, NB_SEGMENTS,
                                                                                EWE]);
            FProcAfficherProgression(WU, NbStart, NbDataToRead, NbDataAlreadyRead);
            NbDataAlreadyRead += 1;
          end;
        end;
      end;
    begin
      Result := -1;
      if (not self.Active) then Exit;
      AdresseDataZone := $0;
      NbStart := 0;
      FDoAbortTransfer:= false;
      NbDataAlreadyRead := 0;
      NbDataToRead := (1 + NumBlockFin - NumBlockDebut) * NB_SEGMENTS;
      Application.ProcessMessages;
      AfficherMessage(Format('%s.ReadMemoryArea(%X)', [ClassName, AdresseDataZone]));
      try
        for QNumBlock := NumBlockDebut to NumBlockFin do //NB_BLOCKS - 1 do
        begin
          AfficherMessage('-----------------------------------------------');
          if (FDoAbortTransfer) then
          begin
            AfficherMessageErreur('*** Transfert arrêté par l''utilisateur');
            FDoAbortTransfer := false;
            Exit;
          end;
          LireUnBlock1024(QNumBlock);
        end;
      except
        ; //AfficherMessageErreur('*** Transfert arrêté par l''utilisateur');
      end;
    end;
    //******************************************************************************
    //******************************************************************************
    //* SECTIONS COMMUNES A TOUTES LES VERSIONS                                    *
    //******************************************************************************
     
     
    // GESTION DES BUFFERS
    //******************************************************************************
    function TPilotageDistoX.MakeContentBuffer(const B: TDistoXDataBuffer): string;
    var
      i: Integer;
    begin
      Result := '';
      for i := 0 to High(B) do Result += Format('%.2X', [B[i]]);
    end;
    function TPilotageDistoX.MakeBufferVierge(): TDistoXDataBuffer;
    var
      q: Integer;
    begin
      for q := 0 to High(Result) do Result[q] := $0;
    end;
    function TPilotageDistoX.MakeBootloaderBufferVierge(): TBootloaderModeDataBuffer;
    var
      q: Integer;
    begin
      for q := 0 to High(Result) do Result[q] := $0;
    end;
     
    // INDICATEUR DE PROGRESSION - STATUT
    //******************************************************************************
    procedure TPilotageDistoX.SetProcProgression(const P: TProcDisplayProgression);
    begin
      FProcAfficherProgression := P;
    end;
    procedure TPilotageDistoX.SetLabelActionsProcessing(const L: TStaticText);
    begin
      FLabelActionsProcessing := L;
    end;
     
     
     
    function TPilotageDistoX.GetDataGMFromGrid(const grd: TStringGrid): boolean;
    var
      l, c, NbC, NbL: Integer;
      EWE: String;
    begin
      Result := false;
      AfficherMessage(Format('%s.GetDataGMFromGrid()', [ClassName]));
      ViderListesMesuresGM;
      NbC := grd.ColCount;
      NbL := grd.RowCount;
      for l := 1 to NbL - 1 do
      begin
        EWE := '';
        for c := 1 to NbC - 1 do EWE += Trim(grd.Cells[c, l]);
        if (Length(EWE) < 6) then Break;
        AddMesuresGMByValues(StrToFloatDef(Trim(grd.Cells[1, l]), 0.00),
                             StrToFloatDef(Trim(grd.Cells[2, l]), 0.00),
                             StrToFloatDef(Trim(grd.Cells[3, l]), 0.00),
                             StrToFloatDef(Trim(grd.Cells[4, l]), 0.00),
                             StrToFloatDef(Trim(grd.Cells[5, l]), 0.00),
                             StrToFloatDef(Trim(grd.Cells[6, l]), 0.00)
                             );
      end;
      CalculerCalibration();
    end;
     
    function TPilotageDistoX.SetDataGMInGrid(const grd: TStringGrid): boolean;
      procedure SetHeaderGrdGM;
      begin
        grd.Cells[1, 0] := 'Gx';
        grd.Cells[2, 0] := 'Gy';
        grd.Cells[3, 0] := 'Gz';
        grd.Cells[4, 0] := 'Mx';
        grd.Cells[5, 0] := 'My';
        grd.Cells[6, 0] := 'Mz';
        grd.Cells[7, 0] := '|G|';
        grd.Cells[8, 0] := '|M|';
        grd.Cells[9, 0] := '/a\';
      end;
    var
      i, NbG, NbM: Integer;
      mG, mM : TPoint3Df;
    begin
      Result := false;
      NbG := self.GetNbMesuresG;
      NbM := self.GetNbMesuresM;
      AfficherMessage(Format('%s.SetDataGMInGrid(%d G, %d M)', [ClassName, NbG, NbM]));
      SetHeaderGrdGM;
     
      for i := 0 to NbG - 1 do
      begin
        mG  := GetMesureG(i);
        grd.Cells[1, i+1] := Format('%d', [Trunc(mG.X * FV)]);
        grd.Cells[2, i+1] := Format('%d', [Trunc(mG.Y * FV)]);
        grd.Cells[3, i+1] := Format('%d', [Trunc(mG.Z * FV)]);
      end;
      for i := 0 to NbM - 1 do
      begin
        mM  := GetMesureM(i);
        grd.Cells[4, i+1] := Format('%d', [Trunc(mM.X * FV)]);
        grd.Cells[5, i+1] := Format('%d', [Trunc(mM.Y * FV)]);
        grd.Cells[6, i+1] := Format('%d', [Trunc(mM.Z * FV)]);
      end;
    end;
     
    // PARTIES FACTORISABLES
    //******************************************************************************
    procedure TPilotageDistoX.SendReadCommandAtAddress(var MyBuffer: TDistoXDataBuffer;const QCmd: word; const QAddress: word);
    begin
      MyBuffer[0] :=  QCmd;                        //DISTOX_COMMAND_READ_DATA = 56; // 00111000
      MyBuffer[1] :=  QAddress and $FF;           //  Address & 0xFF
      MyBuffer[2] := (QAddress shr 8) and $FF;    // (Address >> 8) & 0xFF
      self.WriteBuffer(MyBuffer, 3); //1 + High(MyBuffer));  // WriteBuffer() command
    end;
     
    procedure TPilotageDistoX.BootloaderSendReadCommandAtAddress(var MyBuffer: TBootloaderModeDataBuffer;const QCmd: word; const QAddress: word);
    begin
      MyBuffer[0] :=  QCmd;
      MyBuffer[1] :=  QAddress and $FF;           //  Address & 0xFF
      MyBuffer[2] := (QAddress shr 8) and $FF;    // (Address >> 8) & 0xFF
      self.WriteBuffer(MyBuffer, 3); //1 + High(MyBuffer));  // WriteBuffer() command
    end;
     
    procedure TPilotageDistoX.ProcTimer(Sender: TObject);
    begin
      AfficherMessageErreur('ProcTimer');
      self.LireEtDepilerTrameDe8OctetsData;
    end;
     
    // interprétation des trames
    function TPilotageDistoX.MakeTMesureViseeDistoXFromDataBuffer(const QBlock, QSegment: integer;
                                                                  const MyBuffer: TDistoXDataBuffer): TMesureViseeDistoX;
    var
      QType, QX, QY, QZ: Integer;
      i: Integer;
      WU: String;
      Dist: Integer;
      P: Double;
    begin
      Result.TypeMesure := tmdxUNKNOWN;
      Result.DistoXSerialNumber := FDistoXSerialNumber;
      Result.Block      := QBlock;
      Result.Segment    := QSegment;
      Result.Longueur := 0.00;
      Result.Azimut   := 0.00;
      Result.Pente    := 0.00;
      Result.IsMarked := false;
      Result.TimeStamp:= Now();
      WU := '';
      for i := 0 to High(MyBuffer) do WU := WU + Format('%X', [MyBuffer[i]]);
      Result.HexaData := WU;
      QType := MyBuffer[0];
      QX := MyBuffer[1] + (MyBuffer[2] shl 8);
      QY := MyBuffer[3] + (MyBuffer[4] shl 8);
      QZ := MyBuffer[5] + (MyBuffer[6] shl 8);
      Result.TypeMesure := tmdxUNKNOWN;
      // distances exprimées en mm si < 100 m, sinon en cm
      Dist := QX + ((QType and $40) shr 10);     // OK
      Result.Longueur := Dist * 0.001; // TODO: Cas où Dist > 100 m
      Result.Azimut   := radtodeg(QY * HEX_TO_RAD);                   // OK
      P  := radtodeg(QZ * HEX_TO_RAD);
      if (Not InRange(P, -0.001, 90.001)) then P := P - 360.00;
      Result.Pente := P;
    end;
    function TPilotageDistoX.GetDelay: integer;
    begin
      Result := FTimer.Interval;
    end;
    procedure TPilotageDistoX.SetDelay(const D: integer);
    begin
      FTimer.Interval := D;
    end;
     
    procedure TPilotageDistoX.SetFlagAbort(const F: boolean);
    begin
      AfficherMessageErreur('*** SetFlagAbort ***');
      FDoAbortTransfer := F;
    end;
    procedure TPilotageDistoX.SetReadingTopoData(const B: boolean);
    begin
      FIsReadingTopoData := B;
    end;
    function TPilotageDistoX.IsAcquiringTopoData(): boolean;
    begin
      result := FIsReadingTopoData;
    end;
     
    function TPilotageDistoX.IsLaserON(): boolean;
    begin
      Result := FLaserON;
    end;
     
    function TPilotageDistoX.IsInCalibrationMode: boolean;
    begin
      Result := FCalibrationModeON;
    end;
     
     
    procedure TPilotageDistoX.SetLazSerialDevice(const D: string);
    begin
      self.Device := D;
    end;
    procedure TPilotageDistoX.SetNonLinearCalibration(const o: boolean);
    begin
      FDoNonLinearCalibration := o;
    end;
     
    // GESTION DES MESURES DE VISEES
    //******************************************************************************
     
    procedure TPilotageDistoX.AddMesureVisee(const V: TMesureViseeDistoX);
    begin
      FListeMesuresTopo.AddElement(V);
    end;
     
    procedure TPilotageDistoX.RemoveMesureVisee(const Idx: integer);
    begin
      FListeMesuresTopo.RemoveElement(Idx);
    end;
     
    procedure TPilotageDistoX.RemoveLastMesureVisee;
    var
      Nb: Integer;
    begin
      Nb := FListeMesuresTopo.GetNbElements();
      RemoveMesureVisee(Nb - 1);
    end;
     
    function TPilotageDistoX.GetMesureVisee(const Idx: integer): TMesureViseeDistoX;
    begin
      Result := FListeMesuresTopo.GetElement(Idx);
    end;
     
    function TPilotageDistoX.GetLastMesureVisee: TMesureViseeDistoX;
    var
      Nb: Integer;
    begin
      Nb := FListeMesuresTopo.GetNbElements();
      Result := GetMesureVisee(Nb - 1);
    end;
     
    procedure TPilotageDistoX.PutMesureVisee(const Idx: integer; const V: TMesureViseeDistoX);
    begin
      FListeMesuresTopo.PutElement(Idx, V);
    end;
     
    function TPilotageDistoX.GetNbViseesAcquises: integer;
    begin
      Result := FListeMesuresTopo.GetNbElements();
    end;
     
     
     
    procedure TPilotageDistoX.ViderListeMesuresTopo(const DoAddViseeBidon: boolean);
    begin
      AfficherMessage(Format('%s.ViderListeMesuresTopo',[self.ClassName]));
      FListeMesuresTopo.ClearListe();
      // et on ajoute une mesure bidon
      if (DoAddViseeBidon) then self.AddMesureVisee(getEmptyMesure(tmdxUNKNOWN));
    end;
     
    // LOAD-SAVE DONNEES BRUTES
    //******************************************************************************
    procedure TPilotageDistoX.ChargerDonneesViseesBrutes(const Filename: string);
    var
      LS: TStringList;
      i, Nb: Integer;
      EWE: TStringArray;
      myMesure : TMesureViseeDistoX;
    begin
      //0	26/11/15 09:30	0.000	0.000	0.000
      //1	26/11/15 09:31	1.398	260.513	6.229	01760541B96E0425
     
      AfficherMessage(Format('%s.ChargerDonneesBrutes: %s',[self.ClassName, Filename]));
      LS := TStringList.Create;
      try
        LS.Clear;
        LS.LoadFromFile(Filename);
     
        Nb := LS.Count;
        // 1	3.114	329.529	32.382		012A0C55EA0717F9
        // on ajoute trois visées de signalisation en tête
        myMesure := getEmptyMesure(tmdxSIGNALISATION);
        for i := 0 to 2 do self.AddMesureVisee(myMesure);
        for i := 0 to Nb - 1 do
        begin
          try
            EWE := split(LS.Strings[i], #9);
            myMesure.TimeStamp  := Now();
            myMesure.TypeMesure := tmdxUNKNOWN;
            myMesure.Longueur   := StrToFloatDef(Trim(EWE[2]), 0.00);
            myMesure.Azimut     := StrToFloatDef(Trim(EWE[3]), 0.00);
            myMesure.Pente      := StrToFloatDef(Trim(EWE[4]), 0.00);
            myMesure.IsMarked   := false;
            myMesure.HexaData   := Trim(EWE[5]);
            //AfficherMessage(Format('%d: %.3f, %.3f, %.3f', [i, myMesure.Longueur, myMesure.Azimut, myMesure.Pente]));
            // Visées non nulles uniquement
            if (myMesure.Longueur > 0.0005) then self.AddMesureVisee(myMesure);
          except
          end;
        end;
      finally
        LS.Free;
      end;
    end;
     
    procedure TPilotageDistoX.SauverDonneesViseesBrutes(const Filename: string);
    const
      QFMT = '%s' + #9 + '%.3f' + #9 + '%.3f' + #9 + '%.3f' + #9 + '%s' + #9 + '%s' + #9 + '%s';
    var
      fp: TextFile;
      myMesure: TMesureViseeDistoX;
      i, Nb: Integer;
    begin
      AfficherMessage(Format('%s.SauverDonneesBrutes: %s',[self.ClassName, Filename]));
      AssignFile(fp, Filename);
      Nb := self.GetNbViseesAcquises;
      try
        ReWrite(fp);
        WriteLn(fp, 'Type' + #9 + 'Long' + #9 + 'Azimut' + #9 + 'Incl' + #9 + 'Marked' + #9 + 'Trame' + #9 + 'TimeStamp');
        for i := 0 to Nb - 1 do
        begin
          myMesure := GetMesureVisee(i);
          WriteLn(fp, Format(QFMT,
                            [getLitteralTypeMesureDistoX(myMesure.TypeMesure),
                             myMesure.Longueur, myMesure.Azimut, myMesure.Pente,
                             BoolToStr(myMesure.IsMarked, 'O', 'N'),
                             myMesure.HexaData,
                             DatePascalToDateCondensee(myMesure.TimeStamp)
                            ]));
        end;
     
      finally
        CloseFile(fp);
      end;
    end;
     
    // GESTION DE LA CALIBRATION
    //******************************************************************************
    procedure TPilotageDistoX.SetHeaderGrdGM;
    begin
      FGridDataGMDistoX.Cells[1, 0] := 'Gx';
      FGridDataGMDistoX.Cells[2, 0] := 'Gy';
      FGridDataGMDistoX.Cells[3, 0] := 'Gz';
      FGridDataGMDistoX.Cells[4, 0] := 'Mx';
      FGridDataGMDistoX.Cells[5, 0] := 'My';
      FGridDataGMDistoX.Cells[6, 0] := 'Mz';
      FGridDataGMDistoX.Cells[7, 0] := '|G|';
      FGridDataGMDistoX.Cells[8, 0] := '|y|';
      FGridDataGMDistoX.Cells[9, 0] := '/a\';
    end;
     
    function TPilotageDistoX.getEmptyMesure(const QTypeMesure: TTypeMesureDistoX): TMesureViseeDistoX;
    begin
      Result.TypeMesure := QTypeMesure;
      Result.DistoXSerialNumber := 0;
      Result.Block      := 0;
      Result.Segment    := 0;
      Result.Longueur := 0.00;
      Result.Azimut   := 0.00;
      Result.Pente    := 0.00;
      Result.IsMarked := false;
      Result.TimeStamp:= Now();
      Result.HexaData := '';
    end;
     
     
    procedure TPilotageDistoX.ViderListesMesuresGM;
    var
      i, Nb: Integer;
    begin
      try
        FListeMesuresDeG.ClearListe();
        FListeMesuresDeM.ClearListe();
      finally
      end;
    end;
    function TPilotageDistoX.IsReadyForCalibrate: boolean;
    var
      NbG, NbM: Integer;
    begin
      NbG := self.GetNbMesuresG;
      NbM := self.GetNbMesuresM;
      Result := (NbG = 56) and (NbM = 56);
    end;
    function TPilotageDistoX.GetMesureM(const Idx: integer): TPoint3Df;
    begin
      Result := FListeMesuresDeM.GetElement(Idx);
    end;
     
    function TPilotageDistoX.GetNbMesuresG: integer;
    begin
      Result := FListeMesuresDeG.GetNbElements();
    end;
     
    function TPilotageDistoX.GetNbMesuresM: integer;
    begin
      Result := FListeMesuresDeM.GetNbElements();
    end;
    function TPilotageDistoX.GetMesureG(const Idx: integer): TPoint3Df;
    begin
      Result := FListeMesuresDeG.GetElement(Idx);
    end;
    procedure TPilotageDistoX.AddMesureG(const MG: TPoint3Df);
    begin
      FListeMesuresDeG.AddElement(MG);
    end;
     
    procedure TPilotageDistoX.AddMesureM(const MG: TPoint3Df);
    begin
      FListeMesuresDeM.AddElement(MG);
    end;
     
    procedure TPilotageDistoX.AddMesuresGMByValues(const gx, gy, gz, mx, my, mz: double);
    var
      M, G: TPoint3Df;
    begin
      M.X := mx / FV;
      M.Y := my / FV;
      M.Z := mz / FV;
      G.X := gx / FV;
      G.Y := gy / FV;
      G.Z := gz / FV;
      AddMesureG(G);
      AddMesureM(M);
    end;
    // jeu de données exemple
    procedure TPilotageDistoX.setJeuDeDonneesExemple;
    var
      i: integer;
      G: TPoint3Df;
      M: TPoint3Df;
    begin
      AfficherMessage(Format('%s.setJeuDeDonneesExemple()', [ClassName]));
      //AddMesuresMGByValues(  Gx,  Gy,   Gz,   Mx,   My,   Mz); // Azim,  Incl,  Roll,  |G|,  |M|,   a,   d
      AddMesuresGMByValues(3,109, 14158, 10445, -7506, 18917); //   36.2,    -1.8,    -4.5,   1.001,   1.002,    26.8,    0.28
      AddMesuresGMByValues(169,14774, 105, 10475, 20752, 5286); //   36.3,    -1.9,    92.1,   0.998,   1.002,    26.7,    0.34
      AddMesuresGMByValues(47,2512, -12877, 9405, 8914, -20075); //   36.0,    -1.8,   174.6,   1.001,   1.000,    26.7,    0.09
      AddMesuresGMByValues(-88,-12335, -791, 9275, -18631, -9399); //   35.9,    -1.9,   -96.1,   0.999,   1.003,    26.6,    0.34
      AddMesuresGMByValues(-862,1478, 14217, -6522, 6721, 19965); //  216.2,     1.9,     1.3,   1.002,   1.001,    26.7,    0.34
      AddMesuresGMByValues(-705,14790, 788, -7153, 20965, -5638); //  215.8,     1.8,    89.2,   0.998,   1.000,    26.8,    0.26
      AddMesuresGMByValues(-826,998, -12943, -8110, -5143, -20801); //  215.7,     1.8,  -179.0,   1.001,   1.000,    26.6,    0.21
      AddMesuresGMByValues(-966,-12411, 394, -7530, -19607, 4711); //  215.9,     1.8,   -91.1,   1.000,   1.000,    26.7,    0.12
      AddMesuresGMByValues(-2269,1578, 14051, -6838, -7320, 19180); //  127.5,     7.9,     1.7,   0.999,   1.002,    26.7,    0.19
      AddMesuresGMByValues(-2356,-12192, 2108, -7947, -19299, -6990); //  127.8,     7.8,   -83.8,   0.998,   1.003,    26.7,    0.39
      AddMesuresGMByValues(-2283,672, -12772, -7864, 8468, -20059); //  127.2,     8.0,  -177.6,   0.999,   1.001,    26.7,    0.24
      AddMesuresGMByValues(-2151,14674, 106, -6762, 20132, 7609); //  127.6,     7.9,    92.1,   0.998,   1.001,    26.7,    0.26
      AddMesuresGMByValues(1416,1979, 14067, 10762, 9360, 18618); //  308.0,    -7.7,     3.5,   1.002,   1.001,    26.7,    0.19
      AddMesuresGMByValues(1529,14658, -233, 9945, 19543, -9505); //  307.8,    -7.7,    93.6,   1.000,   0.999,    26.7,    0.19
      AddMesuresGMByValues(1426,132, -12782, 9153, -8529, -19752); //  308.1,    -7.8,  -175.4,   1.001,   0.999,    26.6,    0.25
      AddMesuresGMByValues(1301,-12242, 1929, 9910, -18115, 8792); //  307.9,    -7.8,   -84.6,   0.999,   0.999,    26.6,    0.20
      AddMesuresGMByValues(-13966,734, 935, -18632, 10043, -1414); //  196.8,    87.3,   -62.7,   1.001,   1.001,    26.8,    0.15
      AddMesuresGMByValues(-13965,1711, 1054, -19057, -1034, -9666); //  209.1,    87.6,    43.9,   1.001,   1.001,    26.7,    0.15
      AddMesuresGMByValues(-13961,1811, -78, -18921, -8598, 35); //  226.1,    86.3,   145.2,   1.002,   1.002,    26.7,    0.25
      AddMesuresGMByValues(-13932,703, 144, -18427, 2085, 9096); //  216.8,    86.7,  -129.4,   0.999,   1.000,    26.7,    0.14
      AddMesuresGMByValues(13076,1335, -430, 21856, 3865, 7470); //   31.3,   -85.4,   166.9,   0.998,   1.000,    26.7,    0.23
      AddMesuresGMByValues(13016,2738, 685, 21897, -6662, 2658); //   22.5,   -83.0,    87.7,   0.997,   1.001,    26.7,    0.35
      AddMesuresGMByValues(13050,1302, 2094, 21571, -2582, -8377); //   11.9,   -83.7,     8.4,   0.999,   1.002,    26.8,    0.23
      AddMesuresGMByValues(13034,-196, 716, 21736, 8068, -4382); //   18.1,   -84.6,   -86.0,   0.997,   1.000,    26.7,    0.30
      AddMesuresGMByValues(-9490,1217, 10687, -13615, 10039, 13038); //  251.1,    42.1,    -0.2,   0.998,   0.999,    26.6,    0.21
      AddMesuresGMByValues(-9412,11414, 922, -14300, 14112, -9325); //  250.9,    42.0,    88.3,   1.002,   1.000,    26.7,    0.21
      AddMesuresGMByValues(-9502,1287, -9425, -14847, -8669, -13613); //  251.3,    42.1,  -180.0,   1.000,   1.001,    26.7,    0.10
      AddMesuresGMByValues(-9513,-8900, 708, -14152, -12330, 9147); //  250.3,    41.7,   -89.7,   1.000,   1.000,    26.7,    0.06
      AddMesuresGMByValues(7913,9350, 7639, 11143, 20569, 4494); //  250.6,   -37.4,    49.4,   1.002,   1.000,    26.7,    0.22
      AddMesuresGMByValues(7951,8031, -7745, 9936, 5291, -21004); //  249.5,   -37.5,   140.6,   1.005,   1.000,    26.5,    0.52
      AddMesuresGMByValues(7699,-6757, -6746, 9813, -19233, -6981); //  249.1,   -37.2,  -133.2,   0.998,   1.000,    26.5,    0.30
      AddMesuresGMByValues(7645,-6359, 8576, 10708, -5566, 19444); //  248.7,   -36.8,   -43.2,   1.001,   0.999,    26.8,    0.22
      AddMesuresGMByValues(-9092,758, 11042, -7062, -9533, 17966); //   60.4,    39.8,    -2.7,   0.999,   1.000,    26.8,    0.15
      AddMesuresGMByValues(-9105,11649, 1085, -7045, 18771, 9955); //   60.6,    40.4,    87.4,   1.001,   0.998,    26.7,    0.19
      AddMesuresGMByValues(-9095,1406, -9744, -8019, 10262, -19061); //   60.6,    40.0,   179.4,   0.998,   0.999,    26.8,    0.23
      AddMesuresGMByValues(-9092,-9260, 300, -8056, -17696, -10533); //   60.4,    39.3,   -91.9,   1.000,   0.999,    26.6,    0.14
      AddMesuresGMByValues(7456,1015, 11630, 15208, -9738, 13998); //   74.1,   -35.6,    -0.5,   0.998,   0.999,    26.6,    0.28
      AddMesuresGMByValues(7445,12368, 613, 15181, 15466, 9639); //   74.8,   -34.8,    90.0,   1.003,   0.997,    26.6,    0.45
      AddMesuresGMByValues(7362,465, -10491, 14283, 9771, -16343); //   74.6,   -34.9,  -176.5,   1.002,   0.998,    26.7,    0.28
      AddMesuresGMByValues(7240,-10092, 1614, 14085, -15201, -9746); //   74.1,   -34.7,   -85.1,   1.005,   0.999,    26.7,    0.52
      AddMesuresGMByValues(-8871,8519, 8273, -18098, 5385, 8559); //  166.5,    39.0,    43.4,   0.999,   0.998,    26.7,    0.25
      AddMesuresGMByValues(-8849,8836, -6856, -18468, 9476, -5228); //  166.4,    38.8,   134.8,   1.003,   1.001,    26.5,    0.39
      AddMesuresGMByValues(-8840,-7572, -5334, -18781, -5812, -8079); //  166.2,    38.1,  -124.2,   0.998,   1.001,    26.8,    0.25
      AddMesuresGMByValues(-8816,-6548, 7995, -18351, -8290, 4604); //  165.9,    38.0,   -46.6,   0.999,   1.001,    26.7,    0.17
      AddMesuresGMByValues(8749,1689, 10586, 8788, -3017, 20940); //  154.5,   -42.6,     3.4,   0.999,   1.000,    26.3,    0.45
      AddMesuresGMByValues(8630,11393, -474, 7842, 22272, 2084); //  154.9,   -41.1,    96.0,   1.005,   0.998,    26.9,    0.58
      AddMesuresGMByValues(8315,-310, -9598, 6439, 2280, -22733); //  155.3,   -40.2,  -171.9,   0.997,   0.999,    26.6,    0.31
      AddMesuresGMByValues(8324,-9072, 2251, 6894, -21223, -2419); //  153.5,   -40.7,   -81.0,   0.999,   0.999,    26.8,    0.22
      AddMesuresGMByValues(-8692,1264, 11355, -2286, 2618, 22065); //  346.3,    37.7,     0.1,   0.999,   1.001,    26.8,    0.23
      AddMesuresGMByValues(-8663,11976, 542, -2841, 22873, -2412); //  346.7,    38.1,    90.4,   0.998,   1.000,    26.9,    0.32
      AddMesuresGMByValues(-8740,923, -10032, -3863, -1974, -22865); //  346.6,    38.0,  -178.1,   0.999,   0.998,    27.1,    0.55
      AddMesuresGMByValues(-8671,-9581, 1375, -3135, -21434, 2871); //  346.3,    37.1,   -86.2,   0.999,   0.999,    26.8,    0.13
      AddMesuresGMByValues(7555,619, 11593, 21153, -245, 9692); //    0.2,   -36.0,    -2.6,   1.000,   0.999,    26.8,    0.10
      AddMesuresGMByValues(7642,12197, 1101, 20946, 10980, -11); //    0.2,   -35.8,    87.4,   1.003,   0.998,    26.6,    0.32
      AddMesuresGMByValues(7578,581, -10323, 20446, 224, -11374); //    0.2,   -36.1,  -177.0,   1.000,   0.999,    26.6,    0.10
      AddMesuresGMByValues(7552,-9887, 596, 20676, -9827, -1094); //  359.7,   -36.3,   -90.3,   1.004,   1.000,    26.7,    0.36
      afficherMessage('   Gx     Gy     Gz     Mx     My     Mz    Azim   Incl   Roll   |G|    |M|     a      d');
      for i := 0 to GetNbMesuresG - 1 do
      begin
        G := self.GetMesureG(i);
        M := self.GetMesureM(i);
        AfficherMessage(Format('%d: %.6f, %.6f, %.6f, , %.6f, %.6f, %.6f', [i, G.X * FV, G.Y * FV, G.Z * FV, M.X * FV, M.Y * FV, M.Z * FV]));
      end;
    end;
     
    //******************************************************************************
    //* FONCTIONS DE CALCUL COMMUNES TOUTES VERSIONS                               *
    //******************************************************************************
    function TPilotageDistoX.GetMatrix_aG: TMatrix3x3;
    begin
      result := fMatrix_aG;
    end;
    function TPilotageDistoX.GetMatrix_aM: TMatrix3x3;
    begin
      result := fMatrix_aM;
    end;
     
    function TPilotageDistoX.GetVecteur_bG: TPoint3Df;
    begin
      result := fVecteur_bG;
    end;
     
    function TPilotageDistoX.GetVecteur_bM: TPoint3Df;
    begin
      result := fVecteur_bM;
    end;
     
    //******************************************************************************
     
     
    function TPilotageDistoX.GetDelta: double;
    begin
      result := fDelta;
    end;
     
    function TPilotageDistoX.GetNbIters: integer;
    begin
      result := fNbIters;
    end;
     
     
     
    procedure TPilotageDistoX.OptVectors(const gr, mr: TPoint3Df; const alpha: double; out gx, mx: TPoint3Df);
    var
      no: TPoint3Df;
      s, c: double;
      s1, s2, s3, s4: TPoint3Df;
    begin
      no := produitVectoriel(gr, mr, true); //Vector no = Vector.Normalized(gr % mr);  // plane normal
      s  := sin(alpha);
      c  := cos(alpha);
      s1 := MultVectorByScalar(mr, c); // mr * c
      s2 := MultVectorByScalar(produitVectoriel(mr, no, false), s);// (mr % no) * s
      s4 := AddVecteurs([s1, s2, gr]);
      gx := NormaliseVecteur(s4);
      // mx = gx * c + (no % gx) * s;
      s1 := MultVectorByScalar(gx, c); // gx * c +
      s2 := MultVectorByScalar(produitVectoriel(no, gx, false), s);// (no % gx) * s;
      mx := AddTwoVecteurs(s1, s2);
    end;
    procedure TPilotageDistoX.TurnVectors(const gxp, mxp, gr, mr: TPoint3Df; out gx, mx: TPoint3Df);
    var
      s, c, a: Extended;
    begin
      s  := gr.Z * gxp.Y - gr.Y * gxp.Z + mr.Z * mxp.Y - mr.Y * mxp.Z;          //float s = gr.z * gxp.y - gr.y * gxp.z + mr.z * mxp.y - mr.y * mxp.z;
      c  := gr.Y * gxp.Y + gr.Z * gxp.Z + mr.Y * mxp.Y + mr.Z * mxp.Z;          //float c = gr.y * gxp.y + gr.z * gxp.z + mr.y * mxp.y + mr.z * mxp.z;
      a  := arctan2(s, c);                                                      //float a = (float)Math.Atan2(s, c);
      gx := TurnX(gxp, a);                                                      // gx = gxp.TurnX(a);
      mx := TurnX(mxp, a);                                                      // mx = mxp.TurnX(a);
    end;
    // Cette fonction peut modifier les paramètres d'entrée
    procedure TPilotageDistoX.CheckOverflow(var M: TMatrix3x3; var V: TPoint3Df);
    const
      SHORT_MAX_VALUE = 32767;
    var
      Mo: TMatrix3x3;
      Vo: TPoint3Df;
      qmax: Extended;
      qM: TMatrix3x3;
      qV: TPoint3Df;
    begin
       Mo := makeMatrix3x3Nulle;
       Vo := makeTPoint3Df(0.00, 0.00, 0.00);
       qmax := max(MaxDiffMatrix(m, Mo) * FM,
                   MaxDiffVector(v, Vo) * FV);
      if (qmax > SHORT_MAX_VALUE) then
      begin
         qM := MultMatrix3x3ByScalar(M, SHORT_MAX_VALUE / qmax); //           m = m * (short.MaxValue / max);
         qV := MultVectorByScalar(V, SHORT_MAX_VALUE / qmax);
      end;
    end;
    // Calibration
    procedure TPilotageDistoX.CalculerCalibration();
    var
      Nb: Integer;
      gr: array of TPoint3Df;
      mr: array of TPoint3Df;
      gx: array of TPoint3Df;
      mx: array of TPoint3Df;
      InvNb: Extended;
      i: Integer;
      aG0, aM0: TMatrix3x3;
      sumG, sumM: TPoint3Df;
      sumG2, sumM2: TMatrix3x3;
      CarreKronecker: TMatrix3x3;
      sa, ca: Extended;
      G, M: TPoint3Df;
      alpha: float;
      avG, avM: TPoint3Df;
      WU: TMatrix3x3;
      invG, invM: TMatrix3x3;
      aG, aM: TMatrix3x3;
      oO, bG, bM: TPoint3Df;
      NbIter: Integer;
      delta: double;
      dg: TPoint3Df;
      dm: TPoint3Df;
      Cnt: Integer;
      grp: TPoint3Df;
      mrp: TPoint3Df;
      first: Integer;
      gt: TPoint3Df;
      mt: TPoint3Df;
      gxp: TPoint3Df;
      mxp: TPoint3Df;
      avGx: TPoint3Df;
      avMx: TPoint3Df;
      sumGxG: TMatrix3x3;
      sumMxM: TMatrix3x3;
      GG: TPoint3Df;
      MM: TPoint3Df;
      pk: TMatrix3x3;
      QQ: TMatrix3x3;
      moy: Extended;
      EWE: Double;
    begin
      Nb := GetNbMesuresG;
      AfficherMessage(Format('%s.Calibrage: Nb = %d', [ClassName, Nb]));
     
      InvNb := 1.0/Nb;
      SetLength(gr, Nb);
      SetLength(mr, Nb);
      SetLength(gx, Nb);
      SetLength(mx, Nb);
      for i := 0 to Nb-1 do
      begin
        gr[i] := makeVecteurNul;
        mr[i] := makeVecteurNul;
        gx[i] := makeVecteurNul;
        mx[i] := makeVecteurNul;
      end;
      aG0   := makeMatrix3x3Nulle;                                                  // Matrix aG0,
      aM0   := makeMatrix3x3Nulle;                                                  //        aM0;
      sumG  := makeVecteurNul;                                                      // Vector sumG = Vector.zero;
      sumM  := makeVecteurNul;                                                      // Vector sumM = Vector.zero;
      sumG2 := makeMatrix3x3Nulle;                                                  // Matrix sumG2 = Matrix.zero;
      sumM2 := makeMatrix3x3Nulle;                                                  // Matrix sumM2 = Matrix.zero;
      CarreKronecker := makeMatrix3x3Nulle;
      sa := 0.0;                                                                    //float sa = 0, ca = 0;
      ca := 0.0;                                                                    //float sa = 0, ca = 0;
      AfficherMessage(Format('%s: %s', [{$I %FILE%}, {$I %LINE%}]));
      AfficherMessage(' -- Boucle 001');
      //Boucle 001
      for i := 0 to Nb - 1 do                                                       // for (int i = 0; i < num; i++)
      begin                                                                         // {
        // sum up g x m for initial alpha                                           //     sum up g x m for initial alpha
        G := self.GetMesureG(i);                                                    //     TPoint3Df G = this.getMesureG(i)
        M := self.GetMesureM(i);                                                    //     TPoint3Df M = this.getMesureM(i);    ;
        sa += NormeVecteur(produitVectoriel(G, M, false));                          //     sa += NormeVecteur(produitVectoriel(G, M, false)); //     Vector.Abs(g[i] % m[i]); // cross product
        ca += produitScalaire(G, M);                                                //     ca += produitScalaire(G, M);                       //     g[i] * m[i]; // dot product
        //AfficherMessage(Format('%d: G = (%.6f, %.6f, %.6f), M = (%.6f, %.6f, %.6f), sa = %.6f, ca = %.6f',
        //                       [i, G.X, G.Y, G.Z, M.X, M.Y, M.Z, sa, ca]));
        sumG := AddTwoVecteurs(sumG, G);                                            //     sumG = AddVecteurs(sumG, G);
        sumM := AddTwoVecteurs(sumM, M);                                            //     sumM := AddVecteurs(sumM, M);
        CarreKronecker := ProduitKroneckerVecteurs(G, G);                           //     CarreKronecker = ProduitKroneckerVecteurs(G, G);
        sumG2 := AddMatrix3x3(sumG2, CarreKronecker);                               //     sumG2 = AddMatrix3x3(sumG2, CarreKronecker) ;      //     sumG2 += (g[i] & g[i]); // outer product
        //afficherMatrix3x3('CarreKronecker', CarreKronecker);
        CarreKronecker := ProduitKroneckerVecteurs(M, M);                           //         CarreKronecker = ProduitKroneckerVecteurs(M, M);
        sumM2 := AddMatrix3x3(sumM2, CarreKronecker);                               //  sumM2 = AddMatrix3x3(sumM2, CarreKronecker);       //     sumM2 += (m[i] & m[i]); // outer product
        //afficherMatrix3x3('sumG2', sumG2);
        //afficherMatrix3x3('CarreKronecker', CarreKronecker);
        //afficherMatrix3x3('sumM2', sumM2);
      end;                                                                          // }
      //AfficherMessage(format('sa = %.6f, ca = %.6f', [sa, ca]));
      alpha := Math.arctan2(sa, ca);
      avG := MultVectorByScalar(sumG, invNb);                                       // TPoint3Df avG = MultVectorByScalar(sumG, invNb);         // Vector avG = sumG * invNum; // average g
      avM := MultVectorByScalar(sumM, invNb);                                       // TPoint3Df avM = MultVectorByScalar(sumM, invNb);         // Vector avM = sumM * invNum;
      // average Matrix invG = Matrix.Inverse(sumG2 - (sumG & avG));
                                                                                    // TMatrix3x3 WU = new TMatrix3x3();
      CarreKronecker := ProduitKroneckerVecteurs(sumG, avG);                        // CarreKronecker = ProduitKroneckerVecteurs(sumG, avG);
      WU   := SubstractMatrix3x3(sumG2, CarreKronecker);                            // WU = SubstractMatrix3x3(sumG2, CarreKronecker);
      invG := InvMat3x3(WU);                                                        // TMatrix3x3 invG = InvMat3x3(WU);     // Matrix invG = Matrix.Inverse(sumG2 - (sumG & avG));
      // average Matrix invM = Matrix.Inverse(sumM2 - (sumM & avM));
      CarreKronecker := ProduitKroneckerVecteurs(sumM, avM);                        // CarreKronecker = ProduitKroneckerVecteurs(sumM, avM);
      WU   := SubstractMatrix3x3(sumM2, CarreKronecker);                            // WU = SubstractMatrix3x3(sumM2, CarreKronecker);
      invM := InvMat3x3(WU);                                                        // TMatrix3x3 invM = InvMat3x3(WU);     // Matrix invM = Matrix.Inverse(sumM2 - (sumM & avM));
      aG   := LoadIdentity3x3();                                                    // aG = makeIdentity(); // aG = aM = Matrix.one;
      aM   := LoadIdentity3x3();                                                    // aM = makeIdentity();
      oO   := makeVecteurNul();                                                     // TPoint3Df oO = makeVecteurNul();
      bG   := SubstractVecteurs(oO, avG);                                           // bG = SubstractVecteurs(oO, avG); //bG = Vector.zero - avG; // use negative average as initial offset
      bM   := SubstractVecteurs(oO, avM);                                           //  bM = SubstractVecteurs(oO, avM); //bM = Vector.zero - avM;
      NbIter := 0;
      // OK jusqu'ici
      afficherMatrix3x3('invG', invG);
      afficherMatrix3x3('invM', invM);
      AfficherMessage('-- Boucle principale');
      //*** Boucle principale                                                       // Boucle principale
      // Validée. Revoir la condition de sortie
      while (true) do                                                               // do
      begin                                                                         // {
        // Boucle 001: Validé
        for i := 0 to Nb -1 do                                                      //     for (int i = 0; i < Nb; i++)
        begin                                                                       //     {
          gr[i] := AddTwoVecteurs(MultMat3x3ByVector(aG, getMesureG(i)), bG);       //         fgr[i] = AddVecteurs(MultMat3x3ByVector(aG, this.getMesureG(i)), bG); //     gr[i] = (aG * g[i]) + bG;
          mr[i] := AddTwoVecteurs(MultMat3x3ByVector(aM, getMesureM(i)), bM);       //         fmr[i] = AddVecteurs(MultMat3x3ByVector(aM, this.getMesureM(i)), bM); //     mr[i] = (aM * m[i]) + bM;
        end;                                                                        //     }
        sa := 0.00; ca := 0.00;                                                     //     sa = 0F; ca = 0F;
        Cnt := 0; // Boucle à remplacer par un while                                // Boucle à remplacer par un while
        while (Cnt < Nb) do                                                         //     for (int i = 0; i < Nb; i++)
        begin                                                                       //     {
           // get optimal gx & mx from gr & mr                                      //        // get optimal gx & mx from gr & mr
           if (Cnt < 16) then // equidirectional sample groups                      //        if (i < 16)  // equidirectional sample groups
           begin                                                                    //        {
             grp := makeVecteurNul();                                               //            Vector grp = Vector.zero;
             mrp := makeVecteurNul();                                               //            Vector mrp = Vector.zero;
             first := cnt;                                                          //            int first = i;
             for i := first to (first + 4) - 1 do                                   //            for (; i < first + 4; i++)
             begin                                                                  //            {
               // match gr & mr to first gr & mr                                    //                // match gr & mr to first gr & mr
               TurnVectors(gr[Cnt], mr[Cnt], gr[first], mr[first], gt, mt);         //                TurnVectors(gr[i], mr[i], gr[first], mr[first], out gt, out mt);
               grp := AddTwoVecteurs(grp, gt);                                      //                grp += gt;
               mrp := AddTwoVecteurs(mrp, mt);                                      //                mrp += mt;
               Cnt := Cnt + 1;
             end;                                                                   //            }
             // get optimal matched gx & mx from sum of matched gr & mr             //            // get optimal matched gx & mx from sum of matched gr & mr
             OptVectors(grp, mrp, alpha, gxp, mxp);                                 //            OptVectors(grp, mrp, alpha, out gxp, out mxp);
     
             // alpha calculation                                                   //            alpha calculation
             sa += NormeVecteur(produitVectoriel(mrp, gxp, false));                 //            sa += Vector.Abs(mrp % gxp);
             ca += produitScalaire(mrp, gxp);                                       //            ca += mrp * gxp;
             // Boucle0004
             Cnt := first;
             for i := first to (first + 4) - 1 do                                   //            for (i = first; i < first + 4; i++)
             begin                                                                  //            { // get optimal gx & mx from matched gx & mx
               TurnVectors(gxp, mxp, gr[Cnt], mr[Cnt], gt, mt);                     //                TurnVectors(gxp, mxp, gr[i], mr[i], out gx[i], out mx[i]);
               gx[Cnt] := gt;
               mx[Cnt] := mt;
               Cnt := Cnt + 1;
             end;                                                                   //           }
             Cnt := Cnt - 1;                                                        //           i--;  // Instruction interdite en Pascal
           end                                                                      //        } //  if (i < 16) // equidirectional sample groups
           else                                                                     //        else
           begin // individual sample                                               //        { // individual sample
             ;                                                                      //             this.OutOptVectors_gx = makeVecteurNul();
             ;                                                                      //             this.OutOptVectors_mx = makeVecteurNul();
             OptVectors(gr[Cnt], mr[Cnt], alpha, gt, mt);                           //             OptVectors(gr[i], mr[i], alpha, out gx[i], out mx[i]);
             gx[Cnt] := gt;
             mx[Cnt] := mt;
             // alpha calculation                                                   //             // alpha calculation
             sa += NormeVecteur(produitVectoriel(mr[Cnt], gx[Cnt], false));         //             sa += Vector.Abs(mr[i] % gx[i]);
             ca += produitScalaire(mr[Cnt], gx[Cnt]);
           end;                                                                     //        }
           Cnt += 1;
        end;                                                                        //     }  // fin à remplacer par un while
        alpha := arctan2(sa, ca);                                                   //     alpha = Math.atan2(sa, ca);
     
        // get aG & aM from g, m, gx, & mx                                          //     get aG & aM from g, m, gx, & mx
        avGx := makeVecteurNul();                                                   //     Vector avGx = Vector.zero;
        avMx := makeVecteurNul();                                                   //     Vector avMx = Vector.zero;
        sumGxG := makeMatrix3x3Nulle();                                             //     Matrix sumGxG = Matrix.zero;
        sumMxM := makeMatrix3x3Nulle();                                             //     Matrix sumMxM = Matrix.zero;
        for i := 0 to Nb - 1 do                                                     //     for (int i = 0; i < num; i++)
        begin                                                                       //     {
          avGx   := AddTwoVecteurs(avGx, gx[i]);                                    //         avGx += gx[i];
          avMx   := AddTwoVecteurs(avMx, mx[i]);                                    //         avMx += mx[i];
          GG     := getMesureG(i);
          MM     := getMesureM(i);
          pk     := ProduitKroneckerVecteurs(gx[i], GG);
          sumGxG := AddMatrix3x3(sumGxG, pk);                                       //         sumGxG += (gx[i] & g[i]); // outer product
          pk     := ProduitKroneckerVecteurs(mx[i], MM);
          sumMxM := AddMatrix3x3(sumMxM, pk);                                       //         sumMxM += (mx[i] & m[i]);
        end;                                                                        //     }
        // get new aG & aM                                                          //     // get new aG & aM
        aG0 := aG;                                                                  //     aG0 = aG; aM0 = aM;
        aM0 := aM;
        //afficherMatrix3x3("-- aM", aM);
        avGx := MultVectorByScalar(avGx, invNb);                                    //     avGx = avGx * invNum; // average gx
        avMx := MultVectorByScalar(avMx, invNb);                                    //     avMx = avMx * invNum;
        CarreKronecker := ProduitKroneckerVecteurs(avGx, sumG);                     //     aG = (sumGxG - (avGx & sumG)) * invG;
        QQ := SubstractMatrix3x3(sumGxG, CarreKronecker);
        aG := ProduitMat3x3(QQ, invG);
        // aM = (sumMxM - (avMx & sumM)) * invM;                                    //     aM = (sumMxM - (avMx & sumM)) * invM;
        CarreKronecker := ProduitKroneckerVecteurs(avMx, sumM);
        //afficherMatrix3x3("Kronecker aM", CarreKronecker);
        QQ := SubstractMatrix3x3(sumMxM, CarreKronecker);
        aM := ProduitMat3x3(QQ, invM);
        // enforce symmetric aG(y,z)                                                //     // enforce symmetric aG(y,z)
                                                                                    //     aG.y.z = aG.z.y = (aG.y.z + aG.z.y) * 0.5F;
        // Rappel: M.getValue(i,j) = M[i][j]
        moy := (aG[2, 3] + aG[3, 2]) * 0.50;
        aG[2, 3] := moy;
        aG[3, 2] := moy;
        // get new bG & bM
        bG := SubstractVecteurs(avGx, MultMat3x3ByVector(aG, avG));                 //     bG = avGx - (aG * avG);
        bM := SubstractVecteurs(avMx, MultMat3x3ByVector(aM, avM));                 //     bM = avMx - (aM * avM);
        //-----------
        NbIter += 1;                                                                //     it++;
        EWE := max(MaxDiffMatrix(aG, aG0), MaxDiffMatrix(aM, aM0));
        AfficherMessage(Format('EWE = %.8f', [EWE]));
        if ((NbIter > MAX_IT) or (EWE < EPS)) then break;
      end;                                                                          // } while (it < MAX_IT && Math.max(MaxDiffMatrix(aG, aG0), MaxDiffMatrix(aM, aM0)) > EPS);
      //*** fin boucle principale
      CheckOverflow(aG, bG);                                                        // CheckOverflow(aG, bG);
      CheckOverflow(aM, bM);                                                        // CheckOverflow(aM, bM);
      delta := 0;                                                                   // double delta = 0;
      for i := 0 to Nb -1 do                                                        // for (int i = 0; i < Nb; i++)
      begin                                                                         // {
        dg := SubstractVecteurs(gx[i], gr[i]);                                      //     TPoint3Df dg = SubstractVecteurs(fgx[i], fgr[i]);
        dm := SubstractVecteurs(mx[i], mr[i]);                                      //     TPoint3Df dm = SubstractVecteurs(fmx[i], fmr[i]);
        delta += produitScalaire(dg, dg) + produitScalaire(dm, dm);                 //     delta += produitScalaire(dg, dg) + produitScalaire(dm, dm);
      end;                                                                          // }
      delta := sqrt(delta / Nb) * 100;                                              // delta = Math.sqrt(delta / Nb) * 100;
      afficherMessage(format('%d itérations - Delta %.5f', [NbIter, delta]));       // afficherMessageFmt("%d itérations - Delta %.5f", it, delta); // delta = 0.28
      afficherMatrix3x3('aG', aG);
      afficherVecteur('bG', bG);
      afficherMatrix3x3('aM', aM);
      afficherVecteur('bM', bM);
      //*************
      fMatrix_aG  := aG;
      fMatrix_aM  := aM;
      fVecteur_bG := bG;
      fVecteur_bM := bM;
      fDelta      := delta;
      fNbIters    := NbIter;
    end;
     
     
    // contrôle de la calibration
    function TPilotageDistoX.CheckMethodeCalibration(): boolean;
    var
      A, B, C: TMatrix3x3;
      T1, T2 : Boolean;
      //U, V, W: TPoint3Df;
      O: TMatrix3x3;
    begin
      (* Valeurs attendues pour le jeu de données de Beat HEEB heeb@speleo.ch
         n: 56  it: 55  delta: 0.28
     
               aG              bG
        1.770 -0.016  0.001    0.031
        0.015  1.761  0.003   -0.088
        0.001  0.003  1.769   -0.047
               aM              bM
        1.092 -0.019 -0.037   -0.059
        0.008  1.053  0.024   -0.028
        0.015 -0.029  1.041    0.023
     
                Cg
        29001   -256     17      745
          238  28854     56    -2105
           17     56  28989    -1120
                Cm
        17889   -317   -600    -1418
          132  17255    388     -660
          247   -477  17050      550
      //*)
      Result := False;
      try
        O := makeMatrix3x3Nulle;
        ViderListesMesuresGM;
        setJeuDeDonneesExemple;
        CalculerCalibration();
        afficherMessage(format('%d itérations - Delta %.5f', [GetNbIters, GetDelta]));       // afficherMessageFmt("%d itérations - Delta %.5f", it, delta); // delta = 0.28
        afficherMatrix3x3('aG', GetMatrix_aG);
        afficherVecteur('bG', GetVecteur_bG);
        afficherMatrix3x3('aM', GetMatrix_aM);
        afficherVecteur('bM', GetVecteur_bM);
        A := GetMatrix_aG;
        B := makeMatrix3x3ByValues(1.77010915, -0.01559756, 0.00105569,
                                   0.01452583,  1.76108466, 0.00341350,
                                   0.00104294,  0.00341350, 1.76935746
                                  );
        C := SubstractMatrix3x3(A, B);
        afficherMatrix3x3('O', O);
     
        afficherMatrix3x3('aG - aG0', C);
     
        T1 := IsSameMatrix(C, O, 10 * EPS);
        AfficherMessage(IIF(T1, 'Matrice aG identique à la matrice de référence aGo', 'Matrice aG non conforme'));
        A := GetMatrix_aM;
        B := makeMatrix3x3ByValues(1.09186956, -0.01935603, -0.03660849,
                                   0.00804544,  1.05315657,  0.02369314,
                                   0.01509844, -0.02908758,  1.04066124
                                  );
        C := SubstractMatrix3x3(A, B);
        afficherMatrix3x3('aM - aM0', C);
     
        T2 := IsSameMatrix(C, O, 10 * EPS);
        AfficherMessage(IIF(T2, 'Matrice aM identique à la matrice de référence aMo', 'Matrice aM non conforme'));
     
        result := (T1 and T2);
      except
      end;
    end;
     
    procedure TPilotageDistoX.ProcOnRXData(Sender: TObject);
    begin
      ; // AfficherMessage('OnRXData()');
    end;
    (*
    procedure TPilotageDistoX.ProcOnStatus(Sender: TObject; Reason: THookSerialReason; const Value: string);
    var
      WU: String;
    begin
      WU := ChooseString(Ord(Reason),
                        ['HR_SerialClose',
                        'HR_Connect',
                        'HR_CanRead',
                        'HR_CanWrite',
                        'HR_ReadCount',
                        'HR_WriteCount',
                        'HR_Wait'
                        ]);
     
      case (Reason) of
        HR_SerialClose:
          begin
            if (FDistoXMustBeReady) then
            begin
              AfficherMessage('*** DistoX déconnecté intempestivement - Tentative de redémarrage');
              OpenDistoXConnexion();
            end;
          end;
        HR_Connect:
          begin
            FDistoXSerialNumber    := -1;
            FDistoXVersionFirmware := -1;
            FDistoXVersionHardware := -1;
            AfficherMessage(Format('OnStatus: %s - %s', [WU, Value]));
            if (assigned(FProcNotifyDistoXConnected)) then FProcNotifyDistoXConnected;
            AfficherMessage(Format('DistoX: %d - Firmware: %d - Hardware: %d', [
                                  ExtractNumSerieFromDistoX(),
                                  ExtractVersionFirmWareFromDistoX(),
                                  ExtractVersionHardwareFromDistoX()]));
     
          end;
        HR_CanRead:
          begin
            ;//pass;
          end;
        HR_CanWrite: ;
        HR_ReadCount: ;
        HR_WriteCount: ;
        HR_Wait: ;
      end;
     
     
    end;
    //*)
     
     
    end.

  2. #2
    Expert éminent
    Avatar de jurassic pork
    Homme Profil pro
    Bidouilleur
    Inscrit en
    Décembre 2008
    Messages
    3 947
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Bidouilleur
    Secteur : Industrie

    Informations forums :
    Inscription : Décembre 2008
    Messages : 3 947
    Points : 9 275
    Points
    9 275
    Par défaut
    hello,
    houla ! il ne faut pas utiliser un timer pour lire les informations reçues par le port série. Il faut utiliser l'événement de réception de data qui tourne dans un thread. Voir l'exemple sertest livré avec TLazserial.
    Ami calmant, Phipic
    Jurassic computer : Sinclair ZX81 - Zilog Z80A à 3,25 MHz - RAM 1 Ko - ROM 8 Ko

  3. #3
    Membre confirmé

    Homme Profil pro
    Développeur informatique
    Inscrit en
    Novembre 2013
    Messages
    342
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Gironde (Aquitaine)

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : Administration - Collectivité locale

    Informations forums :
    Inscription : Novembre 2013
    Messages : 342
    Points : 536
    Points
    536
    Billets dans le blog
    2
    Par défaut
    Citation Envoyé par jurassic pork Voir le message
    hello,
    houla ! il ne faut pas utiliser un timer pour lire les informations reçues par le port série. Il faut utiliser l'événement de réception de data qui tourne dans un thread. Voir l'exemple sertest livré avec TLazserial.
    Ami calmant, Phipic
    Bjr,

    Cà marche

    Autre question: Comment notifier une déconnexion ou un chgt de statut (utilisation du TLazserial.OnStatus ?)

    cdlt

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Réponses: 0
    Dernier message: 16/07/2013, 15h12
  2. [2.x] Comment utiliser un bundle après son installation ?
    Par lionceau dans le forum Symfony
    Réponses: 5
    Dernier message: 11/05/2013, 16h43
  3. Réponses: 2
    Dernier message: 20/08/2008, 15h45
  4. [MySQL] Après une requête globale comment utiliser deux champs
    Par gb76 dans le forum PHP & Base de données
    Réponses: 4
    Dernier message: 07/06/2007, 13h46
  5. Réponses: 6
    Dernier message: 04/10/2006, 18h40

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo