summaryrefslogtreecommitdiffstats
path: root/firmware/powermgmt.c
blob: 17acd3d5035f228e7cdaca9eb63140e79307f419 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
/***************************************************************************
 *             __________               __   ___.
 *   Open      \______   \ ____   ____ |  | _\_ |__   _______  ___
 *   Source     |       _//  _ \_/ ___\|  |/ /| __ \ /  _ \  \/  /
 *   Jukebox    |    |   (  <_> )  \___|    < | \_\ (  <_> > <  <
 *   Firmware   |____|_  /\____/ \___  >__|_ \|___  /\____/__/\_ \
 *                     \/            \/     \/    \/            \/
 * $Id$
 *
 * Copyright (C) 2002 by Heikki Hannikainen, Uwe Freese
 * Revisions copyright (C) 2005 by Gerald Van Baren
 *
 * All files in this archive are subject to the GNU General Public License.
 * See the file COPYING in the source tree root for full license agreement.
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
 * KIND, either express or implied.
 *
 ****************************************************************************/
#include "config.h"
#include "cpu.h"
#include "kernel.h"
#include "thread.h"
#include "system.h"
#include "debug.h"
#include "panic.h"
#include "adc.h"
#include "string.h"
#include "sprintf.h"
#include "ata.h"
#include "power.h"
#include "button.h"
#include "ata.h"
#include "audio.h"
#include "mp3_playback.h"
#include "usb.h"
#include "powermgmt.h"
#include "backlight.h"
#include "lcd.h"
#include "rtc.h"
#ifdef CONFIG_TUNER
#include "fmradio.h"
#endif
#ifdef HAVE_UDA1380
#include "uda1380.h"
#elif defined(HAVE_TLV320)
#include "tlv320.h"
#elif defined(HAVE_WM8758)
#include "wm8758.h"
#elif defined(HAVE_WM8975)
#include "wm8975.h"
#elif defined(HAVE_WM8731)
#include "wm8731l.h"
#endif
#ifdef HAVE_LCD_BITMAP
#include "font.h"
#endif
#if defined(HAVE_RECORDING) && (CONFIG_CODEC == SWCODEC)
#include "pcm_record.h"
#endif
#include "logf.h"
#include "lcd-remote.h"
#ifdef SIMULATOR
#include <time.h>
#endif

#if defined(IAUDIO_X5) && !defined (SIMULATOR)
#include "pcf50606.h"
#include "lcd-remote-target.h"
#endif

/*
 * Define DEBUG_FILE to create a csv (spreadsheet) with battery information
 * in it (one sample per minute).  This is only for very low level debug.
 */
#undef  DEBUG_FILE
#if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
#include "file.h"
#define DEBUG_FILE_NAME   "/powermgmt.csv"
#define DEBUG_MESSAGE_LEN 133
static char debug_message[DEBUG_MESSAGE_LEN];
#define DEBUG_STACK ((0x1000)/sizeof(long))
static int fd;          /* write debug information to this file */
static int wrcount;
#else
#define DEBUG_STACK 0
#endif

static int shutdown_timeout = 0;

#ifdef SIMULATOR /***********************************************************/

#define TIME2CHANGE     10              /* change levels every 10 seconds */
#define BATT_MINCVOLT   250             /* minimum centivolts of battery */
#define BATT_MAXCVOLT   450             /* maximum centivolts of battery */
#define BATT_MAXRUNTIME (10 * 60)       /* maximum runtime with full battery in minutes */

static unsigned int batt_centivolts = (unsigned int)BATT_MAXCVOLT;
static int batt_level = 100;            /* battery capacity level in percent */
static int batt_time = BATT_MAXRUNTIME; /* estimated remaining time in minutes */
static time_t last_change = 0;

static void battery_status_update(void)
{
    time_t          now;

    time(&now);
    if (last_change < (now - TIME2CHANGE)) {
        last_change = now;

        /* change the values: */
        batt_centivolts -= (unsigned int)(BATT_MAXCVOLT - BATT_MINCVOLT) / 11;
        if (batt_centivolts < (unsigned int)BATT_MINCVOLT)
            batt_centivolts = (unsigned int)BATT_MAXCVOLT;

        batt_level = 100 * (batt_centivolts - BATT_MINCVOLT) / (BATT_MAXCVOLT - BATT_MINCVOLT);
        batt_time = batt_level * BATT_MAXRUNTIME / 100;
    }
}

void battery_read_info(int *adc, int *voltage, int *level)
{
    battery_status_update();

    if (adc)
        *adc = batt_centivolts; /* just return something */

    if (voltage)
        *voltage = batt_centivolts;

    if (level)
        *level = batt_level;
}

unsigned int battery_voltage(void)
{
    battery_status_update();
    return batt_centivolts;
}

int battery_level(void)
{
    battery_status_update();
    return batt_level;
}

int battery_time(void)
{
    battery_status_update();
    return batt_time;
}

bool battery_level_safe(void)
{
    return battery_level() >= 10;
}

bool battery_level_critical(void)
{
    return false;
}

void set_poweroff_timeout(int timeout)
{
    (void)timeout;
}

void set_battery_capacity(int capacity)
{
  (void)capacity;
}

void reset_poweroff_timer(void)
{
}


#else /* not SIMULATOR ******************************************************/

static const int poweroff_idle_timeout_value[15] =
{
    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 30, 45, 60
};

