1 /***************************************************************************
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
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 ****************************************************************************/
34 #include "mp3_playback.h"
36 #include "powermgmt.h"
37 #include "backlight.h"
45 #elif defined(HAVE_TLV320)
47 #elif defined(HAVE_WM8758)
49 #elif defined(HAVE_WM8975)
51 #elif defined(HAVE_WM8731)
54 #ifdef HAVE_LCD_BITMAP
57 #if defined(HAVE_RECORDING) && (CONFIG_CODEC == SWCODEC)
58 #include "pcm_record.h"
61 #include "lcd-remote.h"
66 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
68 #include "lcd-remote-target.h"
72 * Define DEBUG_FILE to create a csv (spreadsheet) with battery information
73 * in it (one sample per minute). This is only for very low level debug.
76 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
78 #define DEBUG_FILE_NAME "/powermgmt.csv"
79 #define DEBUG_MESSAGE_LEN 133
80 static char debug_message
[DEBUG_MESSAGE_LEN
];
81 #define DEBUG_STACK ((0x1000)/sizeof(long))
82 static int fd
; /* write debug information to this file */
88 static int shutdown_timeout
= 0;
90 #ifdef SIMULATOR /***********************************************************/
92 #define BATT_MINCVOLT 250 /* minimum centivolts of battery */
93 #define BATT_MAXCVOLT 450 /* maximum centivolts of battery */
94 #define BATT_MAXRUNTIME (10 * 60) /* maximum runtime with full battery in minutes */
96 static unsigned int batt_centivolts
= (unsigned int)BATT_MAXCVOLT
;
97 static int batt_level
= 100; /* battery capacity level in percent */
98 static int batt_time
= BATT_MAXRUNTIME
; /* estimated remaining time in minutes */
99 static time_t last_change
= 0;
101 static void battery_status_update(void)
106 if (last_change
< now
) {
109 /* change the values: */
110 batt_centivolts
-= (unsigned int)(BATT_MAXCVOLT
- BATT_MINCVOLT
) / 101;
111 if (batt_centivolts
< (unsigned int)BATT_MINCVOLT
)
112 batt_centivolts
= (unsigned int)BATT_MAXCVOLT
;
114 batt_level
= 100 * (batt_centivolts
- BATT_MINCVOLT
) / (BATT_MAXCVOLT
- BATT_MINCVOLT
);
115 batt_time
= batt_level
* BATT_MAXRUNTIME
/ 100;
119 void battery_read_info(int *adc
, int *voltage
, int *level
)
121 battery_status_update();
124 *adc
= batt_centivolts
; /* just return something */
127 *voltage
= batt_centivolts
;
133 unsigned int battery_voltage(void)
135 battery_status_update();
136 return batt_centivolts
;
139 int battery_level(void)
141 battery_status_update();
145 int battery_time(void)
147 battery_status_update();
151 bool battery_level_safe(void)
153 return battery_level() >= 10;
156 bool battery_level_critical(void)
161 void set_poweroff_timeout(int timeout
)
166 void set_battery_capacity(int capacity
)
171 void reset_poweroff_timer(void)
176 #else /* not SIMULATOR ******************************************************/
178 static const int poweroff_idle_timeout_value
[15] =
180 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 30, 45, 60
183 static const unsigned int battery_level_dangerous
[BATTERY_TYPES_COUNT
] =
185 #if CONFIG_BATTERY == BATT_LIION2200 /* FM Recorder, LiIon */
187 #elif CONFIG_BATTERY == BATT_3AAA /* Ondio: Alkaline, NiHM */
189 #elif CONFIG_BATTERY == BATT_1AA /* iRiver iFP: Alkaline, NiHM */
191 #elif CONFIG_BATTERY == BATT_LIPOL1300 /* iRiver H1x0: LiPolymer */
193 #elif CONFIG_BATTERY == BATT_LIION750 /* Sansa e200 */
195 #elif CONFIG_BATTERY == BATT_LIION830 /* Gigabeat F */
197 #elif CONFIG_BATTERY == BATT_IAUDIO_X5M5 /* iAudio X5 */
199 #elif CONFIG_BATTERY == BATT_LPCS355385 /* iriver H10 20GB: LiPolymer*/
201 #elif CONFIG_BATTERY == BATT_BP009 /* iriver H10 5/6GB: LiPolymer */
203 #else /* Player/recorder: NiMH */
208 static const unsigned short battery_level_shutoff
[BATTERY_TYPES_COUNT
] =
210 #if CONFIG_BATTERY == BATT_LIION2200 /* FM Recorder */
212 #elif CONFIG_BATTERY == BATT_3AAA /* Ondio */
214 #elif CONFIG_BATTERY == BATT_LIPOL1300 /* iRiver Hxxx */
216 #elif CONFIG_BATTERY == BATT_LIION750 /* Sansa e200 */
218 #elif CONFIG_BATTERY == BATT_LIION830 /* Gigabeat F */
220 #elif CONFIG_BATTERY == BATT_IAUDIO_X5M5 /* iAudio X5 */
222 #elif CONFIG_BATTERY == BATT_LPCS355385 /* iriver H10 20GB */
224 #elif CONFIG_BATTERY == BATT_BP009 /* iriver H10 5/6GB */
226 #else /* Player/recorder: NiMH */
231 /* voltages (centivolt) of 0%, 10%, ... 100% when charging disabled */
232 static const unsigned short percent_to_volt_discharge
[BATTERY_TYPES_COUNT
][11] =
234 #if CONFIG_BATTERY == BATT_LIION2200
235 /* measured values */
236 { 260, 285, 295, 303, 311, 320, 330, 345, 360, 380, 400 }
237 #elif CONFIG_BATTERY == BATT_3AAA
238 /* measured values */
239 { 280, 325, 341, 353, 364, 374, 385, 395, 409, 427, 475 }, /* Alkaline */
240 { 310, 355, 363, 369, 372, 374, 376, 378, 380, 386, 405 } /* NiMH */
241 #elif CONFIG_BATTERY == BATT_LIPOL1300
242 /* Below 337 the backlight starts flickering during HD access */
243 { 337, 365, 370, 374, 378, 382, 387, 393, 400, 408, 416 }
244 #elif CONFIG_BATTERY == BATT_IAUDIO_X5M5
245 /* average measured values from X5 and M5L */
246 { 350, 365, 372, 374, 376, 379, 384, 390, 395, 404, 412 }
247 #elif CONFIG_BATTERY == BATT_LPCS355385
248 /* iriver H10 20GB */
249 { 376, 380, 385, 387, 390, 395, 402, 407, 411, 418, 424 }
250 #elif CONFIG_BATTERY == BATT_BP009
251 /* iriver H10 5/6GB */
252 { 372, 374, 380, 382, 384, 388, 394, 402, 406, 415, 424 }
253 #elif CONFIG_BATTERY == BATT_1AA
254 /* These values are the same as for 3AAA divided by 3. */
255 /* May need recalibration. */
256 { 93, 108, 114, 118, 121, 125, 128, 132, 136, 142, 158 }, /* alkaline */
257 { 103, 118, 121, 123, 124, 125, 126, 127, 128, 129, 135 } /* NiMH */
258 #elif CONFIG_BATTERY == BATT_LIION830
259 /* Toshiba Gigabeat Li Ion 830mAH figured from discharge curve */
260 { 354, 357, 359, 361, 364, 366, 372, 381, 377, 381, 394 },
261 #elif CONFIG_BATTERY == BATT_LIION750
262 /* Sansa Li Ion 750mAH FIXME this is a first linear approach */
263 { 330, 339, 348, 357, 366, 375, 384, 393, 402, 411, 420 },
265 /* original values were taken directly after charging, but it should show
266 100% after turning off the device for some hours, too */
267 { 450, 481, 491, 497, 503, 507, 512, 514, 517, 525, 540 }
268 /* orig. values: ...,528,560 */
273 charger_input_state_type charger_input_state IDATA_ATTR
;
276 /* voltages (centivolt) of 0%, 10%, ... 100% when charging enabled */
277 static const unsigned short percent_to_volt_charge
[11] =
279 #if CONFIG_BATTERY == BATT_LIPOL1300
280 /* values measured over one full charging cycle */
281 354, 386, 393, 398, 400, 402, 404, 408, 413, 418, 423 /* LiPo */
282 #elif CONFIG_BATTERY == BATT_LIION750
283 /* Sansa Li Ion 750mAH FIXME*/
284 330, 339, 348, 357, 366, 375, 384, 393, 402, 411, 420
285 #elif CONFIG_BATTERY == BATT_LIION830
286 /* Toshiba Gigabeat Li Ion 830mAH */
287 354, 357, 359, 361, 364, 366, 372, 381, 377, 381, 394
288 #elif CONFIG_BATTERY == BATT_LPCS355385
289 /* iriver H10 20GB */
290 399, 403, 406, 408, 410, 412, 415, 418, 422, 426, 431
291 #elif CONFIG_BATTERY == BATT_BP009
292 /* iriver H10 5/6GB: Not yet calibrated */
293 388, 392, 396, 400, 406, 410, 415, 419, 424, 428, 433
295 /* values guessed, see
296 http://www.seattlerobotics.org/encoder/200210/LiIon2.pdf until someone
297 measures voltages over a charging cycle */
298 476, 544, 551, 556, 561, 564, 566, 576, 582, 584, 585 /* NiMH */
301 #endif /* CONFIG_CHARGING */
303 #if CONFIG_CHARGING >= CHARGING_MONITOR
304 charge_state_type charge_state
; /* charging mode */
307 #if CONFIG_CHARGING == CHARGING_CONTROL
308 int long_delta
; /* long term delta battery voltage */
309 int short_delta
; /* short term delta battery voltage */
310 bool disk_activity_last_cycle
= false; /* flag set to aid charger time
312 char power_message
[POWER_MESSAGE_LEN
] = ""; /* message that's shown in
314 /* percentage at which charging
316 int powermgmt_last_cycle_startstop_min
= 0; /* how many minutes ago was the
319 int powermgmt_last_cycle_level
= 0; /* which level had the
320 batteries at this time? */
321 int trickle_sec
= 0; /* how many seconds should the
322 charger be enabled per
325 int pid_p
= 0; /* PID proportional term */
326 int pid_i
= 0; /* PID integral term */
327 #endif /* CONFIG_CHARGING == CHARGING_CONTROL */
330 * Average battery voltage and charger voltage, filtered via a digital
331 * exponential filter.
333 static unsigned int avgbat
; /* average battery voltage (filtering) */
334 static unsigned int battery_centivolts
;/* filtered battery voltage, centvolts */
335 #ifdef HAVE_CHARGE_CTRL
336 #define BATT_AVE_SAMPLES 32 /* filter constant / @ 2Hz sample rate */
337 #elif CONFIG_BATTERY == BATT_LIPOL1300
338 #define BATT_AVE_SAMPLES 128 /* slow filter for iriver */
340 #define BATT_AVE_SAMPLES 64 /* medium filter constant for all others */
343 /* battery level (0-100%) of this minute, updated once per minute */
344 static int battery_percent
= -1;
345 static int battery_capacity
= BATTERY_CAPACITY_DEFAULT
; /* default value, mAh */
346 static int battery_type
= 0;
348 /* Power history: power_history[0] is the newest sample */
349 unsigned short power_history
[POWER_HISTORY_LEN
];
351 static char power_stack
[DEFAULT_STACK_SIZE
/2 + DEBUG_STACK
];
352 static const char power_thread_name
[] = "power";
354 static int poweroff_timeout
= 0;
355 static int powermgmt_est_runningtime_min
= -1;
357 static bool sleeptimer_active
= false;
358 static long sleeptimer_endtick
;
360 static long last_event_tick
;
362 static int voltage_to_battery_level(int battery_centivolts
);
363 static void battery_status_update(void);
364 static int runcurrent(void);
366 void battery_read_info(int *adc
, int *voltage
, int *level
)
368 int adc_battery
= adc_read(ADC_UNREG_POWER
);
369 int centivolts
= adc_battery
*BATTERY_SCALE_FACTOR
/ 10000;
375 *voltage
= centivolts
;
378 *level
= voltage_to_battery_level(centivolts
);
381 void reset_poweroff_timer(void)
383 last_event_tick
= current_tick
;
386 #if BATTERY_TYPES_COUNT > 1
387 void set_battery_type(int type
)
389 if (type
!= battery_type
) {
391 battery_status_update(); /* recalculate the battery status */
396 void set_battery_capacity(int capacity
)
398 battery_capacity
= capacity
;
399 if (battery_capacity
> BATTERY_CAPACITY_MAX
)
400 battery_capacity
= BATTERY_CAPACITY_MAX
;
401 if (battery_capacity
< BATTERY_CAPACITY_MIN
)
402 battery_capacity
= BATTERY_CAPACITY_MIN
;
403 battery_status_update(); /* recalculate the battery status */
406 int battery_time(void)
408 return powermgmt_est_runningtime_min
;
411 /* Returns battery level in percent */
412 int battery_level(void)
414 return battery_percent
;
417 /* Returns filtered battery voltage [centivolts] */
418 unsigned int battery_voltage(void)
420 return battery_centivolts
;
423 /* Returns battery voltage from ADC [centivolts] */
424 int battery_adc_voltage(void)
426 return (adc_read(ADC_UNREG_POWER
) * BATTERY_SCALE_FACTOR
+ 5000) / 10000;
429 /* Tells if the battery level is safe for disk writes */
430 bool battery_level_safe(void)
432 return battery_centivolts
> battery_level_dangerous
[battery_type
];
435 /* Tells if the battery is in critical powersaving state */
436 bool battery_level_critical(void)
438 return ((battery_capacity
* battery_percent
/ BATTERY_CAPACITY_MIN
) < 10);
441 void set_poweroff_timeout(int timeout
)
443 poweroff_timeout
= timeout
;
446 void set_sleep_timer(int seconds
)
449 sleeptimer_active
= true;
450 sleeptimer_endtick
= current_tick
+ seconds
* HZ
;
453 sleeptimer_active
= false;
454 sleeptimer_endtick
= 0;
458 int get_sleep_timer(void)
460 if(sleeptimer_active
)
461 return (sleeptimer_endtick
- current_tick
) / HZ
;
466 /* look into the percent_to_volt_* table and get a realistic battery level */
467 static int voltage_to_percent(int voltage
, const short* table
)
469 if (voltage
<= table
[0])
472 if (voltage
>= table
[10])
475 /* search nearest value */
477 while ((i
< 10) && (table
[i
+1] < voltage
))
479 /* interpolate linear between the smaller and greater value */
480 return (i
* 10) /* Tens digit, 10% per entry */
481 + (((voltage
- table
[i
]) * 10)
482 / (table
[i
+1] - table
[i
])); /* Ones digit: interpolated */
486 /* update battery level and estimated runtime, called once per minute or
487 * when battery capacity / type settings are changed */
488 static int voltage_to_battery_level(int battery_centivolts
)
492 #if defined(CONFIG_CHARGER) && CONFIG_BATTERY == BATT_LIPOL1300
493 if (charger_input_state
== NO_CHARGER
) {
494 /* discharging. calculate new battery level and average with last */
495 level
= voltage_to_percent(battery_centivolts
,
496 percent_to_volt_discharge
[battery_type
]);
497 if (level
!= (battery_percent
- 1))
498 level
= (level
+ battery_percent
+ 1) / 2;
500 else if (charger_input_state
== CHARGER_UNPLUGGED
) {
501 /* just unplugged. adjust filtered values */
502 battery_centivolts
-= percent_to_volt_charge
[battery_percent
/10] -
503 percent_to_volt_discharge
[0][battery_percent
/10];
504 avgbat
= battery_centivolts
* 10000 * BATT_AVE_SAMPLES
;
505 level
= battery_percent
;
507 else if (charger_input_state
== CHARGER_PLUGGED
) {
508 /* just plugged in. adjust battery values */
509 battery_centivolts
+= percent_to_volt_charge
[battery_percent
/10] -
510 percent_to_volt_discharge
[0][battery_percent
/10];
511 avgbat
= battery_centivolts
* 10000 * BATT_AVE_SAMPLES
;
512 level
= MIN(12 * battery_percent
/ 10, 99);
514 else { /* charging. calculate new battery level */
515 level
= voltage_to_percent(battery_centivolts
,
516 percent_to_volt_charge
);
518 #elif CONFIG_CHARGING >= CHARGING_MONITOR
519 if (charge_state
== DISCHARGING
) {
520 level
= voltage_to_percent(battery_centivolts
,
521 percent_to_volt_discharge
[battery_type
]);
523 else if (charge_state
== CHARGING
) {
524 /* battery level is defined to be < 100% until charging is finished */
525 level
= MIN(voltage_to_percent(battery_centivolts
,
526 percent_to_volt_charge
), 99);
528 else { /* in topoff/trickle charge, battery is by definition 100% full */
532 /* always use the discharge table */
533 level
= voltage_to_percent(battery_centivolts
,
534 percent_to_volt_discharge
[battery_type
]);
540 static void battery_status_update(void)
542 int level
= voltage_to_battery_level(battery_centivolts
);
545 /* calculate estimated remaining running time */
546 /* discharging: remaining running time */
547 /* charging: remaining charging time */
548 #if CONFIG_CHARGING >= CHARGING_MONITOR
549 if (charge_state
== CHARGING
) {
550 powermgmt_est_runningtime_min
= (100 - level
) * battery_capacity
* 60
551 / 100 / (CURRENT_MAX_CHG
- runcurrent());
554 #elif CONFIG_CHARGING && CONFIG_BATTERY == BATT_LIPOL1300
555 if (charger_inserted()) {
556 #ifdef IRIVER_H300_SERIES
557 /* H300_SERIES use CURRENT_MAX_CHG for basic charge time (80%)
558 * plus 110 min top off charge time */
559 powermgmt_est_runningtime_min
= ((100-level
) * battery_capacity
* 80
560 /100 / CURRENT_MAX_CHG
) + 110;
562 /* H100_SERIES scaled for 160 min basic charge time (80%) on
563 * 1600 mAh battery plus 110 min top off charge time */
564 powermgmt_est_runningtime_min
= ((100 - level
) * battery_capacity
567 level
= (level
* 80) / 100;
568 if (level
> 72) { /* > 91% */
569 int i
= POWER_HISTORY_LEN
;
571 #ifdef HAVE_CHARGE_STATE
572 if (charge_state
== DISCHARGING
)
575 while ((i
> 2) && (d
> 0)) /* search zero or neg. delta */
576 d
= power_history
[0] - power_history
[--i
];
577 if ((((d
== 0) && (i
> 6)) || (d
== -1)) && (i
< 118)) {
578 /* top off charging */
579 level
= MIN(80 + (i
*19 / 113), 99); /* show 81% .. 99% */
580 powermgmt_est_runningtime_min
= MAX(116 - i
, 0);
582 else if ((d
< 0) || (i
> 117)) {
583 /* charging finished */
585 powermgmt_est_runningtime_min
= battery_capacity
* 60
591 #endif /* BATT_LIPOL1300 */
593 if ((battery_centivolts
+ 2) > percent_to_volt_discharge
[0][0])
594 powermgmt_est_runningtime_min
= (level
+ battery_percent
) * 60 *
595 battery_capacity
/ 200 / runcurrent();
597 powermgmt_est_runningtime_min
= (battery_centivolts
-
598 battery_level_shutoff
[0]) / 2;
601 battery_percent
= level
;
605 * We shut off in the following cases:
606 * 1) The unit is idle, not playing music
607 * 2) The unit is playing music, but is paused
608 * 3) The battery level has reached shutdown limit
610 * We do not shut off in the following cases:
611 * 1) The USB is connected
612 * 2) The charger is connected
613 * 3) We are recording, or recording with pause
614 * 4) The radio is playing
616 static void handle_auto_poweroff(void)
618 long timeout
= poweroff_idle_timeout_value
[poweroff_timeout
]*60*HZ
;
619 int audio_stat
= audio_status();
623 * Inhibit shutdown as long as the charger is plugged in. If it is
624 * unplugged, wait for a timeout period and then shut down.
626 if(charger_input_state
== CHARGER
|| audio_stat
== AUDIO_STATUS_PLAY
) {
627 last_event_tick
= current_tick
;
631 /* switch off unit if battery level is too low for reliable operation */
632 #if (CONFIG_BATTERY!=BATT_4AA_NIMH) && (CONFIG_BATTERY!=BATT_3AAA)&& \
633 (CONFIG_BATTERY!=BATT_1AA)
634 if(battery_centivolts
< battery_level_shutoff
[battery_type
]) {
635 if(!shutdown_timeout
) {
643 #if CONFIG_TUNER && !defined(BOOTLOADER)
644 (!(get_radio_status() & FMRADIO_PLAYING
)) &&
647 ((audio_stat
== 0) ||
648 ((audio_stat
== (AUDIO_STATUS_PLAY
| AUDIO_STATUS_PAUSE
)) &&
649 !sleeptimer_active
)))
651 if(TIME_AFTER(current_tick
, last_event_tick
+ timeout
) &&
652 TIME_AFTER(current_tick
, last_disk_activity
+ timeout
))
659 /* Handle sleeptimer */
660 if(sleeptimer_active
&& !usb_inserted())
662 if(TIME_AFTER(current_tick
, sleeptimer_endtick
))
665 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
666 if((charger_input_state
== CHARGER
) ||
667 (charger_input_state
== CHARGER_PLUGGED
))
669 DEBUGF("Sleep timer timeout. Stopping...\n");
671 backlight_off(); /* Nighty, nighty... */
676 DEBUGF("Sleep timer timeout. Shutting off...\n");
685 * Estimate how much current we are drawing just to run.
687 static int runcurrent(void)
691 #if MEM == 8 && !defined(HAVE_MMC)
692 /* assuming 192 kbps, the running time is 22% longer with 8MB */
693 current
= (CURRENT_NORMAL
*100/122);
695 current
= CURRENT_NORMAL
;
696 #endif /* MEM == 8 */
699 #if defined(HAVE_USB_POWER)
700 #if (CURRENT_USB < CURRENT_NORMAL)
708 current
= CURRENT_USB
;
711 #if CONFIG_BACKLIGHT && !defined(BOOTLOADER)
712 if (backlight_get_current_timeout() == 0) /* LED always on */
713 current
+= CURRENT_BACKLIGHT
;
716 #if defined(HAVE_RECORDING) && defined(CURRENT_RECORD)
717 if (audio_status() & AUDIO_STATUS_RECORD
)
718 current
+= CURRENT_RECORD
;
721 #ifdef HAVE_SPDIF_POWER
723 current
+= CURRENT_SPDIF_OUT
;
726 #ifdef HAVE_REMOTE_LCD
728 current
+= CURRENT_REMOTE
;
735 /* Check to see whether or not we've received an alarm in the last second */
736 #ifdef HAVE_RTC_ALARM
737 static void power_thread_rtc_process(void)
739 if (rtc_check_alarm_flag()) {
740 rtc_enable_alarm(false);
746 * This function is called to do the relativly long sleep waits from within the
747 * main power_thread loop while at the same time servicing any other periodic
748 * functions in the power thread which need to be called at a faster periodic
749 * rate than the slow periodic rate of the main power_thread loop.
751 * While we are waiting for the time to expire, we average the battery
754 static void power_thread_sleep(int ticks
)
762 * Detect charger plugged/unplugged transitions. On a plugged or
763 * unplugged event, we return immediately, run once through the main
764 * loop (including the subroutines), and end up back here where we
765 * transition to the appropriate steady state charger on/off state.
767 if(charger_inserted()
768 #ifdef HAVE_USB_POWER /* USB powered or USB inserted both provide power */
771 || (usb_inserted() && usb_charging_enabled())
775 switch(charger_input_state
) {
777 case CHARGER_UNPLUGGED
:
778 charger_input_state
= CHARGER_PLUGGED
;
780 case CHARGER_PLUGGED
:
781 queue_broadcast(SYS_CHARGER_CONNECTED
, 0);
782 charger_input_state
= CHARGER
;
787 } else { /* charger not inserted */
788 switch(charger_input_state
) {
791 case CHARGER_UNPLUGGED
:
792 queue_broadcast(SYS_CHARGER_DISCONNECTED
, 0);
793 charger_input_state
= NO_CHARGER
;
795 case CHARGER_PLUGGED
:
797 charger_input_state
= CHARGER_UNPLUGGED
;
802 #if CONFIG_CHARGING == CHARGING_MONITOR
803 switch (charger_input_state
) {
804 case CHARGER_UNPLUGGED
:
806 charge_state
= DISCHARGING
;
808 case CHARGER_PLUGGED
:
810 if (charging_state()) {
811 charge_state
= CHARGING
;
813 charge_state
= DISCHARGING
;
818 #endif /* CONFIG_CHARGING == CHARGING_MONITOR */
820 small_ticks
= MIN(HZ
/2, ticks
);
822 ticks
-= small_ticks
;
824 /* If the power off timeout expires, the main thread has failed
825 to shut down the system, and we need to force a power off */
826 if(shutdown_timeout
) {
827 shutdown_timeout
-= small_ticks
;
828 if(shutdown_timeout
<= 0)
832 #ifdef HAVE_RTC_ALARM
833 power_thread_rtc_process();
837 * Do a digital exponential filter. We don't sample the battery if
838 * the disk is spinning unless we are in USB mode (the disk will most
839 * likely always be spinning in USB mode).
841 if (!ata_disk_is_active() || usb_inserted()) {
842 avgbat
+= adc_read(ADC_UNREG_POWER
) * BATTERY_SCALE_FACTOR
843 - (avgbat
/ BATT_AVE_SAMPLES
);
845 * battery_centivolts is the centivolt-scaled filtered battery value.
847 battery_centivolts
= (avgbat
/ BATT_AVE_SAMPLES
+ 5000) / 10000;
849 /* update battery status every time an update is available */
850 battery_status_update();
852 else if (battery_percent
< 8) {
853 /* If battery is low, observe voltage during disk activity.
854 * Shut down if voltage drops below shutoff level and we are not
855 * using NiMH or Alkaline batteries.
857 battery_centivolts
= (battery_adc_voltage() +
858 battery_centivolts
+ 1) / 2;
860 /* update battery status every time an update is available */
861 battery_status_update();
863 #if (CONFIG_BATTERY!=BATT_4AA_NIMH) && (CONFIG_BATTERY!=BATT_3AAA)&& \
864 (CONFIG_BATTERY!=BATT_1AA)
865 if (!shutdown_timeout
&&
866 (battery_centivolts
< battery_level_shutoff
[battery_type
]))
870 avgbat
+= battery_centivolts
* 10000
871 - (avgbat
/ BATT_AVE_SAMPLES
);
874 #if CONFIG_CHARGING == CHARGING_CONTROL
875 if (ata_disk_is_active()) {
876 /* flag hdd use for charging calculation */
877 disk_activity_last_cycle
= true;
880 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
882 * If we have a lot of pending writes or if the disk is spining,
883 * fsync the debug log file.
885 if((wrcount
> 10) || ((wrcount
> 0) && ata_disk_is_active())) {
895 * This power thread maintains a history of battery voltage
896 * and implements a charging algorithm.
897 * For a complete description of the charging algorithm read
898 * docs/CHARGING_ALGORITHM.
901 static void power_thread(void)
904 short *phps
, *phpd
; /* power history rotation pointers */
905 #if CONFIG_CHARGING == CHARGING_CONTROL
906 unsigned int target_voltage
= TRICKLE_VOLTAGE
; /* desired topoff/trickle
908 int charge_max_time_idle
= 0; /* max. charging duration, calculated at
909 * beginning of charging */
910 int charge_max_time_now
= 0; /* max. charging duration including
912 int minutes_disk_activity
= 0; /* count minutes of hdd use during
914 int last_disk_activity
= CHARGE_END_LONGD
+ 1; /* last hdd use x mins ago */
917 /* initialize the voltages for the exponential filter */
918 avgbat
= adc_read(ADC_UNREG_POWER
) * BATTERY_SCALE_FACTOR
+ 15000;
920 #ifndef HAVE_MMC /* this adjustment is only needed for HD based */
921 /* The battery voltage is usually a little lower directly after
922 turning on, because the disk was used heavily. Raise it by 5% */
924 if(!charger_inserted()) /* only if charger not connected */
926 avgbat
+= (percent_to_volt_discharge
[battery_type
][6] -
927 percent_to_volt_discharge
[battery_type
][5]) * 5000;
928 #endif /* not HAVE_MMC */
930 avgbat
= avgbat
* BATT_AVE_SAMPLES
;
931 battery_centivolts
= avgbat
/ BATT_AVE_SAMPLES
/ 10000;
934 if(charger_inserted()) {
935 battery_percent
= voltage_to_percent(battery_centivolts
,
936 percent_to_volt_charge
);
937 #if CONFIG_BATTERY == BATT_LIPOL1300
938 charger_input_state
= CHARGER
;
942 { battery_percent
= voltage_to_percent(battery_centivolts
,
943 percent_to_volt_discharge
[battery_type
]);
944 battery_percent
+= (battery_percent
< 100);
947 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
954 /* rotate the power history */
955 phpd
= &power_history
[POWER_HISTORY_LEN
- 1];
957 for (i
= 0; i
< POWER_HISTORY_LEN
-1; i
++)
960 /* insert new value at the start, in centivolts 8-) */
961 power_history
[0] = battery_centivolts
;
963 #if CONFIG_CHARGING == CHARGING_CONTROL
964 if (charger_input_state
== CHARGER_PLUGGED
) {
967 snprintf(power_message
, POWER_MESSAGE_LEN
, "Charger plugged in");
969 * The charger was just plugged in. If the battery level is
970 * nearly charged, just trickle. If the battery is low, start
971 * a full charge cycle. If the battery level is in between,
972 * top-off and then trickle.
974 if(battery_percent
> START_TOPOFF_CHG
) {
975 powermgmt_last_cycle_level
= battery_percent
;
976 powermgmt_last_cycle_startstop_min
= 0;
977 if(battery_percent
>= START_TRICKLE_CHG
) {
978 charge_state
= TRICKLE
;
979 target_voltage
= TRICKLE_VOLTAGE
;
981 charge_state
= TOPOFF
;
982 target_voltage
= TOPOFF_VOLTAGE
;
986 * Start the charger full strength
988 i
= CHARGE_MAX_TIME_1500
* battery_capacity
/ 1500;
989 charge_max_time_idle
=
990 i
* (100 + 35 - battery_percent
) / 100;
991 if (charge_max_time_idle
> i
) {
992 charge_max_time_idle
= i
;
994 charge_max_time_now
= charge_max_time_idle
;
996 snprintf(power_message
, POWER_MESSAGE_LEN
,
997 "ChgAt %d%% max %dm", battery_level(),
998 charge_max_time_now
);
1000 /* enable the charger after the max time calc is done,
1001 because battery_level depends on if the charger is
1003 DEBUGF("power: charger inserted and battery"
1004 " not full, charging\n");
1005 powermgmt_last_cycle_level
= battery_percent
;
1006 powermgmt_last_cycle_startstop_min
= 0;
1008 long_delta
= short_delta
= 999999;
1009 charge_state
= CHARGING
;
1012 if (charge_state
== CHARGING
) {
1013 /* alter charge time max length with extra disk use */
1014 if (disk_activity_last_cycle
) {
1015 minutes_disk_activity
++;
1016 charge_max_time_now
= charge_max_time_idle
+
1017 (minutes_disk_activity
* 2 / 5);
1018 disk_activity_last_cycle
= false;
1019 last_disk_activity
= 0;
1021 last_disk_activity
++;
1024 * Check the delta voltage over the last X minutes so we can do
1025 * our end-of-charge logic based on the battery level change.
1026 *(no longer use minimum time as logic for charge end has 50
1027 * minutes minimum charge built in)
1029 if (powermgmt_last_cycle_startstop_min
> CHARGE_END_SHORTD
) {
1030 short_delta
= power_history
[0] -
1031 power_history
[CHARGE_END_SHORTD
- 1];
1034 if (powermgmt_last_cycle_startstop_min
> CHARGE_END_LONGD
) {
1036 * Scan the history: the points where measurement is taken need to
1037 * be fairly static. (check prior to short delta 'area')
1038 * (also only check first and last 10 cycles - delta in middle OK)
1040 long_delta
= power_history
[0] -
1041 power_history
[CHARGE_END_LONGD
- 1];
1043 for(i
= CHARGE_END_SHORTD
; i
< CHARGE_END_SHORTD
+ 10; i
++) {
1044 if(((power_history
[i
] - power_history
[i
+1]) > 5) ||
1045 ((power_history
[i
] - power_history
[i
+1]) < -5)) {
1046 long_delta
= 777777;
1050 for(i
= CHARGE_END_LONGD
- 11; i
< CHARGE_END_LONGD
- 1 ; i
++) {
1051 if(((power_history
[i
] - power_history
[i
+1]) > 5) ||
1052 ((power_history
[i
] - power_history
[i
+1]) < -5)) {
1053 long_delta
= 888888;
1059 snprintf(power_message
, POWER_MESSAGE_LEN
,
1060 "Chg %dm, max %dm", powermgmt_last_cycle_startstop_min
,
1061 charge_max_time_now
);
1063 * End of charge criteria (any qualify):
1064 * 1) Charged a long time
1065 * 2) DeltaV went negative for a short time ( & long delta static)
1066 * 3) DeltaV was negative over a longer period (no disk use only)
1067 * Note: short_delta and long_delta are centivolts
1069 if ((powermgmt_last_cycle_startstop_min
>= charge_max_time_now
) ||
1070 (short_delta
<= -5 && long_delta
< 5 ) || (long_delta
< -2 &&
1071 last_disk_activity
> CHARGE_END_LONGD
)) {
1072 if (powermgmt_last_cycle_startstop_min
> charge_max_time_now
) {
1073 DEBUGF("power: powermgmt_last_cycle_startstop_min > charge_max_time_now, "
1076 *have charged too long and deltaV detection did not
1079 snprintf(power_message
, POWER_MESSAGE_LEN
,
1080 "Chg tmout %d min", charge_max_time_now
);
1082 * Switch to trickle charging. We skip the top-off
1083 * since we've effectively done the top-off operation
1084 * already since we charged for the maximum full
1087 powermgmt_last_cycle_level
= battery_percent
;
1088 powermgmt_last_cycle_startstop_min
= 0;
1089 charge_state
= TRICKLE
;
1092 * set trickle charge target to a relative voltage instead
1093 * of an arbitrary value - the fully charged voltage may
1094 * vary according to ambient temp, battery condition etc
1095 * trickle target is -0.15v from full voltage acheived
1096 * topup target is -0.05v from full voltage
1098 target_voltage
= power_history
[0] - 15;
1101 if(short_delta
<= -5) {
1102 DEBUGF("power: short-term negative"
1103 " delta, enough!\n");
1104 snprintf(power_message
, POWER_MESSAGE_LEN
,
1105 "end negd %d %dmin", short_delta
,
1106 powermgmt_last_cycle_startstop_min
);
1107 target_voltage
= power_history
[CHARGE_END_SHORTD
- 1]
1110 DEBUGF("power: long-term small "
1111 "positive delta, enough!\n");
1112 snprintf(power_message
, POWER_MESSAGE_LEN
,
1113 "end lowd %d %dmin", long_delta
,
1114 powermgmt_last_cycle_startstop_min
);
1115 target_voltage
= power_history
[CHARGE_END_LONGD
- 1]
1119 * Switch to top-off charging.
1121 powermgmt_last_cycle_level
= battery_percent
;
1122 powermgmt_last_cycle_startstop_min
= 0;
1123 charge_state
= TOPOFF
;
1127 else if (charge_state
!= DISCHARGING
) /* top off or trickle */
1130 *Time to switch from topoff to trickle?
1132 if ((charge_state
== TOPOFF
) &&
1133 (powermgmt_last_cycle_startstop_min
> TOPOFF_MAX_TIME
))
1135 powermgmt_last_cycle_level
= battery_percent
;
1136 powermgmt_last_cycle_startstop_min
= 0;
1137 charge_state
= TRICKLE
;
1138 target_voltage
= target_voltage
- 10;
1141 * Adjust trickle charge time (proportional and integral terms).
1142 * Note: I considered setting the level higher if the USB is
1143 * plugged in, but it doesn't appear to be necessary and will
1144 * generate more heat [gvb].
1147 pid_p
= target_voltage
- battery_centivolts
;
1148 if((pid_p
> PID_DEADZONE
) || (pid_p
< -PID_DEADZONE
))
1149 pid_p
= pid_p
* PID_PCONST
;
1152 if((unsigned) battery_centivolts
< target_voltage
) {
1154 pid_i
++; /* limit so it doesn't "wind up" */
1158 pid_i
--; /* limit so it doesn't "wind up" */
1162 trickle_sec
= pid_p
+ pid_i
;
1164 if(trickle_sec
> 60) {
1167 if(trickle_sec
< 0) {
1171 } else if (charge_state
== DISCHARGING
) {
1174 * The charger is enabled here only in one case: if it was
1175 * turned on at boot time (power_init). Turn it off now.
1177 if (charger_enabled
)
1178 charger_enable(false);
1181 if (charger_input_state
== CHARGER_UNPLUGGED
) {
1183 * The charger was just unplugged.
1185 DEBUGF("power: charger disconnected, disabling\n");
1187 charger_enable(false);
1188 powermgmt_last_cycle_level
= battery_percent
;
1189 powermgmt_last_cycle_startstop_min
= 0;
1193 charge_state
= DISCHARGING
;
1194 snprintf(power_message
, POWER_MESSAGE_LEN
, "Charger: discharge");
1197 #endif /* CONFIG_CHARGING == CHARGING_CONTROL */
1199 /* sleep for a minute */
1201 #if CONFIG_CHARGING == CHARGING_CONTROL
1202 if(trickle_sec
> 0) {
1203 charger_enable(true);
1204 power_thread_sleep(HZ
* trickle_sec
);
1206 if(trickle_sec
< 60)
1207 charger_enable(false);
1208 power_thread_sleep(HZ
* (60 - trickle_sec
));
1210 power_thread_sleep(HZ
* 60);
1213 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
1214 if(usb_inserted()) {
1216 /* It is probably too late to close the file but we can try...*/
1222 fd
= open(DEBUG_FILE_NAME
, O_WRONLY
| O_APPEND
| O_CREAT
);
1224 snprintf(debug_message
, DEBUG_MESSAGE_LEN
,
1225 "cycle_min, bat_centivolts, bat_percent, chgr_state, charge_state, pid_p, pid_i, trickle_sec\n");
1226 write(fd
, debug_message
, strlen(debug_message
));
1227 wrcount
= 99; /* force a flush */
1231 snprintf(debug_message
, DEBUG_MESSAGE_LEN
,
1232 "%d, %d, %d, %d, %d, %d, %d, %d\n",
1233 powermgmt_last_cycle_startstop_min
, battery_centivolts
,
1234 battery_percent
, charger_input_state
, charge_state
,
1235 pid_p
, pid_i
, trickle_sec
);
1236 write(fd
, debug_message
, strlen(debug_message
));
1241 handle_auto_poweroff();
1243 #if CONFIG_CHARGING == CHARGING_CONTROL
1244 powermgmt_last_cycle_startstop_min
++;
1249 void powermgmt_init(void)
1251 /* init history to 0 */
1252 memset(power_history
, 0x00, sizeof(power_history
));
1253 create_thread(power_thread
, power_stack
, sizeof(power_stack
),
1254 power_thread_name
IF_PRIO(, PRIORITY_SYSTEM
)
1255 IF_COP(, CPU
, false));
1258 #endif /* SIMULATOR */
1260 void sys_poweroff(void)
1262 logf("sys_poweroff()");
1263 /* If the main thread fails to shut down the system, we will force a
1264 power off after an 20 second timeout - 28 seconds if recording */
1265 if (shutdown_timeout
== 0)
1267 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
1268 pcf50606_reset_timeout(); /* Reset timer on first attempt only */
1270 #ifdef HAVE_RECORDING
1271 if (audio_status() & AUDIO_STATUS_RECORD
)
1272 shutdown_timeout
+= HZ
*8;
1274 shutdown_timeout
+= HZ
*20;
1277 queue_post(&button_queue
, SYS_POWEROFF
, 0);
1280 void cancel_shutdown(void)
1282 logf("sys_cancel_shutdown()");
1284 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
1285 /* TODO: Move some things to target/ tree */
1286 if (shutdown_timeout
)
1287 pcf50606_reset_timeout();
1290 shutdown_timeout
= 0;
1293 /* Various hardware housekeeping tasks relating to shutting down the jukebox */
1294 void shutdown_hw(void)
1297 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
1304 if (!battery_level_critical()) { /* do not save on critical battery */
1305 #ifdef HAVE_LCD_BITMAP
1308 if(ata_disk_is_active())
1311 while(ata_disk_is_active())
1315 #if defined(HAVE_BACKLIGHT_PWM_FADING) && !defined(SIMULATOR)
1316 backlight_set_fade_out(0);
1319 #endif /* IAUDIO_X5 */
1320 #ifdef HAVE_REMOTE_LCD
1321 remote_backlight_off();
1324 #if CONFIG_CODEC != SWCODEC
1330 #elif defined(HAVE_TLV320)
1332 #elif defined(HAVE_WM8758) || defined(HAVE_WM8975) | defined(HAVE_WM8731)
1335 /* If HD is still active we try to wait for spindown, otherwise the
1336 shutdown_timeout in power_thread_sleep will force a power off */
1337 while(ata_disk_is_active())
1340 lcd_set_contrast(0);
1341 #endif /* IAUDIO_X5 */
1342 #ifdef HAVE_REMOTE_LCD
1343 lcd_remote_set_contrast(0);
1346 /* Small delay to make sure all HW gets time to flush. Especially
1347 eeprom chips are quite slow and might be still writing the last
1351 #endif /* #ifndef SIMULATOR */