-
-
Notifications
You must be signed in to change notification settings - Fork 77
/
Copy pathusbTrainer.py
3107 lines (2731 loc) · 158 KB
/
usbTrainer.py
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
#-------------------------------------------------------------------------------
# Version info
#-------------------------------------------------------------------------------
__version__ = "2021-03-16"
# 2021-03-16 @Meanhat's odd T1902 supported: 0547:2131
# 2021-02-11 added: -e homeTrainer --> MultiplyPower()
# removed: self.DynamicAdjust code (which was experimental code)
# 2021-02-11 Vortex HU: request mode switch whenever wrong mode detected
# increase keep-alive interval to 10s
# Vortex brake: handle alarm status (errors/warnings)
# 2021-01-12 @TotalReverse comment added on 128866
# Power calculation incorrect due to GearboxReduction
# 2021-01-11 Error-recovery improved on USB_Read
# --> USB_Read(), USB_Read_retry4x40() and _ReceiveFromTrainer_MotorBrake
# 2021-01-10 Digital gearbox changed to front/rear index
# GearboxReduction provided by caller
# Also applies in power mode, modifying TargetPower
# theoretically against ERG-mode idea, but (see #195) if
# you're done, then it's nice to be able to modify.
# The returned power remains the produced power.
# 2021-01-10 Motorbrake version message decomposition improved #201
# Informative messages on brake type
# 2021-01-05 Tacxtype Motorbrake added
# 2021-01-04 lib_programname used to get correct dirname
# 2020-12-30 Added: clsTacxAntTrainer, clsTacxAntBushidoTrainer,
# clsTacxAntGeniusTrainer, GeniusState, BushidoState
# (support for Tacx Genius and Tacx Bushido trainers)
# Fix formula for wind resistance (with tail wind)
# 2020-12-29 message < 40; error message extended (signal AND power)
# 2020-12-27 #173 message < 40 received; retry implemented
# 2020-12-21 #173 T1946 was not detected as motor brake.
# 2020-12-20 Constants used from constants.py
# 2020-12-10 Removed: -u uphill
# 2020-12-03 For Magnetic brake -r uses the resistance table [0...13]
# introduced: Resistance2PowerMB(), under investigation!!
# 2020-12-01 Speedscale set to 289.75
# 2020-12-01 -G option and Magnetic Brake formula's removed
# and marked "TO BE IMPLEMENTED"
# 2020-11-23 Motor Brake command implemented for NewUSB interface
# CalibrateSupported depends on motorbrake, not head unit
# -r TargetResistance = TargetPower implemented
# 2020-11-18 Calibration also supported for 1942 headunit
# 2020-11-10 Issue 135: React on button press only once corrected
# Function Power2Speed() added
# 2020-11-03 Issue 118: Adjust virtual flywheel according to virtual gearbox
# 2020-10-22 Removed: superfluous logging in _ReceiveFromTrainer()
# 2020-10-20 Changed: minimum resistance was limitted to the calibrate value
# which complicated life for low-FTP athletes.
# Therefore this lower limit is removed.
# 2020-10-20 Added: self.DynamicAdjust
# 2020-10-09 Added: -u uphill
# 2020-09-29 Short buffer <40 error recovery improved
# Typo's corrected (thanks RogerPleijers)
# 2020-06-16 Corrected: USB_read() must always return array of bytes
# 2020-06-12 Added: BikePowerProfile and SpeedAndCadenceSensor final
# 2020-06-11 Changed: if clsTacxNewUsbTrainer less than 40 bytes received, retry
# 2020-06-10 Changed: Speed and Cadence Sensor metrics (PedalEchoCount)
# 2020-06-09 Changed: VirtualSpeed in clsSimulatedTrainer corrected
# 2020-06-08 Changed: clsTacxAntVortexTrainer uses TargetResistance, even
# when expressed in Watts, so that also PowerFactor applies.
# Previously TargetPower was used directly, short-cutting
# this mechanism, only because Watts were needed.
# Now also Resistance is displayed, which usually equals
# TargetPower.
# 2020-05-27 Changed: SetGrade() limits Grade to -30...+30
# clsSimulatedTrainer improved
# 2020-05-24 Changed: logfile typo's
# 2020-05-20 Added: PedalEcho also simulated, for PedalStrokeAnalysis during
# simulation, so that screen shots can be made for documentation.
# 2020-05-19 Changed: exception handling when loading firmware (issue #89)
# 2020-05-18 Changed: Some clode cleanup in clsTacxAntVortexTrainer
# 2020-05-15 Changed: self.AntDevice initialized in clsTacxAntVortexTrainer
# 2020-05-15 Added: logging for SetPower() and SetGrade(),
# TargetPower2Resistance()
# 2020-05-14 Changed: Refresh() QuarterSecond added, mandatory fields
# clsTacxTrainer with __init__
# Added: HandleANTmessage + iVortex ANT handling done here
# Virtual gearbox: 0.1 ... 3.0. 0.1 should be light enough.
# 2020-05-13 Minor code changes
# Added: AddGrade(), SetRollingResistance(), SetWind()
# Implemented VirtualSpeedKmh to realize the virtual gearbox
# Flywheel changed as suggested by mattipee, totalreverse.
# Weight = self.UserAndBikeWeight in GradeMode
# totalreverse wiki updated 2020-01-04
# Grade2Power according Gribble
# 2020-05-11 usbTrainer refactored for the following reasons:
# - attributes are now stored in one place and not passed to
# functions and returned to callers; in the end it was
# unclear what values were changed where and by whome
# - separate Tacx-dependant code into their own classes
# - Enable further improvement on the Grade2Power
# algorithm in one separated location.
# - Grade2Power() replaces Grade2Resistance() and is therefore
# immediatly usable for i-Vortex
# Power2Resistance() is for USB-connected trainers only
# - Grade2Power() is brought back to the very basic, with a
# formula based on physics and no additions.
# Ready for testing and -perhaps- finetuning.
# - Introduction VirtualSpeedKmh (not yet finalized)
# 2020-05-07 pylint error free
# 2020-04-28 FortiusAntGui; only two constants imported (I do not want a link here with GUI)
# 2020-04-16 Write() replaced by Console() where needed
# 2020-04-15 Message changed "Connected to Tacx Trainer"
# 2020-04-12 Timeout-handling improved; Macintosh returns "timed out".
# 2020-04-07 SendToTrainer() also logs Mode-parameters
# 2020-03-29 ReceiveFromTrainer() returns Error="Not found"
# I'm finally rid of text in Speed causing errors!
# 2020-03-29 PowercurveFactor implemented to increment/decrement resistance
# 2020-03-29 .hex files in same folder as .py or .exe and correct path used
# 2020-03-23 Short received buffer for tt_FortiusSB extended to 64 bytes
# 2020-03-06 Resistance2Power and Power2Resistance
# implemented for iMagic, based upon Yegorvin's work.
# 2020-03-02 Speed = km/hr and only where required WheelSpeed is used.
# 2020-03-02 InitialiseTrainer() code moved into GetTrainer(); new interface
# only
# 2020-02-27 GoldenCheetah calculations for LegacyProtocol used
# 2020-02-26 CalibrateSupported() added
# For LegacyProtocol (iMagic) only modeResistance supported
# trainer_types corrected (ref TotalReverse)
# 2020-02-25 feedback from fritz-hh implemented
# 2020-02-25 added: idVendor_Tacx (I do not like constants in code)
# changed: firmware command to be executed to be confirmed (fxload...)
# struct-definition: 'sc.no_alignment + ' added
#
# 2020-02-24 added: trainer_types defined (tt_) and iMagic added
# LegacyProtocol added
# todo: firmware command to be executed to be provided
# ReceiveFromTrainer() and SendToTrainer() defined according TotalReverse
# BUT: note '# To be investigated' comments!
# This version will not work bu I expect can be used
# for interface testing and further development.
# 2020-01-22 Error handling in GetTrainer() added (similar to GetDongle())
# 2020-01-15 Grade2Resistance() option3 tested and OK
# 2020-01-10 Test done at 200W and dropping cadence (100, 90...30)
# resulting in explanation at Power2Resistance()
# 2020-01-08 Grade2Resistance() modified; test-version to be removed
# 2019-12-25 Target grade implemented; modes defined
#-------------------------------------------------------------------------------
import array
import lib_programname
from enum import Enum
import usb.core
import os
import random
import struct
import sys
import time
import antDongle as ant
from constants import mode_Power, mode_Grade
import debug
import logfile
import structConstants as sc
import FortiusAntCommand as cmd
import fxload
#-------------------------------------------------------------------------------
# Constants
#-------------------------------------------------------------------------------
hu1902 = 0x1902 # Old "solid green" iMagic headunit (with or without firmware)
hu1902_nfw = 0x2131 # @Meanhats headunit, without fw
hu1904 = 0x1904 # New "white green" iMagic headunit (firmware inside)
hu1932 = 0x1932 # New "white blue" Fortius headunit (firmware inside)
hu1942 = 0x1942 # Old "solid blue" Fortius (firmware inside)
hue6be_nfw = 0xe6be # Old "solid blue" Fortius (without firmware)
idVendor_Tacx = 0x3561
EnterButton = 1
DownButton = 2
UpButton = 4
CancelButton = 8
OKButton = 16 # Non-existant for USB-trainers, for Vortex only
modeStop = 0 # USB Tacx modes
modeResistance = 2
modeCalibrate = 3
modeMotorBrake = 10 # To distinguish from the previous real modes
#-------------------------------------------------------------------------------
# See https://github.com/totalreverse/ttyT1941/issues/20
#-------------------------------------------------------------------------------
USB_ControlCommand = 0x00010801
USB_ControlResponse = 0x00021303
USB_VersionRequest = 0x00000002
USB_VersionResponse = 0x00000c03
#-------------------------------------------------------------------------------
# path to firmware files; since 29-3-2020 in same folder as .py or .exe
#-------------------------------------------------------------------------------
if getattr(sys, 'frozen', False):
dirname = sys._MEIPASS # pylint: disable=maybe-no-member
else:
# dirname = os.path.dirname(__file__) # not always desired result!!
dirname = str(lib_programname.get_path_executed_script()) # type: pathlib.Path
dirname = os.path.dirname(dirname)
imagic_fw = os.path.join(dirname, 'tacximagic_1902_firmware.hex')
fortius_fw = os.path.join(dirname, 'tacxfortius_1942_firmware.hex')
#-------------------------------------------------------------------------------
# Class inheritance
# -----------------
# clsTacxTrainer = Base class with attributes
# -> clsSimulatedTrainer = Simulated trainer
# -> clsTacxAntVortexTrainer = Tacx Vortex
# -> clsTacxUsbTrainer
# -> clsTacxLegacyUsbTrainer = Tacx iMagic
# -> clsTacxNewUsbTrainer = Tacx Fortius
#-------------------------------------------------------------------------------
# Class functions (more info in the classes)
# ------------------------------------------
# class clsTacxTrainer()
# def GetTrainer(clv, AntDevice=None)
#
# def SetGearboxReduction() # Virtual Gearbox
#
# def SetPower(Power) # Store Power
# def AddPower(deltaPower)
# def MultiplyPower(factor)
# def SetGrade(Grade) # Store Grade
# def AddGrade(deltaGrade)
# def SetRollingResistance(RollingResistance)
# def SetWind()
# def SetUserConfiguration(UserWeight, ...) # Store User
#
# def Refresh(QuarterSecond, TacxMode) # Receive, Calculate, Send
# def SendToTrainer(QuarterSecond, TacxMode) # To be defined by child class
# def _ReceiveFromTrainer() # To be defined by child class
# def TargetPower2Resistance() # To be defined by child class
#
# def CalibrateSupported() # Return whether calibration supported
#
# def _Grade2Power() # Calculate required Power from Grade
# # This is where the magic is done!
#
# class clsSimulatedTrainer(clsTacxTrainer)
# def Refresh(QuarterSecond, Tacxmode) # Randomize data (does not receive/send!)
# # Completely replaces parent.Refresh()
#
# class clsTacxAntVortexTrainer(clsTacxTrainer)
# def Refresh(QuarterSecond, TacxMode)
# def SendToTrainer(QuarterSecond, TacxMode)
# def _ReceiveFromTrainer()
# def TargetPower2Resistance() # Conversion TargetPower -> TargetResistance
# def HandleANTmessage(message)
#
# class clsTacxUsbTrainer(clsTacxTrainer)
# def Wheel2Speed() # Convert Wheelspeed -> Kmh
# def Speed2Wheel(SpeedKmh) # Convert Kmh --> Wheelspeed
# def Refresh(QuarterSecond, TacxMode) # Add USB-special(s) to parent.Refresh()
# def USB_Read() # Read buffer from USB connected Tacx
# def SendToTrainer(tacxMode) # Send buffer to USB connected Tacx
#
# class clsTacxLegacyUsbTrainer(clsTacxUsbTrainer)
# def TargetPower2Resistance() # Legacy conversion TargetPower -> TargetResistance
# def CurrentResistance2Power() # Legacy conversion CurrentResistance -> CurrentPower
# def SendToTrainerUSBData(TacxMode, ...) # Compose legacy buffer to be sent
# def _ReceiveFromTrainer () # Read and parse legacy data from trainer
#
# class clsTacxNewUsbTrainer(clsTacxUsbTrainer)
# def TargetPower2Resistance() # New conversion TargetPower -> TargetResistance
# def CurrentResistance2Power() # New conversion CurrentResistance -> CurrentPower
# def SendToTrainerUSBData(TacxMode, ...) # Compose new buffer to be sent
# def _ReceiveFromTrainer () # Read and parse new data from trainer
#
#-------------------------------------------------------------------------------
# c l s T a c x T r a i n e r The parent for all trainers
#-------------------------------------------------------------------------------
class clsTacxTrainer():
UsbDevice = None # clsHeadUnitLegacy and clsHeadUnitNew only!
AntDevice = None # clsVortexTrainer only!
OK = False
Message = None
MotorBrake = False # Fortius motorbrake, supports calibration
# Target provided by CTP (Trainer Road, Zwift, Rouvy, ...)
# See Refresh() for dependencies
TargetMode = mode_Power # Start with power mode
TargetGrade = 0 # no grade
TargetPowerProvided = 100 # and 100Watts
TargetPower = 100 # and 100Watts
TargetResistance = 0 # calculated and input to trainer
# Information provided by CTP
BicycleWeight = 10
BicycleWheelDiameter = None
GearRatio = None
UserWeight = 75
UserAndBikeWeight = 75 + 10 # defined according the standard (data page 51)
RollingResistance = 0.004
WindResistance = 0.51 # 1.275 * 0.4 * 1.0
WindSpeed = 0
DraftingFactor = 1.0
# Information provided by _ReceiveFromTrainer()
Axis = 0 # int
Buttons = 0 # int
PreviousButtons = 0 # int Issue 135
Cadence = 0 # int
CurrentPower = 0 # int
CurrentResistance = 0 # int
HeartRate = 0 # int
PedalEcho = 0
PreviousPedalEcho = 0 # detection for PedalEcho=1
PedalEchoCount = 0 # count of PedalEcho=1 events
PedalEchoTime = time.time() # the time of the last PedalEcho event
SpeedKmh = 0 # round(,1)
VirtualSpeedKmh = 0 # see Grade_mode
CalculatedSpeedKmh = 0 # see #Power2Speed#
TargetResistanceFT = 0 # int Returned from trainer
WheelSpeed = 0 # int
# Other general variables
clv = None # Command line variables
GearboxReduction = 1 # 1.1 causes higher load
# 0.9 causes lower load
# Is manually set in Grademode
# USB devices only:
Headunit = 0 # The connected headunit in GetTrainer()
Calibrate = 0 # The value as established during calibration
SpeedScale = None # To be set in sub-class
ControlCommand = 0xffffffff # Last command sent
Header = 0xffffffff # Last command received
def __init__(self, clv, Message):
if debug.on(debug.Function):logfile.Write ("clsTacxTrainer.__init__()")
self.clv = clv
self.Message = Message
self.OK = False
#---------------------------------------------------------------------------
# G e t T r a i n e r
#---------------------------------------------------------------------------
# Function Create a TacxTrainer-child class, depending on the
# circumstances.
#
# Output object.OK and object.Message
#
# Returns Object of a TacxTrainer sub-class
#---------------------------------------------------------------------------
@staticmethod # pretent to be c++ factory function
def GetTrainer(clv, AntDevice=None):
if debug.on(debug.Function):logfile.Write ("clsTacxTrainer.GetTrainer()")
#-----------------------------------------------------------------------
# Usually I do not like multiple exit points, but here it's too handy
#-----------------------------------------------------------------------
if clv.SimulateTrainer: return clsSimulatedTrainer(clv)
if clv.Tacx_Vortex: return clsTacxAntVortexTrainer(clv, AntDevice)
if clv.Tacx_Genius: return clsTacxAntGeniusTrainer(clv, AntDevice)
if clv.Tacx_Bushido: return clsTacxAntBushidoTrainer(clv, AntDevice)
#-----------------------------------------------------------------------
# So we are going to initialize USB
# This may be either 'Legacy interface' or 'New interface'
#-----------------------------------------------------------------------
msg = "No Tacx trainer found"
hu = None # TrainerType
dev = False
LegacyProtocol = False
#-----------------------------------------------------------------------
# Find supported trainer (actually we talk to a headunit)
#-----------------------------------------------------------------------
for hu in [hu1902, hu1902_nfw, hu1904, hu1932, hu1942, hue6be_nfw]:
try:
if debug.on(debug.Function):
logfile.Write ("GetTrainer - Check for trainer %s" % (hex(hu)))
if hu == hu1902_nfw:
vendor = 0x0547 # Unknown special vendor
else:
vendor = idVendor_Tacx # For all others
dev = usb.core.find(idVendor=vendor, idProduct=hu) # find trainer USB device
if dev:
msg = "Connected to Tacx Trainer T" + hex(hu)[2:] # remove 0x from result
if debug.on(debug.Data2 | debug.Function):
logfile.Print (dev)
break
except Exception as e:
if debug.on(debug.Function):
logfile.Write ("GetTrainer - " + str(e))
if "AttributeError" in str(e):
msg = "GetTrainer - Could not find USB trainer: " + str(e)
elif "No backend" in str(e):
msg = "GetTrainer - No backend, check libusb: " + str(e)
else:
msg = "GetTrainer: " + str(e)
#-----------------------------------------------------------------------
# Initialise trainer (if found)
#-----------------------------------------------------------------------
if not dev:
hu = 0
dev = False
else: # found trainer
#-------------------------------------------------------------------
# iMagic As defined together with fritz-hh and jegorvin)
#-------------------------------------------------------------------
if hu in (hu1902, hu1902_nfw):
LegacyProtocol = True
logfile.Console ("Initialising head unit T1902 (iMagic), please wait 5 seconds")
logfile.Console (imagic_fw) # Hint what may be wrong if absent
try:
fxload.loadHexFirmware(dev, imagic_fw)
except Exception as e: # file not found?
msg = "GetTrainer: " + str(e)
dev = False
else:
time.sleep(5)
msg = "T1902 head unit initialised (iMagic)"
hu = hu1902 # so we do not need to think of hu1902_nfw elsewhere
#-------------------------------------------------------------------
# unintialised Fortius (as provided by antifier original code)
#-------------------------------------------------------------------
if hu == hue6be_nfw:
logfile.Console ("Initialising head unit T1942 (Fortius), please wait 5 seconds")
logfile.Console (fortius_fw) # Hint what may be wrong if absent
try:
fxload.loadHexFirmware(dev, fortius_fw)
except Exception as e: # file not found?
msg = "GetTrainer: " + str(e)
dev = False
else:
time.sleep(5)
dev = usb.core.find(idVendor=idVendor_Tacx, idProduct=hu1942)
if dev != None:
msg = "T1942 head unit initialised (Fortius)"
hu = hu1942
else:
msg = "GetTrainer - Unable to load firmware"
dev = False
#-------------------------------------------------------------------
# Set configuration
#-------------------------------------------------------------------
if dev != False:
dev.set_configuration()
if hu == hu1902:
dev.set_interface_altsetting(0, 1)
#-------------------------------------------------------------------
# InitialiseTrainer (will not read cadence until init str is sent)
#-------------------------------------------------------------------
if dev != False and LegacyProtocol == False:
data = struct.pack (sc.unsigned_int, USB_VersionRequest)
if debug.on(debug.Data2):
logfile.Write ("InitialiseTrainer data=%s (len=%s)" % (logfile.HexSpace(data), len(data)))
dev.write(0x02,data)
#-----------------------------------------------------------------------
# Done
#-----------------------------------------------------------------------
logfile.Console(msg)
if debug.on(debug.Function):
logfile.Write ("GetTrainer() returns, trainertype=" + hex(hu))
#-----------------------------------------------------------------------
# Return the correct Object
#-----------------------------------------------------------------------
if dev != False:
if LegacyProtocol:
return clsTacxLegacyUsbTrainer(clv, msg, hu, dev)
else:
return clsTacxNewUsbTrainer(clv, msg, hu, dev)
else:
return clsTacxTrainer (clv, msg) # where .OK = False
#---------------------------------------------------------------------------
# Functions from external to provide data
#---------------------------------------------------------------------------
def SetGearboxReduction(self, Reduction):
self.GearboxReduction = Reduction
def SetPower(self, Power):
if debug.on(debug.Function):logfile.Write ("SetPower(%s)" % Power)
self.TargetMode = mode_Power
self.TargetGrade = 0
self.TargetPowerProvided= Power
self.TargetPower = self.TargetPowerProvided * self.GearboxReduction
self.TargetResistance = 0 # .Refresh() must be called
def MultiplyPower(self, factor):
if factor < 1 and self.TargetPowerProvided <= 10:
pass # 10Watt is Minimum
else:
self.SetPower(self.TargetPowerProvided * factor)
def AddPower(self, deltaPower):
self.SetPower(self.TargetPowerProvided + deltaPower)
def SetGrade(self, Grade):
if debug.on(debug.Function): logfile.Write ("SetGrade(%s)" % Grade)
if Grade < -30 or Grade > 30: logfile.Console ("Grade limitted to range -30 ... 30")
if Grade > 30: Grade = 30
if Grade < -30: Grade = -30
self.TargetMode = mode_Grade
self.TargetGrade = Grade
self.TargetPower = 0 # .Refresh() must be called
self.TargetResistance = 0 # .Refresh() must be called
def AddGrade(self, deltaGrade):
self.SetGrade(self.TargetGrade + deltaGrade)
def SetRollingResistance(self, RollingResistance):
if debug.on(debug.Function):
logfile.Write ("SetRollingResistance(%s[def=0.004])" % RollingResistance)
self.RollingResistance = RollingResistance
def SetWind(self, WindResistance, WindSpeed, DraftingFactor):
if debug.on(debug.Function):
logfile.Write ("SetWind(%s[def=0.51], %s[def=0], %s[def=1])" %
(WindResistance, WindSpeed, DraftingFactor) )
self.WindResistance = WindResistance
self.WindSpeed = WindSpeed
self.DraftingFactor = DraftingFactor
def SetUserConfiguration(self, UserWeight, BicycleWeight, BicycleWheelDiameter, GearRatio):
self.BicycleWeight = BicycleWeight
self.BicycleWheelDiameter = BicycleWheelDiameter
self.GearRatio = GearRatio
self.UserWeight = UserWeight
self.UserAndBikeWeight = UserWeight + BicycleWeight
#---------------------------------------------------------------------------
# SendToTrainer() and ReceivedFromTrainer() to be defined by sub-class
#---------------------------------------------------------------------------
def SendToTrainer(self, QuarterSecond, TacxMode): # no return
pass
def _ReceiveFromTrainer(self): # No return
pass
def TargetPower2Resistance(self):
self.TargetResistance = 0 # child class must redefine
#---------------------------------------------------------------------------
# R e f r e s h
#---------------------------------------------------------------------------
# Input Class variables Target***
# QuarterSecond, indicates that 1/4 second since previous
# for ANTdevices only
# TacxMode, to pass to SendToTrainer()
#
# Function Refresh updates the actual values from the trainer
# Then does required calculations
# And finally instructs the trainer what to do
#
# It appears more logical to do calculations when inputs change
# but it's done here because some calculations depend on the
# wheelspeed, so must be redone after each _ReceiveFromTrainer()
#
# Output Class variables match with Target***
#---------------------------------------------------------------------------
def Refresh(self, QuarterSecond, TacxMode):
if debug.on(debug.Function):logfile.Write ( \
'clsTacxTrainer.Refresh(%s, %s)' % (QuarterSecond, TacxMode))
#-----------------------------------------------------------------------
# FIrst get data from the trainer
#-----------------------------------------------------------------------
self._ReceiveFromTrainer()
#-----------------------------------------------------------------------
# Make all variables consistent
#-----------------------------------------------------------------------
#-----------------------------------------------------------------------
# Issue 135
# Avoid multiple button press when polling faster than button released
#-----------------------------------------------------------------------
if self.PreviousButtons == 0:
# if self.Buttons: print('Button press %s' % self.Buttons)
# The button was NOT pressed the previous cycle
# Therefore the button is accepted (rising edge)
self.PreviousButtons = self.Buttons
else:
# if self.Buttons: print('Button press %s ignored' % self.Buttons)
# Remember the current state of Buttons, must become zero before
# a button press is accepted
self.PreviousButtons = self.Buttons
# Button was pressed previous cycle, so ignore now
self.Buttons = 0
#-----------------------------------------------------------------------
# PedalEcho for Speed and Cadence Sensor
#-----------------------------------------------------------------------
if self.PedalEcho == 1 and self.PreviousPedalEcho == 0:
self.PedalEchoCount += 1
self.PedalEchoTime = time.time()
self.PreviousPedalEcho = self.PedalEcho
#-----------------------------------------------------------------------
# Calculate Virtual speed applying the digital gearbox
# if DOWN has been pressed, we pretend to be riding slower than the
# trainer wheel rotates
# if UP has been pressed, we pretend to be faster than the trainer
#
# Note that Grade2Power() depends on the VirtualSpeed.
#-----------------------------------------------------------------------
# No negative value defined for ANT message Page25 (#)
# if self.CurrentPower < 0: self.CurrentPower = 0 # --> msgPage25_TrainerData
assert (self.TargetMode in (mode_Power, mode_Grade))
if self.TargetMode == mode_Grade:
self.VirtualSpeedKmh = self.SpeedKmh * self.GearboxReduction
self._Grade2Power() # Resulting in self.TargetPower
#-----------------------------------------------------------------------
# Apply GearboxReduction to provided TargetPower
# Then calculate resistance
#
# Modifying the VirtualSpeed would not affect the resistance, which is
# based upon TargetPower and WheelSpeed.
#-----------------------------------------------------------------------
if self.TargetMode == mode_Power:
self.VirtualSpeedKmh = self.SpeedKmh
self.TargetPower = self.TargetPowerProvided * self.GearboxReduction
#-----------------------------------------------------------------------
# For all modes: To be implemented by USB-trainers; pass for others
#-----------------------------------------------------------------------
self.TargetPower2Resistance()
#-----------------------------------------------------------------------
# Antifier's calibration; valid for USB devices only
# non-USB classes will set PowerFactor=1
#
# The idea is that Power2Resistance gives insufficient resistance
# and that the formula can be corrected with the PowerFactor.
# Therefore before Send:
# the TargetResistance is multiplied by factor
# and after Receive:
# the CurrentResistance and CurrentPower are divided by factor
# Just for antifier upwards compatibility; usage unknown.
#-----------------------------------------------------------------------
if self.clv.PowerFactor:
self.TargetResistance *= self.clv.PowerFactor # Will be sent
self.CurrentResistance /= self.clv.PowerFactor # Was just received
self.CurrentPower /= self.clv.PowerFactor # Was just received
# ----------------------------------------------------------------------
# Round after all these calculations
# ----------------------------------------------------------------------
self.TargetPower = int(self.TargetPower)
self.TargetResistance = int(self.TargetResistance)
self.CurrentResistance = int(self.CurrentResistance)
self.CurrentPower = int(self.CurrentPower)
self.SpeedKmh = round(self.SpeedKmh,1)
self.VirtualSpeedKmh = round(self.VirtualSpeedKmh,1)
#-----------------------------------------------------------------------
# Then send the results to the trainer again
#-----------------------------------------------------------------------
self.SendToTrainer(QuarterSecond, TacxMode)
#---------------------------------------------------------------------------
# C a l i b r a t e S u p p o r t e d
#---------------------------------------------------------------------------
# input self.tt
#
# function Return whether this trainer support calibration
#
# returns True/False
#---------------------------------------------------------------------------
def CalibrateSupported(self):
# if self.Headunit in (hu1932, hu1942): # And perhaps others as well
# return True
# else:
# return False
return self.MotorBrake
#---------------------------------------------------------------------------
# Convert G r a d e T o P o w e r | Grade = slope
#---------------------------------------------------------------------------
# TotalReverse:
# documents: LOAD ~= (slope (in %) - 0.4) * 650
# ttyT1941.py: SlopeScale = 2 * 5 * 130 = 1300
# commented = 13 * 5 * 10 * 5 = 3250
#
# TotalReverse, Issue #2:
# ANT+ describes a simple physical model:
# Total resistance [N] = Gravitational Resistance + Rolling Resistance + Wind Resistance
# Gravitational Resistance [N] = (Equipment Mass + User Mass) x Grade(%)/100 x 9.81
# With the assumption of a total weight of about 80 kg and without rolling and wind
# resistance together with the simple assumption
# Load = Force [N] * 137 (the result of a fitting in ergo mode) one get:
#
# Load = 137 * 80 * 9.81 * slope_in_percent / 100
#
# SlopeScale = 137 * 80 * 9.81 / 100 = 1075
#
# Tests:
# factor 650 causes Zwift to think we ride @ 20km/h where the wheel runs at 40km/hr
# factor 1300 to be tested
#
#---------------------------------------------------------------------------
# Refer to ANT msgUnpage51_TrackResistance()
# where zwift grade does not seem to match the definition
#---------------------------------------------------------------------------
# Input TargetGrade, UserAndBikeWeight, VirtualSpeedKmh
#
# Function Calculate what power must be produced, given the current
# grade, speed and weigth
#
# Output TargetPower
#---------------------------------------------------------------------------
def _Grade2Power(self): #Grade2Power#
if self.UserAndBikeWeight < 70:
self.UserAndBikeWeight = 75 + 10
self.__Grade2Power_Gribble()
if debug.on(debug.Function):
logfile.Write ("Grade2Power (TargetGrade=%4.1f%%, Speed=%4.1f, Weight=%3.0f, rR=%s, wR=%s, wS=%s, d=%s) = TargetPower=%3.0fW" % \
(self.TargetGrade, self.VirtualSpeedKmh, self.UserAndBikeWeight, \
self.RollingResistance, self.WindResistance, self.WindSpeed, self.DraftingFactor, \
self.TargetPower) )
#---------------------------------------------------------------------------
# www.gribble.org
#---------------------------------------------------------------------------
def __Grade2Power_Gribble(self):
#-----------------------------------------------------------------------
# Matthew updates according www.gribble.org
# See: https://www.gribble.org/cycling/power_v_speed.html
#-----------------------------------------------------------------------
c = self.RollingResistance # default=0.004
m = self.UserAndBikeWeight # default=75+10 kg
g = 9.81 # m/s2
v = self.VirtualSpeedKmh / 3.6 # m/s km/hr * 1000 / 3600
Proll = c * m * g * v # Watt
p_cdA = self.WindResistance # default=0.51
w = self.WindSpeed / 3.6 # default=0
d = self.DraftingFactor # default=1
# without abs a strong tailwind would result in a higher power
Pair = 0.5 * p_cdA * (v+w) * abs(v+w) * d * v # Watt
i = self.TargetGrade # Percentage 0...100
Pslope= i/100 * m * g * v # Watt
self.TargetPower = int(Proll + Pair + Pslope)
#---------------------------------------------------------------------------
# www.fiets.nl
#---------------------------------------------------------------------------
def __Grade2Power_FietsNL(self):
#-----------------------------------------------------------------------
# Thanks to https://www.fiets.nl/2016/05/02/de-natuurkunde-van-het-fietsen/
# Required power = roll + air + slope + mechanical
#-----------------------------------------------------------------------
c = self.RollingResistance # roll-resistance constant
m = self.UserAndBikeWeight # kg
g = 9.81 # m/s2
v = self.VirtualSpeedKmh / 3.6 # m/s km/hr * 1000 / 3600
Proll = c * m * g * v # Watt
p = 1.205 # air-density
cdA = 0.3 # resistance factor
# p_cdA = 0.375
w = 0 # wind-speed
Pair = 0.5 * p * cdA * (v+w)*(v+w)* v # Watt
i = self.TargetGrade # Percentage 0...100
Pslope= i/100 * m * g * v # Watt
Pbike = 37
self.TargetPower = int(Proll + Pair + Pslope + Pbike)
#---------------------------------------------------------------------------
# Convert Power to Speed
#---------------------------------------------------------------------------
# When Power is known, Zwift shows the speed - based upon the known slope
# This function should be similar
#---------------------------------------------------------------------------
# input: self.CurrentPower, self.UserAndBikeWeight, self.TargetGrade
#
# description Based upon inputs, estimate Speed
#
# Note: the Grade2Power() functions operate on self, and
# therefore do not require input/return variables.
#
# The reason we do NOT modify self.VirtualSpeedKmh here is
# that that speed is directly related to the physical wheel-
# speed. So CalculatedSpeed is added and the consumer of the
# data can choose which of the two to use.
#
# _Grade2Power() uses self.VirtualSpeedKmh as input to
# calculate power. Therefore the value is saved and restored.
# The field is used here to find the correct speed resulting
# in the searched power.
# *** appologies for this construction ***
#
# output: self.CalculatedSpeed
#
# returns: None
#---------------------------------------------------------------------------
def Power2Speed(self, Grade=0): #Power2Speed#
SpeedLo = 1 # The low speed in the range where we estimate
SpeedHi = 100 # The high ...
Speed = 0 # The estimated speed
PrevPower = 0 # The previous power
# ----------------------------------------------------------------------
# We are going to SEARCH a VirtualSpeedKmh, resulting in TargetPower
# that equals CurrentPower. Save these two fields and restore afterwards
# ----------------------------------------------------------------------
SaveVirtualSpeedKmh = self.VirtualSpeedKmh
SaveTargetPower = self.TargetPower
SaveTargetGrade = self.TargetGrade
# ----------------------------------------------------------------------
# In powermode, by default we use TargetGrade=0 to calculate the speed
# if we ride a virtual route, the TargetGrade is taken from the GPX and
# provided as a parameter.
# We COULD leave TargetGrade modified, but restore it just to be neat.
#
# In GradeMode, the TargetGrade is already set.
# ----------------------------------------------------------------------
if self.TargetMode == mode_Power:
self.TargetGrade = Grade
if self.CurrentPower == 0:
Speed = 0 # No power, no speed
else:
SpeedLo = 1 # We do not cycle backwards
SpeedHi = 100 # Smart guy going faster :-)
# ------------------------------------------------------------------
# If power is negative, find point where curve goes up
# The powercurve with a big negative slope has two solutions for the
# speed when the (negative) power is given; herewith we chose to get
# the highest speed of the two.
# ------------------------------------------------------------------
if self.CurrentPower < 0:
self.VirtualSpeedKmh = SpeedLo
self._Grade2Power()
PrevPower = 10000
while self.TargetPower < PrevPower:
SpeedLo = SpeedLo + 5
PrevPower = self.TargetPower
self.VirtualSpeedKmh = SpeedLo
self._Grade2Power()
# ------------------------------------------------------------------
# Find the power that matches the searched speed
#
# +----------+----------+
# SpeedLo ... Speed ... SpeedHi
# TargetPower
# Move SpeedLo/SpeedHi based upon power, untill close enough.
# ------------------------------------------------------------------
while (SpeedHi / SpeedLo) > 1.05:
Speed = (SpeedLo + SpeedHi) / 2 # The estimated speed
self.VirtualSpeedKmh = Speed # results in
self._Grade2Power() # TargetPower
if self.TargetPower < self.CurrentPower:
SpeedLo = Speed # New boundary
else:
SpeedHi = Speed # New boundary
# ----------------------------------------------------------------------
# Restore fields
# ----------------------------------------------------------------------
self.VirtualSpeedKmh = SaveVirtualSpeedKmh
self.TargetPower = SaveTargetPower
self.TargetGrade = SaveTargetGrade
# ----------------------------------------------------------------------
# Our output
# ----------------------------------------------------------------------
self.CalculatedSpeedKmh = Speed
#-------------------------------------------------------------------------------
# c l s S i m u l a t e d T r a i n e r
#-------------------------------------------------------------------------------
# Simulate Tacx-trainer
#-------------------------------------------------------------------------------
class clsSimulatedTrainer(clsTacxTrainer):
def __init__(self, clv):
super().__init__(clv, "Simulated Tacx Trainer to test ANT-interface")
if debug.on(debug.Function):logfile.Write ("clsSimulatedTrainer.__init__()")
self.OK = True
self.clv.PowerFactor = 1 # Not applicable for simulation
# --------------------------------------------------------------------------
# R e f r e s h
# --------------------------------------------------------------------------
# input: self.TargetPower
#
# Description: Basically, values are set so that no trainer-interface is needed
# Especially, to be able to test without the trainer being active
#
# Just for fun, generate values based upon what the trainer
# program wants so that a live simulation can be generated.
# For example to make a video without pedaling.
#
# The CurrentPower smoothly adjust to TargetPower
# The HeartRate follows the CurrentPower produced
# The Cadence is floating around 100
# The Speed follows the Cadence
#
# Output: self.* variables, see next 10 lines
# --------------------------------------------------------------------------
def Refresh (self, _QuarterSecond=None, _TacxMode=None):
if debug.on(debug.Function):logfile.Write ("clsSimulatedTrainer.Refresh()")
# ----------------------------------------------------------------------
# Trigger for pedalstroke analysis (PedalEcho)
# Data for Speed and Cadence Sensor (-Time and -Count)
# ----------------------------------------------------------------------
if self.Cadence and (time.time() - self.PedalEchoTime) > 60 / self.Cadence:
self.PedalEchoTime = time.time()
self.PedalEcho = 1
self.PedalEchoCount += 1
else:
self.PedalEcho = 0
# ----------------------------------------------------------------------
# Randomize figures
# ----------------------------------------------------------------------
self.Axis = 0
self.Buttons = 0
self.TargetResistance = 2345
if self.TargetMode == mode_Grade:
self._Grade2Power()
if False or self.TargetPower < 10: # Return fixed value
self.SpeedKmh = 34.5
self.HeartRate = 135
self.CurrentPower= 246
self.Cadence = 113
else: # Return animated value
# Using this setting, you let TrainerRoad and FortiusANT play together
# and sip a beer yourself :-)
HRmax = 180
ftp = 246 # at 80% HRmax
deltaPower = (self.TargetPower - self.CurrentPower)
if deltaPower < 8:
self.CurrentPower = self.TargetPower
deltaPower = 0
else:
self.CurrentPower = self.CurrentPower + deltaPower / 8 # Step towards TargetPower
self.CurrentPower *= (1 + random.randint(-3,3) / 100) # Variation of 5%
self.Cadence = 100 - min(10, deltaPower) / 10 # Cadence drops when Target increases
self.Cadence *= (1 + random.randint(-2,2) / 100) # Variation of 2%
self.SpeedKmh = 35 * self.Cadence / 100 # Speed is 35 kmh at cadence 100 (My highest gear)
self.HeartRate = HRmax * (0.5 + ((self.CurrentPower - 100) / (ftp - 100) ) * 0.3)
# As if power is linear with power
# 100W is reached at 50%
# ftp is reached at 80%
# Assume lineair between 100W and ftp
if self.HeartRate < HRmax * 0.5: self.HeartRate = HRmax * 0.5 # minimize HR
if self.HeartRate > HRmax: self.HeartRate = HRmax # maximize HR
self.HeartRate += random.randint(-5,5) # Variation of heartrate by 5 beats
self.VirtualSpeedKmh= self.SpeedKmh
#-------------------------------------------------------------------------------
# c l s T a c x A n t V o r t e x T r a i n e r
#-------------------------------------------------------------------------------
# Tacx-trainer with ANT connection
# Actually, only the data-storage and Refresh() with Grade2Power() is used!
#-------------------------------------------------------------------------------
class clsTacxAntVortexTrainer(clsTacxTrainer):
def __init__(self, clv, AntDevice):
super().__init__(clv, "Pair with Tacx Vortex and Headunit")
if debug.on(debug.Function):logfile.Write ("clsTacxAntVortexTrainer.__init__()")
self.AntDevice = AntDevice
self.OK = True # The AntDevice is there,
# the trainer not yet paired!
self.__VHUmode = ant.VHU_Normal # current HU mode
self.__ResetTrainer()
def __ResetTrainer(self):
self.__AntVTXpaired = False
self.__AntVHUpaired = False
self.__DeviceNumberVTX = 0 # provided by CHANNEL_ID msg
self.__DeviceNumberVHU = 0
self.__Cadence = 0 # provided by datapage 0
self.__CurrentPower = 0
self.__WheelSpeed = 0