static const unsigned int battery_level_dangerous[BATTERY_TYPES_COUNT] =
{
#if CONFIG_BATTERY == BATT_LIION2200    /* FM Recorder, LiIon */
    280
#elif CONFIG_BATTERY == BATT_3AAA       /* Ondio: Alkaline, NiHM */
    310, 345
#elif CONFIG_BATTERY == BATT_1AA        /* iRiver iFP: Alkaline, NiHM */
    105, 115
#elif CONFIG_BATTERY == BATT_LIPOL1300  /* iRiver H1x0: LiPolymer */
    338
#elif CONFIG_BATTERY == BATT_IAUDIO_X5  /* iAudio X5 */
    354
#elif CONFIG_BATTERY == BATT_LPCS355385 /* iriver H10 20GB: LiPolymer*/
    376
#elif CONFIG_BATTERY == BATT_BP009      /* iriver H10 5/6GB: LiPolymer */
    372
#else                                   /* Player/recorder: NiMH */
    475
#endif
};

static const unsigned short battery_level_shutoff[BATTERY_TYPES_COUNT] =
{
#if   CONFIG_BATTERY == BATT_LIION2200  /* FM Recorder */
    258
#elif CONFIG_BATTERY == BATT_3AAA       /* Ondio */
    270, 280
#elif CONFIG_BATTERY == BATT_LIPOL1300  /* iRiver Hxxx */
    299
#elif CONFIG_BATTERY == BATT_IAUDIO_X5  /* iAudio X5 */
    350
#elif CONFIG_BATTERY == BATT_LPCS355385 /* iriver H10 20GB */
    365
#elif CONFIG_BATTERY == BATT_BP009      /* iriver H10 5/6GB */
    365
#else                                   /* Player/recorder: NiMH */
    440
#endif
};

/* voltages (centivolt) of 0%, 10%, ... 100% when charging disabled */
static const unsigned short percent_to_volt_discharge[BATTERY_TYPES_COUNT][11] =
{
#if CONFIG_BATTERY == BATT_LIION2200
    /* measured values */
    { 260, 285, 295, 303, 311, 320, 330, 345, 360, 380, 400 }
#elif CONFIG_BATTERY == BATT_3AAA
    /* measured values */
    { 280, 325, 341, 353, 364, 374, 385, 395, 409, 427, 475 }, /* Alkaline */
    { 310, 355, 363, 369, 372, 374, 376, 378, 380, 386, 405 }  /* NiMH */
#elif CONFIG_BATTERY == BATT_LIPOL1300
    /* Below 337 the backlight starts flickering during HD access */
     { 337, 365, 370, 374, 378, 382, 387, 393, 400, 408, 416 }
#elif CONFIG_BATTERY == BATT_IAUDIO_X5
    /* iAudio x5 series  - still experimenting with best curve */
// Lithium ion discharge curve
    { 355, 356, 357, 359, 362, 365, 369, 374, 380, 387, 395 }
// Linear
//  { 355, 360, 364, 369, 373, 378, 382, 387, 391, 390, 400 }
//  { 355, 359, 363, 367, 371, 375, 379, 383, 387, 391, 395 }
#elif CONFIG_BATTERY == BATT_LPCS355385
    /* iriver H10 20GB */
    { 376, 380, 385, 387, 390, 395, 402, 407, 411, 418, 424 }
#elif CONFIG_BATTERY == BATT_BP009
    /* iriver H10 5/6GB */
    { 372, 374, 380, 382, 384, 388, 394, 402, 406, 415, 424 }
#elif CONFIG_BATTERY == BATT_1AA
    /* These values are the same as for 3AAA divided by 3. */
    /* May need recalibration. */
    {  93, 108, 114, 118, 121, 125, 128, 132, 136, 142, 158 }, /* alkaline */
    { 103, 118, 121, 123, 124, 125, 126, 127, 128, 129, 135 }  /* NiMH */
#else /* NiMH */
    /* original values were taken directly after charging, but it should show
       100% after turning off the device for some hours, too */
    { 450, 481, 491, 497, 503, 507, 512, 514, 517, 525, 540 }
                                            /* orig. values: ...,528,560 */
#endif
};

#ifdef CONFIG_CHARGING
charger_input_state_type charger_input_state IDATA_ATTR;

/* voltages (centivolt) of 0%, 10%, ... 100% when charging enabled */
static const unsigned short percent_to_volt_charge[11] =
{
#if CONFIG_BATTERY == BATT_LIPOL1300
    /* values measured over one full charging cycle */
    354, 386, 393, 398, 400, 402, 404, 408, 413, 418, 423 /* LiPo */
#elif CONFIG_BATTERY == BATT_LPCS355385
    /* iriver H10 20GB */
    399, 403, 406, 408, 410, 412, 415, 418, 422, 426, 431
#elif CONFIG_BATTERY == BATT_BP009
    /* iriver H10 5/6GB: Not yet calibrated */
    388, 392, 396, 400, 406, 410, 415, 419, 424, 428, 433
#else
    /* values guessed, see
       http://www.seattlerobotics.org/encoder/200210/LiIon2.pdf until someone
       measures voltages over a charging cycle */
    476, 544, 551, 556, 561, 564, 566, 576, 582, 584, 585 /* NiMH */
#endif
};
#endif /* CONFIG_CHARGING */

#if CONFIG_CHARGING >= CHARGING_MONITOR
charge_state_type charge_state;     /* charging mode */
#endif

#if CONFIG_CHARGING == CHARGING_CONTROL
int long_delta;                     /* long term delta battery voltage */
int short_delta;                    /* short term delta battery voltage */
bool disk_activity_last_cycle = false;         /* flag set to aid charger time
                                                * calculation */
char power_message[POWER_MESSAGE_LEN] = "";    /* message that's shown in
                                                  debug menu */
                                               /* percentage at which charging
                                                  starts */
int powermgmt_last_cycle_startstop_min = 0;    /* how many minutes ago was the
                                                  charging started or
                                                  stopped? */
int powermgmt_last_cycle_level = 0;            /* which level had the
                                                  batteries at this time? */
int trickle_sec = 0;                           /* how many seconds should the
                                                  charger be enabled per
                                                  minute for trickle
                                                  charging? */
