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"
44 #ifdef HAVE_LCD_BITMAP
47 #if defined(HAVE_RECORDING) && (CONFIG_CODEC == SWCODEC)
48 #include "pcm_record.h"
51 #include "lcd-remote.h"
56 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
58 #include "lcd-remote-target.h"
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.
66 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
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 */
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)
96 if (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();
114 *adc
= batt_centivolts
; /* just return something */
117 *voltage
= batt_centivolts
;
123 unsigned int battery_voltage(void)
125 battery_status_update();
126 return batt_centivolts
;
129 int battery_level(void)
131 battery_status_update();
135 int battery_time(void)
137 battery_status_update();
141 bool battery_level_safe(void)
143 return battery_level() >= 10;
146 void set_poweroff_timeout(int timeout
)
151 void set_battery_capacity(int 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 */
174 #elif CONFIG_BATTERY == BATT_1AA /* iRiver iFP: Alkaline, NiHM */
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 */
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 */
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 */
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 },
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 */
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
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 */
306 #endif /* CONFIG_CHARGING */
308 #if CONFIG_CHARGING >= CHARGING_MONITOR
309 charge_state_type charge_state
; /* charging mode */
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
317 char power_message
[POWER_MESSAGE_LEN
] = ""; /* message that's shown in
319 /* percentage at which charging
321 int powermgmt_last_cycle_startstop_min
= 0; /* how many minutes ago was the
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
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 */
345 #define BATT_AVE_SAMPLES 64 /* medium filter constant for all others */
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;
380 *voltage
= centivolts
;
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
) {
396 battery_status_update(); /* recalculate the battery status */
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
)
448 sleeptimer_active
= true;
449 sleeptimer_endtick
= current_tick
+ seconds
* HZ
;
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
;
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])
471 if (voltage
>= table
[10])
474 /* search nearest value */
476 while ((i
< 10) && (table
[i
+1] < voltage
))
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
)
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 */
531 /* always use the discharge table */
532 level
= voltage_to_percent(battery_centivolts
,
533 percent_to_volt_discharge
[battery_type
]);
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());
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;
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
566 level
= (level
* 80) / 100;
567 if (level
> 72) { /* > 91% */
568 int i
= POWER_HISTORY_LEN
;
570 #ifdef HAVE_CHARGE_STATE
571 if (charge_state
== DISCHARGING
)
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 */
584 powermgmt_est_runningtime_min
= battery_capacity
* 60
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();
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();
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
;
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
) {
642 #if CONFIG_TUNER && !defined(BOOTLOADER)
643 (!(get_radio_status() & FMRADIO_PLAYING
)) &&
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
))
658 /* Handle sleeptimer */
659 if(sleeptimer_active
&& !usb_inserted())
661 if(TIME_AFTER(current_tick
, sleeptimer_endtick
))
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");
670 backlight_off(); /* Nighty, nighty... */
675 DEBUGF("Sleep timer timeout. Shutting off...\n");
684 * Estimate how much current we are drawing just to run.
686 static int runcurrent(void)
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);
694 current
= CURRENT_NORMAL
;
695 #endif /* MEM == 8 */
698 #if defined(HAVE_USB_POWER)
699 #if (CURRENT_USB < CURRENT_NORMAL)
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
;
715 #if defined(HAVE_RECORDING) && defined(CURRENT_RECORD)
716 if (audio_status() & AUDIO_STATUS_RECORD
)
717 current
+= CURRENT_RECORD
;
720 #ifdef HAVE_SPDIF_POWER
722 current
+= CURRENT_SPDIF_OUT
;
725 #ifdef HAVE_REMOTE_LCD
727 current
+= CURRENT_REMOTE
;
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);
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
753 static void power_thread_sleep(int ticks
)
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 */
770 || (usb_inserted() && usb_charging_enabled())
774 switch(charger_input_state
) {
776 case CHARGER_UNPLUGGED
:
777 charger_input_state
= CHARGER_PLUGGED
;
779 case CHARGER_PLUGGED
:
780 queue_broadcast(SYS_CHARGER_CONNECTED
, 0);
781 charger_input_state
= CHARGER
;
786 } else { /* charger not inserted */
787 switch(charger_input_state
) {
790 case CHARGER_UNPLUGGED
:
791 queue_broadcast(SYS_CHARGER_DISCONNECTED
, 0);
792 charger_input_state
= NO_CHARGER
;
794 case CHARGER_PLUGGED
:
796 charger_input_state
= CHARGER_UNPLUGGED
;
801 #if CONFIG_CHARGING == CHARGING_MONITOR
802 switch (charger_input_state
) {
803 case CHARGER_UNPLUGGED
:
805 charge_state
= DISCHARGING
;
807 case CHARGER_PLUGGED
:
809 if (charging_state()) {
810 charge_state
= CHARGING
;
812 charge_state
= DISCHARGING
;
817 #endif /* CONFIG_CHARGING == CHARGING_MONITOR */
819 small_ticks
= MIN(HZ
/2, 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)
831 #ifdef HAVE_RTC_ALARM
832 power_thread_rtc_process();
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
]))
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;
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())) {
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)
903 short *phps
, *phpd
; /* power history rotation pointers */
904 #if CONFIG_CHARGING == CHARGING_CONTROL
905 unsigned int target_voltage
= TRICKLE_VOLTAGE
; /* desired topoff/trickle
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
911 int minutes_disk_activity
= 0; /* count minutes of hdd use during
913 int last_disk_activity
= CHARGE_END_LONGD
+ 1; /* last hdd use x mins ago */
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% */
923 if(!charger_inserted()) /* only if charger not connected */
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;
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
;
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)
953 /* rotate the power history */
954 phpd
= &power_history
[POWER_HISTORY_LEN
- 1];
956 for (i
= 0; i
< POWER_HISTORY_LEN
-1; i
++)
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
) {
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
;
980 charge_state
= TOPOFF
;
981 target_voltage
= TOPOFF_VOLTAGE
;
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
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;
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;
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;
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;
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, "
1075 *have charged too long and deltaV detection did not
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
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;
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]
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]
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
;
1151 if((unsigned) battery_centivolts
< target_voltage
) {
1153 pid_i
++; /* limit so it doesn't "wind up" */
1157 pid_i
--; /* limit so it doesn't "wind up" */
1161 trickle_sec
= pid_p
+ pid_i
;
1163 if(trickle_sec
> 60) {
1166 if(trickle_sec
< 0) {
1170 } else if (charge_state
== DISCHARGING
) {
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;
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
));
1209 power_thread_sleep(HZ
* 60);
1212 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
1213 if(usb_inserted()) {
1215 /* It is probably too late to close the file but we can try...*/
1221 fd
= open(DEBUG_FILE_NAME
, O_WRONLY
| O_APPEND
| O_CREAT
);
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 */
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
));
1240 handle_auto_poweroff();
1242 #if CONFIG_CHARGING == CHARGING_CONTROL
1243 powermgmt_last_cycle_startstop_min
++;
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 */
1269 #ifdef HAVE_RECORDING
1270 if (audio_status() & AUDIO_STATUS_RECORD
)
1271 shutdown_timeout
+= HZ
*8;
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();
1289 shutdown_timeout
= 0;
1292 /* Various hardware housekeeping tasks relating to shutting down the jukebox */
1293 void shutdown_hw(void)
1296 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
1303 if (battery_level_safe()) { /* do not save on critical battery */
1304 #ifdef HAVE_LCD_BITMAP
1307 if(ata_disk_is_active())
1310 while(ata_disk_is_active())
1313 #if !defined (IAUDIO_X5) && !defined (SANSA_E200)
1314 #if defined(HAVE_BACKLIGHT_PWM_FADING) && !defined(SIMULATOR)
1315 backlight_set_fade_out(0);
1318 #endif /* IAUDIO_X5, SANSA_E200 */
1319 #ifdef HAVE_REMOTE_LCD
1320 remote_backlight_off();
1323 #if CONFIG_CODEC != SWCODEC
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())
1334 lcd_set_contrast(0);
1335 #endif /* IAUDIO_X5 */
1336 #ifdef HAVE_REMOTE_LCD
1337 lcd_remote_set_contrast(0);
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
1345 #endif /* #ifndef SIMULATOR */