/
batManagement.c
5401 lines (4532 loc) · 186 KB
/
batManagement.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
/****************************************************************************
* nxp_bms/BMS_v1/src/batManagement.c
*
* BSD 3-Clause License
*
* Copyright 2020-2022 NXP
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <stdint.h>
#include <stdbool.h>
#include <nuttx/board.h>
#include "batManagement.h"
#include <time.h>
#include <semaphore.h>
#include <math.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include "gpio.h"
#include "bcc.h"
#include "bcc_spiwrapper.h"
#include "bcc_configuration.h"
#include "bcc_monitoring.h"
#include "bcc_define.h"
#include "data.h"
#include "cli.h"
#include "spi.h"
/****************************************************************************
* Defines
****************************************************************************/
//#define OUTPUT_OTHER_FAULT
//#define DEBUG_OV_UV
//#define DEBUG_OT_UT
//#define DEBUG_FAULT_STATUS
#define DEBUG_OUTPUT_ERROR_CURRENT
#define RBAL 82 //!< [Ohm] balancing resistor (84 Ohm for the Drone BMS)
#define CALC_OTHER_PRIORITY 140
#define MEASURE_PRIORITY 120
#define SDCHAR_PRIORITY 110
#define DEFAULT_MEASURE_STACK_SIZE_L 1024 //2048
#define DEFAULT_MEASURE_STACK_SIZE_M 1536 //2048
#define DEFAULT_MEASURE_STACK_SIZE_H 2048 //2048
#define MAX_SEC 0xFFFFFFFF
//! this macro is used to print a byte value to binary, use as variable to BYTE_TO_BINARY_PATTERN
#ifndef BYTE_TO_BINARY
#define BYTE_TO_BINARY(byte) \
(byte & 0x80 ? '1' : '0'), \
(byte & 0x40 ? '1' : '0'), \
(byte & 0x20 ? '1' : '0'), \
(byte & 0x10 ? '1' : '0'), \
(byte & 0x08 ? '1' : '0'), \
(byte & 0x04 ? '1' : '0'), \
(byte & 0x02 ? '1' : '0'), \
(byte & 0x01 ? '1' : '0')
#endif
/****************************************************************************
* Types
****************************************************************************/
/*!
* @brief Enumeration to check what triggered a (software) fault.
* @note This is checked with the new measurement from the BCC.
*/
typedef enum
{
BMS_SW_CELL1_OV = (1<<BMS_FAULT_CELL1_BIT_SHIFT), /*!< there is a SW OV fault with cell 1 */
BMS_SW_CELL2_OV = (1<<BMS_FAULT_CELL2_BIT_SHIFT), /*!< there is a SW OV fault with cell 2 */
BMS_SW_CELL3_OV = (1<<BMS_FAULT_CELL3_BIT_SHIFT), /*!< there is a SW OV fault with cell 3 */
BMS_SW_CELL4_OV = (1<<BMS_FAULT_CELL4_BIT_SHIFT), /*!< there is a SW OV fault with cell 4 */
BMS_SW_CELL5_OV = (1<<BMS_FAULT_CELL5_BIT_SHIFT), /*!< there is a SW OV fault with cell 5 */
BMS_SW_CELL6_OV = (1<<BMS_FAULT_CELL6_BIT_SHIFT), /*!< there is a SW OV fault with cell 6 */
BMS_SW_AVG_OVER_CURRENT = (1<<BMS_FAULT_AVG_OVER_CURRENT_BIT_SHIFT), /*!< there is a SW average overcurrent */
BMS_SW_PEAK_OVER_CURRENT = (1<<BMS_FAULT_PEAK_OVER_CURRENT_BIT_SHIFT), /*!< there is a SW peak overcurrent */
}BMSSWFault_t;
/****************************************************************************
* private data
****************************************************************************/
// the callback functions
/*! @brief callback function to report there is an overcurrent */
swMeasuredFaultCallbackFunction g_swMeasuredFaultCallbackFunctionfp;
/*! @brief callback function to change the LED color */
changeLedColorCallbackBatFuntion g_changeLedColorCallbackBatFuntionfp;
/*! @brief callback function to act on new setted measurements */
newMeasurementsCallbackFunction g_newMeasurementsCallbackFunctionfp;
/*! @brief mutex for controlling the gate */
static pthread_mutex_t gGateLock;
/*! @brief semaphore for the continue measure task*/
static sem_t gMeasureSem;
/*! @brief to indicate the semaphore is initialized*/
static bool gMeasureSemInitialized = false;
/*! @brief semaphore for skipping the wait in the continue measure task*/
static sem_t gSkipMeasureWaitSem;
/*! @brief to indicate the semaphore is initialized*/
static bool gSkipMeasureWaitSemInitialized = false;
/*! @brief semaphore for the continue measure task*/
static sem_t gCalcOtherSem;
/*! @brief to indicate the semaphore is initialized*/
static bool gCalcOtherSemInitialized = false;
/*! @brief semaphore for the continues charging task*/
static sem_t gChargeSem;
/*! @brief to indicate the semaphore is initialized*/
static bool gChargeSemInitialized = false;
/*! @brief semaphore for the self discharge task*/
static sem_t gSdChargeSem;
/*! @brief to indicate the semaphore is initialized*/
static bool gSdChargeSemInitialized = false;
/*! @brief semaphore to enable the do selfdischarge function*/
static sem_t gDoSdChargeSem;
/*! @brief to indicate the semaphore is initialized*/
static bool gDoSdChargeSemInitialized = false;
/*! @brief semaphore to enable the do selfdischarge function*/
static sem_t gDoCellBalanceSem;
/*! @brief to indicate the semaphore is initialized*/
static bool gDoCellBalanceSemInitialized = false;
/*! @brief variable to indicate of it is initialized */
static bool gBatManInitialized = false;
static uint32_t gMeasCycleTime = 1000;
//static bool gMeasCycleLessThan1s = false;
static struct timespec gTargetTime;
/*! @brief variable to pass to the sdchar task */
static bool gSelfDischargeOn = false;
/*! @brief variable to pass to the sdchar task */
static bool gCellBalanceOn = false;
/*! @brief variable to slow down the current measurement to t-meas
can be used to reduce MCU load */
static bool gSlowCurrentMeasurements = false;
/*! @brief mutex for the measureTime */
static pthread_mutex_t gMeasureTimeMutex;
static bool gMeasureTimeMutexInitialized = false;
/*! @brief mutex for the balancing value */
static pthread_mutex_t gBalanceCellsMutex;
static bool gBalanceCellsMutexInitialized = false;
/*! @brief mutex for the discharing handshake variable value */
static pthread_mutex_t gDisCharHandshakeVarMutex;
static bool gDisCharHandshakeVarMutexInitialized = false;
/*! @brief mutex for the balancing value */
static pthread_mutex_t gEndOfChargeValueMutex;
static bool gEndOfChargeValueMutexInitialized = false;
/*! @brief mutex for the balancing value */
static pthread_mutex_t gChargeToStorageVarMutex;
static bool gChargeToStorageVarMutexInitialized = false;
/*! @brief mutex for the chargingstate variable */
static pthread_mutex_t chargingStateMutex;
static bool chargingStateMutexInitialized = false;
/*! @brief [-] BCC configuration data */
//bcc_data_t g_bccData;
bcc_drv_config_t gBccDrvConfig;
/*! @brief [-] BCC CT filter configuration data */
ct_filter_t g_ctFilterComp;
/*! @brief [-] BCC I-sense filter configuration data */
isense_filter_t g_isenseFilterComp;
/*! @brief [-] BCC NTC configuration data */
ntc_config_t g_ntcConfig;
/*! @brief variable to keep track of the lowest cell voltage */
float gLowestCellVoltage = V_CELL_OV_DEFAULT;
/*! @brief Variable to keep track of a sw defined fault using the BMSSWFault_t enum */
uint32_t gSWFaultVariable = 0;
/****************************************************************************
* private Functions
****************************************************************************/
/*!
* @brief function to do the meanual measurements, calculate current
* and if the semaphore is availeable read the rest and do the calculations
*
* @param argc the amount of arguments there are in argv (if the last argument is NULL!)
* @param argv a character pointer array with the arguments, first is the taskname than the arguments
*/
static int batManagement_MeasTaskFunc(int argc, char *argv[]);
/*!
* @brief function to increase the semaphore at the right time to calculate the other measurements
*
* @param the amount of arguments there are in argv (if the last argument is NULL!)
* @param a character pointer array with the arguments, first is the taskname than the arguments
*/
static int batManagement_OtherCalcTaskFunc(int argc, char *argv[]);
/*!
* @brief function to check if the discharging/CB is done
*
* @param the amount of arguments there are in argv (if the last argument is NULL!)
* @param a character pointer array with the arguments, first is the taskname than the arguments
*/
static int batManagement_SelfDischargeTaskFunc(int argc, char *argv[]);
/*!
* @brief function used to calculate the new measureinterval to read and calculate
* voltages and temperatures
* it will set the variable gMeasCycleTime with the right value
*
* @param measMs the send interval in ms
*/
static void batManagement_calcSendInterval(uint16_t measMs);
/*!
* @brief function to initialize the BCC
* could return without init if communication failed!
*
* @param none
* @return the bcc status from bcc_status_t
*/
static bcc_status_t BatManagement_initializeBCC(void);
/*!
* @brief function to set the battery under and over temperature threshold
*
* @param chargingMode true if the temperature thresholds are set for the charging mode.
* false if the temperature thresholds are set for the normal mode
* @return the bcc status
*/
static bcc_status_t batManagement_setBatTempTHState(bool chargingMode);
/*!
* @brief function to set of get the chargingMode variable
*
* @param set true if the value is being set, false if get
* @param setValue if set is true, this is the new value of it
*
* @return the value of the chargingMode variable
*/
static bool batManagement_setNGetChargingState(bool set, bool setValue);
/*!
* @brief function to set of get the active balancing cells the battery under and over temperature threshold
* this function can be used by multiple threads
*
* @param set true if the value is being set, false if get
* @param setValue if set is true, this is the new value of it
*
* @return the value of the activeBalancingCells, UINT8_MAX if failed
*/
static uint8_t batManagement_setNGetActiveBalancingCells(bool set, uint8_t setValue);
/*!
* @brief function to set of get the dischargingHandshakeVariable variable
*
* @param forSelfDischarge if this is true it is for the self discharge handshake,
otherwise it is for the balancing handshake
* @param set true if the value is being set, false if get
* @param setValue if set is true, this is the new value of it
*
* @return the value of the dischargingHandshakeVariable variable or UINT8_MAX for error
*/
static uint8_t batManagement_setNGetDisCharHandshakeVar(bool forSelfDischarge, bool set, bool setValue);
/****************************************************************************
* main
****************************************************************************/
/*!
* @brief this function initializes the battery management unit
*
* It will configure the BCC, connect the callback functions
* and set the power switches open, disconecting the battery
*
* @param p_swMeasuredFaultCallbackFunction the address of the function to call when a sw measured fault occured.
* @param p_changeLedColorCallbackBatFuntion the address of the function to call to change the LED color
* @param p_newMeasurementsCallbackFunction the address of the function to call when new data is set
* should be quick
* @param skipSelfTest if this is true it will skip the self-test
*
* @return If successful, the function will return zero (OK). Otherwise, an error number will be returned to indicate the error:
*
*/
int batManagement_initialize(swMeasuredFaultCallbackFunction p_swMeasuredFaultCallbackFunction,
changeLedColorCallbackBatFuntion p_changeLedColorCallbackBatFuntion,
newMeasurementsCallbackFunction p_newMeasurementsCallbackFunction,
bool skipSelfTest)
{
int lvRetValue = !gBatManInitialized;
int error, errcode;
bool boolValue = 1;
float current = 0.0;
uint8_t sleepCurrentmA = 0;
// check if already configured
if(!gBatManInitialized)
{
// connect the callback functions
g_swMeasuredFaultCallbackFunctionfp = p_swMeasuredFaultCallbackFunction;
g_changeLedColorCallbackBatFuntionfp = p_changeLedColorCallbackBatFuntion;
g_newMeasurementsCallbackFunctionfp = p_newMeasurementsCallbackFunction;
// initialze the mutex
pthread_mutex_init(&gGateLock, NULL);
pthread_mutex_init(&gMeasureTimeMutex, NULL);
gMeasureTimeMutexInitialized = true;
pthread_mutex_init(&gBalanceCellsMutex, NULL);
gBalanceCellsMutexInitialized = true;
pthread_mutex_init(&gDisCharHandshakeVarMutex, NULL);
gDisCharHandshakeVarMutexInitialized = true;
pthread_mutex_init(&gEndOfChargeValueMutex, NULL);
gEndOfChargeValueMutexInitialized = true;
pthread_mutex_init(&gChargeToStorageVarMutex, NULL);
gChargeToStorageVarMutexInitialized = true;
pthread_mutex_init(&chargingStateMutex, NULL);
chargingStateMutexInitialized = true;
// initialize the semaphore in the monitoring part
error = bcc_monitoring_initializeSem();
// check for errors
if(error)
{
cli_printfError("batManagement ERROR: failed to initialze sem! error: %d\n",
error);
return error;
}
// initialize the semaphore
error = sem_init(&gMeasureSem, 0, 0);
if(error)
{
// output to user
cli_printfError("batManagement ERROR: failed to initialze sem! error: %d\n",
error);
}
else
{
sem_setprotocol(&gMeasureSem, SEM_PRIO_NONE);
// set the variable true
gMeasureSemInitialized = true;
}
// initialize the semaphore
error = sem_init(&gSkipMeasureWaitSem, 0, 0);
if(error)
{
// output to user
cli_printfError("batManagement ERROR: failed to initialze sem! error: %d\n",
error);
}
else
{
sem_setprotocol(&gSkipMeasureWaitSem, SEM_PRIO_NONE);
// set the variable true
gSkipMeasureWaitSemInitialized = true;
}
// initialize the semaphore
error = sem_init(&gCalcOtherSem, 0, 0);
if(error)
{
// output to user
cli_printfError("batManagement ERROR: failed to initialze other sem! error: %d\n",
error);
}
else
{
sem_setprotocol(&gCalcOtherSem, SEM_PRIO_NONE);
// set the variable true
gCalcOtherSemInitialized = true;
}
// initialize the semaphore
error = sem_init(&gChargeSem, 0, 0);
if(error)
{
// output to user
cli_printfError("batManagement ERROR: failed to initialze charge sem! error: %d\n",
error);
}
else
{
sem_setprotocol(&gChargeSem, SEM_PRIO_NONE);
// set the variable true
gChargeSemInitialized = true;
}
// initialize the semaphore
error = sem_init(&gSdChargeSem, 0, 0);
if(error)
{
// output to user
cli_printfError("batManagement ERROR: failed to initialze sdchar sem! error: %d\n",
error);
}
else
{
sem_setprotocol(&gSdChargeSem, SEM_PRIO_NONE);
// set the variable true
gSdChargeSemInitialized = true;
}
// initialize the semaphore
error = sem_init(&gDoSdChargeSem, 0, 0);
if(error)
{
// output to user
cli_printfError("batManagement ERROR: failed to initialze dosdchar sem! error: %d\n",
error);
}
else
{
sem_setprotocol(&gDoSdChargeSem, SEM_PRIO_NONE);
// set the variable true
gDoSdChargeSemInitialized = true;
}
// initialize the semaphore
error = sem_init(&gDoCellBalanceSem, 0, 0);
if(error)
{
// output to user
cli_printfError("batManagement ERROR: failed to initialze docellbalance sem! error: %d\n",
error);
}
else
{
sem_setprotocol(&gDoCellBalanceSem, SEM_PRIO_NONE);
// set the variable true
gDoCellBalanceSemInitialized = true;
}
// create the task
lvRetValue = task_create("meas", MEASURE_PRIORITY,
DEFAULT_MEASURE_STACK_SIZE_H, batManagement_MeasTaskFunc, NULL);
// check for errors
if(lvRetValue < 0)
{
// inform user
errcode = errno;
cli_printfError("batManagement ERROR: Failed to start task: %d\n", errcode);
return lvRetValue;
}
// create the task
lvRetValue = task_create("otherCalc", CALC_OTHER_PRIORITY,
DEFAULT_MEASURE_STACK_SIZE_L, batManagement_OtherCalcTaskFunc, NULL);
// check for errors
if(lvRetValue < 0)
{
// inform user
errcode = errno;
cli_printfError("batManagement ERROR: Failed to start task: %d\n", errcode);
return lvRetValue;
}
// create the task
lvRetValue = task_create("sdchar", SDCHAR_PRIORITY,
DEFAULT_MEASURE_STACK_SIZE_M, batManagement_SelfDischargeTaskFunc, NULL);
// check for errors
if(lvRetValue < 0)
{
// inform user
errcode = errno;
cli_printfError("batManagement ERROR: Failed to start task: %d\n", errcode);
return lvRetValue;
}
// initialize SPI mutex
lvRetValue = BCC_initialze_spi_mutex();
if(lvRetValue)
{
cli_printfError("batManagement ERROR: failed to initialze spi mutex!\n");
return lvRetValue;
}
// set that the battery management is configured
gBatManInitialized = true;
// reset the BCC
// write the reset pin
lvRetValue = gpio_writePin(BCC_RESET, 1);
// check if it went wrong
if(lvRetValue)
{
cli_printfError("batManagement ERROR: writing BCC_RESET high went wrong!\n");
cli_printf("SELF-TEST GPIO: \e[31mFAIL\e[39m\n");
return lvRetValue;
}
// wait a time longer than needed
usleep(1000);
// pull down the reset pin
lvRetValue = gpio_writePin(BCC_RESET, 0);
// check if it went wrong
if(lvRetValue)
{
cli_printfError("batManagement ERROR: writing BCC_RESET low went wrong!\n");
cli_printf("SELF-TEST GPIO: \e[31mFAIL\e[39m\n");
return lvRetValue;
}
// check if the reset does not come from the external watchdog
if(!(skipSelfTest))
{
//turn off the gate
lvRetValue = batManagement_setGatePower(GATE_OPEN);
// check if it went wrong
if(lvRetValue)
{
cli_printfError("batManagement ERROR: opening the gate went wrong!\n");
cli_printf("SELF-TEST GPIO: \e[31mFAIL\e[39m\n");
return lvRetValue;
}
cli_printf("SELF-TEST BCC: START\n");
}
else
{
// output warning
cli_printfWarning("WARNING: not turning off power due to watchdog reset!\n");
}
// initalize the BCC
lvRetValue = BatManagement_initializeBCC();
// check for errors
if(lvRetValue != BCC_STATUS_SUCCESS)
{
// inform user
//errcode = errno;
cli_printfError("batManagement ERROR: Failed to initialze BCC: %d\n",
lvRetValue);
// Check if the self-test shouldn't be skipped
if(!skipSelfTest)
{
cli_printf("SELF-TEST BCC: \e[31mFAIL\e[39m\n");
return lvRetValue;
}
}
// Check if the self-test shouldn't be skipped
if(!skipSelfTest)
{
cli_printf("SELF-TEST BCC: \e[32mPASS\e[39m\n");
// do the Gate check at least once
do
{
cli_printf("SELF-TEST GATE: START\n");
//turn off the gate
batManagement_setGatePower(GATE_OPEN);
// check the gate output to verify if it works
// do a measurement
lvRetValue = bcc_monitoring_doBlockingMeasurement(&gBccDrvConfig);
// check for errors
if(lvRetValue != 0)
{
// inform user
//errcode = errno;
cli_printfError("batManagement ERROR: Failed to do measurement: %d\n",
lvRetValue);
cli_printf("SELF-TEST GATE: \e[31mFAIL\e[39m\n");
return lvRetValue;
}
// get the output voltage and check if it is off
// read the output voltage
lvRetValue = bcc_monitoring_checkOutput(&gBccDrvConfig, &boolValue);
// check for errors
if(lvRetValue != 0)
{
// inform user
//errcode = errno;
cli_printfError("batManagement ERROR: Failed get output: %d\n", lvRetValue);
cli_printf("SELF-TEST GATE: \e[31mFAIL\e[39m\n");
return lvRetValue;
}
// check if the output is high
if(boolValue == 1)
{
cli_printfError("batManagement ERROR: Failed to disable the gate!\n");
cli_printf("Make sure there is no charger connected and press the button to try again\n");
cli_printf("SELF-TEST GATE: \e[31mFAIL\e[39m\n");
//lvRetValue = BCC_STATUS_DIAG_FAIL;
// set the LED color to indicate the charger is connected and is wrong
g_changeLedColorCallbackBatFuntionfp(RED, BLUE, LED_BLINK_ON);
// loop until the button is not pushed
while(!gpio_readPin(SBC_WAKE))
{
// wait for a little while
usleep(1000*10);
}
// loop until the button is pushed
while(gpio_readPin(SBC_WAKE))
{
// wait for a little while
usleep(1000*10);
}
}
// loop while the output is high
}while(boolValue == 1);
// change the LED color to RED again
g_changeLedColorCallbackBatFuntionfp(RED, OFF, LED_BLINK_OFF);
cli_printf("SELF-TEST GATE: \e[32mPASS\e[39m\n");
cli_printf("SELF-TEST CURRENT_SENSE: START\n");
// get the sleepcurrent
if(data_getParameter(I_SLEEP_OC, &sleepCurrentmA, NULL) == NULL)
{
cli_printfError("batManagement ERROR: getting sleepcurrent went wrong!\n");
sleepCurrentmA = I_SLEEP_OC_DEFAULT;
}
// do a blockingmeasurement
lvRetValue = bcc_monitoring_doBlockingMeasurement(&gBccDrvConfig);
// check for errors
if(lvRetValue != 0)
{
// inform user
cli_printfError("batManagement ERROR: Failed to do measurement: %d\n",
lvRetValue);
cli_printf("SELF-TEST CURRENT_SENSE: \e[31mFAIL\e[39m\n");
return lvRetValue;
}
// get the ISENSE pin open load value
lvRetValue = bcc_monitoring_getIsenseOpenLoad(&gBccDrvConfig, &boolValue);
// check for errors
if(lvRetValue != 0)
{
// inform user
//errcode = errno;
cli_printfError("batManagement ERROR: Failed to open load value: %d\n",
lvRetValue);
cli_printf("SELF-TEST CURRENT_SENSE: \e[31mFAIL\e[39m\n");
return lvRetValue;
}
// check if the ISENSE pins have an open load
if(boolValue)
{
// there is an ISENSE pins open load detected
cli_printfError("batManagement ERROR: ISENSE open load pin detected!\n");
cli_printf("SELF-TEST CURRENT_SENSE: \e[31mFAIL\e[39m\n");
return BCC_STATUS_PARAM_RANGE;
}
// set the current in the struct
lvRetValue = bcc_monitoring_getBattCurrent(&gBccDrvConfig, SHUNT_RESISTOR_UOHM);
// check for errors
if(lvRetValue != 0)
{
// inform user
cli_printfError("batManagement ERROR: Failed to read current: %d\n",
lvRetValue);
cli_printf("SELF-TEST CURRENT_SENSE: \e[31mFAIL\e[39m\n");
return lvRetValue;
}
// get the batterycurrent
if(data_getParameter(I_BATT, ¤t, NULL) == NULL)
{
cli_printfError("batManagement ERROR: getting current went wrong!\n");
current = I_BATT_MAX;
}
// check if the abs current is higher than the sleepcurrent or the overcurrent is hight
if(((int)(fabs(current)*1000) > sleepCurrentmA) || (gpio_readPin(OVERCURRENT)))
{
// why did it happend?
if(((int)(fabs(current)*1000) > sleepCurrentmA))
{
cli_printfError("BatManagement ERROR: current: |%.3fA| > %.3fA\n",
current, (float)sleepCurrentmA/1000.0);
}
else
{
cli_printfError("BatManagement ERROR: overcurrent pin high!\n");
}
// output that the test has failed
cli_printf("SELF-TEST CURRENT_SENSE: \e[31mFAIL\e[39m\n");
return BCC_STATUS_PARAM_RANGE;
}
// mention that the self test has passed
cli_printf("SELF-TEST CURRENT_SENSE: \e[32mPASS\e[39m\n");
}
// if the self test should be skipped
else
{
// make sure to set the current in the struct
// do a blockingmeasurement
lvRetValue = bcc_monitoring_doBlockingMeasurement(&gBccDrvConfig);
// check for errors
if(lvRetValue != 0)
{
// inform user
cli_printfError("batManagement ERROR: Failed to do measurement: %d\n",
lvRetValue);
}
// set the current in the struct
lvRetValue = bcc_monitoring_getBattCurrent(&gBccDrvConfig,
SHUNT_RESISTOR_UOHM);
// check for errors
if(lvRetValue != 0)
{
// inform user
cli_printfError("batManagement ERROR: Failed to read current: %d\n",
lvRetValue);
}
}
// change the return value
lvRetValue = !gBatManInitialized;
}
// return the value
return lvRetValue;
}
/*!
* @brief This function is used to set the gate driver it can turns the gate driver OFF,
* so output power is OFF. But it can also set it on, enabling output power.
* Does not function when in over-current (hardware protection turns
* the gate driver OFF automatically).
* This function is protected against multiple threads using this or the on function
* batManagement_initialize should be called before calling this function
*
* @param on if true the gate will be set on, otherwise it will be set off
*
* @return If successful, the function will return zero (OK). Otherwise, an error number will be returned to indicate the error.
*/
int batManagement_setGatePower(bool on)
{
int lvRetValue = -1;
// check if initialized
if(!gBatManInitialized)
{
// error
cli_printfError("batmanagement ERROR: Battery management not initialized, pleaze initialze\n");
return lvRetValue;
}
// set return value for 0, if everything goes right it will stay 0
lvRetValue = 0;
// lock the mutex
pthread_mutex_lock(&gGateLock);
// Set Data pin to 1 so GATE_IN signal turns 1 (power OFF) when clock rises.
lvRetValue += gpio_writePin(GATE_CTRL_D, !on);
// check if writing GATE_CTRL_D went wrong
if(lvRetValue)
{
cli_printfError("batmanagement ERROR: could not write GATE_CTRL_D to %d\n", !on);
}
// Reset then set again Clock signal so Data gets through the flip-flop
lvRetValue += gpio_writePin(GATE_CTRL_CP, 0);
// N.B.: flip-flop is working on rising edge.
lvRetValue += gpio_writePin(GATE_CTRL_CP, 1);
// Reset pin for idle mode.
lvRetValue += gpio_writePin(GATE_CTRL_CP, 0);
// unlock the mutex
pthread_mutex_unlock(&gGateLock);
// return value to the user
return lvRetValue;
}
/*!
* @brief This function is used to check the AFE.
* It will check the fault masks of the AFE and set it in the variable
* It will check the whole configuration and change it if possible.
* batManagement_initialize should be called before calling this function
*
* @param BMSFault this is the address of the uint32_t variable to store the error (from the BMSFault_t enum)
* @param resetFaultPin this will reset the BCC_FAULT pin if it is up.
*
* @return If successful, the function will return zero (OK). Otherwise, an error number will be returned to indicate the error.
*/
int batManagement_checkAFE(uint32_t *BMSFault, bool resetFaultPin)
{
int lvRetValue = 0;
// check for faults
batManagement_checkFault(BMSFault, resetFaultPin);
return lvRetValue;
}
/*!
* @brief This function is used to check what the fault is.
* It will check the fault masks of the AFE and set it in the variable
* batManagement_initialize should be called before calling this function
*
* @param BMSFault this is the address of the uint32_t variable to store the error (from the BMSFault_t enum)
* @param resetFaultPin this will reset the BCC_FAULT pin if it is up.
*
* @return If successful, the function will return zero (OK). Otherwise, an error number will be returned to indicate the error.
*/
int batManagement_checkFault(uint32_t *BMSFault, bool resetFaultPin)
{
int lvRetValue = -1, i;
bcc_status_t lvBccStatus;
bcc_fault_status_t resetBCCFaultValue;
uint16_t lvBccFaultStatus[BCC_STAT_CNT];
uint8_t NumCells = 0;
uint8_t checkBCCCell = 0;
int32_t *dataReturn = NULL;
//float lvCurrent, lvMaxCurrent;
uint16_t maskedFaultReg = 0;
// reset the fault value
*BMSFault = 0;
// check for a software fault (sw cell ov, peak overcurrent, overcurrent)
if(gSWFaultVariable)
{
// set the fault
*BMSFault |= gSWFaultVariable;
// check if there was a cell ov
if(gSWFaultVariable & (BMS_SW_CELL1_OV + BMS_SW_CELL2_OV +
BMS_SW_CELL3_OV + BMS_SW_CELL4_OV + BMS_SW_CELL5_OV +
BMS_SW_CELL6_OV))
{
// set the sw cell ov bit
*BMSFault |= BMS_SW_CELL_OV;
}
// check if the fault needs to be reset
if(resetFaultPin)
{
// make sure to trigger a fault in order to act on the SW fault
g_swMeasuredFaultCallbackFunctionfp(true);
}
}
// get the amount of cells
dataReturn = (int32_t*)data_getParameter(N_CELLS, &NumCells, NULL);
if(dataReturn == NULL)
{
cli_printfError("batManagement_checkFault ERROR: couldn't get num cells\n");
return lvRetValue;
}
// lock the BCC SPI for this thread
if(spi_lockNotUnlockBCCSpi(true))
{
cli_printfError("batManagement_checkFault ERROR: Couldn't lock spi\n");
}
// get the BCC fault
lvBccStatus = bcc_spiwrapper_BCC_Fault_GetStatus(&gBccDrvConfig, BCC_CID_DEV1, lvBccFaultStatus);
// unlock the BCC spi
if(spi_lockNotUnlockBCCSpi(false))
{
cli_printfError("batManagement_checkFault ERROR: Couldn't unlock spi\n");
}
#ifdef DEBUG_FAULT_STATUS
for(i = 0; i < BCC_STAT_CNT; i++)
{
if(lvBccFaultStatus[i])
{
cli_printf("faultStatus[%d]: %d\n", i, lvBccFaultStatus[i]);
}
}
#endif
// check the OV and UV fault
for(i = 0; i < NumCells; i++)
{
// check which bcc cell it is
if(i >= 2)
{
// calculat the BCC pin index
checkBCCCell = (6-NumCells) + i;
}
else
{
// it is the first 2 cells
checkBCCCell = i;
}
// check for an cell overvoltage
if((lvBccFaultStatus[BCC_FS_CELL_OV] >> checkBCCCell) & 1)
{
// set the cell and overvoltage
*BMSFault |= (1<<i);
*BMSFault |= BMS_CELL_OV;
#ifdef DEBUG_OV_UV
cli_printf("OV on: cell%d\n", i+1);
dataReturn = (int32_t*)data_getParameter((parameterKind_t)(V_CELL1 + i),
&lvCurrent, NULL);
if(dataReturn == NULL)
{
cli_printfError("batManagement_checkFault ERROR: couldn't get cell voltage\n");
}
else
{
cli_printf("cell %d voltage: %.3f\n", i+1, lvCurrent);
}
#endif
}
// check for cell undervoltage
if((lvBccFaultStatus[BCC_FS_CELL_UV] >> checkBCCCell) & 1)
{
// set the cell and undervoltage