int pid_p = 0;                      /* PID proportional term */
int pid_i = 0;                      /* PID integral term */
#endif /* CONFIG_CHARGING == CHARGING_CONTROL */

/*
 * Average battery voltage and charger voltage, filtered via a digital
 * exponential filter.
 */
static unsigned int avgbat;     /* average battery voltage (filtering) */
static unsigned int battery_centivolts;/* filtered battery voltage, centvolts */
#ifdef HAVE_CHARGE_CTRL
#define BATT_AVE_SAMPLES    32  /* filter constant / @ 2Hz sample rate */
#elif CONFIG_BATTERY == BATT_LIPOL1300
#define BATT_AVE_SAMPLES   128  /* slow filter for iriver */
#else
#define BATT_AVE_SAMPLES    64  /* medium filter constant for all others */
#endif

/* battery level (0-100%) of this minute, updated once per minute */
static int battery_percent  = -1;
static int battery_capacity = BATTERY_CAPACITY_DEFAULT; /* default value, mAh */
static int battery_type     = 0;

/* Power history: power_history[0] is the newest sample */
unsigned short power_history[POWER_HISTORY_LEN];

static char power_stack[DEFAULT_STACK_SIZE/2 + DEBUG_STACK];
static const char power_thread_name[] = "power";

static int poweroff_timeout = 0;
static int powermgmt_est_runningtime_min = -1;
static bool low_battery = false;

static bool sleeptimer_active = false;
static long sleeptimer_endtick;

static long last_event_tick;

static int voltage_to_battery_level(int battery_centivolts);
static void battery_status_update(void);
static int runcurrent(void);

void battery_read_info(int *adc, int *voltage, int *level)
{
    int adc_battery = adc_read(ADC_UNREG_POWER);
    int centivolts  = adc_battery*BATTERY_SCALE_FACTOR / 10000;

    if (adc)
        *adc = adc_battery;

    if (voltage)
        *voltage = centivolts;

    if (level)
        *level = voltage_to_battery_level(centivolts);
}

void reset_poweroff_timer(void)
{
    last_event_tick = current_tick;
}

#if BATTERY_TYPES_COUNT > 1
void set_battery_type(int type)
{
    if (type != battery_type) {
        battery_type = type;
        battery_status_update();     /* recalculate the battery status */
    }
}
#endif

void set_battery_capacity(int capacity)
{
    battery_capacity = capacity;
    if (battery_capacity > BATTERY_CAPACITY_MAX)
        battery_capacity = BATTERY_CAPACITY_MAX;
    if (battery_capacity < BATTERY_CAPACITY_MIN)
        battery_capacity = BATTERY_CAPACITY_MIN;
    battery_status_update();     /* recalculate the battery status */
}

int battery_time(void)
{
    return powermgmt_est_runningtime_min;
}

/* Returns battery level in percent */
int battery_level(void)
{
    return battery_percent;
}

/* Returns filtered battery voltage [centivolts] */
unsigned int battery_voltage(void)
{
    return battery_centivolts;
}

/* Returns battery voltage from ADC [centivolts] */
int battery_adc_voltage(void)
{
    return (adc_read(ADC_UNREG_POWER) * BATTERY_SCALE_FACTOR + 5000) / 10000;
}

/* Tells if the battery level is safe for disk writes */
bool battery_level_safe(void)
{
    return battery_centivolts > battery_level_dangerous[battery_type];
}

/* Tells if the battery is in critical powersaving state */
bool battery_level_critical(void)
{
    return ((battery_capacity * battery_percent / BATTERY_CAPACITY_MIN) < 10);
}

void set_poweroff_timeout(int timeout)
{
    poweroff_timeout = timeout;
}

void set_sleep_timer(int seconds)
{
    if(seconds) {
        sleeptimer_active  = true;
        sleeptimer_endtick = current_tick + seconds * HZ;
    }
    else {
        sleeptimer_active  = false;
        sleeptimer_endtick = 0;
    }
}

int get_sleep_timer(void)
{
    if(sleeptimer_active)
        return (sleeptimer_endtick - current_tick) / HZ;
    else
        return 0;
}

/* look into the percent_to_volt_* table and get a realistic battery level */
static int voltage_to_percent(int voltage, const short* table)
{
    if (voltage <= table[0])
        return 0;
    else
        if (voltage >= table[10])
            return 100;
        else {
            /* search nearest value */
            int i = 0;
            while ((i < 10) && (table[i+1] < voltage))
                i++;
            /* interpolate linear between the smaller and greater value */
            return (i * 10) /* Tens digit, 10% per entry */
                + (((voltage - table[i]) * 10)
                   / (table[i+1] - table[i])); /* Ones digit: interpolated */
        }
}

/* update battery level and estimated runtime, called once per minute or
 * when battery capacity / type settings are changed */
static int voltage_to_battery_level(int battery_centivolts)
{
    int level;

#if defined(CONFIG_CHARGER) && CONFIG_BATTERY == BATT_LIPOL1300
    if (charger_input_state == NO_CHARGER) {
        /* discharging. calculate new battery level and average with last */
        level = voltage_to_percent(battery_centivolts,
                percent_to_volt_discharge[battery_type]);
        if (level != (battery_percent - 1))
            level = (level + battery_percent + 1) / 2;
    }
    else if (charger_input_state == CHARGER_UNPLUGGED) {
        /* just unplugged. adjust filtered values */
        battery_centivolts -= percent_to_volt_charge[battery_percent/10] -
                              percent_to_volt_discharge[0][battery_percent/10];
        avgbat = battery_centivolts * 10000 * BATT_AVE_SAMPLES;
        level  = battery_percent;
    }
    else if (charger_input_state == CHARGER_PLUGGED) {
        /* just plugged in. adjust battery values */
        battery_centivolts += percent_to_volt_charge[battery_percent/10] -
                              percent_to_volt_discharge[0][battery_percent/10];
        avgbat = battery_centivolts * 10000 * BATT_AVE_SAMPLES;
        level  = MIN(12 * battery_percent / 10, 99);
    }
    else { /* charging. calculate new battery level */
        level = voltage_to_percent(battery_centivolts,
                percent_to_volt_charge);
    }
#elif CONFIG_CHARGING >= CHARGING_MONITOR
    if (charge_state == DISCHARGING) {
        level = voltage_to_percent(battery_centivolts,
                    percent_to_volt_discharge[battery_type]);
    }
    else if (charge_state == CHARGING) {
        /* battery level is defined to be < 100% until charging is finished */
        level = MIN(voltage_to_percent(battery_centivolts,
                    percent_to_volt_charge), 99);
    }
    else { /* in topoff/trickle charge, battery is by definition 100% full */
        level = 100;
    }
#else
    /* always use the discharge table */
    level = voltage_to_percent(battery_centivolts,
                percent_to_volt_discharge[battery_type]);
#endif

    return level;
}

