FS#7353 - mktime() is only used by targets that have an RTC
[Rockbox.git] / firmware / powermgmt.c
blob484c97eda9bb63d5c70c9096329c4808fdcfff5f
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_LIION750 /* Sansa e200 */
180 #elif CONFIG_BATTERY == BATT_LIION830 /* Gigabeat F */
182 #elif CONFIG_BATTERY == BATT_IAUDIO_X5M5 /* iAudio X5 */
184 #elif CONFIG_BATTERY == BATT_LPCS355385 /* iriver H10 20GB: LiPolymer*/
186 #elif CONFIG_BATTERY == BATT_BP009 /* iriver H10 5/6GB: LiPolymer */
188 #else /* Player/recorder: NiMH */
190 #endif
193 static const unsigned short battery_level_shutoff[BATTERY_TYPES_COUNT] =
195 #if CONFIG_BATTERY == BATT_LIION2200 /* FM Recorder */
197 #elif CONFIG_BATTERY == BATT_3AAA /* Ondio */
198 270, 280
199 #elif CONFIG_BATTERY == BATT_LIPOL1300 /* iRiver Hxxx */
201 #elif CONFIG_BATTERY == BATT_LIION750 /* Sansa e200 */
203 #elif CONFIG_BATTERY == BATT_LIION830 /* Gigabeat F */
205 #elif CONFIG_BATTERY == BATT_IAUDIO_X5M5 /* iAudio X5 */
207 #elif CONFIG_BATTERY == BATT_LPCS355385 /* iriver H10 20GB */
209 #elif CONFIG_BATTERY == BATT_BP009 /* iriver H10 5/6GB */
211 #else /* Player/recorder: NiMH */
213 #endif
216 /* voltages (centivolt) of 0%, 10%, ... 100% when charging disabled */
217 static const unsigned short percent_to_volt_discharge[BATTERY_TYPES_COUNT][11] =
219 #if CONFIG_BATTERY == BATT_LIION2200
220 /* measured values */
221 { 260, 285, 295, 303, 311, 320, 330, 345, 360, 380, 400 }
222 #elif CONFIG_BATTERY == BATT_3AAA
223 /* measured values */
224 { 280, 325, 341, 353, 364, 374, 385, 395, 409, 427, 475 }, /* Alkaline */
225 { 310, 355, 363, 369, 372, 374, 376, 378, 380, 386, 405 } /* NiMH */
226 #elif CONFIG_BATTERY == BATT_LIPOL1300
227 /* Below 337 the backlight starts flickering during HD access */
228 { 337, 365, 370, 374, 378, 382, 387, 393, 400, 408, 416 }
229 #elif CONFIG_BATTERY == BATT_IAUDIO_X5M5
230 /* average measured values from X5 and M5L */
231 { 350, 365, 372, 374, 376, 379, 384, 390, 395, 404, 412 }
232 #elif CONFIG_BATTERY == BATT_LPCS355385
233 /* iriver H10 20GB */
234 { 376, 380, 385, 387, 390, 395, 402, 407, 411, 418, 424 }
235 #elif CONFIG_BATTERY == BATT_BP009
236 /* iriver H10 5/6GB */
237 { 372, 374, 380, 382, 384, 388, 394, 402, 406, 415, 424 }
238 #elif CONFIG_BATTERY == BATT_1AA
239 /* These values are the same as for 3AAA divided by 3. */
240 /* May need recalibration. */
241 { 93, 108, 114, 118, 121, 125, 128, 132, 136, 142, 158 }, /* alkaline */
242 { 103, 118, 121, 123, 124, 125, 126, 127, 128, 129, 135 } /* NiMH */
243 #elif CONFIG_BATTERY == BATT_LIION830
244 /* Toshiba Gigabeat Li Ion 830mAH figured from discharge curve */
245 { 354, 357, 359, 361, 364, 366, 372, 381, 377, 381, 394 },
246 #elif CONFIG_BATTERY == BATT_LIION750
247 /* Sansa Li Ion 750mAH FIXME this is a first linear approach */
248 { 330, 339, 348, 357, 366, 375, 384, 393, 402, 411, 420 },
249 #else /* NiMH */
250 /* original values were taken directly after charging, but it should show
251 100% after turning off the device for some hours, too */
252 { 450, 481, 491, 497, 503, 507, 512, 514, 517, 525, 540 }
253 /* orig. values: ...,528,560 */
254 #endif
257 #if CONFIG_CHARGING
258 charger_input_state_type charger_input_state IDATA_ATTR;
261 /* voltages (centivolt) of 0%, 10%, ... 100% when charging enabled */
262 static const unsigned short percent_to_volt_charge[11] =
264 #if CONFIG_BATTERY == BATT_LIPOL1300
265 /* values measured over one full charging cycle */
266 354, 386, 393, 398, 400, 402, 404, 408, 413, 418, 423 /* LiPo */
267 #elif CONFIG_BATTERY == BATT_LIION750
268 /* Sansa Li Ion 750mAH FIXME*/
269 330, 339, 348, 357, 366, 375, 384, 393, 402, 411, 420
270 #elif CONFIG_BATTERY == BATT_LIION830
271 /* Toshiba Gigabeat Li Ion 830mAH */
272 354, 357, 359, 361, 364, 366, 372, 381, 377, 381, 394
273 #elif CONFIG_BATTERY == BATT_LPCS355385
274 /* iriver H10 20GB */
275 399, 403, 406, 408, 410, 412, 415, 418, 422, 426, 431
276 #elif CONFIG_BATTERY == BATT_BP009
277 /* iriver H10 5/6GB: Not yet calibrated */
278 388, 392, 396, 400, 406, 410, 415, 419, 424, 428, 433
279 #else
280 /* values guessed, see
281 http://www.seattlerobotics.org/encoder/200210/LiIon2.pdf until someone
282 measures voltages over a charging cycle */
283 476, 544, 551, 556, 561, 564, 566, 576, 582, 584, 585 /* NiMH */
284 #endif
286 #endif /* CONFIG_CHARGING */
288 #if CONFIG_CHARGING >= CHARGING_MONITOR
289 charge_state_type charge_state; /* charging mode */
290 #endif
292 #if CONFIG_CHARGING == CHARGING_CONTROL
293 int long_delta; /* long term delta battery voltage */
294 int short_delta; /* short term delta battery voltage */
295 bool disk_activity_last_cycle = false; /* flag set to aid charger time
296 * calculation */
297 char power_message[POWER_MESSAGE_LEN] = ""; /* message that's shown in
298 debug menu */
299 /* percentage at which charging
300 starts */
301 int powermgmt_last_cycle_startstop_min = 0; /* how many minutes ago was the
302 charging started or
303 stopped? */
304 int powermgmt_last_cycle_level = 0; /* which level had the
305 batteries at this time? */
306 int trickle_sec = 0; /* how many seconds should the
307 charger be enabled per
308 minute for trickle
309 charging? */
310 int pid_p = 0; /* PID proportional term */
311 int pid_i = 0; /* PID integral term */
312 #endif /* CONFIG_CHARGING == CHARGING_CONTROL */
315 * Average battery voltage and charger voltage, filtered via a digital
316 * exponential filter.
318 static unsigned int avgbat; /* average battery voltage (filtering) */
319 static unsigned int battery_centivolts;/* filtered battery voltage, centvolts */
320 #ifdef HAVE_CHARGE_CTRL
321 #define BATT_AVE_SAMPLES 32 /* filter constant / @ 2Hz sample rate */
322 #elif CONFIG_BATTERY == BATT_LIPOL1300
323 #define BATT_AVE_SAMPLES 128 /* slow filter for iriver */
324 #else
325 #define BATT_AVE_SAMPLES 64 /* medium filter constant for all others */
326 #endif
328 /* battery level (0-100%) of this minute, updated once per minute */
329 static int battery_percent = -1;
330 static int battery_capacity = BATTERY_CAPACITY_DEFAULT; /* default value, mAh */
331 static int battery_type = 0;
333 /* Power history: power_history[0] is the newest sample */
334 unsigned short power_history[POWER_HISTORY_LEN];
336 static char power_stack[DEFAULT_STACK_SIZE/2 + DEBUG_STACK];
337 static const char power_thread_name[] = "power";
339 static int poweroff_timeout = 0;
340 static int powermgmt_est_runningtime_min = -1;
342 static bool sleeptimer_active = false;
343 static long sleeptimer_endtick;
345 static long last_event_tick;
347 static int voltage_to_battery_level(int battery_centivolts);
348 static void battery_status_update(void);
349 static int runcurrent(void);
351 void battery_read_info(int *adc, int *voltage, int *level)
353 int adc_battery = adc_read(ADC_UNREG_POWER);
354 int centivolts = adc_battery*BATTERY_SCALE_FACTOR / 10000;
356 if (adc)
357 *adc = adc_battery;
359 if (voltage)
360 *voltage = centivolts;
362 if (level)
363 *level = voltage_to_battery_level(centivolts);
366 void reset_poweroff_timer(void)
368 last_event_tick = current_tick;
371 #if BATTERY_TYPES_COUNT > 1
372 void set_battery_type(int type)
374 if (type != battery_type) {
375 battery_type = type;
376 battery_status_update(); /* recalculate the battery status */
379 #endif
381 void set_battery_capacity(int capacity)
383 battery_capacity = capacity;
384 if (battery_capacity > BATTERY_CAPACITY_MAX)
385 battery_capacity = BATTERY_CAPACITY_MAX;
386 if (battery_capacity < BATTERY_CAPACITY_MIN)
387 battery_capacity = BATTERY_CAPACITY_MIN;
388 battery_status_update(); /* recalculate the battery status */
391 int battery_time(void)
393 return powermgmt_est_runningtime_min;
396 /* Returns battery level in percent */
397 int battery_level(void)
399 return battery_percent;
402 /* Returns filtered battery voltage [centivolts] */
403 unsigned int battery_voltage(void)
405 return battery_centivolts;
408 /* Returns battery voltage from ADC [centivolts] */
409 int battery_adc_voltage(void)
411 return (adc_read(ADC_UNREG_POWER) * BATTERY_SCALE_FACTOR + 5000) / 10000;
414 /* Tells if the battery level is safe for disk writes */
415 bool battery_level_safe(void)
417 return battery_centivolts > battery_level_dangerous[battery_type];
420 void set_poweroff_timeout(int timeout)
422 poweroff_timeout = timeout;
425 void set_sleep_timer(int seconds)
427 if(seconds) {
428 sleeptimer_active = true;
429 sleeptimer_endtick = current_tick + seconds * HZ;
431 else {
432 sleeptimer_active = false;
433 sleeptimer_endtick = 0;
437 int get_sleep_timer(void)
439 if(sleeptimer_active)
440 return (sleeptimer_endtick - current_tick) / HZ;
441 else
442 return 0;
445 /* look into the percent_to_volt_* table and get a realistic battery level */
446 static int voltage_to_percent(int voltage, const short* table)
448 if (voltage <= table[0])
449 return 0;
450 else
451 if (voltage >= table[10])
452 return 100;
453 else {
454 /* search nearest value */
455 int i = 0;
456 while ((i < 10) && (table[i+1] < voltage))
457 i++;
458 /* interpolate linear between the smaller and greater value */
459 return (i * 10) /* Tens digit, 10% per entry */
460 + (((voltage - table[i]) * 10)
461 / (table[i+1] - table[i])); /* Ones digit: interpolated */
465 /* update battery level and estimated runtime, called once per minute or
466 * when battery capacity / type settings are changed */
467 static int voltage_to_battery_level(int battery_centivolts)
469 int level;
471 #if defined(CONFIG_CHARGER) && CONFIG_BATTERY == BATT_LIPOL1300
472 if (charger_input_state == NO_CHARGER) {
473 /* discharging. calculate new battery level and average with last */
474 level = voltage_to_percent(battery_centivolts,
475 percent_to_volt_discharge[battery_type]);
476 if (level != (battery_percent - 1))
477 level = (level + battery_percent + 1) / 2;
479 else if (charger_input_state == CHARGER_UNPLUGGED) {
480 /* just unplugged. adjust filtered values */
481 battery_centivolts -= percent_to_volt_charge[battery_percent/10] -
482 percent_to_volt_discharge[0][battery_percent/10];
483 avgbat = battery_centivolts * 10000 * BATT_AVE_SAMPLES;
484 level = battery_percent;
486 else if (charger_input_state == CHARGER_PLUGGED) {
487 /* just plugged in. adjust battery values */
488 battery_centivolts += percent_to_volt_charge[battery_percent/10] -
489 percent_to_volt_discharge[0][battery_percent/10];
490 avgbat = battery_centivolts * 10000 * BATT_AVE_SAMPLES;
491 level = MIN(12 * battery_percent / 10, 99);
493 else { /* charging. calculate new battery level */
494 level = voltage_to_percent(battery_centivolts,
495 percent_to_volt_charge);
497 #elif CONFIG_CHARGING >= CHARGING_MONITOR
498 if (charge_state == DISCHARGING) {
499 level = voltage_to_percent(battery_centivolts,
500 percent_to_volt_discharge[battery_type]);
502 else if (charge_state == CHARGING) {
503 /* battery level is defined to be < 100% until charging is finished */
504 level = MIN(voltage_to_percent(battery_centivolts,
505 percent_to_volt_charge), 99);
507 else { /* in topoff/trickle charge, battery is by definition 100% full */
508 level = 100;
510 #else
511 /* always use the discharge table */
512 level = voltage_to_percent(battery_centivolts,
513 percent_to_volt_discharge[battery_type]);
514 #endif
516 return level;
519 static void battery_status_update(void)
521 int level = voltage_to_battery_level(battery_centivolts);
524 /* calculate estimated remaining running time */
525 /* discharging: remaining running time */
526 /* charging: remaining charging time */
527 #if CONFIG_CHARGING >= CHARGING_MONITOR
528 if (charge_state == CHARGING) {
529 powermgmt_est_runningtime_min = (100 - level) * battery_capacity * 60
530 / 100 / (CURRENT_MAX_CHG - runcurrent());
532 else
533 #elif CONFIG_CHARGING && CONFIG_BATTERY == BATT_LIPOL1300
534 if (charger_inserted()) {
535 #ifdef IRIVER_H300_SERIES
536 /* H300_SERIES use CURRENT_MAX_CHG for basic charge time (80%)
537 * plus 110 min top off charge time */
538 powermgmt_est_runningtime_min = ((100-level) * battery_capacity * 80
539 /100 / CURRENT_MAX_CHG) + 110;
540 #else
541 /* H100_SERIES scaled for 160 min basic charge time (80%) on
542 * 1600 mAh battery plus 110 min top off charge time */
543 powermgmt_est_runningtime_min = ((100 - level) * battery_capacity
544 / 993) + 110;
545 #endif
546 level = (level * 80) / 100;
547 if (level > 72) { /* > 91% */
548 int i = POWER_HISTORY_LEN;
549 int d = 1;
550 #ifdef HAVE_CHARGE_STATE
551 if (charge_state == DISCHARGING)
552 d = -2;
553 #endif
554 while ((i > 2) && (d > 0)) /* search zero or neg. delta */
555 d = power_history[0] - power_history[--i];
556 if ((((d == 0) && (i > 6)) || (d == -1)) && (i < 118)) {
557 /* top off charging */
558 level = MIN(80 + (i*19 / 113), 99); /* show 81% .. 99% */
559 powermgmt_est_runningtime_min = MAX(116 - i, 0);
561 else if ((d < 0) || (i > 117)) {
562 /* charging finished */
563 level = 100;
564 powermgmt_est_runningtime_min = battery_capacity * 60
565 / runcurrent();
569 else
570 #endif /* BATT_LIPOL1300 */
572 if ((battery_centivolts + 2) > percent_to_volt_discharge[0][0])
573 powermgmt_est_runningtime_min = (level + battery_percent) * 60 *
574 battery_capacity / 200 / runcurrent();
575 else
576 powermgmt_est_runningtime_min = (battery_centivolts -
577 battery_level_shutoff[0]) / 2;
580 battery_percent = level;
584 * We shut off in the following cases:
585 * 1) The unit is idle, not playing music
586 * 2) The unit is playing music, but is paused
587 * 3) The battery level has reached shutdown limit
589 * We do not shut off in the following cases:
590 * 1) The USB is connected
591 * 2) The charger is connected
592 * 3) We are recording, or recording with pause
593 * 4) The radio is playing
595 static void handle_auto_poweroff(void)
597 long timeout = poweroff_idle_timeout_value[poweroff_timeout]*60*HZ;
598 int audio_stat = audio_status();
600 #if CONFIG_CHARGING
602 * Inhibit shutdown as long as the charger is plugged in. If it is
603 * unplugged, wait for a timeout period and then shut down.
605 if(charger_input_state == CHARGER || audio_stat == AUDIO_STATUS_PLAY) {
606 last_event_tick = current_tick;
608 #endif
610 /* switch off unit if battery level is too low for reliable operation */
611 #if (CONFIG_BATTERY!=BATT_4AA_NIMH) && (CONFIG_BATTERY!=BATT_3AAA)&& \
612 (CONFIG_BATTERY!=BATT_1AA)
613 if(battery_centivolts < battery_level_shutoff[battery_type]) {
614 if(!shutdown_timeout) {
615 backlight_on();
616 sys_poweroff();
619 #endif
621 if(timeout &&
622 #if CONFIG_TUNER && !defined(BOOTLOADER)
623 (!(get_radio_status() & FMRADIO_PLAYING)) &&
624 #endif
625 !usb_inserted() &&
626 ((audio_stat == 0) ||
627 ((audio_stat == (AUDIO_STATUS_PLAY | AUDIO_STATUS_PAUSE)) &&
628 !sleeptimer_active)))
630 if(TIME_AFTER(current_tick, last_event_tick + timeout) &&
631 TIME_AFTER(current_tick, last_disk_activity + timeout))
633 sys_poweroff();
636 else
638 /* Handle sleeptimer */
639 if(sleeptimer_active && !usb_inserted())
641 if(TIME_AFTER(current_tick, sleeptimer_endtick))
643 audio_stop();
644 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
645 if((charger_input_state == CHARGER) ||
646 (charger_input_state == CHARGER_PLUGGED))
648 DEBUGF("Sleep timer timeout. Stopping...\n");
649 set_sleep_timer(0);
650 backlight_off(); /* Nighty, nighty... */
652 else
653 #endif
655 DEBUGF("Sleep timer timeout. Shutting off...\n");
656 sys_poweroff();
664 * Estimate how much current we are drawing just to run.
666 static int runcurrent(void)
668 int current;
670 #if MEM == 8 && !defined(HAVE_MMC)
671 /* assuming 192 kbps, the running time is 22% longer with 8MB */
672 current = (CURRENT_NORMAL*100/122);
673 #else
674 current = CURRENT_NORMAL;
675 #endif /* MEM == 8 */
677 if(usb_inserted()
678 #if defined(HAVE_USB_POWER)
679 #if (CURRENT_USB < CURRENT_NORMAL)
680 || usb_powered()
681 #else
682 && !usb_powered()
683 #endif
684 #endif
687 current = CURRENT_USB;
690 #if defined(HAVE_BACKLIGHT) && !defined(BOOTLOADER)
691 if (backlight_get_current_timeout() == 0) /* LED always on */
692 current += CURRENT_BACKLIGHT;
693 #endif
695 #if defined(HAVE_RECORDING) && defined(CURRENT_RECORD)
696 if (audio_status() & AUDIO_STATUS_RECORD)
697 current += CURRENT_RECORD;
698 #endif
700 #ifdef HAVE_SPDIF_POWER
701 if (spdif_powered())
702 current += CURRENT_SPDIF_OUT;
703 #endif
705 #ifdef HAVE_REMOTE_LCD
706 if (remote_detect())
707 current += CURRENT_REMOTE;
708 #endif
710 return(current);
714 /* Check to see whether or not we've received an alarm in the last second */
715 #ifdef HAVE_RTC_ALARM
716 static void power_thread_rtc_process(void)
718 if (rtc_check_alarm_flag()) {
719 rtc_enable_alarm(false);
722 #endif
725 * This function is called to do the relativly long sleep waits from within the
726 * main power_thread loop while at the same time servicing any other periodic
727 * functions in the power thread which need to be called at a faster periodic
728 * rate than the slow periodic rate of the main power_thread loop.
730 * While we are waiting for the time to expire, we average the battery
731 * voltages.
733 static void power_thread_sleep(int ticks)
735 int small_ticks;
737 while (ticks > 0) {
739 #if CONFIG_CHARGING
741 * Detect charger plugged/unplugged transitions. On a plugged or
742 * unplugged event, we return immediately, run once through the main
743 * loop (including the subroutines), and end up back here where we
744 * transition to the appropriate steady state charger on/off state.
746 if(charger_inserted()
747 #ifdef HAVE_USB_POWER /* USB powered or USB inserted both provide power */
748 || usb_powered()
749 #if CONFIG_CHARGING
750 || (usb_inserted() && usb_charging_enabled())
751 #endif
752 #endif
754 switch(charger_input_state) {
755 case NO_CHARGER:
756 case CHARGER_UNPLUGGED:
757 charger_input_state = CHARGER_PLUGGED;
758 return;
759 case CHARGER_PLUGGED:
760 queue_broadcast(SYS_CHARGER_CONNECTED, 0);
761 charger_input_state = CHARGER;
762 break;
763 case CHARGER:
764 break;
766 } else { /* charger not inserted */
767 switch(charger_input_state) {
768 case NO_CHARGER:
769 break;
770 case CHARGER_UNPLUGGED:
771 queue_broadcast(SYS_CHARGER_DISCONNECTED, 0);
772 charger_input_state = NO_CHARGER;
773 break;
774 case CHARGER_PLUGGED:
775 case CHARGER:
776 charger_input_state = CHARGER_UNPLUGGED;
777 return;
780 #endif
781 #if CONFIG_CHARGING == CHARGING_MONITOR
782 switch (charger_input_state) {
783 case CHARGER_UNPLUGGED:
784 case NO_CHARGER:
785 charge_state = DISCHARGING;
786 break;
787 case CHARGER_PLUGGED:
788 case CHARGER:
789 if (charging_state()) {
790 charge_state = CHARGING;
791 } else {
792 charge_state = DISCHARGING;
794 break;
797 #endif /* CONFIG_CHARGING == CHARGING_MONITOR */
799 small_ticks = MIN(HZ/2, ticks);
800 sleep(small_ticks);
801 ticks -= small_ticks;
803 /* If the power off timeout expires, the main thread has failed
804 to shut down the system, and we need to force a power off */
805 if(shutdown_timeout) {
806 shutdown_timeout -= small_ticks;
807 if(shutdown_timeout <= 0)
808 power_off();
811 #ifdef HAVE_RTC_ALARM
812 power_thread_rtc_process();
813 #endif
816 * Do a digital exponential filter. We don't sample the battery if
817 * the disk is spinning unless we are in USB mode (the disk will most
818 * likely always be spinning in USB mode).
820 if (!ata_disk_is_active() || usb_inserted()) {
821 avgbat += adc_read(ADC_UNREG_POWER) * BATTERY_SCALE_FACTOR
822 - (avgbat / BATT_AVE_SAMPLES);
824 * battery_centivolts is the centivolt-scaled filtered battery value.
826 battery_centivolts = (avgbat / BATT_AVE_SAMPLES + 5000) / 10000;
828 /* update battery status every time an update is available */
829 battery_status_update();
831 else if (battery_percent < 8) {
832 /* If battery is low, observe voltage during disk activity.
833 * Shut down if voltage drops below shutoff level and we are not
834 * using NiMH or Alkaline batteries.
836 battery_centivolts = (battery_adc_voltage() +
837 battery_centivolts + 1) / 2;
839 /* update battery status every time an update is available */
840 battery_status_update();
842 #if (CONFIG_BATTERY!=BATT_4AA_NIMH) && (CONFIG_BATTERY!=BATT_3AAA)&& \
843 (CONFIG_BATTERY!=BATT_1AA)
844 if (!shutdown_timeout &&
845 (battery_centivolts < battery_level_shutoff[battery_type]))
846 sys_poweroff();
847 else
848 #endif
849 avgbat += battery_centivolts * 10000
850 - (avgbat / BATT_AVE_SAMPLES);
853 #if CONFIG_CHARGING == CHARGING_CONTROL
854 if (ata_disk_is_active()) {
855 /* flag hdd use for charging calculation */
856 disk_activity_last_cycle = true;
858 #endif
859 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
861 * If we have a lot of pending writes or if the disk is spining,
862 * fsync the debug log file.
864 if((wrcount > 10) || ((wrcount > 0) && ata_disk_is_active())) {
865 fsync(fd);
866 wrcount = 0;
868 #endif
874 * This power thread maintains a history of battery voltage
875 * and implements a charging algorithm.
876 * For a complete description of the charging algorithm read
877 * docs/CHARGING_ALGORITHM.
880 static void power_thread(void)
882 int i;
883 short *phps, *phpd; /* power history rotation pointers */
884 #if CONFIG_CHARGING == CHARGING_CONTROL
885 unsigned int target_voltage = TRICKLE_VOLTAGE; /* desired topoff/trickle
886 * voltage level */
887 int charge_max_time_idle = 0; /* max. charging duration, calculated at
888 * beginning of charging */
889 int charge_max_time_now = 0; /* max. charging duration including
890 * hdd activity */
891 int minutes_disk_activity = 0; /* count minutes of hdd use during
892 * charging */
893 int last_disk_activity = CHARGE_END_LONGD + 1; /* last hdd use x mins ago */
894 #endif
896 /* initialize the voltages for the exponential filter */
897 avgbat = adc_read(ADC_UNREG_POWER) * BATTERY_SCALE_FACTOR + 15000;
899 #ifndef HAVE_MMC /* this adjustment is only needed for HD based */
900 /* The battery voltage is usually a little lower directly after
901 turning on, because the disk was used heavily. Raise it by 5% */
902 #ifdef HAVE_CHARGING
903 if(!charger_inserted()) /* only if charger not connected */
904 #endif
905 avgbat += (percent_to_volt_discharge[battery_type][6] -
906 percent_to_volt_discharge[battery_type][5]) * 5000;
907 #endif /* not HAVE_MMC */
909 avgbat = avgbat * BATT_AVE_SAMPLES;
910 battery_centivolts = avgbat / BATT_AVE_SAMPLES / 10000;
912 #if CONFIG_CHARGING
913 if(charger_inserted()) {
914 battery_percent = voltage_to_percent(battery_centivolts,
915 percent_to_volt_charge);
916 #if CONFIG_BATTERY == BATT_LIPOL1300
917 charger_input_state = CHARGER;
918 #endif
919 } else
920 #endif
921 { battery_percent = voltage_to_percent(battery_centivolts,
922 percent_to_volt_discharge[battery_type]);
923 battery_percent += (battery_percent < 100);
926 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
927 fd = -1;
928 wrcount = 0;
929 #endif
931 while (1)
933 /* rotate the power history */
934 phpd = &power_history[POWER_HISTORY_LEN - 1];
935 phps = phpd - 1;
936 for (i = 0; i < POWER_HISTORY_LEN-1; i++)
937 *phpd-- = *phps--;
939 /* insert new value at the start, in centivolts 8-) */
940 power_history[0] = battery_centivolts;
942 #if CONFIG_CHARGING == CHARGING_CONTROL
943 if (charger_input_state == CHARGER_PLUGGED) {
944 pid_p = 0;
945 pid_i = 0;
946 snprintf(power_message, POWER_MESSAGE_LEN, "Charger plugged in");
948 * The charger was just plugged in. If the battery level is
949 * nearly charged, just trickle. If the battery is low, start
950 * a full charge cycle. If the battery level is in between,
951 * top-off and then trickle.
953 if(battery_percent > START_TOPOFF_CHG) {
954 powermgmt_last_cycle_level = battery_percent;
955 powermgmt_last_cycle_startstop_min = 0;
956 if(battery_percent >= START_TRICKLE_CHG) {
957 charge_state = TRICKLE;
958 target_voltage = TRICKLE_VOLTAGE;
959 } else {
960 charge_state = TOPOFF;
961 target_voltage = TOPOFF_VOLTAGE;
963 } else {
965 * Start the charger full strength
967 i = CHARGE_MAX_TIME_1500 * battery_capacity / 1500;
968 charge_max_time_idle =
969 i * (100 + 35 - battery_percent) / 100;
970 if (charge_max_time_idle > i) {
971 charge_max_time_idle = i;
973 charge_max_time_now = charge_max_time_idle;
975 snprintf(power_message, POWER_MESSAGE_LEN,
976 "ChgAt %d%% max %dm", battery_level(),
977 charge_max_time_now);
979 /* enable the charger after the max time calc is done,
980 because battery_level depends on if the charger is
981 on */
982 DEBUGF("power: charger inserted and battery"
983 " not full, charging\n");
984 powermgmt_last_cycle_level = battery_percent;
985 powermgmt_last_cycle_startstop_min = 0;
986 trickle_sec = 60;
987 long_delta = short_delta = 999999;
988 charge_state = CHARGING;
991 if (charge_state == CHARGING) {
992 /* alter charge time max length with extra disk use */
993 if (disk_activity_last_cycle) {
994 minutes_disk_activity++;
995 charge_max_time_now = charge_max_time_idle +
996 (minutes_disk_activity * 2 / 5);
997 disk_activity_last_cycle = false;
998 last_disk_activity = 0;
999 } else {
1000 last_disk_activity++;
1003 * Check the delta voltage over the last X minutes so we can do
1004 * our end-of-charge logic based on the battery level change.
1005 *(no longer use minimum time as logic for charge end has 50
1006 * minutes minimum charge built in)
1008 if (powermgmt_last_cycle_startstop_min > CHARGE_END_SHORTD) {
1009 short_delta = power_history[0] -
1010 power_history[CHARGE_END_SHORTD - 1];
1013 if (powermgmt_last_cycle_startstop_min > CHARGE_END_LONGD) {
1015 * Scan the history: the points where measurement is taken need to
1016 * be fairly static. (check prior to short delta 'area')
1017 * (also only check first and last 10 cycles - delta in middle OK)
1019 long_delta = power_history[0] -
1020 power_history[CHARGE_END_LONGD - 1];
1022 for(i = CHARGE_END_SHORTD; i < CHARGE_END_SHORTD + 10; i++) {
1023 if(((power_history[i] - power_history[i+1]) > 5) ||
1024 ((power_history[i] - power_history[i+1]) < -5)) {
1025 long_delta = 777777;
1026 break;
1029 for(i = CHARGE_END_LONGD - 11; i < CHARGE_END_LONGD - 1 ; i++) {
1030 if(((power_history[i] - power_history[i+1]) > 5) ||
1031 ((power_history[i] - power_history[i+1]) < -5)) {
1032 long_delta = 888888;
1033 break;
1038 snprintf(power_message, POWER_MESSAGE_LEN,
1039 "Chg %dm, max %dm", powermgmt_last_cycle_startstop_min,
1040 charge_max_time_now);
1042 * End of charge criteria (any qualify):
1043 * 1) Charged a long time
1044 * 2) DeltaV went negative for a short time ( & long delta static)
1045 * 3) DeltaV was negative over a longer period (no disk use only)
1046 * Note: short_delta and long_delta are centivolts
1048 if ((powermgmt_last_cycle_startstop_min >= charge_max_time_now) ||
1049 (short_delta <= -5 && long_delta < 5 ) || (long_delta < -2 &&
1050 last_disk_activity > CHARGE_END_LONGD)) {
1051 if (powermgmt_last_cycle_startstop_min > charge_max_time_now) {
1052 DEBUGF("power: powermgmt_last_cycle_startstop_min > charge_max_time_now, "
1053 "enough!\n");
1055 *have charged too long and deltaV detection did not
1056 *work!
1058 snprintf(power_message, POWER_MESSAGE_LEN,
1059 "Chg tmout %d min", charge_max_time_now);
1061 * Switch to trickle charging. We skip the top-off
1062 * since we've effectively done the top-off operation
1063 * already since we charged for the maximum full
1064 * charge time.
1066 powermgmt_last_cycle_level = battery_percent;
1067 powermgmt_last_cycle_startstop_min = 0;
1068 charge_state = TRICKLE;
1071 * set trickle charge target to a relative voltage instead
1072 * of an arbitrary value - the fully charged voltage may
1073 * vary according to ambient temp, battery condition etc
1074 * trickle target is -0.15v from full voltage acheived
1075 * topup target is -0.05v from full voltage
1077 target_voltage = power_history[0] - 15;
1079 } else {
1080 if(short_delta <= -5) {
1081 DEBUGF("power: short-term negative"
1082 " delta, enough!\n");
1083 snprintf(power_message, POWER_MESSAGE_LEN,
1084 "end negd %d %dmin", short_delta,
1085 powermgmt_last_cycle_startstop_min);
1086 target_voltage = power_history[CHARGE_END_SHORTD - 1]
1087 - 5;
1088 } else {
1089 DEBUGF("power: long-term small "
1090 "positive delta, enough!\n");
1091 snprintf(power_message, POWER_MESSAGE_LEN,
1092 "end lowd %d %dmin", long_delta,
1093 powermgmt_last_cycle_startstop_min);
1094 target_voltage = power_history[CHARGE_END_LONGD - 1]
1095 - 5;
1098 * Switch to top-off charging.
1100 powermgmt_last_cycle_level = battery_percent;
1101 powermgmt_last_cycle_startstop_min = 0;
1102 charge_state = TOPOFF;
1106 else if (charge_state != DISCHARGING) /* top off or trickle */
1109 *Time to switch from topoff to trickle?
1111 if ((charge_state == TOPOFF) &&
1112 (powermgmt_last_cycle_startstop_min > TOPOFF_MAX_TIME))
1114 powermgmt_last_cycle_level = battery_percent;
1115 powermgmt_last_cycle_startstop_min = 0;
1116 charge_state = TRICKLE;
1117 target_voltage = target_voltage - 10;
1120 * Adjust trickle charge time (proportional and integral terms).
1121 * Note: I considered setting the level higher if the USB is
1122 * plugged in, but it doesn't appear to be necessary and will
1123 * generate more heat [gvb].
1126 pid_p = target_voltage - battery_centivolts;
1127 if((pid_p > PID_DEADZONE) || (pid_p < -PID_DEADZONE))
1128 pid_p = pid_p * PID_PCONST;
1129 else
1130 pid_p = 0;
1131 if((unsigned) battery_centivolts < target_voltage) {
1132 if(pid_i < 60) {
1133 pid_i++; /* limit so it doesn't "wind up" */
1135 } else {
1136 if(pid_i > 0) {
1137 pid_i--; /* limit so it doesn't "wind up" */
1141 trickle_sec = pid_p + pid_i;
1143 if(trickle_sec > 60) {
1144 trickle_sec = 60;
1146 if(trickle_sec < 0) {
1147 trickle_sec = 0;
1150 } else if (charge_state == DISCHARGING) {
1151 trickle_sec = 0;
1153 * The charger is enabled here only in one case: if it was
1154 * turned on at boot time (power_init). Turn it off now.
1156 if (charger_enabled)
1157 charger_enable(false);
1160 if (charger_input_state == CHARGER_UNPLUGGED) {
1162 * The charger was just unplugged.
1164 DEBUGF("power: charger disconnected, disabling\n");
1166 charger_enable(false);
1167 powermgmt_last_cycle_level = battery_percent;
1168 powermgmt_last_cycle_startstop_min = 0;
1169 trickle_sec = 0;
1170 pid_p = 0;
1171 pid_i = 0;
1172 charge_state = DISCHARGING;
1173 snprintf(power_message, POWER_MESSAGE_LEN, "Charger: discharge");
1176 #endif /* CONFIG_CHARGING == CHARGING_CONTROL */
1178 /* sleep for a minute */
1180 #if CONFIG_CHARGING == CHARGING_CONTROL
1181 if(trickle_sec > 0) {
1182 charger_enable(true);
1183 power_thread_sleep(HZ * trickle_sec);
1185 if(trickle_sec < 60)
1186 charger_enable(false);
1187 power_thread_sleep(HZ * (60 - trickle_sec));
1188 #else
1189 power_thread_sleep(HZ * 60);
1190 #endif
1192 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
1193 if(usb_inserted()) {
1194 if(fd >= 0) {
1195 /* It is probably too late to close the file but we can try...*/
1196 close(fd);
1197 fd = -1;
1199 } else {
1200 if(fd < 0) {
1201 fd = open(DEBUG_FILE_NAME, O_WRONLY | O_APPEND | O_CREAT);
1202 if(fd >= 0) {
1203 snprintf(debug_message, DEBUG_MESSAGE_LEN,
1204 "cycle_min, bat_centivolts, bat_percent, chgr_state, charge_state, pid_p, pid_i, trickle_sec\n");
1205 write(fd, debug_message, strlen(debug_message));
1206 wrcount = 99; /* force a flush */
1209 if(fd >= 0) {
1210 snprintf(debug_message, DEBUG_MESSAGE_LEN,
1211 "%d, %d, %d, %d, %d, %d, %d, %d\n",
1212 powermgmt_last_cycle_startstop_min, battery_centivolts,
1213 battery_percent, charger_input_state, charge_state,
1214 pid_p, pid_i, trickle_sec);
1215 write(fd, debug_message, strlen(debug_message));
1216 wrcount++;
1219 #endif
1220 handle_auto_poweroff();
1222 #if CONFIG_CHARGING == CHARGING_CONTROL
1223 powermgmt_last_cycle_startstop_min++;
1224 #endif
1228 void powermgmt_init(void)
1230 /* init history to 0 */
1231 memset(power_history, 0x00, sizeof(power_history));
1232 create_thread(power_thread, power_stack, sizeof(power_stack),
1233 power_thread_name IF_PRIO(, PRIORITY_SYSTEM)
1234 IF_COP(, CPU, false));
1237 #endif /* SIMULATOR */
1239 void sys_poweroff(void)
1241 logf("sys_poweroff()");
1242 /* If the main thread fails to shut down the system, we will force a
1243 power off after an 20 second timeout - 28 seconds if recording */
1244 if (shutdown_timeout == 0)
1246 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
1247 pcf50606_reset_timeout(); /* Reset timer on first attempt only */
1248 #endif
1249 #ifdef HAVE_RECORDING
1250 if (audio_status() & AUDIO_STATUS_RECORD)
1251 shutdown_timeout += HZ*8;
1252 #endif
1253 shutdown_timeout += HZ*20;
1256 queue_post(&button_queue, SYS_POWEROFF, 0);
1259 void cancel_shutdown(void)
1261 logf("sys_cancel_shutdown()");
1263 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
1264 /* TODO: Move some things to target/ tree */
1265 if (shutdown_timeout)
1266 pcf50606_reset_timeout();
1267 #endif
1269 shutdown_timeout = 0;
1272 /* Various hardware housekeeping tasks relating to shutting down the jukebox */
1273 void shutdown_hw(void)
1275 #ifndef SIMULATOR
1276 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
1277 if(fd >= 0) {
1278 close(fd);
1279 fd = -1;
1281 #endif
1282 audio_stop();
1283 if (battery_level_safe()) { /* do not save on critical battery */
1284 #ifdef HAVE_LCD_BITMAP
1285 glyph_cache_save();
1286 #endif
1287 if(ata_disk_is_active())
1288 ata_spindown(1);
1290 while(ata_disk_is_active())
1291 sleep(HZ/10);
1293 #if !defined (IAUDIO_X5) && !defined (SANSA_E200)
1294 #if defined(HAVE_BACKLIGHT_PWM_FADING) && !defined(SIMULATOR)
1295 backlight_set_fade_out(0);
1296 #endif
1297 backlight_off();
1298 #endif /* IAUDIO_X5, SANSA_E200 */
1299 #ifdef HAVE_REMOTE_LCD
1300 remote_backlight_off();
1301 #endif
1303 #if CONFIG_CODEC != SWCODEC
1304 mp3_shutdown();
1305 #else
1306 audiohw_close();
1307 #endif
1309 /* If HD is still active we try to wait for spindown, otherwise the
1310 shutdown_timeout in power_thread_sleep will force a power off */
1311 while(ata_disk_is_active())
1312 sleep(HZ/10);
1313 #ifndef IAUDIO_X5
1314 lcd_set_contrast(0);
1315 #endif /* IAUDIO_X5 */
1316 #ifdef HAVE_REMOTE_LCD
1317 lcd_remote_set_contrast(0);
1318 #endif
1320 /* Small delay to make sure all HW gets time to flush. Especially
1321 eeprom chips are quite slow and might be still writing the last
1322 byte. */
1323 sleep(HZ/4);
1324 power_off();
1325 #endif /* #ifndef SIMULATOR */