-
Notifications
You must be signed in to change notification settings - Fork 0
/
calculations.c
1509 lines (1243 loc) · 54.8 KB
/
calculations.c
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
#include "sdk_common.h"
#include <string.h>
#define NRF_LOG_MODULE_NAME calculations
#if CALCULATIONS_CONFIG_LOG_ENABLED
#define NRF_LOG_LEVEL CALCULATIONS_CONFIG_LOG_LEVEL
#define NRF_LOG_INFO_COLOR CALCULATIONS_CONFIG_INFO_COLOR
#define NRF_LOG_DEBUG_COLOR CALCULATIONS_CONFIG_DEBUG_COLOR
#else // CALCULATIONS_CONFIG_LOG_ENABLED
#define NRF_LOG_LEVEL 0
#endif // CALCULATIONS_CONFIG_LOG_ENABLED
#include "nrf_log.h"
NRF_LOG_MODULE_REGISTER();
// Important!
/*
https://devzone.nordicsemi.com/f/nordic-q-a/29345/nrf52832-executing-twi-function-from-app_timer-handler
NRF_LOG_FLUSH() is a blocking function and if you are using UART as backend
this is using interrupts while printing messages. Hence, you are triggering
interrupts from within an interrupt context and this might cause priority issues.
If you are using RTT as backend it will not use interrupts the same way, but
since NRF_LOG_FLUSH() is blocking and since it takes a significant amount of
time to format a string you should never flush in an interrupt context. NRF_LOG_FLUSH()
is intended to be used only in main context.
*/
#include "nrf_log.h"
#include "nrf_log_ctrl.h"
#include <string.h>
#include "nordic_common.h"
#include "app_util.h"
#include "calculations.h"
#include "ble_cscs_c.h"
#include "math.h"
#include "helper.h"
#include "assert.h"
#include "app_timer.h"
#include "oled_controller.h"
#include <ble_gattc.h>
static calculation_helper_t calculation_helper;
volatile bool doTriggerFECEvent;
volatile bool doCalcModel;
uint32_t pid_timer = 0;
#define BENCHMARK 0
#define SPEEDS_SIZE 5
#define PID_CONTROLLER_INTERVAL 1000
#define FEC_CONTROLLER_INTERVAL 250
static double speeds[SPEEDS_SIZE] = { 0.0, 0.0, 0.0, 0.0, 0.0 };
static int speed_ptr = 0;
static int speed_size = 0;
static uint8_t schedule[132];
static uint8_t schedule_idx = 0;
// Only to be switched in an "error" condition when not using our setup
static bool external_wheel_sensor_data_present = false;
uint32_t getCumulativeWheelRevs()
{
return (uint32_t) calculation_helper.cumulative_wheel_revs;
}
uint16_t getLastWheelEventTime()
{
return calculation_helper.last_wheel_event_time;
}
uint16_t getLastCrankEventTime()
{
return calculation_helper.last_crank_event_time;
}
void initializeCalculationHelper()
{
memset(&calculation_helper,0,sizeof(calculation_helper_t));
setResistanceLevel(resistance_level); // Initialize with the minimum value (from main.c to ensure values are in sync)
setUserWeight(USER_MASS);
setBikeWeight(EQUIPMENT_MASS);
setCoefficientRollingResistance(80);
setWindResistanceCoefficient(51);
setDraftingFactor(100);
setGrade(20000);
setFECMode(FEC_TARGET_POWER);
}
void incResistanceLevel()
{
if (calculation_helper.resistance_level != resistance_level)
{
NRF_LOG_ERROR("Error resistance_level out of sync");
}
if (resistance_level == 32)
{
///NRF_LOG_ERROR("Error resistance_level already max, can't inc");
}
calculation_helper.resistance_level++;
oled_data.trainer_resistance = calculation_helper.resistance_level;
resistance_level++;
// NRF_LOG_INFO("Updated++");
}
void decResistanceLevel()
{
//Dangerous to log here! In a timer context!
if (calculation_helper.resistance_level != resistance_level)
{
NRF_LOG_ERROR("Error resistance_level out of sync");
}
if (resistance_level == 1)
{
//NRF_LOG_ERROR("Error resistance_level already min, can't dec");
}
calculation_helper.resistance_level--;
oled_data.trainer_resistance = calculation_helper.resistance_level;
resistance_level--;
//NRF_LOG_INFO("Updated--");
}
void setResistanceLevel(uint8_t resistance_level)
{
calculation_helper.resistance_level = resistance_level;
NRF_LOG_INFO("setResistanceLevel() called");
}
uint8_t getResistanceLevel()
{
return calculation_helper.resistance_level;
}
static void updateCadenceReadings()
{
if (calculation_helper.prev_last_crank_event_time == 0)
{
// Handle unrealisitic large first measurements
calculation_helper.prev_last_crank_event_time = calculation_helper.last_crank_event_time;
}
if (calculation_helper.prev_cumulative_crank_revs == 0)
{
// Handle unrealisitic large first measurements
calculation_helper.prev_cumulative_crank_revs == calculation_helper.cumulative_crank_revs;
}
calculation_helper.delta_crank_event_times = calculation_helper.last_crank_event_time - calculation_helper.prev_last_crank_event_time;
calculation_helper.delta_cum_crank_revs = calculation_helper.cumulative_crank_revs - calculation_helper.prev_cumulative_crank_revs;
if (calculation_helper.delta_crank_event_times == 0)
{
// NRF_LOG_ERROR(" delta_crank_event_times = 0");
return;
}
// TODO:
// We do not allow for 0 cadence changes because of the above changes, i.e. i_cadence and avg_cadence stay as they are
//assert(calculation_helper.delta_crank_event_times>0);
//assert(calculation_helper.delta_crank_event_times>0);
// Also set it in the struct directly
calculation_helper.i_cadence = (double) (calculation_helper.delta_cum_crank_revs) * 1024.0 / (double)(calculation_helper.delta_crank_event_times);
calculation_helper.avg_cadence = calculation_helper.i_cadence * 60; // 60s * 1024th
}
double getInstantaneousCadence()
{
return calculation_helper.i_cadence;
}
double getAverageCadence()
{
return calculation_helper.avg_cadence;
}
uint16_t getPrevLastWheelEventTime()
{
return calculation_helper.prev_last_wheel_event_time;
}
static double updateInstantaneousSpeed()
{
//calculation_helper.i_speed = 3.6 * calculation_helper.delta_cum_wheel_revs * CIRCUMFERENCE_WHEEL / calculation_helper.delta_wheel_event_times;
// New!
if (calculation_helper.delta_wheel_event_times > 0)
{
//calculation_helper.i_speed = ((double) calculation_helper.delta_achieved_whole_cumulative_wheel_revs) * CIRCUMFERENCE_WHEEL * 1024.0 / ((double) calculation_helper.delta_wheel_event_times);
calculation_helper.i_speed = calculation_helper.i_wheel_revs * CIRCUMFERENCE_WHEEL;
}
else
{
calculation_helper.i_speed = 0.0;
}
return calculation_helper.i_speed;
}
static double updateInstantaneousWheelRevs()
{
//calculation_helper.i_wheel_revs = ((double) calculation_helper.delta_achieved_whole_cumulative_wheel_revs * 1024.0) / (double) calculation_helper.delta_wheel_event_times;
//calculation_helper.i_wheel_revs = (((double) calculation_helper.delta_cum_wheel_revs) * 1024.0) / ((double) calculation_helper.delta_crank_event_times / (double) calculation_helper.delta_cum_crank_revs);
//calculation_helper.i_wheel_revs = (((double) calculation_helper.delta_cum_wheel_revs) * 1024.0) / (calculation_helper.delta_crank_event_times-calculation_helper.delta_wheel_event_times);
calculation_helper.i_wheel_revs = (double) calculation_helper.delta_achieved_whole_cumulative_wheel_revs * 1024.0 /(double) calculation_helper.delta_wheel_event_times;
return calculation_helper.i_wheel_revs;
}
double getInstantaneousSpeed()
{
return calculation_helper.i_speed;
}
static double getAveragedSpeed(double in_value)
{
// Put value
if (speed_size<SPEEDS_SIZE)
{
speed_size++;
}
speeds[(speed_ptr++) % SPEEDS_SIZE] = in_value;
// Average it
double sum = 0.0;
for (int idx=0; idx<SPEEDS_SIZE-1; idx++)
{
sum+=speeds[idx];
}
double averaged = (double) sum / (double) speed_size;
/*
char buf[16];
sprintf(buf, "%f" , sum);
char buf2[16];
sprintf(buf2, "%f" , averaged);
NRF_LOG_INFO("Averaged km/h: Sum: %s, Elements: %d -> %s", buf, speed_size, buf2);
*/
return averaged;
}
static double updateAverageSpeed()
{
// TODO: Hm, is the following correct? What if we don' pedal? immediately 0.0 km/h?
// We don' update the values at all!
if (calculation_helper.delta_cum_crank_revs == 0 || calculation_helper.delta_crank_event_times == 0)
{
return 0.0;
}
double intermediate_speed = 3.6 * calculation_helper.i_speed;
/*
calculation_helper.crank_events_per_sec = calculation_helper.avg_cadence / 60.0; // rpm can be calculated precisely because delta_cum_crank_revs and delta_last_crank_time is physical correct and precise
calculation_helper.current_time_interval_one_crank_event = (double) calculation_helper.delta_crank_event_times / (double) calculation_helper.delta_cum_crank_revs; // Approx the _current_ time interval for ONE full crank rottion
// The next one does not seem right to me? why h->cumulative_crank-revs... not the delta?
//h->precise_cum_wheel_revs_at_last_crank_event = h->cumulative_crank_revs * getGearRatio();
calculation_helper.precise_cum_wheel_revs_at_last_crank_event = calculation_helper.delta_cum_crank_revs * getGearRatio() + calculation_helper.cumulative_wheel_revs;
if (calculation_helper.prev_last_wheel_event_time == 0)
{
// We initialize it to prev_last_crank_event, to avoid unrealisitic high readings
calculation_helper.prev_last_wheel_event_time = calculation_helper.prev_last_crank_event_time;
}
else
{
calculation_helper.prev_last_wheel_event_time = calculation_helper.last_wheel_event_time;
}
calculation_helper.prev_cumulative_wheel_revs = calculation_helper.cumulative_wheel_revs;
// Sometimes this here goes sky-rocketing...
//kmh = (((double) delta_cum_wheel_revs) * 3.60 * CIRCUMFERENCE_WHEEL ) / ((double)(delta_last_wheel_time));
calculation_helper.timespan_for_wheel_events = calculation_helper.last_crank_event_time - calculation_helper.prev_last_wheel_event_time;
calculation_helper.duration_per_wheel_event = calculation_helper.timespan_for_wheel_events / calculation_helper.precise_cum_wheel_revs_at_last_crank_event;
calculation_helper.timespan_until_last_full_wheel_event = (uint16_t) round(calculation_helper.duration_per_wheel_event * floor(calculation_helper.precise_cum_wheel_revs_at_last_crank_event));
// That's it?
calculation_helper.last_wheel_event_time = (uint16_t) (calculation_helper.prev_last_wheel_event_time + calculation_helper.timespan_until_last_full_wheel_event); // Let it overflow if need be
calculation_helper.cumulative_wheel_revs = floor(calculation_helper.precise_cum_wheel_revs_at_last_crank_event);
// Again prevention of skyrocketing
if (calculation_helper.prev_cumulative_wheel_revs == 0)
{
calculation_helper.prev_cumulative_wheel_revs = calculation_helper.cumulative_wheel_revs;
}
calculation_helper.delta_cum_wheel_revs = calculation_helper.cumulative_wheel_revs - calculation_helper.prev_cumulative_wheel_revs;
//NRF_LOG_INFO("h->last_wheel_event_time: %d", h->last_wheel_event_time);
//NRF_LOG_INFO("h->prev_last_wheel_event_time: %d", h->prev_last_wheel_event_time);
calculation_helper.delta_last_wheel_time = calculation_helper.last_wheel_event_time - calculation_helper.prev_last_wheel_event_time; // We need to cope with uint16_t overflows here (happens every 64 seconds!)
//NRF_LOG_INFO("h->delta_cum_wheel_revs: %d", h->delta_cum_wheel_revs);
//NRF_LOG_INFO("h->delta_last_wheel_time: %d", h->delta_last_wheel_time);
// TODO: Why are we calculating again??? -> Should use existing value
double intermediate_speed = (((double) calculation_helper.delta_cum_wheel_revs) * 3.6 * CIRCUMFERENCE_WHEEL ) / ((double) (calculation_helper.delta_last_wheel_time));
*/
if (intermediate_speed > 120.0)
{
char buf[128];
stopOLEDUpdates();
oled_printStringAt(30,10, "CRITICAL ERROR", true, true);
sprintf(buf, "Something went wrong: intermediate_speed = %f", intermediate_speed);
NRF_LOG_INFO("%s",buf);
NRF_LOG_FLUSH();
debugCalculationHelper();
assert(true==false);
APP_ERROR_CHECK(-1);
}
calculation_helper.avg_speed = intermediate_speed;// getAveragedSpeed(intermediate_speed);
return calculation_helper.avg_speed;
}
uint16_t getCumulativeCrankRevs()
{
return calculation_helper.cumulative_crank_revs;
}
// Not needed
/*
void setCumulativeCrankRevs(uint16_t cumulative_crank_revs)
{
calculation_helper.cumulative_crank_revs = cumulative_crank_revs;
}
*/
double calcPowerFromGivenCadence(uint16_t cadence)
{
}
void debugCalculationHelper()
{
char buf[128];
calculation_helper_t *h = &calculation_helper;
NRF_LOG_INFO("uint8_t resistance_level = %u", h->resistance_level);
NRF_LOG_INFO("uint16_t last_crank_event_time = %u", h->last_crank_event_time);
NRF_LOG_INFO("uint16_t prev_last_crank_event_time = %u", h->prev_last_crank_event_time);
NRF_LOG_INFO("uint16_t cumulative_crank_revs = %u", h->cumulative_crank_revs);
NRF_LOG_INFO("uint16_t prev_cumulative_crank_revs = %u", h->prev_cumulative_crank_revs);
NRF_LOG_INFO("uint16_t cumulative_wheel_revs = %u", h->cumulative_wheel_revs);
NRF_LOG_INFO("uint16_t prev_cumulative_wheel_revs = %u", h->prev_cumulative_wheel_revs);
NRF_LOG_INFO("uint16_t last_wheel_event_time = %u", h->last_wheel_event_time);
NRF_LOG_INFO("uint16_t prev_last_wheel_event_time = %u", h->prev_last_wheel_event_time);
NRF_LOG_INFO("uint16_t timespan_until_last_full_wheel_event = %u", h->timespan_until_last_full_wheel_event);
NRF_LOG_INFO("uint16_t timespan_for_wheel_events = %u", h->timespan_for_wheel_events);
NRF_LOG_INFO("uint16_t delta_wheel_event_times = %u", h->delta_wheel_event_times);
NRF_LOG_INFO("uint16_t delta_cum_wheel_revs = %u", h->delta_cum_wheel_revs);
NRF_LOG_INFO("uint16_t delta_last_wheel_time = %u", h->delta_last_wheel_time);
sprintf(buf, "double crank_events_per_sec = %f", h->crank_events_per_sec);
NRF_LOG_INFO("%s",buf);
sprintf(buf, "double current_time_interval_one_crank_event = %f", h->current_time_interval_one_crank_event);
NRF_LOG_INFO("%s",buf);
sprintf(buf, "double precise_cum_wheel_revs_at_last_crank_event = %f", h->precise_cum_wheel_revs_at_last_crank_event);
NRF_LOG_INFO("%s",buf);
sprintf(buf, "double upper_limit_i_wheel_revs_based_on_cadence = %f", h->upper_limit_i_wheel_revs_based_on_cadence);
NRF_LOG_INFO("%s",buf);
sprintf(buf, "double duration_per_wheel_event = %f", h->duration_per_wheel_event);
NRF_LOG_INFO("%s",buf);
NRF_LOG_INFO("uint16_t delta_crank_event_times = %u", h->delta_crank_event_times);
NRF_LOG_INFO("uint16_t delta_cum_crank_revs = %u", h->delta_cum_crank_revs);
sprintf(buf, "double i_cadence = %f", h->i_cadence);
NRF_LOG_INFO("%s",buf);
sprintf(buf, "double i_wheel_revs = %f", h->i_wheel_revs);
NRF_LOG_INFO("%s",buf);
sprintf(buf, "double i_speed = %f", h->i_speed);
NRF_LOG_INFO("%s",buf);
sprintf(buf, "double avg_speed = %f", h->avg_speed);
NRF_LOG_INFO("%s",buf);
sprintf(buf, "double avg_cadence = %f", h->avg_cadence);
NRF_LOG_INFO("%s",buf);
sprintf(buf, "double i_power = %u", h->i_power);
NRF_LOG_INFO("%s",buf);
sprintf(buf, "double ideal_cumulative_wheel_revs = %f", h->ideal_cumulative_wheel_revs);
NRF_LOG_INFO("%s",buf);
sprintf(buf, "double achieved_wheel_revs_during_crank_time = %f", h->achieved_wheel_revs_during_crank_time);
NRF_LOG_INFO("%s",buf);
sprintf(buf, "double tweak_wheel_cadence = %f", h->tweak_wheel_cadence);
NRF_LOG_INFO("%s",buf);
sprintf(buf, "double timespan_per_wheel_rev = %f", h->timespan_per_wheel_rev);
NRF_LOG_INFO("%s",buf);
sprintf(buf, "double fraction = %f", h->fraction);
NRF_LOG_INFO("%s",buf);
NRF_LOG_INFO("int16_t integrator = %d", h->integrator);
#if HANDLE_FREEROLL
NRF_LOG_INFO("uint16_t freeroll_duration = %u", h->freeroll_duration);
sprintf(buf, "crank_events_per_sec: %f", h->crank_events_per_sec);
NRF_LOG_INFO("%s",buf);
#endif
}
double getAverageSpeed()
{
return calculation_helper.avg_speed;
}
void stopProcessing()
{
ret_code_t err_code;
if (m_pid_timer_id!=NULL)
{
err_code = app_timer_stop(m_pid_timer_id);
APP_ERROR_CHECK(err_code);
}
if (m_fec_timer_id!=NULL)
{
err_code = app_timer_stop(m_fec_timer_id);
APP_ERROR_CHECK(err_code);
}
}
void startProcessing()
{
// Create timers
ret_code_t err_code = app_timer_create(&m_pid_timer_id,
APP_TIMER_MODE_REPEATED,
//pid_handler);
calculation_handler);
APP_ERROR_CHECK(err_code);
// Fire every PID_CONTROLLER_INTERVAL ms
NRF_LOG_DEBUG("Calculation timer start!");
err_code = app_timer_start(m_pid_timer_id, APP_TIMER_TICKS(PID_CONTROLLER_INTERVAL), NULL);
APP_ERROR_CHECK(err_code);
// Check if FE-C over BLE is actually enabled
if (!ble_fec_active) return;
err_code = app_timer_create(&m_fec_timer_id,
APP_TIMER_MODE_REPEATED,
//pid_handler);
fec_timer_handler);
// Populate scheduler;
// Full set;
bool toggle1 = true;
bool toggle2 = true;
for (uint8_t offset=0; offset<132; offset+=66)
{
uint8_t idx = 0;
for (idx = 0; idx < 64; idx+=4)
{
schedule[offset+idx] = BLE_FEC_PAGE_GENERAL_FE_DATA;
schedule[offset+idx+1] = BLE_FEC_PAGE_GENERAL_FE_DATA;
if (toggle1)
{
schedule[offset+idx+2] = BLE_FEC_PAGE_OPEN_SLOT;
schedule[offset+idx+3] = BLE_FEC_PAGE_GENERAL_SETTINGS;
}
else
{
schedule[offset+idx+2] = BLE_FEC_PAGE_GENERAL_FE_METABOLIC_DATA;
schedule[offset+idx+3] = BLE_FEC_PAGE_OPEN_SLOT;
}
toggle1 = !toggle1;
}
if (toggle2)
{
schedule[offset+idx] = BLE_FEC_PAGE_COMMON_MANUFACTURER_IDENT;
schedule[offset+idx+1] = BLE_FEC_PAGE_COMMON_MANUFACTURER_IDENT;
}
else
{
schedule[offset+idx] = BLE_FEC_PAGE_COMMON_PRODUCT_INFORMATION;
schedule[offset+idx+1] = BLE_FEC_PAGE_COMMON_PRODUCT_INFORMATION;
}
toggle2 = !toggle2;
}
schedule_idx = 0;
// Fire every PID_CONTROLLER_INTERVAL ms
NRF_LOG_DEBUG("FEC timer start!");
err_code = app_timer_start(m_fec_timer_id, APP_TIMER_TICKS(FEC_CONTROLLER_INTERVAL), NULL);
APP_ERROR_CHECK(err_code);
}
void updateModelFromCSCSensorData(const ble_gattc_evt_hvx_t *p_notif)
{
uint32_t index = 0;
bool isCrankRevDataPresent = false;
bool isWheelRevDataPresent = false;
isCrankRevDataPresent = p_notif->data[index] >> BLE_CSCS_CRANK_REV_DATA_PRESENT & 0x01;
isWheelRevDataPresent = p_notif->data[index] >> BLE_CSCS_WHEEL_REV_DATA_PRESENT & 0x01;
index++;
if (isWheelRevDataPresent)
{
external_wheel_sensor_data_present = true;
NRF_LOG_WARNING("We have external wheel sensor data! This is not expected!");
uint32_t _cumulative_wheel_revs = uint32_decode(&p_notif->data[index]);
index += sizeof(uint32_t);
uint16_t _last_wheel_event_time = uint16_decode(&p_notif->data[index]);
index += sizeof(uint16_t);
#if HONOR_ZERO_DELTA
if (_cumulative_crank_revs != calculation_helper.cumulative_crank_revs)
{
#endif
if (calculation_helper.prev_cumulative_wheel_revs == 0)
{
calculation_helper.prev_cumulative_wheel_revs = _cumulative_wheel_revs;
}
else
{
calculation_helper.prev_cumulative_wheel_revs = calculation_helper.cumulative_wheel_revs;
}
calculation_helper.cumulative_wheel_revs = _cumulative_wheel_revs;
#if HONOR_ZERO_DELTA
}
if (_last_crank_event_time != calculation_helper.last_crank_event_time)
{
#endif
if (calculation_helper.prev_last_wheel_event_time == 0)
{
calculation_helper.prev_last_wheel_event_time = _last_wheel_event_time;
}
else
{
calculation_helper.prev_last_wheel_event_time = calculation_helper.last_wheel_event_time;
}
calculation_helper.last_wheel_event_time = _last_wheel_event_time;
#if HONOR_ZERO_DELTA
}
#endif
}
if (isCrankRevDataPresent)
{
uint16_t _cumulative_crank_revs = uint16_decode(&p_notif->data[index]);
index += sizeof(uint16_t);
// Last crank event time
uint16_t _last_crank_event_time = uint16_decode(&p_notif->data[index]);
index += sizeof(uint16_t);
#if HONOR_ZERO_DELTA
if (_cumulative_crank_revs != calculation_helper.cumulative_crank_revs)
{
#endif
if (calculation_helper.prev_cumulative_crank_revs == 0)
{
// Ensure the very first measurement is not unrealistic high
calculation_helper.prev_cumulative_crank_revs = _cumulative_crank_revs;
NRF_LOG_INFO("prev_cumulative_crank_revs=0 - Should never happen after start!");
}
else
{
calculation_helper.prev_cumulative_crank_revs = calculation_helper.cumulative_crank_revs;
}
calculation_helper.cumulative_crank_revs = _cumulative_crank_revs;
#if HONOR_ZERO_DELTA
}
if (_last_crank_event_time != calculation_helper.last_crank_event_time)
{
#endif
if (calculation_helper.prev_last_crank_event_time == 0)
{
// Ensure the very first measurement is not unrealistic high
calculation_helper.prev_last_crank_event_time = _last_crank_event_time;
NRF_LOG_INFO("prev_last_crank_event_time=0 - Very unlikely to happen!");
}
else
{
calculation_helper.prev_last_crank_event_time = calculation_helper.last_crank_event_time;
}
calculation_helper.last_crank_event_time = _last_crank_event_time;
// Init on first measurement value
if (calculation_helper.last_wheel_event_time == 0)
{
calculation_helper.last_wheel_event_time = _last_crank_event_time;
}
#if HONOR_ZERO_DELTA
}
#endif
}
// calculation_handler(NULL);
}
static void debugPrintIWheelRevRelations()
{
char s_upper_limit_i_wheel_revs_based_on_cadence[16];
char s_i_wheel_revs[16];
char s_percentage_reached[16];
char s_percentage_int_reached[16];
sprintf(s_upper_limit_i_wheel_revs_based_on_cadence,"%f", calculation_helper.upper_limit_i_wheel_revs_based_on_cadence);
sprintf(s_i_wheel_revs,"%f", calculation_helper.i_wheel_revs);
if (calculation_helper.upper_limit_i_wheel_revs_based_on_cadence > 0)
{
double percentage_reached = calculation_helper.i_wheel_revs * 100.0 / calculation_helper.upper_limit_i_wheel_revs_based_on_cadence;
sprintf(s_percentage_reached, "%f", percentage_reached);
}
else
{
sprintf(s_percentage_reached, "0.0");
}
NRF_LOG_INFO("Delta crank rev = %u, delta_crank_event_time = %u, Target instantaneous wheel revs = %s, Current wheel revs = %s, Percentage reached = %s",
calculation_helper.delta_cum_crank_revs,
calculation_helper.delta_crank_event_times,
s_upper_limit_i_wheel_revs_based_on_cadence,
s_i_wheel_revs,
s_percentage_reached);
NRF_LOG_FLUSH();
}
static void updatePIDIntegrator(double i)
{
if (calculation_helper.fraction > 1 && calculation_helper.fraction < 1023) calculation_helper.integrator+=i;
if (calculation_helper.integrator < -1023)calculation_helper.integrator = -1023;
if (calculation_helper.integrator > 1023) calculation_helper.integrator = 1023;
}
static void debugPrintCadenceReadings()
{
char s_i_cadence[16], s_avg_cadence[16];
sprintf(s_i_cadence,"%f", calculation_helper.i_cadence);
sprintf(s_avg_cadence,"%f", calculation_helper.avg_cadence);
NRF_LOG_INFO("Instantaneous cadence: %s, Average cadence: %s",s_i_cadence, s_avg_cadence);
NRF_LOG_FLUSH();
}
static void debugPrintAchievedWheelRevsDuringCrankTime()
{
char s_achieved_wheel_revs_during_crank_time[32];
sprintf(s_achieved_wheel_revs_during_crank_time,"%f", calculation_helper.achieved_wheel_revs_during_crank_time);
NRF_LOG_INFO("achieved_wheel_revs_during_crank_time = %s", s_achieved_wheel_revs_during_crank_time);
NRF_LOG_FLUSH();
}
static void debugPrintTimeSpanPerWheelRev()
{
char s_timespan_per_wheel_rev[32];
char s_achieved_wheel_revs_during_crank_time[32];
char s_delta_achieved_whole_cumulative_wheel_revs[32];
sprintf(s_timespan_per_wheel_rev, "%f", calculation_helper.timespan_per_wheel_rev);
sprintf(s_achieved_wheel_revs_during_crank_time, "%f", calculation_helper.achieved_wheel_revs_during_crank_time);
NRF_LOG_INFO("timespan_per_wheel_rev = %s, achieved_wheel_revs_during_crank_time = %s, delta_achieved_whole_cumulative_wheel_revs = %u", s_timespan_per_wheel_rev, s_achieved_wheel_revs_during_crank_time,calculation_helper.delta_achieved_whole_cumulative_wheel_revs);
NRF_LOG_FLUSH();
}
static void debugPrintSpeed()
{
char buf[32];
sprintf(buf, "m/s: %.2f, km/h: %.2f", calculation_helper.i_speed, calculation_helper.avg_speed);
NRF_LOG_INFO("%s",buf);
NRF_LOG_FLUSH();
}
static void debugPrintPIDValues(double d1, double d2, double d3, double i, double p, double ki, int16_t integrator, double output1, double output)
{
char buf[256];
sprintf(buf, "d1: %f, d2: %f, d3(*): %f, i: %f, p: %f, ki: %f, integrator: %d, output1: %f: output(*): %f", d1, d2, d3, i, p, ki, integrator, output1, output);
NRF_LOG_INFO("%s", buf);
NRF_LOG_FLUSH();
}
static void debugPrintPower()
{
NRF_LOG_INFO("Inst. power: %u, Avg. power: %d", calculation_helper.i_power, calculation_helper.avg_power);
NRF_LOG_FLUSH();
}
/**@brief Timeout handler for the repeated timer.
*/
static void debugPrintDeltaWheelDetail()
{
char s_delta_cum_wheel_revs[16];
sprintf(s_delta_cum_wheel_revs, "%f", calculation_helper.delta_cum_wheel_revs);
NRF_LOG_INFO("delta_cum_wheel_revs: %s, delta_wheel_event_times: %u", s_delta_cum_wheel_revs, calculation_helper.delta_wheel_event_times);
NRF_LOG_FLUSH();
}
static void debugPrintCumWheel()
{
char s_cumulative_wheel_revs[16];
char s_prev_cumulative_wheel_revs[16];
sprintf(s_cumulative_wheel_revs, "%f", calculation_helper.cumulative_wheel_revs);
sprintf(s_prev_cumulative_wheel_revs, "%f", calculation_helper.prev_cumulative_wheel_revs);
NRF_LOG_INFO("delta_achieved_whole_cumulative_wheel_revs: %d, cumulative_wheel_revs: %s, prev_cumulative_wheel_revs: %s", calculation_helper.delta_achieved_whole_cumulative_wheel_revs, s_cumulative_wheel_revs, s_prev_cumulative_wheel_revs);
NRF_LOG_FLUSH();
}
static void debugPrintTimeCompare()
{
NRF_LOG_INFO("last_crank_event_time: %u, last_wheel_event_time: %u", calculation_helper.last_crank_event_time, calculation_helper.last_wheel_event_time);
NRF_LOG_FLUSH();
}
ble_fec_page_handler_t getFECPageHandler()
{
return calculation_helper.fec_data.fec_page_handler;
}
ble_fec_t *getFECHandle()
{
return calculation_helper.fec_data.fec_handle;
}
uint8_t getFECPage()
{
return calculation_helper.fec_data.page;
}
static void fec_timer_handler(void * p_context)
{
static bool update_toggle = true;
//ble_fec_evt_t ble_fec_evt;
calculation_helper.fec_data.page = schedule[(++schedule_idx % 128)];
if (update_toggle)
{
calculation_helper.fec_data.event_count++;
calculation_helper.fec_data.accumulated_power += calculation_helper.i_power;
calculation_helper.fec_data.elapsed_time++;
calculation_helper.fec_data.distance_traveled += (uint8_t) (0.5 * calculation_helper.i_speed);
}
update_toggle = !update_toggle;
if (!doTriggerFECEvent)
{
doTriggerFECEvent = true;
}
/*
ble_fec_evt.page = schedule[(++schedule_idx % 128)];
// Do this every 500 ms
if (update_toggle)
{
calculation_helper.fec_data.event_count++;
calculation_helper.fec_data.accumulated_power += calculation_helper.i_power;
calculation_helper.fec_data.elapsed_time++;
calculation_helper.fec_data.distance_traveled += (uint8_t) (0.5 * calculation_helper.i_speed);
}
ble_fec_evt.type = BLE_FEC_REQUEST_TYPE_BROADCAST;
if (calculation_helper.fec_data.fec_page_handler != NULL)
{
(calculation_helper.fec_data.fec_page_handler)(calculation_helper.fec_data.fec_handle, &ble_fec_evt);
update_toggle = !update_toggle;
}
*/
}
void setGrade(uint16_t grade)
{
calculation_helper.fec_data.grade = grade;
}
uint16_t getGrade()
{
return calculation_helper.fec_data.grade;
}
void setCoefficientRollingResistance(uint8_t crr)
{
calculation_helper.fec_data.crr = crr;
}
uint8_t getCoefficientRollingResistance()
{
return calculation_helper.fec_data.crr;
}
void setWindResistanceCoefficient(uint8_t wcr)
{
calculation_helper.fec_data.wcr = wcr;
}
uint8_t getWindResistanceCoefficient()
{
return calculation_helper.fec_data.wcr;
}
void setWindSpeed(int8_t windspeed)
{
calculation_helper.fec_data.windspeed = windspeed;
}
int8_t getWindSpeed()
{
return calculation_helper.fec_data.windspeed;
}
void setDraftingFactor(uint8_t drafting_factor)
{
calculation_helper.fec_data.drafting_factor = drafting_factor;
}
uint8_t getDraftingFactor()
{
return calculation_helper.fec_data.drafting_factor;
}
static void setOledGrade()
{
char grade_s[16];
float grade_f = ((double) getGrade() * 0.01) - 200.0;
sprintf(grade_s, "%.2f", grade_f);
oled_data.grade = grade_f;
}
static void performResistanceCalculation()
{
#if BENCHMARK
uint32_t execution_start, execution_end;
execution_start = app_timer_cnt_get();
#endif
char resistance_s[128];
// Wind Resistance [N] = (0.5 Wind Resistance Coefficient * (Relative Speed / 3.6)^2) x Drafting Factor (ANT-FEC, p57)
double wind_resistance_coefficient = ((double) getWindResistanceCoefficient()) * 0.01; // cw (default 0.51 kg/m (INDOOR_BIKE_SIMULATION_PARAMETERS.cw is 51.0)
double rolling_resistance_coefficient = ((double) getCoefficientRollingResistance()) * 0.00005; // crr (default 0.41 ((INDOOR_BIKE_SIMULATION_PARAMETERS.cw is 41.0)
// wind_speed in FTMS is delivered in m/s - not km/h like in FE-C!
double relative_speed_ms = getInstantaneousSpeed() + kmh2ms((double) getWindSpeed());
double wind_resistance = 0.5 * (wind_resistance_coefficient) * pow(relative_speed_ms,2) * ((double) getDraftingFactor()) * 0.01;
// Gravitational Resistance [N] = (Equipment Mass + User Mass) * Grade/100 * 9.81
// uint8_t total_weight = EQUIPMENT_MASS+USER_MASS;
uint8_t total_weight = getBikeWeight() + getUserWeight();
double gravitational_resistance = total_weight * ((((double) getGrade()) * 0.01) - 200.0) * 0.01 * 9.81; // TODO Check this: Always 0 on plain track?
// Set oled_grade
setOledGrade();
// Rolling Resistance [N] = (Bicycle Mass + Cyclist Mass) x Coefficient of Rolling Resistance x 9.8
double rolling_resistance = total_weight * rolling_resistance_coefficient * 9.81;
// Total resistance [N] = Gravitational Resistance + Rolling Resistance + Wind Resistance
int16_t imposed_resistance = (int16_t) round(gravitational_resistance + rolling_resistance + wind_resistance);
//debugPrintSimulationResistance(imposed_resistance, gravitational_resistance, rolling_resistance, wind_resistance);
// Now we have the resistance that is imposed on us. Now try to find the resistance level of the trainer that matches best the resistance
sprintf(resistance_s, "imposed_resistance: %d (Grav: %.3f + Roll: %.3f + Wind: %.3f)", imposed_resistance, gravitational_resistance, rolling_resistance, wind_resistance);
//NRF_LOG_INFO("%s",resistance_s);
oled_data.raw_resistance = imposed_resistance;
oled_data.wind_resistance = (int16_t) round(wind_resistance);
oled_data.rolling_resistance = (int16_t) round(rolling_resistance);
oled_data.gravitational_resistance = (int16_t) round(gravitational_resistance);
double least_error = 100000.0;
uint8_t resistance_level_candidate = 0xff;
// Calc all power values for current cadence
// This really looks superfluous now
double avg_cadence = getAverageCadence(); //kmh2rpm(getAverageSpeed());
//sprintf(buf, "Sanity check: CALC_AVG_CAD: %.2f, TRUE_AVG_CAD: %.2f" , calced_avg_cadence, getAverageCadence());
//NRF_LOG_INFO("%s", buf);
double resulting_power = 0.0;
for (uint8_t pot_resistance_level=1; pot_resistance_level<=NUM_RESISTANCE_LEVELS; pot_resistance_level++)
{
resulting_power = calculatePower(avg_cadence, pot_resistance_level);
// NRF_LOG_INFO("Resulting power at level %d: %d", pot_resistance_level, (uint16_t) resulting_power);
double resulting_resistance = resulting_power / getInstantaneousSpeed();
// NRF_LOG_INFO("Resulting resistance at level %d: %d", pot_resistance_level, (uint16_t) resulting_resistance);
double error = fabs(resulting_resistance - imposed_resistance);
if (error < least_error)
{
resistance_level_candidate = pot_resistance_level;
least_error = error;
}
// Early break
// There is only one minimum - once our error increases again we can stop
/*if (error > least_error)
{
char e_break[128];
sprintf(e_break, "Early exit: error (%.2f) > least error (%.2f)", error, least_error);
//NRF_LOG_INFO("%s", e_break);
break;
}
*/
}
if (resistance_level_candidate != 0xff)
{
if (resistance_level_candidate != resistance_level)
{
NRF_LOG_INFO("%s",resistance_s);
NRF_LOG_INFO("Best resistance_level = %d. Current resistance_level = %d, Current gear delta: %d", resistance_level_candidate, target_resistance_level, gear_offset);
// Change the resistance setting
if (resistance_level_candidate == 0)
{
NRF_LOG_ERROR("Impossible resistance_level_candidate");
}
// TODO/BUG: If we have resistance_level_candidate = 0
// We will assign it in the next line and the handler will assert in main()!
target_resistance_level = resistance_level_candidate;
}
}
#if BENCHMARK
execution_end = app_timer_cnt_get();
uint32_t timer_ticks = app_timer_cnt_diff_compute(execution_end,execution_start);
char buf[16];
snprintf(buf, sizeof(buf), "%.3f", (double) timer_ticks / 32.0);
NRF_LOG_INFO("Execution time resistance (ms): %s", buf);
#endif
}
void setUserWeight(uint8_t kg)
{
NRF_LOG_INFO("Set new user weight: %u", kg);
calculation_helper.userweight = kg;
}
void setBikeWeight(uint8_t kg)
{
NRF_LOG_INFO("Set new bike weight: %u", kg);
calculation_helper.bikeweight = kg;
}
uint8_t getUserWeight()
{
return calculation_helper.userweight;
}
uint8_t getBikeWeight()
{
return calculation_helper.bikeweight;
}
uint8_t getFECElapsedTime()
{
return calculation_helper.fec_data.elapsed_time;
}