static void battery_status_update(void)
{
    int level = voltage_to_battery_level(battery_centivolts);


    /* calculate estimated remaining running time */
    /* discharging: remaining running time */
    /* charging:    remaining charging time */
#if CONFIG_CHARGING >= CHARGING_MONITOR
    if (charge_state == CHARGING) {
        powermgmt_est_runningtime_min = (100 - level) * battery_capacity * 60
                                      / 100 / (CURRENT_MAX_CHG - runcurrent());
    }
    else
#elif defined(CONFIG_CHARGING) && CONFIG_BATTERY == BATT_LIPOL1300
    if (charger_inserted()) {
#ifdef IRIVER_H300_SERIES
        /* H300_SERIES use CURRENT_MAX_CHG for basic charge time (80%)
         * plus 110 min top off charge time */
        powermgmt_est_runningtime_min = ((100-level) * battery_capacity * 80
                                         /100 / CURRENT_MAX_CHG) + 110;
#else
        /* H100_SERIES scaled for 160 min basic charge time (80%) on
         * 1600 mAh battery plus 110 min top off charge time */
        powermgmt_est_runningtime_min = ((100 - level) * battery_capacity
                                         / 993) + 110;
#endif
        level = (level * 80) / 100;
        if (level > 72) { /* > 91% */
            int i = POWER_HISTORY_LEN;
            int d = 1;
#ifdef HAVE_CHARGE_STATE
            if (charge_state == DISCHARGING)
                d = -2;
#endif
            while ((i > 2) && (d > 0)) /* search zero or neg. delta */
                d = power_history[0] - power_history[--i];
            if ((((d == 0) && (i > 6)) || (d == -1)) && (i < 118)) {
                /* top off charging */
                level = MIN(80 + (i*19 / 113), 99);  /* show 81% .. 99% */
                powermgmt_est_runningtime_min = MAX(116 - i, 0);
            }
            else if ((d < 0) || (i > 117)) {
                /* charging finished */
                level = 100;
                powermgmt_est_runningtime_min = battery_capacity * 60
                                                / runcurrent();
            }
        }
    }
    else
#endif /* BATT_LIPOL1300 */
    {
        if ((battery_centivolts + 2) > percent_to_volt_discharge[0][0])
            powermgmt_est_runningtime_min = (level + battery_percent) * 60 *
                                         battery_capacity / 200 / runcurrent();
        else
            powermgmt_est_runningtime_min = (battery_centivolts -
                                             battery_level_shutoff[0]) / 2;
    }

    battery_percent = level;
}

/*
 * We shut off in the following cases:
 * 1) The unit is idle, not playing music
 * 2) The unit is playing music, but is paused
 * 3) The battery level has reached shutdown limit
 *
 * We do not shut off in the following cases:
 * 1) The USB is connected
 * 2) The charger is connected
 * 3) We are recording, or recording with pause
 * 4) The radio is playing
 */
static void handle_auto_poweroff(void)
{
    long timeout = poweroff_idle_timeout_value[poweroff_timeout]*60*HZ;
    int  audio_stat = audio_status();

#ifdef CONFIG_CHARGING
    /*
     * Inhibit shutdown as long as the charger is plugged in.  If it is
     * unplugged, wait for a timeout period and then shut down.
     */
    if(charger_input_state == CHARGER || audio_stat == AUDIO_STATUS_PLAY) {
        last_event_tick = current_tick;
    }
#endif

    /* For low battery condition do some power-saving stuff */
    if (!low_battery && battery_level_critical()) {
#if CONFIG_BACKLIGHT == BL_IRIVER_H100
        backlight_set_fade_in(0);
        backlight_set_fade_out(0);
#endif
#if defined(CONFIG_BACKLIGHT) && !defined(BOOTLOADER)
        if (backlight_get_current_timeout() > 2)
#endif
            backlight_set_timeout(2);
#ifdef HAVE_REMOTE_LCD
        remote_backlight_set_timeout(2);
#endif
        ata_spindown(3);
#ifdef HAVE_ATA_POWER_OFF
        ata_poweroff(true);
#endif
        low_battery = true;
    } else if (low_battery && (battery_percent > 11)) {
        backlight_set_timeout(10);
        ata_spindown(10);
        low_battery = false;
    }

    /* switch off unit if battery level is too low for reliable operation */
#if (CONFIG_BATTERY!=BATT_4AA_NIMH) && (CONFIG_BATTERY!=BATT_3AAA)&& \
    (CONFIG_BATTERY!=BATT_1AA)
    if(battery_centivolts < battery_level_shutoff[battery_type]) {
        if(!shutdown_timeout) {
            backlight_on();
            sys_poweroff();
        }
    }
#endif

    if(timeout &&
#if defined(CONFIG_TUNER) && !defined(BOOTLOADER)
       (!(get_radio_status() & FMRADIO_PLAYING)) &&
#endif
       !usb_inserted() &&
       ((audio_stat == 0) ||
        ((audio_stat == (AUDIO_STATUS_PLAY | AUDIO_STATUS_PAUSE)) &&
         !sleeptimer_active)))
    {
        if(TIME_AFTER(current_tick, last_event_tick    + timeout) &&
           TIME_AFTER(current_tick, last_disk_activity + timeout))
        {
            sys_poweroff();
        }
    }
    else
    {
        /* Handle sleeptimer */
        if(sleeptimer_active && !usb_inserted())
        {
            if(TIME_AFTER(current_tick, sleeptimer_endtick))
            {
                audio_stop();
#if defined(CONFIG_CHARGING) && !defined(HAVE_POWEROFF_WHILE_CHARGING)
                if((charger_input_state == CHARGER) ||
                   (charger_input_state == CHARGER_PLUGGED))
                {
                    DEBUGF("Sleep timer timeout. Stopping...\n");
                    set_sleep_timer(0);
                    backlight_off(); /* Nighty, nighty... */
                }
                else
#endif
                {
                    DEBUGF("Sleep timer timeout. Shutting off...\n");
                    sys_poweroff();
                }
            }
        }
    }
}

