-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathf3f_21.lua
1647 lines (1321 loc) · 60.4 KB
/
f3f_21.lua
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
-- ###############################################################################################
-- # F3F Tool for JETI DC/DS transmitters
-- #
-- # Copyright (c) 2023, 2024 Frank Schreiber
-- #
-- # This program is free software: you can redistribute it and/or modify
-- # it under the terms of the GNU General Public License as published by
-- # the Free Software Foundation, either version 3 of the License, or
-- # (at your option) any later version.
-- #
-- # This program is distributed in the hope that it will be useful,
-- # but WITHOUT ANY WARRANTY; without even the implied warranty of
-- # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- # GNU General Public License for more details.
-- #
-- # You should have received a copy of the GNU General Public License
-- # along with this program. If not, see <http://www.gnu.org/licenses/>.
-- #
-- ###############################################################################################
-- ###############################################################################################
-- # General approach
-- #
-- # For course setup 3 points on the course (or A-Line in case of F3B) are scanned by gps.
-- # One point is defined as starting point, the others are used to determine the
-- # course bearing to north.
-- #
-- # During the flight the distance between ths starting point and the current
-- # GPS position of the model is permanently calculated. Also based on this position
-- # the angle between the course and the flight position is determined.
-- # In order to calculate the course rectangle, this angle is used to shorten the
-- # distance by multiplication with it's cosinus, so the resulting value represents
-- # the distance flown directly in course direction.
-- # When this distance meets half of the course length (f3f: 50m) the model hits the
-- # turn line anywhere.
-- #
-- # In order to handle gps- and telemetry latency a speed-related compensation is done.
-- # Depending on the current speed and flight direction a offset is calculated and added
-- # to the flight distance, so the turn signal will be triggered earlier.
-- # The setting for the amount of compensation was determined empirically, so there is no
-- # theoretical approach for this value. Currently the compensation is simply linear to
-- # the speed.
-- #
-- # To realize this approach for the first course entry it must be turned over, so the
-- # flight distance is shortened to achieve a earlier signal. So there are two offsets
-- # calculated, one for the competition run and one for the first fly in. To give the model
-- # always a defined inside/outside status the fly-in offset is also used for the first fly-out.
-- # Because this offset works in the opposite direction it increases the distance to the
-- # fly out line (instead of decreasing, how it should be for fly-out), so the fly-out may
-- # appear 10m or 20m behind the real fly out line, depending on the speed.
-- # This is kind of a messy effect, but necessary to allow a precise detection of the fly in.
-- #
-- ###############################################################################################
-- ###############################################################################################
-- # Further notices:
-- #
-- # Jeti-Gen1 Support
-- # This program version is not suitable for Jeti Gen1-transmitters (with monochrome diaplay)
-- # For F3F / F3B training with an old transmitter you can use Version 1.x of this software.
-- #
-- # ---------------------------------------------------------------------------------------------
-- # F3B-Mode
-- # In F3B-Mode things are almost handled the same, position and angles are calculated
-- # related to the middle of the course. For convience the course-setup can be done
-- # along the A-Lane and the center point is calculated automatically.
-- #
-- # ---------------------------------------------------------------------------------------------
-- # External course modification
-- # There are some variables provided to support changing a course from an external app
-- # (maybe a course database). A corresponding database app is still experimental and
-- # not published.
-- #
-- ###############################################################################################
local appName = "F3F Tool"
local appVersion = "2.1"
local dataDirRel = "f3fTool-21" -- data dir (relative path)
local dataDir = "Apps/" .. dataDirRel -- data dir (abs. path)
-- ===============================================================================================
-- ===============================================================================================
-- ========== Global Variables ==========
-- ===============================================================================================
-- ===============================================================================================
-- global indicator for external course modification, allows to alter the course by an external tool
f3fTool_extCourseChange = false
local globalVar = {
direction= { UNDEF=0, LEFT=1, RIGHT=2 },
errorStatus = 0, -- error status: 0: ok
resource, -- multi language support (only audio)
lng -- language (de/en)
}
local errorTable = {
{"Sensors", "not", "configured"}, -- 1
{"Sensors", "not", "active"}, -- 2
{"Speedsensor", "not", "active"}, -- 3
{"Slope", "not", "configured"}, -- 4
{"waiting", "for", "GPS-ready"}, -- 5
{"F3F-Tool V. " .. appVersion , "", "not for Gen1 TX"}, -- 6
{"No", "Startpoint", "defined"} -- 7
}
-- Object pointer
local f3fRun = nil
local gpsSensor = nil
local basicCfg = nil
local transmitter = nil
local slope = nil
local slopeManager = nil
local display = nil
-- ===============================================================================================
-- ===============================================================================================
-- ========== Helper functions ==========
-- ===============================================================================================
-- ===============================================================================================
local function handleError ( errMsg )
print ( "ERROR: " .. errMsg )
system.playBeep (2, 500, 500)
end
--------------------------------------------------------------------------------------------
local function setLanguage()
globalVar.lng = system.getLocale();
local file = io.readall(dataDir .. "/audio-" ..globalVar.lng.. ".jsn")
if (not file) then
print ("language: '" .. globalVar.lng .. "' not supported")
globalVar.lng = 'en'
file = io.readall(dataDir .. "/audio-" ..globalVar.lng.. ".jsn")
end
if( file ) then
globalVar.resource = json.decode(file)
else
handleError ("audio config file not found")
end
end
--------------------------------------------------------------------------------------------
local function writeToFile (dir, file, data, append)
if ( dir ~= "" ) then dir = dir.."/" end
local fSpec = dir..file
local mode
if (append) then mode = "a" else mode = "w" end
local f = io.open ( fSpec, mode )
if ( not f ) then
io.mkdir (dir)
f = io.open ( fSpec, mode )
if ( not f) then
handleError ("error writing file: " .. fSpec)
end
end
if ( f ) then
io.write(f, data, "\n")
io.close ( f )
end
end
-- ===============================================================================================
-- ===============================================================================================
-- ========== Object: f3fRun ==========
-- ========== contains the necessary logic for the run ==========
-- ===============================================================================================
-- ===============================================================================================
f3fRun = {
status = { INIT=1, ON_HOLD=2, STARTPHASE=3, TIMEOUT=4, F3F_RUN=5 },
curPosition = nil, -- current position of model
curDist = nil, -- current distance from home position
curBearing = nil, -- current angle from slope
curDir = nil, -- current position on left/right side from home
nextTurnDir = nil, -- side of expected next turn
curSpeed = nil, -- current speed (given from sensor)
curHeading = nil, -- current heading (flight direction)
absCosHeading = nil, -- cosinus heading (abs: always positive)
-- for calculation of heading and smoothening of cos value
lastLat = nil, -- last position
lastLon = nil,
prevCos_1 = nil, -- last cosinus values
prevCos_2 = nil,
-- 'offsets' and 'inside-flags' for launch phase and f3f run.
-- the values are always calculated independently from the current
-- f3f-status. So we know where we are if a status change occurs
-- (from launch phase to f3f run or in case of reset from f3f run to launch phase)
-- the values can differ, because the considered offsets work in opposite directions.
launchPhaseData = { offset=0, insideFlag=0 },
f3fRunData = { offset=0, insideFlag=0 },
-- other stuff
curStatus = nil,
rounds = 0,
launchTime = 0, -- time of launch, 30 seconds started
countdownTime = 0, -- countdown from launch (F3F) or tow hook release (F3B) to fly in
remainingCountdown = 0, -- remaining countdown for start time
halfDistance = 0, -- half length of the course, depending on f3f / f3b
f3fStartTime = 0, -- start time of f3f-run
flightTime = 0,
timerStartSpeed = -1, -- timer for speed-measuring 1,5 sec. after start of f3f-run
}
function f3fRun:isStatus ( status ) return self.curStatus == status end
--------------------------------------------------------------------------------------------
function f3fRun:init ()
-- initial status
self.curStatus = self.status.INIT
self.curDir = globalVar.direction.UNDEF
self.nextTurnDir = globalVar.direction.UNDEF
if slope.mode == 2 then -- F3B
self.halfDistance = basicCfg.f3bDistance / 2
if ( basicCfg.f3bMode == 1 ) then -- speed
self.countdownTime = 60
elseif ( basicCfg.f3bMode == 2 ) then -- distance
self.countdownTime = 0
end
else -- F3F
self.countdownTime = 30
self.halfDistance = basicCfg.f3fDistance / 2
end
end
--------------------------------------------------------------------------------------------
function f3fRun:setNextTurnDir ()
-- set side of next turn
if ( self.curDir == globalVar.direction.LEFT ) then
self.nextTurnDir = globalVar.direction.RIGHT
elseif ( f3fRun.curDir == globalVar.direction.RIGHT ) then
self.nextTurnDir = globalVar.direction.LEFT
end
end
--------------------------------------------------------------------------------------------
-- launch: start button was pressed
function f3fRun:launch ()
-- slope not defined? ?
if ( globalVar.errorStatus == 4 ) then
-- cancel - beep
system.playBeep (2, 1000, 200)
return
end
-- check, if sensors are active
globalVar.errorStatus = 0
gpsSensor:getCurPosition ()
if ( globalVar.errorStatus ~= 0 ) then
-- cancel - beep
system.playBeep (2, 1000, 200)
return
end
-- start launch phase
self.curStatus = self.status.STARTPHASE
self.rounds = 0
self.launchTime = system.getTimeCounter()
self.remainingCountdown = self.countdownTime
transmitter:playAudioFile ( globalVar.resource.audioStart, AUDIO_IMMEDIATE )
-- in F3F and F3B-Speed mode announce countdown time
if ((slope.mode ~= 2) or (basicCfg.f3bMode ~= 2)) then
system.playNumber (self.remainingCountdown, 0)
transmitter:playAudioFile ( globalVar.resource.audioSeconds, AUDIO_QUEUE )
end
end
--------------------------------------------------------------------------------------------
-- start run: A-Base was passed from outside course or timeout occurred
function f3fRun:startRun ( timeout )
-- timeout - late entry ocurred
if (timeout) then
self.curStatus = self.status.TIMEOUT
else
-- regular f3f-start
self.curStatus = self.status.F3F_RUN
end
self.f3fStartTime = system.getTimeCounter()
transmitter:playAudioFile ( globalVar.resource.audioCourse, AUDIO_QUEUE )
-- skip apeed measurement in F3B-Distance mode
if ((slope.mode == 2) and (basicCfg.f3bMode == 2)) then return end
-- start timer for speed measurement after 1,5 sec.
if ( basicCfg.speedAnnouncement and self.curSpeed and self:isStatus (self.status.F3F_RUN) ) then
self.timerStartSpeed = system.getTimeCounter()
end
end
--------------------------------------------------------------------------------------------
-- distance done: A-Base or B-Base was passed from inside course
function f3fRun:distanceDone ()
-- if we are not in a valid f3f-run - just beep to practise
if ( not f3fRun:isStatus ( self.status.F3F_RUN )) then
system.playBeep (0, 700, 300)
end
-- in F3B-Distance mode: always count legs and beep
if ((slope.mode == 2) and (basicCfg.f3bMode == 2)) then
self.rounds = self.rounds+1
self:setNextTurnDir ()
system.playBeep (0, 700, 300)
return
end
local maxRounds
if ( slope.mode == 1 ) then
maxRounds = 10 -- F3F mode
elseif ( slope.mode == 2 ) then
maxRounds = 4 -- F3B mode
end
-- are we in f3f-run ?
if ( self:isStatus (self.status.F3F_RUN) ) then
-- one more leg done
self.rounds = self.rounds+1
-- perform the appropriate beep
if (self.rounds <= maxRounds-2 ) then
system.playBeep (0, 700, 300)
elseif (self.rounds == maxRounds-1 ) then
system.playBeep (1, 700, 300)
else
system.playBeep (2, 850, 200)
end
-- from leg 8 make an announcement
if ( self.rounds > maxRounds-3 and self.rounds < maxRounds ) then
system.playNumber (self.rounds, 0)
end
-- all legs done - get flight time, change status
if ( self.rounds >= maxRounds ) then
local endTime = system.getTimeCounter()
self.flightTime = endTime-self.f3fStartTime
transmitter:playAudioFile ( globalVar.resource.audioTime, AUDIO_QUEUE )
system.playNumber (self.flightTime / 1000, 1)
transmitter:playAudioFile ( globalVar.resource.audioSeconds, AUDIO_QUEUE )
-- log result
if ( basicCfg.logResults ) then
local mode
if (slope.mode == 1) then mode = "F3F" else mode = "F3B" end
local dt = system.getDateTime()
local modelName = system.getProperty ("Model")
local resultFile = string.format( "%d-%02d-%02d.txt", dt.year, dt.mon, dt.day )
local text = string.format( "%d:%02d %s-Time: %.2f (%s)", dt.hour, dt.min, mode, self.flightTime / 1000, modelName)
writeToFile (dataDir.."/results", resultFile, text, true )
end
-- status change
self.curStatus = self.status.ON_HOLD
end
end
-- set side of next turn
self:setNextTurnDir ()
end
--------------------------------------------------------------------------------------------
-- calc remaining time for launch phase and give some announcements
function f3fRun:countdown ()
-- skip countdown for F3B-Distance mode
if ((slope.mode == 2) and (basicCfg.f3bMode == 2)) then
return
end
local prevValue = self.remainingCountdown
local curTime = system.getTimeCounter()
self.remainingCountdown = math.floor (self.countdownTime - (curTime-self.launchTime)/1000)
if (self.remainingCountdown ~= prevValue) then
-- Announcement
if ( (self.remainingCountdown >= 30 and self.remainingCountdown % 10 == 0) or
(self.remainingCountdown < 30 and self.remainingCountdown % 5 == 0) or
(self.remainingCountdown <= 10) ) then
system.playNumber (self.remainingCountdown, 0)
end
end
-- Timeout: start F3F run / cancel F3B run
if ( self.remainingCountdown == 0 ) then
if ( slope.mode == 1 ) then -- F3F
self:startRun ( true )
elseif ( slope.mode == 2 ) then -- F3B
system.playBeep (2, 500, 400)
self:init ()
end
end
end
--------------------------------------------------------------------------------------------
-- update current position, distance and bearing data
function f3fRun:updatePositionData ( point )
if ( not point ) then return end
self.curPosition = point
------ calc current distance
if (slope.gpsHome) then
self.curDist = gps.getDistance (slope.gpsHome, self.curPosition)
end
------ calc current flight angle to slope
if ( slope.gpsHome and slope.bearing ) then
-- current flight angle from north
self.curBearing = gps.getBearing (slope.gpsHome, self.curPosition)
-- current flight angle to slope
self.curBearing = slope.bearing - self.curBearing
if (self.curBearing < 0) then
self.curBearing = self.curBearing + 360
end
-- determine, on which side of home position the model is located
-- curBearing always meant clockwise from flight line to slope
if (self.curBearing <= 90 or self.curBearing > 270) then -- 0-90 deg, 270-360 deg
self.curDir = globalVar.direction.RIGHT
else
self.curDir = globalVar.direction.LEFT -- 90-270 deg
end
end
end
--------------------------------------------------------------------------------------------
-- update current speed from sensor, calculate optimization offsets
-- the whole magic of GPS and latency optimization
function f3fRun:updateSpeedAndOptimizationData ( speed, heading )
-- Speed
self.curSpeed = speed
if ( self.curSpeed ) then
-- offset determination
-- generally speed/6 is taken as 100% offset (max), what means 25m at speed of 150 km/h.
-- this value can be reduced by a configurable speed faktor, which is taken as a percentage value (/100)
self.f3fRunData.offset = self.curSpeed/6 * (basicCfg.speedFaktorF3F/100)
-- *(-1): in launch phase the offset works in the opposite direction to optimize the first fly in
-- also add a static offset, this brought better results in flying tests, can't explain why
self.launchPhaseData.offset = (-1) * ((self.curSpeed/6 * (basicCfg.speedFaktorLaunchPhase/100)) + basicCfg.statOffsetLaunchPhase)
end
-- Heading
local absHeading = heading -- heading to north
if ( absHeading ) then
-- heading related to slope edge
self.curHeading = slope.bearing - absHeading
if (self.curHeading < 0) then
self.curHeading = self.curHeading + 360
end
-- store cosinus for later offset determination
self.absCosHeading = math.abs (math.cos (math.rad ( self.curHeading )))
-- if heading is not provided from sensor we calculate it from position data
else
local lat, lon = gps.getValue (self.curPosition)
-- first occurance
if ( not (self.lastLat and self.lastLon) ) then
self.lastLat = lat
self.lastLon = lon
-- check if new position
-- LAT and LON must have changed to avoid jump between 0, 90, 180, 270 deg.
elseif ( lat ~= self.lastLat and lon ~= self.lastLon ) then
-- calc heading to north from last to current position
absHeading = gps.getBearing (gps.newPoint (self.lastLat, self.lastLon), self.curPosition)
-- heading related to slope edge
self.curHeading = slope.bearing - absHeading
if ( self.curHeading < 0 ) then
self.curHeading = self.curHeading + 360
end
-- get cosinus and smoothen curve
-- it is easier to smoothen than the original heading curve
-- because cosinus has no 0/360 deg. jumps
local cosHead = math.abs (math.cos (math.rad ( self.curHeading )))
-- smoothen
if ( self.prevCos_1 and self.prevCos_2) then
self.absCosHeading = (4*cosHead + 2*self.prevCos_1 + self.prevCos_2) / 7
end
self.prevCos_2 = self.prevCos_1
self.prevCos_1 = cosHead
-- save for next use
self.lastLat = lat
self.lastLon = lon
end
end
end
--------------------------------------------------------------------------------------------
-- returns true if position is in the half the flight direction is:
-- - to right while we should hit the left line next (heading differs more than 100 deg. from 180°)
-- - to left while we should hit the right line next (heading differs more than 100 deg. from 360°)
-- - AND we are already in the half of the course where the next line hit should occur
function f3fRun:flyingAwayFromLine ()
-- not in the right half facing the line?
if ( self.curDir ~= self.nextTurnDir ) then return false end
-- flying to right while left line is next
if (( self.nextTurnDir == globalVar.direction.LEFT ) and
(( math.abs ( self.curHeading - 360 ) < 80 ) or (self.curHeading < 80) )) then
return true -- heading > 280° or < 80°
-- flying to left while right line is next
elseif (( self.nextTurnDir == globalVar.direction.RIGHT ) and
( math.abs ( self.curHeading - 180 ) < 80 )) then -- heading > 100 and < 260
return true
end
return false
end
--------------------------------------------------------------------------------------------
-- check, if a fly out occurred, consider the calculated offsets and the turn line calculation
-- based on the cosinus
function f3fRun:checkFlyOut ( trackData )
if ( trackData.insideFlag ) then
local dist = self.curDist * math.abs ( math.cos (math.rad ( self.curBearing )))
local offset = 0
-- use optimization offset only if we are flying towards the line. Otherwise the
-- increasing cosinus could lead to a wrong beep on the 'way back'
if ( not self:flyingAwayFromLine () ) then
offset = trackData.offset
if ( self.absCosHeading ) then
offset = offset * self.absCosHeading
end
end
if ( dist + offset > self.halfDistance) then
trackData.insideFlag = false
return true
end
end
return false
end
--------------------------------------------------------------------------------------------
-- check, if a fly in occurred, consider the calculated offsets and the turn line calculation
-- based on the cosinus
function f3fRun:checkFlyIn ( trackData )
if ( not trackData.insideFlag ) then
local dist = self.curDist * math.abs ( math.cos (math.rad ( self.curBearing )))
local offset = trackData.offset
if ( self.absCosHeading ) then
offset = offset * self.absCosHeading
end
if ( dist + offset < self.halfDistance) then
trackData.insideFlag = true
return true
end
end
return false
end
--------------------------------------------------------------------------------------------
-- check, if second turn in a f3b-run was done without reaching the turn distance
-- this is allowed, because the pilot standing at the a-base can fly this turn very precise
-- by eye.
-- the turn is recognized if the heading differs 100° from the expected flight direction to course
-- (to left: 180° / to right: 0°)
function f3fRun:checkF3bSecondTurnByHeading ()
if ( (slope.mode == 2) and (basicCfg.f3bMode == 1) and -- are we in f3b speed mode
self:isStatus ( self.status.F3F_RUN ) and -- are we in a competition run
(self.rounds == 1) ) then -- second turn expected
-- trigger turn if flight dierection is away from next line to hit
if ( self:flyingAwayFromLine () ) then
system.playBeep (1, 700, 200) -- double beep
self:setNextTurnDir ()
self.rounds = self.rounds+1
end
end
end
-- ===============================================================================================
-- ===============================================================================================
-- ========== Object: gpsSensor ==========
-- ===============================================================================================
-- ===============================================================================================
gpsSensor = {
lat = {desc="latSensor", id=nil, param=nil},
lon = {desc="lonSensor", id=nil, param=nil},
speed = {desc="speedSensor", id=nil, param=nil},
heading = {desc="headingSensor", id=nil, param=nil}
}
--------------------------------------------------------------------------------------------
function gpsSensor:init ()
self.lat.id = system.pLoad ( self.lat.desc )
self.lat.param = system.pLoad ( self.lat.desc .. "Param" )
self.lon.id = system.pLoad ( self.lon.desc )
self.lon.param = system.pLoad ( self.lon.desc .. "Param" )
self.speed.id = system.pLoad ( self.speed.desc )
self.speed.param = system.pLoad ( self.speed.desc .. "Param" )
self.heading.id = system.pLoad ( self.heading.desc )
self.heading.param = system.pLoad ( self.heading.desc .. "Param" )
end
--------------------------------------------------------------------------------------------
function gpsSensor:setSensorValue (sensorType, sensorValue)
-- empty sensor
if ( sensorValue.id == -1 and sensorValue.param == -1 ) then
sensorType.id = nil
sensorType.param = nil
-- sensor configured
else
sensorType.id = sensorValue.id
sensorType.param = sensorValue.param
end
-- save in model json
system.pSave( sensorType.desc, sensorValue.id )
system.pSave( sensorType.desc .. "Param", sensorValue.param)
end
--------------------------------------------------------------------------------------------
function gpsSensor:getCurPosition ()
local curPosition
if ( self.lat.id and self.lat.param and self.lon.param ) then
curPosition = gps.getPosition ( self.lat.id, self.lat.param, self.lon.param )
else
-- GPS not configured
globalVar.errorStatus = 1
return nil
end
-- check if GPS is active
if ( not curPosition ) then
globalVar.errorStatus = 2
return nil
end
-- check if GPS is ready
local lat, lon = gps.getValue ( curPosition )
if ( lat == 0 and lon == 0 ) then
globalVar.errorStatus = 5
return nil
end
return curPosition
end
--------------------------------------------------------------------------------------------
function gpsSensor:getCurSpeed ()
local sensorData
local sensorvalue = 0
if ( self.speed.id and self.speed.param ) then
sensorData = system.getSensorByID ( self.speed.id, self.speed.param )
end
if(sensorData and sensorData.valid) then
sensorvalue = sensorData.value
-- we need km/h
if ( sensorData.unit == "m/s" ) then
sensorvalue = sensorvalue * 3.6
end
return sensorvalue
else
globalVar.errorStatus = 3
return 0
end
end
--------------------------------------------------------------------------------------------
function gpsSensor:getCurHeading ()
local sensorData
local sensorvalue = 0
if ( self.heading.id and self.heading.param ) then
sensorData = system.getSensorByID ( self.heading.id, self.heading.param )
end
if(sensorData and sensorData.valid) then
sensorvalue = sensorData.value
return sensorvalue
else
return nil
end
end
--------------------------------------------------------------------------------------------
function gpsSensor:isValidPosition ( pos )
if ( not pos ) then return false end
local lat, lon = gps.getValue ( pos )
return ( not (lat == 0 and lon == 0 ) )
end
-- ===============================================================================================
-- ===============================================================================================
-- ========== Object: basicCfg ==========
-- ===============================================================================================
-- ===============================================================================================
basicCfg = {
switch, -- multifunction push button
f3fDistance, -- distance of f3f course (default: 100m)
f3bDistance, -- distance of f3b course (default: 150m)
ctrlCenterShift, -- Control: adjust center to left / right
f3bMode, -- F3B: Speed:1 / Distance: 2
formModuleName = dataDirRel .. "/module/basicCfgForm", -- load basicCfgform module only when
formModule = nil, -- needed during configuration
-- values for adjustment of latency
-- currently not configured, but can be put on potis for adjustment
speedFaktorF3F = 58, -- faktor for speed effect on offset during f3f run
speedFaktorLaunchPhase = 62, -- faktor for speed effect on offset during launch phase
statOffsetLaunchPhase = 6, -- static offset for launch phase
-- further settings
speedAnnouncement,
logResults
}
--------------------------------------------------------------------------------------------
function basicCfg:init ()
-- get configuration values from model json
self.switch = system.pLoad("switch")
self.f3fDistance = system.pLoad("f3fDistance", 100)
self.f3bDistance = system.pLoad("f3bDistance", 150)
self.ctrlCenterShift = system.pLoad("ctrlCenterShift")
self.f3bMode = system.pLoad("f3bMode", 1)
self.speedAnnouncement = (system.pLoad("speedAnnouncement", 1) == 1 ) -- default: true
self.logResults = (system.pLoad("logResults", 0) == 1 ) -- default: false
end
--------------------------------------------------------------------------------------------
function basicCfg:initForm(formID)
self.formModule = require ( self.formModuleName )
-- set needed objects and values
self.formModule.cfgData = self
self.formModule.gpsSensor = gpsSensor
self.formModule.dataDir = dataDir
self.formModule.handleErr = handleError
-- init form
self.formModule:initForm (formID)
end
function basicCfg:closeForm()
if ( self.formModule ) then self.formModule:closeForm () end
-- cleanup and reload f3fRun - Module
self.formModule = nil
package.loaded [ self.formModuleName ] = nil
collectgarbage("collect")
-- print("CloseCfg/GC Count after reload : " .. collectgarbage("count") .. " kB");
end
function basicCfg:toggleF3bMode()
if ( self.f3bMode == 1 ) then
self.f3bMode = 2
transmitter:playAudioFile (globalVar.resource.audioF3bDistance, AUDIO_QUEUE)
else
self.f3bMode = 1
transmitter:playAudioFile (globalVar.resource.audioF3bSpeed, AUDIO_QUEUE)
end
system.pSave( "f3bMode", self.f3bMode )
f3fRun:init ()
end
-- ===============================================================================================
-- ===============================================================================================
-- ========== Object: transmitter ==========
-- ===============================================================================================
-- ===============================================================================================
transmitter = {
-- state = { IDLE=0, ACTIV_1=1, RELEASED_1=2, ACTIV_2=3 }, -- needs too much memory :(
-- use values directly
-- variables for multi-button observation
switchState = 0,
timerStartSwitch, -- timer for detection of long- / double- / long click
-- variables for center shift observation
centerShiftState = 0, -- <=0: released / 1: first shift / 2: 1 ore more shifts trigged by timer
timerCenterShift, -- timer for holding center shift control
shiftDir = globalVar.direction.UNDEF,
shiftCount = 0 -- >0: shift right / <0: shift left
}
--------------------------------------------------------------------------------------------
-- observe multifunction button
-- return 1: single click / 2: double click / 3: long click
function transmitter:observeSwitch ()
local sVal
sVal = system.getInputsVal( basicCfg.switch)
if (not sVal) then return 0 end
local pressed = sVal and sVal>0
local released = sVal and sVal<=0
if (self.switchState == 0 and pressed) then -- status 0: idle
self.switchState = 1
self.timerStartSwitch = system.getTimeCounter() -- wait for long click
elseif (self.switchState == 1 and pressed) then -- status 1: first pressed
-- check timer: long click if expired
if ( (system.getTimeCounter() - self.timerStartSwitch) > 2000 ) then
self.switchState = 3
return 3 -- long click
end
elseif (self.switchState == 1 and released) then -- status 1: first pressed
self.switchState = 2
self.timerStartSwitch = system.getTimeCounter() -- wait for double click
elseif (self.switchState == 2 and released) then -- status 2: first released
-- check timer: single click if expired
if ( (system.getTimeCounter() - self.timerStartSwitch) > 250 ) then
self.switchState = 0
return 1 -- single click
end
elseif (self.switchState == 2 and pressed) then
self.switchState = 3
return 2 -- double click
elseif (self.switchState == 3 and released) then -- status 3: second pressed
self.switchState = 0
end
return 0
end
--------------------------------------------------------------------------------------------
function transmitter:incrShiftCount ( dir )
if ( dir == globalVar.direction.RIGHT ) then
self.shiftCount = self.shiftCount + 1
elseif ( dir == globalVar.direction.LEFT ) then
self.shiftCount = self.shiftCount - 1
end
end
--------------------------------------------------------------------------------------------
-- observe control for center adjustment
function transmitter:observeCenterShift ()
-- get control state
local sVal
sVal = system.getInputsVal( basicCfg.ctrlCenterShift)
if ( not sVal ) then return globalVar.direction.UNDEF end
-- state <0: right or left pressed from idle state ?
if ( self.centerShiftState <= 0 ) then
if ( sVal > 0.3 ) then
self.shiftDir = globalVar.direction.RIGHT -- adjust to right
self.centerShiftState = 1
elseif ( sVal < -0.3 ) then
self.shiftDir = globalVar.direction.LEFT -- adjust to left
self.centerShiftState = 1
end
if ( self.centerShiftState == 1 ) then
self.timerCenterShift = system.getTimeCounter()
self:incrShiftCount ( self.shiftDir )
return self.shiftDir
end
-- control released: start timer to wait some ms, migt be pressed again (State -1)
elseif ( sVal > -0.3 and sVal < 0.3 ) then
self.centerShiftState = -1
self.timerCenterShift = system.getTimeCounter()
self.shiftDir = globalVar.direction.UNDEF
end
-- control was released and timer expired
if ( self.centerShiftState == -1 and (system.getTimeCounter() - self.timerCenterShift) > 400 ) then
-- announce number of shifted meters
if ( self.shiftCount > 0 ) then
transmitter:playAudioFile (globalVar.resource.audioRight, AUDIO_QUEUE)
system.playNumber ( self.shiftCount, 0, "m")
elseif ( self.shiftCount < 0 ) then
transmitter:playAudioFile (globalVar.resource.audioLeft, AUDIO_QUEUE)
system.playNumber ( self.shiftCount*-1, 0, "m")
end
self.centerShiftState = 0
self.shiftCount = 0
end
-- control is held (left or right)
if ( self.centerShiftState == 1 and (system.getTimeCounter() - self.timerCenterShift) > 400 ) then
self.centerShiftState = 2
self.timerCenterShift = system.getTimeCounter()
self:incrShiftCount ( self.shiftDir )
return self.shiftDir
elseif (self.centerShiftState == 2 and (system.getTimeCounter() - self.timerCenterShift) > 150 ) then
self.timerCenterShift = system.getTimeCounter()
self:incrShiftCount ( self.shiftDir )
return self.shiftDir
end
return globalVar.direction.UNDEF
end
--------------------------------------------------------------------------------------------
-- play audio file
function transmitter:playAudioFile ( resourceString, playbackType )
-- input string may contain placeholder for data directory
local res = string.gsub (resourceString, "$dataDir", dataDirRel)
system.playFile ( res, playbackType )
end