add link to homepage to about window.
[Rockbox.git] / firmware / powermgmt.c
blobc1321e67b4d9f712c2f497ecb74edac1fe61b27c
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2002 by Heikki Hannikainen, Uwe Freese
11 * Revisions copyright (C) 2005 by Gerald Van Baren
13 * All files in this archive are subject to the GNU General Public License.
14 * See the file COPYING in the source tree root for full license agreement.
16 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
17 * KIND, either express or implied.
19 ****************************************************************************/
20 #include "config.h"
21 #include "cpu.h"
22 #include "kernel.h"
23 #include "thread.h"
24 #include "system.h"
25 #include "debug.h"
26 #include "panic.h"
27 #include "adc.h"
28 #include "string.h"
29 #include "sprintf.h"
30 #include "ata.h"
31 #include "power.h"
32 #include "button.h"
33 #include "audio.h"
34 #include "mp3_playback.h"
35 #include "usb.h"
36 #include "powermgmt.h"
37 #include "backlight.h"
38 #include "lcd.h"
39 #include "rtc.h"
40 #if CONFIG_TUNER
41 #include "fmradio.h"
42 #endif
43 #include "sound.h"
44 #ifdef HAVE_LCD_BITMAP
45 #include "font.h"
46 #endif
47 #if defined(HAVE_RECORDING) && (CONFIG_CODEC == SWCODEC)
48 #include "pcm_record.h"
49 #endif
50 #include "logf.h"
51 #include "lcd-remote.h"
52 #ifdef SIMULATOR
53 #include <time.h>
54 #endif
56 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
57 #include "pcf50606.h"
58 #include "lcd-remote-target.h"
59 #endif
62 * Define DEBUG_FILE to create a csv (spreadsheet) with battery information
63 * in it (one sample per minute). This is only for very low level debug.
65 #undef DEBUG_FILE
66 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
67 #include "file.h"
68 #define DEBUG_FILE_NAME "/powermgmt.csv"
69 #define DEBUG_MESSAGE_LEN 133
70 static char debug_message[DEBUG_MESSAGE_LEN];
71 #define DEBUG_STACK ((0x1000)/sizeof(long))
72 static int fd; /* write debug information to this file */
73 static int wrcount;
74 #else
75 #define DEBUG_STACK 0
76 #endif
78 static int shutdown_timeout = 0;
80 #ifdef SIMULATOR /***********************************************************/
82 #define BATT_MINCVOLT 250 /* minimum centivolts of battery */
83 #define BATT_MAXCVOLT 450 /* maximum centivolts of battery */
84 #define BATT_MAXRUNTIME (10 * 60) /* maximum runtime with full battery in minutes */
86 static unsigned int batt_centivolts = (unsigned int)BATT_MAXCVOLT;
87 static int batt_level = 100; /* battery capacity level in percent */
88 static int batt_time = BATT_MAXRUNTIME; /* estimated remaining time in minutes */
89 static time_t last_change = 0;
91 static void battery_status_update(void)
93 time_t now;
95 time(&now);
96 if (last_change < now) {
97 last_change = now;
99 /* change the values: */
100 batt_centivolts -= (unsigned int)(BATT_MAXCVOLT - BATT_MINCVOLT) / 101;
101 if (batt_centivolts < (unsigned int)BATT_MINCVOLT)
102 batt_centivolts = (unsigned int)BATT_MAXCVOLT;
104 batt_level = 100 * (batt_centivolts - BATT_MINCVOLT) / (BATT_MAXCVOLT - BATT_MINCVOLT);
105 batt_time = batt_level * BATT_MAXRUNTIME / 100;
109 void battery_read_info(int *adc, int *voltage, int *level)
111 battery_status_update();
113 if (adc)
114 *adc = batt_centivolts; /* just return something */
116 if (voltage)
117 *voltage = batt_centivolts;
119 if (level)
120 *level = batt_level;
123 unsigned int battery_voltage(void)
125 battery_status_update();
126 return batt_centivolts;
129 int battery_level(void)
131 battery_status_update();
132 return batt_level;
135 int battery_time(void)
137 battery_status_update();
138 return batt_time;
141 bool battery_level_safe(void)
143 return battery_level() >= 10;
146 void set_poweroff_timeout(int timeout)
148 (void)timeout;
151 void set_battery_capacity(int capacity)
153 (void)capacity;
156 void reset_poweroff_timer(void)
161 #else /* not SIMULATOR ******************************************************/
163 static const int poweroff_idle_timeout_value[15] =
165 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 30, 45, 60
168 static const unsigned int battery_level_dangerous[BATTERY_TYPES_COUNT] =
170 #if CONFIG_BATTERY == BATT_LIION2200 /* FM Recorder, LiIon */
172 #elif CONFIG_BATTERY == BATT_3AAA /* Ondio: Alkaline, NiHM */
173 310, 345
174 #elif CONFIG_BATTERY == BATT_1AA /* iRiver iFP: Alkaline, NiHM */
175 105, 115
176 #elif CONFIG_BATTERY == BATT_LIPOL1300 /* iRiver H1x0: LiPolymer */
178 #elif CONFIG_BATTERY == BATT_LIION300 /* ipod nano */
180 #elif CONFIG_BATTERY == BATT_LIION400 /* iPOD Video 30GB */
182 #elif CONFIG_BATTERY == BATT_LIION750 /* Sansa e200 */
184 #elif CONFIG_BATTERY == BATT_LIION830 /* Gigabeat F */
186 #elif CONFIG_BATTERY == BATT_IAUDIO_X5M5 /* iAudio X5 */
188 #elif CONFIG_BATTERY == BATT_LPCS355385 /* iriver H10 20GB: LiPolymer*/
190 #elif CONFIG_BATTERY == BATT_BP009 /* iriver H10 5/6GB: LiPolymer */
192 #else /* Player/recorder: NiMH */
194 #endif
197 static const unsigned short battery_level_shutoff[BATTERY_TYPES_COUNT] =
199 #if CONFIG_BATTERY == BATT_LIION2200 /* FM Recorder */
201 #elif CONFIG_BATTERY == BATT_3AAA /* Ondio */
202 270, 280
203 #elif CONFIG_BATTERY == BATT_LIPOL1300 /* iRiver Hxxx */
205 #elif CONFIG_BATTERY == BATT_LIION300 /* ipod nano */
207 #elif CONFIG_BATTERY == BATT_LIION400 /* iPOD Video 30GB */
209 #elif CONFIG_BATTERY == BATT_LIION750 /* Sansa e200 */
211 #elif CONFIG_BATTERY == BATT_LIION830 /* Gigabeat F */
213 #elif CONFIG_BATTERY == BATT_IAUDIO_X5M5 /* iAudio X5 */
215 #elif CONFIG_BATTERY == BATT_LPCS355385 /* iriver H10 20GB */
217 #elif CONFIG_BATTERY == BATT_BP009 /* iriver H10 5/6GB */
219 #else /* Player/recorder: NiMH */
221 #endif
224 /* voltages (centivolt) of 0%, 10%, ... 100% when charging disabled */
225 static const unsigned short percent_to_volt_discharge[BATTERY_TYPES_COUNT][11] =
227 #if CONFIG_BATTERY == BATT_LIION2200
228 /* measured values */
229 { 260, 285, 295, 303, 311, 320, 330, 345, 360, 380, 400 }
230 #elif CONFIG_BATTERY == BATT_3AAA
231 /* measured values */
232 { 280, 325, 341, 353, 364, 374, 385, 395, 409, 427, 475 }, /* Alkaline */
233 { 310, 355, 363, 369, 372, 374, 376, 378, 380, 386, 405 } /* NiMH */
234 #elif CONFIG_BATTERY == BATT_LIPOL1300
235 /* Below 337 the backlight starts flickering during HD access */
236 { 337, 365, 370, 374, 378, 382, 387, 393, 400, 408, 416 }
237 #elif CONFIG_BATTERY == BATT_IAUDIO_X5M5
238 /* average measured values from X5 and M5L */
239 { 350, 365, 372, 374, 376, 379, 384, 390, 395, 404, 412 }
240 #elif CONFIG_BATTERY == BATT_LPCS355385
241 /* iriver H10 20GB */
242 { 376, 380, 385, 387, 390, 395, 402, 407, 411, 418, 424 }
243 #elif CONFIG_BATTERY == BATT_BP009
244 /* iriver H10 5/6GB */
245 { 372, 374, 380, 382, 384, 388, 394, 402, 406, 415, 424 }
246 #elif CONFIG_BATTERY == BATT_1AA
247 /* These values are the same as for 3AAA divided by 3. */
248 /* May need recalibration. */
249 { 93, 108, 114, 118, 121, 125, 128, 132, 136, 142, 158 }, /* alkaline */
250 { 103, 118, 121, 123, 124, 125, 126, 127, 128, 129, 135 } /* NiMH */
251 #elif CONFIG_BATTERY == BATT_LIION830
252 /* Toshiba Gigabeat Li Ion 830mAH figured from discharge curve */
253 { 348, 355, 359, 361, 363, 365, 370, 376, 380, 391, 399 },
254 #elif CONFIG_BATTERY == BATT_LIION750
255 /* Sansa Li Ion 750mAH FIXME this is a first linear approach */
256 { 330, 339, 348, 357, 366, 375, 384, 393, 402, 411, 420 },
257 #elif CONFIG_BATTERY == BATT_LIION400 /* iPOD Video 30GB */
258 /* iPOD Video 30GB Li-Ion 400mAh, first approach based upon measurements */
259 { 345, 367, 371, 375, 379, 383, 387, 393, 401, 410, 418 },
260 #elif CONFIG_BATTERY == BATT_LIION300
261 /* measured values */
262 { 323, 362, 370, 373, 375, 378, 383, 389, 395, 403, 416 },
263 #else /* NiMH */
264 /* original values were taken directly after charging, but it should show
265 100% after turning off the device for some hours, too */
266 { 450, 481, 491, 497, 503, 507, 512, 514, 517, 525, 540 }
267 /* orig. values: ...,528,560 */
268 #endif
271 #if CONFIG_CHARGING
272 charger_input_state_type charger_input_state IDATA_ATTR;
275 /* voltages (centivolt) of 0%, 10%, ... 100% when charging enabled */
276 static const unsigned short percent_to_volt_charge[11] =
278 #if CONFIG_BATTERY == BATT_LIPOL1300
279 /* values measured over one full charging cycle */
280 354, 386, 393, 398, 400, 402, 404, 408, 413, 418, 423 /* LiPo */
281 #elif CONFIG_BATTERY == BATT_LIION300
282 /* measured values */
283 323, 362, 370, 373, 375, 378, 383, 389, 395, 403, 416
284 #elif CONFIG_BATTERY == BATT_LIION400
285 /* iPOD Video 30GB Li-Ion 400mAh, first approach based upon measurements */
286 345, 367, 371, 375, 379, 383, 387, 393, 401, 410, 418
287 #elif CONFIG_BATTERY == BATT_LIION750
288 /* Sansa Li Ion 750mAH FIXME*/
289 330, 339, 348, 357, 366, 375, 384, 393, 402, 411, 420
290 #elif CONFIG_BATTERY == BATT_LIION830
291 /* Toshiba Gigabeat Li Ion 830mAH */
292 348, 355, 359, 361, 363, 365, 370, 376, 380, 391, 399
293 #elif CONFIG_BATTERY == BATT_LPCS355385
294 /* iriver H10 20GB */
295 399, 403, 406, 408, 410, 412, 415, 418, 422, 426, 431
296 #elif CONFIG_BATTERY == BATT_BP009
297 /* iriver H10 5/6GB: Not yet calibrated */
298 388, 392, 396, 400, 406, 410, 415, 419, 424, 428, 433
299 #else
300 /* values guessed, see
301 http://www.seattlerobotics.org/encoder/200210/LiIon2.pdf until someone
302 measures voltages over a charging cycle */
303 476, 544, 551, 556, 561, 564, 566, 576, 582, 584, 585 /* NiMH */
304 #endif
306 #endif /* CONFIG_CHARGING */
308 #if CONFIG_CHARGING >= CHARGING_MONITOR
309 charge_state_type charge_state; /* charging mode */
310 #endif
312 #if CONFIG_CHARGING == CHARGING_CONTROL
313 int long_delta; /* long term delta battery voltage */
314 int short_delta; /* short term delta battery voltage */
315 bool disk_activity_last_cycle = false; /* flag set to aid charger time
316 * calculation */
317 char power_message[POWER_MESSAGE_LEN] = ""; /* message that's shown in
318 debug menu */
319 /* percentage at which charging
320 starts */
321 int powermgmt_last_cycle_startstop_min = 0; /* how many minutes ago was the
322 charging started or
323 stopped? */
324 int powermgmt_last_cycle_level = 0; /* which level had the
325 batteries at this time? */
326 int trickle_sec = 0; /* how many seconds should the
327 charger be enabled per
328 minute for trickle
329 charging? */
330 int pid_p = 0; /* PID proportional term */
331 int pid_i = 0; /* PID integral term */
332 #endif /* CONFIG_CHARGING == CHARGING_CONTROL */
335 * Average battery voltage and charger voltage, filtered via a digital
336 * exponential filter.
338 static unsigned int avgbat; /* average battery voltage (filtering) */
339 static unsigned int battery_centivolts;/* filtered battery voltage, centvolts */
340 #ifdef HAVE_CHARGE_CTRL
341 #define BATT_AVE_SAMPLES 32 /* filter constant / @ 2Hz sample rate */
342 #elif CONFIG_BATTERY == BATT_LIPOL1300
343 #define BATT_AVE_SAMPLES 128 /* slow filter for iriver */
344 #else
345 #define BATT_AVE_SAMPLES 64 /* medium filter constant for all others */
346 #endif
348 /* battery level (0-100%) of this minute, updated once per minute */
349 static int battery_percent = -1;
350 static int battery_capacity = BATTERY_CAPACITY_DEFAULT; /* default value, mAh */
351 static int battery_type = 0;
353 /* Power history: power_history[0] is the newest sample */
354 unsigned short power_history[POWER_HISTORY_LEN];
356 static char power_stack[DEFAULT_STACK_SIZE/2 + DEBUG_STACK];
357 static const char power_thread_name[] = "power";
359 static int poweroff_timeout = 0;
360 static int powermgmt_est_runningtime_min = -1;
362 static bool sleeptimer_active = false;
363 static long sleeptimer_endtick;
365 static long last_event_tick;
367 static int voltage_to_battery_level(int battery_centivolts);
368 static void battery_status_update(void);
369 static int runcurrent(void);
371 void battery_read_info(int *adc, int *voltage, int *level)
373 int adc_battery = adc_read(ADC_UNREG_POWER);
374 int centivolts = adc_battery*BATTERY_SCALE_FACTOR / 10000;
376 if (adc)
377 *adc = adc_battery;
379 if (voltage)
380 *voltage = centivolts;
382 if (level)
383 *level = voltage_to_battery_level(centivolts);
386 void reset_poweroff_timer(void)
388 last_event_tick = current_tick;
391 #if BATTERY_TYPES_COUNT > 1
392 void set_battery_type(int type)
394 if (type != battery_type) {
395 battery_type = type;
396 battery_status_update(); /* recalculate the battery status */
399 #endif
401 void set_battery_capacity(int capacity)
403 battery_capacity = capacity;
404 if (battery_capacity > BATTERY_CAPACITY_MAX)
405 battery_capacity = BATTERY_CAPACITY_MAX;
406 if (battery_capacity < BATTERY_CAPACITY_MIN)
407 battery_capacity = BATTERY_CAPACITY_MIN;
408 battery_status_update(); /* recalculate the battery status */
411 int battery_time(void)
413 return powermgmt_est_runningtime_min;
416 /* Returns battery level in percent */
417 int battery_level(void)
419 return battery_percent;
422 /* Returns filtered battery voltage [centivolts] */
423 unsigned int battery_voltage(void)
425 return battery_centivolts;
428 /* Returns battery voltage from ADC [centivolts] */
429 int battery_adc_voltage(void)
431 return (adc_read(ADC_UNREG_POWER) * BATTERY_SCALE_FACTOR + 5000) / 10000;
434 /* Tells if the battery level is safe for disk writes */
435 bool battery_level_safe(void)
437 return battery_centivolts > battery_level_dangerous[battery_type];
440 void set_poweroff_timeout(int timeout)
442 poweroff_timeout = timeout;
445 void set_sleep_timer(int seconds)
447 if(seconds) {
448 sleeptimer_active = true;
449 sleeptimer_endtick = current_tick + seconds * HZ;
451 else {
452 sleeptimer_active = false;
453 sleeptimer_endtick = 0;
457 int get_sleep_timer(void)
459 if(sleeptimer_active)
460 return (sleeptimer_endtick - current_tick) / HZ;
461 else
462 return 0;
465 /* look into the percent_to_volt_* table and get a realistic battery level */
466 static int voltage_to_percent(int voltage, const short* table)
468 if (voltage <= table[0])
469 return 0;
470 else
471 if (voltage >= table[10])
472 return 100;
473 else {
474 /* search nearest value */
475 int i = 0;
476 while ((i < 10) && (table[i+1] < voltage))
477 i++;
478 /* interpolate linear between the smaller and greater value */
479 return (i * 10) /* Tens digit, 10% per entry */
480 + (((voltage - table[i]) * 10)
481 / (table[i+1] - table[i])); /* Ones digit: interpolated */
485 /* update battery level and estimated runtime, called once per minute or
486 * when battery capacity / type settings are changed */
487 static int voltage_to_battery_level(int battery_centivolts)
489 int level;
491 #if defined(CONFIG_CHARGER) && CONFIG_BATTERY == BATT_LIPOL1300
492 if (charger_input_state == NO_CHARGER) {
493 /* discharging. calculate new battery level and average with last */
494 level = voltage_to_percent(battery_centivolts,
495 percent_to_volt_discharge[battery_type]);
496 if (level != (battery_percent - 1))
497 level = (level + battery_percent + 1) / 2;
499 else if (charger_input_state == CHARGER_UNPLUGGED) {
500 /* just unplugged. adjust filtered values */
501 battery_centivolts -= percent_to_volt_charge[battery_percent/10] -
502 percent_to_volt_discharge[0][battery_percent/10];
503 avgbat = battery_centivolts * 10000 * BATT_AVE_SAMPLES;
504 level = battery_percent;
506 else if (charger_input_state == CHARGER_PLUGGED) {
507 /* just plugged in. adjust battery values */
508 battery_centivolts += percent_to_volt_charge[battery_percent/10] -
509 percent_to_volt_discharge[0][battery_percent/10];
510 avgbat = battery_centivolts * 10000 * BATT_AVE_SAMPLES;
511 level = MIN(12 * battery_percent / 10, 99);
513 else { /* charging. calculate new battery level */
514 level = voltage_to_percent(battery_centivolts,
515 percent_to_volt_charge);
517 #elif CONFIG_CHARGING >= CHARGING_MONITOR
518 if (charge_state == DISCHARGING) {
519 level = voltage_to_percent(battery_centivolts,
520 percent_to_volt_discharge[battery_type]);
522 else if (charge_state == CHARGING) {
523 /* battery level is defined to be < 100% until charging is finished */
524 level = MIN(voltage_to_percent(battery_centivolts,
525 percent_to_volt_charge), 99);
527 else { /* in topoff/trickle charge, battery is by definition 100% full */
528 level = 100;
530 #else
531 /* always use the discharge table */
532 level = voltage_to_percent(battery_centivolts,
533 percent_to_volt_discharge[battery_type]);
534 #endif
536 return level;
539 static void battery_status_update(void)
541 int level = voltage_to_battery_level(battery_centivolts);
544 /* calculate estimated remaining running time */
545 /* discharging: remaining running time */
546 /* charging: remaining charging time */
547 #if CONFIG_CHARGING >= CHARGING_MONITOR
548 if (charge_state == CHARGING) {
549 powermgmt_est_runningtime_min = (100 - level) * battery_capacity * 60
550 / 100 / (CURRENT_MAX_CHG - runcurrent());
552 else
553 #elif CONFIG_CHARGING && CONFIG_BATTERY == BATT_LIPOL1300
554 if (charger_inserted()) {
555 #ifdef IRIVER_H300_SERIES
556 /* H300_SERIES use CURRENT_MAX_CHG for basic charge time (80%)
557 * plus 110 min top off charge time */
558 powermgmt_est_runningtime_min = ((100-level) * battery_capacity * 80
559 /100 / CURRENT_MAX_CHG) + 110;
560 #else
561 /* H100_SERIES scaled for 160 min basic charge time (80%) on
562 * 1600 mAh battery plus 110 min top off charge time */
563 powermgmt_est_runningtime_min = ((100 - level) * battery_capacity
564 / 993) + 110;
565 #endif
566 level = (level * 80) / 100;
567 if (level > 72) { /* > 91% */
568 int i = POWER_HISTORY_LEN;
569 int d = 1;
570 #ifdef HAVE_CHARGE_STATE
571 if (charge_state == DISCHARGING)
572 d = -2;
573 #endif
574 while ((i > 2) && (d > 0)) /* search zero or neg. delta */
575 d = power_history[0] - power_history[--i];
576 if ((((d == 0) && (i > 6)) || (d == -1)) && (i < 118)) {
577 /* top off charging */
578 level = MIN(80 + (i*19 / 113), 99); /* show 81% .. 99% */
579 powermgmt_est_runningtime_min = MAX(116 - i, 0);
581 else if ((d < 0) || (i > 117)) {
582 /* charging finished */
583 level = 100;
584 powermgmt_est_runningtime_min = battery_capacity * 60
585 / runcurrent();
589 else
590 #endif /* BATT_LIPOL1300 */
592 if ((battery_centivolts + 2) > percent_to_volt_discharge[0][0])
593 powermgmt_est_runningtime_min = (level + battery_percent) * 60 *
594 battery_capacity / 200 / runcurrent();
595 else
596 powermgmt_est_runningtime_min = (battery_centivolts -
597 battery_level_shutoff[0]) / 2;
600 battery_percent = level;
604 * We shut off in the following cases:
605 * 1) The unit is idle, not playing music
606 * 2) The unit is playing music, but is paused
607 * 3) The battery level has reached shutdown limit
609 * We do not shut off in the following cases:
610 * 1) The USB is connected
611 * 2) The charger is connected
612 * 3) We are recording, or recording with pause
613 * 4) The radio is playing
615 static void handle_auto_poweroff(void)
617 long timeout = poweroff_idle_timeout_value[poweroff_timeout]*60*HZ;
618 int audio_stat = audio_status();
620 #if CONFIG_CHARGING
622 * Inhibit shutdown as long as the charger is plugged in. If it is
623 * unplugged, wait for a timeout period and then shut down.
625 if(charger_input_state == CHARGER || audio_stat == AUDIO_STATUS_PLAY) {
626 last_event_tick = current_tick;
628 #endif
630 /* switch off unit if battery level is too low for reliable operation */
631 #if (CONFIG_BATTERY!=BATT_4AA_NIMH) && (CONFIG_BATTERY!=BATT_3AAA)&& \
632 (CONFIG_BATTERY!=BATT_1AA)
633 if(battery_centivolts < battery_level_shutoff[battery_type]) {
634 if(!shutdown_timeout) {
635 backlight_on();
636 sys_poweroff();
639 #endif
641 if(timeout &&
642 #if CONFIG_TUNER && !defined(BOOTLOADER)
643 (!(get_radio_status() & FMRADIO_PLAYING)) &&
644 #endif
645 !usb_inserted() &&
646 ((audio_stat == 0) ||
647 ((audio_stat == (AUDIO_STATUS_PLAY | AUDIO_STATUS_PAUSE)) &&
648 !sleeptimer_active)))
650 if(TIME_AFTER(current_tick, last_event_tick + timeout) &&
651 TIME_AFTER(current_tick, last_disk_activity + timeout))
653 sys_poweroff();
656 else
658 /* Handle sleeptimer */
659 if(sleeptimer_active && !usb_inserted())
661 if(TIME_AFTER(current_tick, sleeptimer_endtick))
663 audio_stop();
664 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
665 if((charger_input_state == CHARGER) ||
666 (charger_input_state == CHARGER_PLUGGED))
668 DEBUGF("Sleep timer timeout. Stopping...\n");
669 set_sleep_timer(0);
670 backlight_off(); /* Nighty, nighty... */
672 else
673 #endif
675 DEBUGF("Sleep timer timeout. Shutting off...\n");
676 sys_poweroff();
684 * Estimate how much current we are drawing just to run.
686 static int runcurrent(void)
688 int current;
690 #if MEM == 8 && !defined(HAVE_MMC)
691 /* assuming 192 kbps, the running time is 22% longer with 8MB */
692 current = (CURRENT_NORMAL*100/122);
693 #else
694 current = CURRENT_NORMAL;
695 #endif /* MEM == 8 */
697 if(usb_inserted()
698 #if defined(HAVE_USB_POWER)
699 #if (CURRENT_USB < CURRENT_NORMAL)
700 || usb_powered()
701 #else
702 && !usb_powered()
703 #endif
704 #endif
707 current = CURRENT_USB;
710 #if defined(HAVE_BACKLIGHT) && !defined(BOOTLOADER)
711 if (backlight_get_current_timeout() == 0) /* LED always on */
712 current += CURRENT_BACKLIGHT;
713 #endif
715 #if defined(HAVE_RECORDING) && defined(CURRENT_RECORD)
716 if (audio_status() & AUDIO_STATUS_RECORD)
717 current += CURRENT_RECORD;
718 #endif
720 #ifdef HAVE_SPDIF_POWER
721 if (spdif_powered())
722 current += CURRENT_SPDIF_OUT;
723 #endif
725 #ifdef HAVE_REMOTE_LCD
726 if (remote_detect())
727 current += CURRENT_REMOTE;
728 #endif
730 return(current);
734 /* Check to see whether or not we've received an alarm in the last second */
735 #ifdef HAVE_RTC_ALARM
736 static void power_thread_rtc_process(void)
738 if (rtc_check_alarm_flag()) {
739 rtc_enable_alarm(false);
742 #endif
745 * This function is called to do the relativly long sleep waits from within the
746 * main power_thread loop while at the same time servicing any other periodic
747 * functions in the power thread which need to be called at a faster periodic
748 * rate than the slow periodic rate of the main power_thread loop.
750 * While we are waiting for the time to expire, we average the battery
751 * voltages.
753 static void power_thread_sleep(int ticks)
755 int small_ticks;
757 while (ticks > 0) {
759 #if CONFIG_CHARGING
761 * Detect charger plugged/unplugged transitions. On a plugged or
762 * unplugged event, we return immediately, run once through the main
763 * loop (including the subroutines), and end up back here where we
764 * transition to the appropriate steady state charger on/off state.
766 if(charger_inserted()
767 #ifdef HAVE_USB_POWER /* USB powered or USB inserted both provide power */
768 || usb_powered()
769 #if CONFIG_CHARGING
770 || (usb_inserted() && usb_charging_enabled())
771 #endif
772 #endif
774 switch(charger_input_state) {
775 case NO_CHARGER:
776 case CHARGER_UNPLUGGED:
777 charger_input_state = CHARGER_PLUGGED;
778 return;
779 case CHARGER_PLUGGED:
780 queue_broadcast(SYS_CHARGER_CONNECTED, 0);
781 charger_input_state = CHARGER;
782 break;
783 case CHARGER:
784 break;
786 } else { /* charger not inserted */
787 switch(charger_input_state) {
788 case NO_CHARGER:
789 break;
790 case CHARGER_UNPLUGGED:
791 queue_broadcast(SYS_CHARGER_DISCONNECTED, 0);
792 charger_input_state = NO_CHARGER;
793 break;
794 case CHARGER_PLUGGED:
795 case CHARGER:
796 charger_input_state = CHARGER_UNPLUGGED;
797 return;
800 #endif
801 #if CONFIG_CHARGING == CHARGING_MONITOR
802 switch (charger_input_state) {
803 case CHARGER_UNPLUGGED:
804 case NO_CHARGER:
805 charge_state = DISCHARGING;
806 break;
807 case CHARGER_PLUGGED:
808 case CHARGER:
809 if (charging_state()) {
810 charge_state = CHARGING;
811 } else {
812 charge_state = DISCHARGING;
814 break;
817 #endif /* CONFIG_CHARGING == CHARGING_MONITOR */
819 small_ticks = MIN(HZ/2, ticks);
820 sleep(small_ticks);
821 ticks -= small_ticks;
823 /* If the power off timeout expires, the main thread has failed
824 to shut down the system, and we need to force a power off */
825 if(shutdown_timeout) {
826 shutdown_timeout -= small_ticks;
827 if(shutdown_timeout <= 0)
828 power_off();
831 #ifdef HAVE_RTC_ALARM
832 power_thread_rtc_process();
833 #endif
836 * Do a digital exponential filter. We don't sample the battery if
837 * the disk is spinning unless we are in USB mode (the disk will most
838 * likely always be spinning in USB mode).
840 if (!ata_disk_is_active() || usb_inserted()) {
841 avgbat += adc_read(ADC_UNREG_POWER) * BATTERY_SCALE_FACTOR
842 - (avgbat / BATT_AVE_SAMPLES);
844 * battery_centivolts is the centivolt-scaled filtered battery value.
846 battery_centivolts = (avgbat / BATT_AVE_SAMPLES + 5000) / 10000;
848 /* update battery status every time an update is available */
849 battery_status_update();
851 else if (battery_percent < 8) {
852 /* If battery is low, observe voltage during disk activity.
853 * Shut down if voltage drops below shutoff level and we are not
854 * using NiMH or Alkaline batteries.
856 battery_centivolts = (battery_adc_voltage() +
857 battery_centivolts + 1) / 2;
859 /* update battery status every time an update is available */
860 battery_status_update();
862 #if (CONFIG_BATTERY!=BATT_4AA_NIMH) && (CONFIG_BATTERY!=BATT_3AAA)&& \
863 (CONFIG_BATTERY!=BATT_1AA)
864 if (!shutdown_timeout &&
865 (battery_centivolts < battery_level_shutoff[battery_type]))
866 sys_poweroff();
867 else
868 #endif
869 avgbat += battery_centivolts * 10000
870 - (avgbat / BATT_AVE_SAMPLES);
873 #if CONFIG_CHARGING == CHARGING_CONTROL
874 if (ata_disk_is_active()) {
875 /* flag hdd use for charging calculation */
876 disk_activity_last_cycle = true;
878 #endif
879 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
881 * If we have a lot of pending writes or if the disk is spining,
882 * fsync the debug log file.
884 if((wrcount > 10) || ((wrcount > 0) && ata_disk_is_active())) {
885 fsync(fd);
886 wrcount = 0;
888 #endif
894 * This power thread maintains a history of battery voltage
895 * and implements a charging algorithm.
896 * For a complete description of the charging algorithm read
897 * docs/CHARGING_ALGORITHM.
900 static void power_thread(void)
902 int i;
903 short *phps, *phpd; /* power history rotation pointers */
904 #if CONFIG_CHARGING == CHARGING_CONTROL
905 unsigned int target_voltage = TRICKLE_VOLTAGE; /* desired topoff/trickle
906 * voltage level */
907 int charge_max_time_idle = 0; /* max. charging duration, calculated at
908 * beginning of charging */
909 int charge_max_time_now = 0; /* max. charging duration including
910 * hdd activity */
911 int minutes_disk_activity = 0; /* count minutes of hdd use during
912 * charging */
913 int last_disk_activity = CHARGE_END_LONGD + 1; /* last hdd use x mins ago */
914 #endif
916 /* initialize the voltages for the exponential filter */
917 avgbat = adc_read(ADC_UNREG_POWER) * BATTERY_SCALE_FACTOR + 15000;
919 #ifndef HAVE_MMC /* this adjustment is only needed for HD based */
920 /* The battery voltage is usually a little lower directly after
921 turning on, because the disk was used heavily. Raise it by 5% */
922 #ifdef HAVE_CHARGING
923 if(!charger_inserted()) /* only if charger not connected */
924 #endif
925 avgbat += (percent_to_volt_discharge[battery_type][6] -
926 percent_to_volt_discharge[battery_type][5]) * 5000;
927 #endif /* not HAVE_MMC */
929 avgbat = avgbat * BATT_AVE_SAMPLES;
930 battery_centivolts = avgbat / BATT_AVE_SAMPLES / 10000;
932 #if CONFIG_CHARGING
933 if(charger_inserted()) {
934 battery_percent = voltage_to_percent(battery_centivolts,
935 percent_to_volt_charge);
936 #if CONFIG_BATTERY == BATT_LIPOL1300
937 charger_input_state = CHARGER;
938 #endif
939 } else
940 #endif
941 { battery_percent = voltage_to_percent(battery_centivolts,
942 percent_to_volt_discharge[battery_type]);
943 battery_percent += (battery_percent < 100);
946 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
947 fd = -1;
948 wrcount = 0;
949 #endif
951 while (1)
953 /* rotate the power history */
954 phpd = &power_history[POWER_HISTORY_LEN - 1];
955 phps = phpd - 1;
956 for (i = 0; i < POWER_HISTORY_LEN-1; i++)
957 *phpd-- = *phps--;
959 /* insert new value at the start, in centivolts 8-) */
960 power_history[0] = battery_centivolts;
962 #if CONFIG_CHARGING == CHARGING_CONTROL
963 if (charger_input_state == CHARGER_PLUGGED) {
964 pid_p = 0;
965 pid_i = 0;
966 snprintf(power_message, POWER_MESSAGE_LEN, "Charger plugged in");
968 * The charger was just plugged in. If the battery level is
969 * nearly charged, just trickle. If the battery is low, start
970 * a full charge cycle. If the battery level is in between,
971 * top-off and then trickle.
973 if(battery_percent > START_TOPOFF_CHG) {
974 powermgmt_last_cycle_level = battery_percent;
975 powermgmt_last_cycle_startstop_min = 0;
976 if(battery_percent >= START_TRICKLE_CHG) {
977 charge_state = TRICKLE;
978 target_voltage = TRICKLE_VOLTAGE;
979 } else {
980 charge_state = TOPOFF;
981 target_voltage = TOPOFF_VOLTAGE;
983 } else {
985 * Start the charger full strength
987 i = CHARGE_MAX_TIME_1500 * battery_capacity / 1500;
988 charge_max_time_idle =
989 i * (100 + 35 - battery_percent) / 100;
990 if (charge_max_time_idle > i) {
991 charge_max_time_idle = i;
993 charge_max_time_now = charge_max_time_idle;
995 snprintf(power_message, POWER_MESSAGE_LEN,
996 "ChgAt %d%% max %dm", battery_level(),
997 charge_max_time_now);
999 /* enable the charger after the max time calc is done,
1000 because battery_level depends on if the charger is
1001 on */
1002 DEBUGF("power: charger inserted and battery"
1003 " not full, charging\n");
1004 powermgmt_last_cycle_level = battery_percent;
1005 powermgmt_last_cycle_startstop_min = 0;
1006 trickle_sec = 60;
1007 long_delta = short_delta = 999999;
1008 charge_state = CHARGING;
1011 if (charge_state == CHARGING) {
1012 /* alter charge time max length with extra disk use */
1013 if (disk_activity_last_cycle) {
1014 minutes_disk_activity++;
1015 charge_max_time_now = charge_max_time_idle +
1016 (minutes_disk_activity * 2 / 5);
1017 disk_activity_last_cycle = false;
1018 last_disk_activity = 0;
1019 } else {
1020 last_disk_activity++;
1023 * Check the delta voltage over the last X minutes so we can do
1024 * our end-of-charge logic based on the battery level change.
1025 *(no longer use minimum time as logic for charge end has 50
1026 * minutes minimum charge built in)
1028 if (powermgmt_last_cycle_startstop_min > CHARGE_END_SHORTD) {
1029 short_delta = power_history[0] -
1030 power_history[CHARGE_END_SHORTD - 1];
1033 if (powermgmt_last_cycle_startstop_min > CHARGE_END_LONGD) {
1035 * Scan the history: the points where measurement is taken need to
1036 * be fairly static. (check prior to short delta 'area')
1037 * (also only check first and last 10 cycles - delta in middle OK)
1039 long_delta = power_history[0] -
1040 power_history[CHARGE_END_LONGD - 1];
1042 for(i = CHARGE_END_SHORTD; i < CHARGE_END_SHORTD + 10; i++) {
1043 if(((power_history[i] - power_history[i+1]) > 5) ||
1044 ((power_history[i] - power_history[i+1]) < -5)) {
1045 long_delta = 777777;
1046 break;
1049 for(i = CHARGE_END_LONGD - 11; i < CHARGE_END_LONGD - 1 ; i++) {
1050 if(((power_history[i] - power_history[i+1]) > 5) ||
1051 ((power_history[i] - power_history[i+1]) < -5)) {
1052 long_delta = 888888;
1053 break;
1058 snprintf(power_message, POWER_MESSAGE_LEN,
1059 "Chg %dm, max %dm", powermgmt_last_cycle_startstop_min,
1060 charge_max_time_now);
1062 * End of charge criteria (any qualify):
1063 * 1) Charged a long time
1064 * 2) DeltaV went negative for a short time ( & long delta static)
1065 * 3) DeltaV was negative over a longer period (no disk use only)
1066 * Note: short_delta and long_delta are centivolts
1068 if ((powermgmt_last_cycle_startstop_min >= charge_max_time_now) ||
1069 (short_delta <= -5 && long_delta < 5 ) || (long_delta < -2 &&
1070 last_disk_activity > CHARGE_END_LONGD)) {
1071 if (powermgmt_last_cycle_startstop_min > charge_max_time_now) {
1072 DEBUGF("power: powermgmt_last_cycle_startstop_min > charge_max_time_now, "
1073 "enough!\n");
1075 *have charged too long and deltaV detection did not
1076 *work!
1078 snprintf(power_message, POWER_MESSAGE_LEN,
1079 "Chg tmout %d min", charge_max_time_now);
1081 * Switch to trickle charging. We skip the top-off
1082 * since we've effectively done the top-off operation
1083 * already since we charged for the maximum full
1084 * charge time.
1086 powermgmt_last_cycle_level = battery_percent;
1087 powermgmt_last_cycle_startstop_min = 0;
1088 charge_state = TRICKLE;
1091 * set trickle charge target to a relative voltage instead
1092 * of an arbitrary value - the fully charged voltage may
1093 * vary according to ambient temp, battery condition etc
1094 * trickle target is -0.15v from full voltage acheived
1095 * topup target is -0.05v from full voltage
1097 target_voltage = power_history[0] - 15;
1099 } else {
1100 if(short_delta <= -5) {
1101 DEBUGF("power: short-term negative"
1102 " delta, enough!\n");
1103 snprintf(power_message, POWER_MESSAGE_LEN,
1104 "end negd %d %dmin", short_delta,
1105 powermgmt_last_cycle_startstop_min);
1106 target_voltage = power_history[CHARGE_END_SHORTD - 1]
1107 - 5;
1108 } else {
1109 DEBUGF("power: long-term small "
1110 "positive delta, enough!\n");
1111 snprintf(power_message, POWER_MESSAGE_LEN,
1112 "end lowd %d %dmin", long_delta,
1113 powermgmt_last_cycle_startstop_min);
1114 target_voltage = power_history[CHARGE_END_LONGD - 1]
1115 - 5;
1118 * Switch to top-off charging.
1120 powermgmt_last_cycle_level = battery_percent;
1121 powermgmt_last_cycle_startstop_min = 0;
1122 charge_state = TOPOFF;
1126 else if (charge_state != DISCHARGING) /* top off or trickle */
1129 *Time to switch from topoff to trickle?
1131 if ((charge_state == TOPOFF) &&
1132 (powermgmt_last_cycle_startstop_min > TOPOFF_MAX_TIME))
1134 powermgmt_last_cycle_level = battery_percent;
1135 powermgmt_last_cycle_startstop_min = 0;
1136 charge_state = TRICKLE;
1137 target_voltage = target_voltage - 10;
1140 * Adjust trickle charge time (proportional and integral terms).
1141 * Note: I considered setting the level higher if the USB is
1142 * plugged in, but it doesn't appear to be necessary and will
1143 * generate more heat [gvb].
1146 pid_p = target_voltage - battery_centivolts;
1147 if((pid_p > PID_DEADZONE) || (pid_p < -PID_DEADZONE))
1148 pid_p = pid_p * PID_PCONST;
1149 else
1150 pid_p = 0;
1151 if((unsigned) battery_centivolts < target_voltage) {
1152 if(pid_i < 60) {
1153 pid_i++; /* limit so it doesn't "wind up" */
1155 } else {
1156 if(pid_i > 0) {
1157 pid_i--; /* limit so it doesn't "wind up" */
1161 trickle_sec = pid_p + pid_i;
1163 if(trickle_sec > 60) {
1164 trickle_sec = 60;
1166 if(trickle_sec < 0) {
1167 trickle_sec = 0;
1170 } else if (charge_state == DISCHARGING) {
1171 trickle_sec = 0;
1173 * The charger is enabled here only in one case: if it was
1174 * turned on at boot time (power_init). Turn it off now.
1176 if (charger_enabled)
1177 charger_enable(false);
1180 if (charger_input_state == CHARGER_UNPLUGGED) {
1182 * The charger was just unplugged.
1184 DEBUGF("power: charger disconnected, disabling\n");
1186 charger_enable(false);
1187 powermgmt_last_cycle_level = battery_percent;
1188 powermgmt_last_cycle_startstop_min = 0;
1189 trickle_sec = 0;
1190 pid_p = 0;
1191 pid_i = 0;
1192 charge_state = DISCHARGING;
1193 snprintf(power_message, POWER_MESSAGE_LEN, "Charger: discharge");
1196 #endif /* CONFIG_CHARGING == CHARGING_CONTROL */
1198 /* sleep for a minute */
1200 #if CONFIG_CHARGING == CHARGING_CONTROL
1201 if(trickle_sec > 0) {
1202 charger_enable(true);
1203 power_thread_sleep(HZ * trickle_sec);
1205 if(trickle_sec < 60)
1206 charger_enable(false);
1207 power_thread_sleep(HZ * (60 - trickle_sec));
1208 #else
1209 power_thread_sleep(HZ * 60);
1210 #endif
1212 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
1213 if(usb_inserted()) {
1214 if(fd >= 0) {
1215 /* It is probably too late to close the file but we can try...*/
1216 close(fd);
1217 fd = -1;
1219 } else {
1220 if(fd < 0) {
1221 fd = open(DEBUG_FILE_NAME, O_WRONLY | O_APPEND | O_CREAT);
1222 if(fd >= 0) {
1223 snprintf(debug_message, DEBUG_MESSAGE_LEN,
1224 "cycle_min, bat_centivolts, bat_percent, chgr_state, charge_state, pid_p, pid_i, trickle_sec\n");
1225 write(fd, debug_message, strlen(debug_message));
1226 wrcount = 99; /* force a flush */
1229 if(fd >= 0) {
1230 snprintf(debug_message, DEBUG_MESSAGE_LEN,
1231 "%d, %d, %d, %d, %d, %d, %d, %d\n",
1232 powermgmt_last_cycle_startstop_min, battery_centivolts,
1233 battery_percent, charger_input_state, charge_state,
1234 pid_p, pid_i, trickle_sec);
1235 write(fd, debug_message, strlen(debug_message));
1236 wrcount++;
1239 #endif
1240 handle_auto_poweroff();
1242 #if CONFIG_CHARGING == CHARGING_CONTROL
1243 powermgmt_last_cycle_startstop_min++;
1244 #endif
1248 void powermgmt_init(void)
1250 /* init history to 0 */
1251 memset(power_history, 0x00, sizeof(power_history));
1252 create_thread(power_thread, power_stack, sizeof(power_stack),
1253 power_thread_name IF_PRIO(, PRIORITY_SYSTEM)
1254 IF_COP(, CPU, false));
1257 #endif /* SIMULATOR */
1259 void sys_poweroff(void)
1261 logf("sys_poweroff()");
1262 /* If the main thread fails to shut down the system, we will force a
1263 power off after an 20 second timeout - 28 seconds if recording */
1264 if (shutdown_timeout == 0)
1266 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
1267 pcf50606_reset_timeout(); /* Reset timer on first attempt only */
1268 #endif
1269 #ifdef HAVE_RECORDING
1270 if (audio_status() & AUDIO_STATUS_RECORD)
1271 shutdown_timeout += HZ*8;
1272 #endif
1273 shutdown_timeout += HZ*20;
1276 queue_post(&button_queue, SYS_POWEROFF, 0);
1279 void cancel_shutdown(void)
1281 logf("sys_cancel_shutdown()");
1283 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
1284 /* TODO: Move some things to target/ tree */
1285 if (shutdown_timeout)
1286 pcf50606_reset_timeout();
1287 #endif
1289 shutdown_timeout = 0;
1292 /* Various hardware housekeeping tasks relating to shutting down the jukebox */
1293 void shutdown_hw(void)
1295 #ifndef SIMULATOR
1296 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
1297 if(fd >= 0) {
1298 close(fd);
1299 fd = -1;
1301 #endif
1302 audio_stop();
1303 if (battery_level_safe()) { /* do not save on critical battery */
1304 #ifdef HAVE_LCD_BITMAP
1305 glyph_cache_save();
1306 #endif
1307 if(ata_disk_is_active())
1308 ata_spindown(1);
1310 while(ata_disk_is_active())
1311 sleep(HZ/10);
1313 #if !defined (IAUDIO_X5) && !defined (SANSA_E200)
1314 #if defined(HAVE_BACKLIGHT_PWM_FADING) && !defined(SIMULATOR)
1315 backlight_set_fade_out(0);
1316 #endif
1317 backlight_off();
1318 #endif /* IAUDIO_X5, SANSA_E200 */
1319 #ifdef HAVE_REMOTE_LCD
1320 remote_backlight_off();
1321 #endif
1323 #if CONFIG_CODEC != SWCODEC
1324 mp3_shutdown();
1325 #else
1326 audiohw_close();
1327 #endif
1329 /* If HD is still active we try to wait for spindown, otherwise the
1330 shutdown_timeout in power_thread_sleep will force a power off */
1331 while(ata_disk_is_active())
1332 sleep(HZ/10);
1333 #ifndef IAUDIO_X5
1334 lcd_set_contrast(0);
1335 #endif /* IAUDIO_X5 */
1336 #ifdef HAVE_REMOTE_LCD
1337 lcd_remote_set_contrast(0);
1338 #endif
1340 /* Small delay to make sure all HW gets time to flush. Especially
1341 eeprom chips are quite slow and might be still writing the last
1342 byte. */
1343 sleep(HZ/4);
1344 power_off();
1345 #endif /* #ifndef SIMULATOR */