/*
 * Estimate how much current we are drawing just to run.
 */
static int runcurrent(void)
{
    int current;

#if MEM == 8 && !defined(HAVE_MMC)
    /* assuming 192 kbps, the running time is 22% longer with 8MB */
    current = (CURRENT_NORMAL*100/122);
#else
    current = CURRENT_NORMAL;
#endif /* MEM == 8 */

    if(usb_inserted()
#if defined(HAVE_USB_POWER)
  #if (CURRENT_USB < CURRENT_NORMAL)
       || usb_powered()
  #else
       && !usb_powered()
  #endif
#endif
    )
    {
        current = CURRENT_USB;
    }

#if defined(CONFIG_BACKLIGHT) && !defined(BOOTLOADER)
    if (backlight_get_current_timeout() == 0) /* LED always on */
        current += CURRENT_BACKLIGHT;
#endif

#if defined(HAVE_RECORDING) && defined(CURRENT_RECORD)
    if (audio_status() & AUDIO_STATUS_RECORD)
        current += CURRENT_RECORD;
#endif

#ifdef HAVE_SPDIF_POWER
    if (spdif_powered())
        current += CURRENT_SPDIF_OUT;
#endif

#ifdef HAVE_REMOTE_LCD
    if (remote_detect())
        current += CURRENT_REMOTE;
#endif

    return(current);
}


/* Check to see whether or not we've received an alarm in the last second */
#ifdef HAVE_ALARM_MOD
static void power_thread_rtc_process(void)
{
    if (rtc_check_alarm_flag()) {
        rtc_enable_alarm(false);
    }
}
#endif

/*
 * This function is called to do the relativly long sleep waits from within the
 * main power_thread loop while at the same time servicing any other periodic
 * functions in the power thread which need to be called at a faster periodic
 * rate than the slow periodic rate of the main power_thread loop.
 *
 * While we are waiting for the time to expire, we average the battery
 * voltages.
 */
static void power_thread_sleep(int ticks)
{
    int small_ticks;

    while (ticks > 0) {

#ifdef CONFIG_CHARGING
        /*
         * Detect charger plugged/unplugged transitions.  On a plugged or
         * unplugged event, we return immediately, run once through the main
         * loop (including the subroutines), and end up back here where we
         * transition to the appropriate steady state charger on/off state.
         */
        if(charger_inserted()
#ifdef HAVE_USB_POWER
                || usb_powered()
#endif
                ) {
            switch(charger_input_state) {
                case NO_CHARGER:
                case CHARGER_UNPLUGGED:
                    charger_input_state = CHARGER_PLUGGED;
                    return;
                case CHARGER_PLUGGED:
                    queue_broadcast(SYS_CHARGER_CONNECTED, NULL);
                    charger_input_state = CHARGER;
                    break;
                case CHARGER:
                    break;
            }
        } else {    /* charger not inserted */
            switch(charger_input_state) {
                case NO_CHARGER:
                    break;
                case CHARGER_UNPLUGGED:
                    queue_broadcast(SYS_CHARGER_DISCONNECTED, NULL);
                    charger_input_state = NO_CHARGER;
                    break;
                case CHARGER_PLUGGED:
                case CHARGER:
                    charger_input_state = CHARGER_UNPLUGGED;
                    return;
            }
        }
#endif
#if CONFIG_CHARGING == CHARGING_MONITOR
        switch (charger_input_state) {
            case CHARGER_UNPLUGGED:
            case NO_CHARGER:
                charge_state = DISCHARGING;
                break;
            case CHARGER_PLUGGED:
            case CHARGER:
                if (charging_state()) {
                    charge_state = CHARGING;
                } else {
                    charge_state = DISCHARGING;
                }
                break;
        }

#endif /* CONFIG_CHARGING == CHARGING_MONITOR */

        small_ticks = MIN(HZ/2, ticks);
        sleep(small_ticks);
        ticks -= small_ticks;

        /* If the power off timeout expires, the main thread has failed
           to shut down the system, and we need to force a power off */
        if(shutdown_timeout) {
            shutdown_timeout -= small_ticks;
            if(shutdown_timeout <= 0)
                power_off();
        }

#ifdef HAVE_ALARM_MOD
        power_thread_rtc_process();
#endif

        /*
         * Do a digital exponential filter.  We don't sample the battery if
         * the disk is spinning unless we are in USB mode (the disk will most
         * likely always be spinning in USB mode).
         */
        if (!ata_disk_is_active() || usb_inserted()) {
            avgbat += adc_read(ADC_UNREG_POWER) * BATTERY_SCALE_FACTOR
                      - (avgbat / BATT_AVE_SAMPLES);
            /*
             * battery_centivolts is the centivolt-scaled filtered battery value.
             */
            battery_centivolts = (avgbat / BATT_AVE_SAMPLES + 5000) / 10000;
            
            /* update battery status every time an update is available */
            battery_status_update();
        }
        else if (battery_percent < 8) {
            /* If battery is low, observe voltage during disk activity.
             * Shut down if voltage drops below shutoff level and we are not
             * using NiMH or Alkaline batteries.
             */
            battery_centivolts = (battery_adc_voltage() +
                                  battery_centivolts + 1) / 2;

            /* update battery status every time an update is available */
            battery_status_update();
            
#if (CONFIG_BATTERY!=BATT_4AA_NIMH) && (CONFIG_BATTERY!=BATT_3AAA)&& \
    (CONFIG_BATTERY!=BATT_1AA)
            if (!shutdown_timeout &&
                (battery_centivolts < battery_level_shutoff[battery_type]))
                sys_poweroff();
            else
#endif
                avgbat += battery_centivolts * 10000
                          - (avgbat / BATT_AVE_SAMPLES);
        }

#if CONFIG_CHARGING == CHARGING_CONTROL
        if (ata_disk_is_active()) {
            /* flag hdd use for charging calculation */
            disk_activity_last_cycle = true;
        }
#endif
#if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
        /*
         * If we have a lot of pending writes or if the disk is spining,
         * fsync the debug log file.
         */
        if((wrcount > 10) || ((wrcount > 0) && ata_disk_is_active())) {
            fsync(fd);
            wrcount = 0;
        }
#endif
    }
}


/*
 * This power thread maintains a history of battery voltage
 * and implements a charging algorithm.
 * For a complete description of the charging algorithm read
 * docs/CHARGING_ALGORITHM.
 */

static void power_thread(void)
{
    int i;
    short *phps, *phpd;         /* power history rotation pointers */
#if CONFIG_CHARGING == CHARGING_CONTROL
    unsigned int target_voltage = TRICKLE_VOLTAGE;    /* desired topoff/trickle
                                       * voltage level */
    int charge_max_time_idle = 0;     /* max. charging duration, calculated at
                                       * beginning of charging */
    int charge_max_time_now = 0;      /* max. charging duration including
                                       * hdd activity */
    int minutes_disk_activity = 0;    /* count minutes of hdd use during
                                       * charging */
    int last_disk_activity = CHARGE_END_LONGD + 1; /* last hdd use x mins ago */
#endif

    /* initialize the voltages for the exponential filter */
    avgbat = adc_read(ADC_UNREG_POWER) * BATTERY_SCALE_FACTOR + 15000;

#ifndef HAVE_MMC  /* this adjustment is only needed for HD based */
        /* The battery voltage is usually a little lower directly after
           turning on, because the disk was used heavily. Raise it by 5% */
#ifdef HAVE_CHARGING
    if(!charger_inserted()) /* only if charger not connected */
#endif
        avgbat += (percent_to_volt_discharge[battery_type][6] -
                   percent_to_volt_discharge[battery_type][5]) * 5000;
#endif /* not HAVE_MMC */

    avgbat = avgbat * BATT_AVE_SAMPLES;
    battery_centivolts = avgbat / BATT_AVE_SAMPLES / 10000;

#ifdef CONFIG_CHARING
    if(charger_inserted()) {
        battery_percent  = voltage_to_percent(battery_centivolts,
                           percent_to_volt_charge);
#if CONFIG_BATTERY == BATT_LIPOL1300
        charger_input_state = CHARGER;
#endif
    } else
#endif
    {   battery_percent  = voltage_to_percent(battery_centivolts,
                           percent_to_volt_discharge[battery_type]);
        battery_percent += (battery_percent < 100);
    }

#if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
    fd      = -1;
    wrcount = 0;
#endif

    while (1)
    {
        /* rotate the power history */
        phpd = &power_history[POWER_HISTORY_LEN - 1];
        phps = phpd - 1;
        for (i = 0; i < POWER_HISTORY_LEN-1; i++)
            *phpd-- = *phps--;

        /* insert new value at the start, in centivolts 8-) */
        power_history[0] = battery_centivolts;

#if CONFIG_CHARGING == CHARGING_CONTROL
        if (charger_input_state == CHARGER_PLUGGED) {
            pid_p = 0;
            pid_i = 0;
            snprintf(power_message, POWER_MESSAGE_LEN, "Charger plugged in");
            /*
             * The charger was just plugged in.  If the battery level is
             * nearly charged, just trickle.  If the battery is low, start
             * a full charge cycle.  If the battery level is in between,
             * top-off and then trickle.
             */
            if(battery_percent > START_TOPOFF_CHG) {
                powermgmt_last_cycle_level = battery_percent;
                powermgmt_last_cycle_startstop_min = 0;
                if(battery_percent >= START_TRICKLE_CHG) {
                    charge_state = TRICKLE;
                    target_voltage = TRICKLE_VOLTAGE;
                } else {
                    charge_state = TOPOFF;
                    target_voltage = TOPOFF_VOLTAGE;
                }
            } else {
                /*
                 * Start the charger full strength
                 */
                i = CHARGE_MAX_TIME_1500 * battery_capacity / 1500;
                charge_max_time_idle =
                    i * (100 + 35 - battery_percent) / 100;
                if (charge_max_time_idle > i) {
                    charge_max_time_idle = i;
                }
                charge_max_time_now = charge_max_time_idle;

                snprintf(power_message, POWER_MESSAGE_LEN,
                         "ChgAt %d%% max %dm", battery_level(),
                         charge_max_time_now);

                /* enable the charger after the max time calc is done,
                   because battery_level depends on if the charger is
                   on */
                DEBUGF("power: charger inserted and battery"
                       " not full, charging\n");
                powermgmt_last_cycle_level = battery_percent;
                powermgmt_last_cycle_startstop_min = 0;
                trickle_sec  = 60;
                long_delta   = short_delta = 999999;
                charge_state = CHARGING;
            }
        }
        if (charge_state == CHARGING) {
            /* alter charge time max length with extra disk use */
            if (disk_activity_last_cycle) {
                minutes_disk_activity++;
                charge_max_time_now = charge_max_time_idle +
                                     (minutes_disk_activity * 2 / 5);
                disk_activity_last_cycle = false;
                last_disk_activity = 0;
            } else {
                last_disk_activity++;
            }
            /*
             * Check the delta voltage over the last X minutes so we can do
             * our end-of-charge logic based on the battery level change.
             *(no longer use minimum time as logic for charge end has 50
             * minutes minimum charge built in)
             */
            if (powermgmt_last_cycle_startstop_min > CHARGE_END_SHORTD) {
                short_delta = power_history[0] -
                              power_history[CHARGE_END_SHORTD - 1];
            }

            if (powermgmt_last_cycle_startstop_min > CHARGE_END_LONGD) {
            /*
             * Scan the history: the points where measurement is taken need to
             * be fairly static. (check prior to short delta 'area')
             * (also only check first and last 10 cycles - delta in middle OK)
             */
                long_delta = power_history[0] -
                             power_history[CHARGE_END_LONGD - 1];

                for(i = CHARGE_END_SHORTD; i < CHARGE_END_SHORTD + 10; i++) {
                    if(((power_history[i] - power_history[i+1]) >  5) ||
                       ((power_history[i] - power_history[i+1]) < -5)) {
                        long_delta = 777777;
                        break;
                    }
                }
                 for(i = CHARGE_END_LONGD - 11; i < CHARGE_END_LONGD - 1 ; i++) {
                    if(((power_history[i] - power_history[i+1]) >  5) ||
                       ((power_history[i] - power_history[i+1]) < -5)) {
                        long_delta = 888888;
                        break;
                    }
                }
            }

            snprintf(power_message, POWER_MESSAGE_LEN,
                     "Chg %dm, max %dm", powermgmt_last_cycle_startstop_min,
                     charge_max_time_now);
            /*
             * End of charge criteria (any qualify):
             * 1) Charged a long time
             * 2) DeltaV went negative for a short time ( & long delta static)
             * 3) DeltaV was negative over a longer period (no disk use only)
             * Note: short_delta and long_delta are centivolts
             */
            if ((powermgmt_last_cycle_startstop_min >= charge_max_time_now) ||
                (short_delta <= -5 && long_delta < 5 ) || (long_delta  < -2 &&
                last_disk_activity > CHARGE_END_LONGD)) {
                if (powermgmt_last_cycle_startstop_min > charge_max_time_now) {
                    DEBUGF("power: powermgmt_last_cycle_startstop_min > charge_max_time_now, "
                           "enough!\n");
                    /*
                     *have charged too long and deltaV detection did not
                     *work!
                     */
                     snprintf(power_message, POWER_MESSAGE_LEN,
                             "Chg tmout %d min", charge_max_time_now);
                    /*
                     * Switch to trickle charging.  We skip the top-off
                     * since we've effectively done the top-off operation
                     * already since we charged for the maximum full
                     * charge time.
                     */
                    powermgmt_last_cycle_level = battery_percent;
                    powermgmt_last_cycle_startstop_min = 0;
                    charge_state = TRICKLE;

                    /*
                     * set trickle charge target to a relative voltage instead
                     * of an arbitrary value - the fully charged voltage may
                     * vary according to ambient temp, battery condition etc
                     * trickle target is -0.15v from full voltage acheived
                     * topup target is -0.05v from full voltage
                     */
                    target_voltage = power_history[0] - 15;

                } else {
                    if(short_delta <= -5) {
                        DEBUGF("power: short-term negative"
                               " delta, enough!\n");
                        snprintf(power_message, POWER_MESSAGE_LEN,
                                 "end negd %d %dmin", short_delta,
                                 powermgmt_last_cycle_startstop_min);
                        target_voltage = power_history[CHARGE_END_SHORTD - 1]
                                         - 5;
                    } else {
                        DEBUGF("power: long-term small "
                               "positive delta, enough!\n");
                        snprintf(power_message, POWER_MESSAGE_LEN,
                                 "end lowd %d %dmin", long_delta,
                                 powermgmt_last_cycle_startstop_min);
                        target_voltage = power_history[CHARGE_END_LONGD - 1]
                                         - 5;
                    }
                    /*
                     * Switch to top-off charging.
                     */
                    powermgmt_last_cycle_level = battery_percent;
                    powermgmt_last_cycle_startstop_min = 0;
                    charge_state = TOPOFF;
                }
            }
        }
        else if (charge_state != DISCHARGING)  /* top off or trickle */
        {
            /*
             *Time to switch from topoff to trickle?
             */
            if ((charge_state == TOPOFF) &&
                (powermgmt_last_cycle_startstop_min > TOPOFF_MAX_TIME))
            {
                powermgmt_last_cycle_level = battery_percent;
                powermgmt_last_cycle_startstop_min = 0;
                charge_state = TRICKLE;
                target_voltage = target_voltage - 10;
            }
            /*
             * Adjust trickle charge time (proportional and integral terms).
             * Note: I considered setting the level higher if the USB is
             * plugged in, but it doesn't appear to be necessary and will
             * generate more heat [gvb].
             */

            pid_p = target_voltage - battery_centivolts;
            if((pid_p > PID_DEADZONE) || (pid_p < -PID_DEADZONE))
                pid_p = pid_p * PID_PCONST;
            else
                pid_p = 0;
            if((unsigned) battery_centivolts < target_voltage) {
                if(pid_i < 60) {
                    pid_i++;        /* limit so it doesn't "wind up" */
                }
            } else {
                if(pid_i > 0) {
                    pid_i--;        /* limit so it doesn't "wind up" */
                }
            }

            trickle_sec = pid_p + pid_i;

            if(trickle_sec > 60) {
                trickle_sec = 60;
            }
            if(trickle_sec < 0) {
                trickle_sec = 0;
            }

        } else if (charge_state == DISCHARGING) {
            trickle_sec = 0;
            /*
             * The charger is enabled here only in one case: if it was
             * turned on at boot time (power_init).  Turn it off now.
             */
            if (charger_enabled)
                charger_enable(false);
        }

        if (charger_input_state == CHARGER_UNPLUGGED) {
            /*
             * The charger was just unplugged.
             */
            DEBUGF("power: charger disconnected, disabling\n");

            charger_enable(false);
            powermgmt_last_cycle_level = battery_percent;
            powermgmt_last_cycle_startstop_min = 0;
            trickle_sec  = 0;
            pid_p        = 0;
            pid_i        = 0;
            charge_state = DISCHARGING;
            snprintf(power_message, POWER_MESSAGE_LEN, "Charger: discharge");
        }

#endif /* CONFIG_CHARGING == CHARGING_CONTROL */

        /* sleep for a minute */

#if CONFIG_CHARGING == CHARGING_CONTROL
        if(trickle_sec > 0) {
            charger_enable(true);
            power_thread_sleep(HZ * trickle_sec);
        }
        if(trickle_sec < 60)
            charger_enable(false);
        power_thread_sleep(HZ * (60 - trickle_sec));
#else
        power_thread_sleep(HZ * 60);
#endif

#if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
        if(usb_inserted()) {
            if(fd >= 0) {
                /* It is probably too late to close the file but we can try...*/
                close(fd);
                fd = -1;
            }
        } else {
            if(fd < 0) {
                fd = open(DEBUG_FILE_NAME, O_WRONLY | O_APPEND | O_CREAT);
                if(fd >= 0) {
                    snprintf(debug_message, DEBUG_MESSAGE_LEN,
                    "cycle_min, bat_centivolts, bat_percent, chgr_state, charge_state, pid_p, pid_i, trickle_sec\n");
                    write(fd, debug_message, strlen(debug_message));
                    wrcount = 99;   /* force a flush */
                }
            }
            if(fd >= 0) {
                snprintf(debug_message, DEBUG_MESSAGE_LEN,
                        "%d, %d, %d, %d, %d, %d, %d, %d\n",
                    powermgmt_last_cycle_startstop_min, battery_centivolts,
                    battery_percent, charger_input_state, charge_state,
                    pid_p, pid_i, trickle_sec);
                write(fd, debug_message, strlen(debug_message));
                wrcount++;
            }
        }
#endif
        handle_auto_poweroff();

#if CONFIG_CHARGING == CHARGING_CONTROL
        powermgmt_last_cycle_startstop_min++;
#endif
    }
}

void powermgmt_init(void)
{
    /* init history to 0 */
    memset(power_history, 0x00, sizeof(power_history));
    create_thread(power_thread, power_stack, sizeof(power_stack),
                  power_thread_name IF_PRIO(, PRIORITY_SYSTEM));
}

#endif /* SIMULATOR */

void sys_poweroff(void)
{
    logf("sys_poweroff()");
    /* If the main thread fails to shut down the system, we will force a
       power off after an 20 second timeout */
    shutdown_timeout = HZ*20;
#if defined(HAVE_RECORDING)
    int audio_stat = audio_status();
    if (audio_stat & AUDIO_STATUS_RECORD) {
        audio_stop_recording();
        shutdown_timeout += 8*HZ;
    }
#endif
    
    queue_post(&button_queue, SYS_POWEROFF, NULL);
}

void cancel_shutdown(void)
{
    logf("sys_cancel_shutdown()");

#if defined(IAUDIO_X5) && !defined (SIMULATOR)
    /* TODO: Move some things to target/ tree */
    if (shutdown_timeout)
        pcf50606_reset_timeout();
#endif

    shutdown_timeout = 0;
}

/* Various hardware housekeeping tasks relating to shutting down the jukebox */
void shutdown_hw(void)
{
#ifndef SIMULATOR
#if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
    if(fd >= 0) {
        close(fd);
        fd = -1;
    }
#endif
    audio_stop();
    if (!battery_level_critical()) { /* do not save on critical battery */
#ifdef HAVE_LCD_BITMAP
        glyph_cache_save();
#endif
        if(ata_disk_is_active())
            ata_spindown(1);
    }
    while(ata_disk_is_active())
        sleep(HZ/10);

#ifndef IAUDIO_X5
#if defined(HAVE_BACKLIGHT_PWM_FADING) && !defined(SIMULATOR)
    backlight_set_fade_out(0);
#endif
    backlight_off();
#endif /* IAUDIO_X5 */
#ifdef HAVE_REMOTE_LCD
    remote_backlight_off();
#endif

    mp3_shutdown();
#ifdef HAVE_UDA1380
    uda1380_close();
#elif defined(HAVE_TLV320)
    tlv320_close();
#elif defined(HAVE_WM8758) || defined(HAVE_WM8975) | defined(HAVE_WM8731)
    wmcodec_close();
#endif
    /* If HD is still active we try to wait for spindown, otherwise the
       shutdown_timeout in power_thread_sleep will force a power off */ 
    while(ata_disk_is_active())
        sleep(HZ/10);
#ifndef IAUDIO_X5
    lcd_set_contrast(0);
#endif /* IAUDIO_X5 */
#ifdef HAVE_REMOTE_LCD
    lcd_remote_set_contrast(0);
#endif
    power_off();
#endif /* #ifndef SIMULATOR */
}